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.monopriceaudio.internal.communication;
15 import java.util.Arrays;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.openhab.binding.monopriceaudio.internal.MonopriceAudioException;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
23 * A class that reads messages from the MonopriceAudio device in a dedicated thread
25 * @author Laurent Garnier - Initial contribution
26 * @author Michael Lobstein - Adapted for the MonopriceAudio binding
29 public class MonopriceAudioReaderThread extends Thread {
30 private static final int READ_BUFFER_SIZE = 16;
31 private static final int SIZE = 64;
32 private static final char TERM_CHAR = '\r';
33 private final Logger logger = LoggerFactory.getLogger(MonopriceAudioReaderThread.class);
35 private MonopriceAudioConnector connector;
40 * @param connector the object that should handle the received message
41 * @param uid the thing uid string
42 * @param connectionId a string that uniquely identifies the particular connection
44 public MonopriceAudioReaderThread(MonopriceAudioConnector connector, String uid, String connectionId) {
45 super("OH-binding-" + uid + "-" + connectionId);
46 this.connector = connector;
52 logger.debug("Data listener started");
54 byte[] readDataBuffer = new byte[READ_BUFFER_SIZE];
55 byte[] dataBuffer = new byte[SIZE];
59 while (!Thread.interrupted()) {
60 int len = connector.readInput(readDataBuffer);
62 for (int i = 0; i < len; i++) {
65 dataBuffer[index++] = readDataBuffer[i];
67 if (readDataBuffer[i] == TERM_CHAR) {
69 dataBuffer[index - 1] = (byte) TERM_CHAR;
71 byte[] msg = Arrays.copyOf(dataBuffer, index);
72 connector.handleIncomingMessage(msg);
79 } catch (MonopriceAudioException e) {
80 logger.debug("Reading failed: {}", e.getMessage(), e);
81 connector.handleIncomingMessage(MonopriceAudioConnector.READ_ERROR.getBytes());
84 logger.debug("Data listener stopped");