2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.phc.internal.handler;
15 import java.util.Arrays;
16 import java.util.concurrent.BlockingQueue;
17 import java.util.concurrent.LinkedBlockingQueue;
20 * Buffer for received messages
22 * @author Jonas Hohaus - Initial contribution
24 class InternalBuffer {
25 private static final int MAX_SIZE = 512;
27 private final BlockingQueue<byte[]> byteQueue = new LinkedBlockingQueue<>();
28 private byte[] buffer;
29 private int bufferIndex = 0;
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);
39 size += localBuffer.length;
44 public boolean hasNext() {
48 public byte get() throws InterruptedException {
49 byte[] buf = getBuffer();
51 byte result = buf[bufferIndex++];
59 throw new IllegalStateException("get without hasNext");
66 private byte[] getBuffer() throws InterruptedException {
67 if (buffer == null || bufferIndex == buffer.length) {
68 buffer = byteQueue.take();