]> git.basschouten.com Git - openhab-addons.git/blob
3c3065925260e0298427dd0454648e31cd8fc12d
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.phc.internal.handler;
14
15 import java.util.Arrays;
16 import java.util.concurrent.BlockingQueue;
17 import java.util.concurrent.LinkedBlockingQueue;
18
19 /**
20  * Buffer for received messages
21  *
22  * @author Jonas Hohaus - Initial contribution
23  */
24 class InternalBuffer {
25     private static final int MAX_SIZE = 512;
26
27     private final BlockingQueue<byte[]> byteQueue = new LinkedBlockingQueue<>();
28     private byte[] buffer;
29     private int bufferIndex = 0;
30     private int size;
31
32     public void offer(byte[] buffer) {
33         // If the buffer becomes too large, already processed commands accumulate and
34         // the reaction becomes slow.
35         if (size < MAX_SIZE) {
36             byte[] localBuffer = Arrays.copyOf(buffer, Math.min(MAX_SIZE - size, buffer.length));
37             byteQueue.offer(localBuffer);
38             synchronized (this) {
39                 size += localBuffer.length;
40             }
41         }
42     }
43
44     public boolean hasNext() {
45         return (size > 0);
46     }
47
48     public byte get() throws InterruptedException {
49         byte[] buf = getBuffer();
50         if (buf != null) {
51             byte result = buf[bufferIndex++];
52             synchronized (this) {
53                 size--;
54             }
55
56             return result;
57         }
58
59         throw new IllegalStateException("get without hasNext");
60     }
61
62     public int size() {
63         return size;
64     }
65
66     private byte[] getBuffer() throws InterruptedException {
67         if (buffer == null || bufferIndex == buffer.length) {
68             buffer = byteQueue.take();
69             bufferIndex = 0;
70         }
71
72         return buffer;
73     }
74 }