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.plugwise.internal;
15 import static org.openhab.binding.plugwise.internal.PlugwiseCommunicationContext.*;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.nio.ByteBuffer;
20 import java.util.TooManyListenersException;
21 import java.util.regex.Matcher;
22 import java.util.regex.Pattern;
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.openhab.binding.plugwise.internal.protocol.AcknowledgementMessage;
27 import org.openhab.binding.plugwise.internal.protocol.Message;
28 import org.openhab.binding.plugwise.internal.protocol.MessageFactory;
29 import org.openhab.binding.plugwise.internal.protocol.field.MessageType;
30 import org.openhab.core.io.transport.serial.SerialPort;
31 import org.openhab.core.io.transport.serial.SerialPortEvent;
32 import org.openhab.core.io.transport.serial.SerialPortEventListener;
33 import org.openhab.core.util.StringUtils;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
38 * Processes messages received from the Plugwise Stick using a serial connection.
40 * @author Wouter Born, Karel Goderis - Initial contribution
43 public class PlugwiseMessageProcessor implements SerialPortEventListener {
45 private class MessageProcessorThread extends Thread {
47 public MessageProcessorThread() {
48 super("OH-binding-" + context.getBridgeUID() + "-message-processor");
54 while (!interrupted()) {
56 Message message = context.getReceivedQueue().take();
57 if (message != null) {
58 logger.debug("Took message from receivedQueue (length={})", context.getReceivedQueue().size());
59 processMessage(message);
61 logger.debug("Skipping null message from receivedQueue (length={})",
62 context.getReceivedQueue().size());
64 } catch (InterruptedException e) {
65 // That's our signal to stop
67 } catch (Exception e) {
68 logger.warn("Error while taking message from receivedQueue", e);
74 /** Matches Plugwise responses into the following groups: protocolHeader command sequence payload CRC */
75 private static final Pattern RESPONSE_PATTERN = Pattern.compile("(.{4})(\\w{4})(\\w{4})(\\w*?)(\\w{4})");
77 private final Logger logger = LoggerFactory.getLogger(PlugwiseMessageProcessor.class);
78 private final PlugwiseCommunicationContext context;
79 private final MessageFactory messageFactory = new MessageFactory();
81 private final ByteBuffer readBuffer = ByteBuffer.allocate(PlugwiseCommunicationContext.MAX_BUFFER_SIZE);
82 private int previousByte = -1;
84 private @Nullable MessageProcessorThread thread;
86 public PlugwiseMessageProcessor(PlugwiseCommunicationContext context) {
87 this.context = context;
91 * Parse a buffer into a Message and put it in the appropriate queue for further processing
93 * @param readBuffer - the string to parse
95 private void parseAndQueue(ByteBuffer readBuffer) {
96 String response = new String(readBuffer.array(), 0, readBuffer.limit());
97 response = StringUtils.chomp(response);
99 Matcher matcher = RESPONSE_PATTERN.matcher(response);
101 if (matcher.matches()) {
102 String protocolHeader = matcher.group(1);
103 String messageTypeHex = matcher.group(2);
104 String sequence = matcher.group(3);
105 String payload = matcher.group(4);
106 String crc = matcher.group(5);
108 if (protocolHeader.equals(PROTOCOL_HEADER)) {
109 String calculatedCRC = Message.getCRC(messageTypeHex + sequence + payload);
110 if (calculatedCRC.equals(crc)) {
111 MessageType messageType = MessageType.forValue(Integer.parseInt(messageTypeHex, 16));
112 int sequenceNumber = Integer.parseInt(sequence, 16);
114 if (messageType == null) {
115 logger.debug("Received unrecognized message: messageTypeHex=0x{}, sequence={}, payload={}",
116 messageTypeHex, sequenceNumber, payload);
120 logger.debug("Received message: messageType={}, sequenceNumber={}, payload={}", messageType,
121 sequenceNumber, payload);
124 Message message = messageFactory.createMessage(messageType, sequenceNumber, payload);
126 if (message instanceof AcknowledgementMessage acknowledgementMessage
127 && !acknowledgementMessage.isExtended()) {
128 logger.debug("Adding to acknowledgedQueue: {}", message);
129 context.getAcknowledgedQueue().put(acknowledgementMessage);
131 logger.debug("Adding to receivedQueue: {}", message);
132 context.getReceivedQueue().put(message);
134 } catch (IllegalArgumentException e) {
135 logger.warn("Failed to create message", e);
136 } catch (InterruptedException e) {
137 Thread.interrupted();
140 logger.warn("Plugwise protocol CRC error: {} does not match {} in message", calculatedCRC, crc);
143 logger.debug("Plugwise protocol header error: {} in message {}", protocolHeader, response);
145 } else if (!response.contains("APSRequestNodeInfo") && !response.contains("APSSetSleepBehaviour")
146 && !response.startsWith("# ")) {
147 logger.warn("Plugwise protocol message error: {}", response);
151 private void processMessage(Message message) {
152 context.getFilteredListeners().notifyListeners(message);
154 // After processing the response to a message, we remove any reference to the original request
155 // stored in the sentQueue
156 // WARNING: We assume that each request sent out can only be followed bye EXACTLY ONE response - so
157 // far it seems that the Plugwise protocol is operating in that way
160 context.getSentQueueLock().lock();
162 for (PlugwiseQueuedMessage queuedSentMessage : context.getSentQueue()) {
163 if (queuedSentMessage != null
164 && queuedSentMessage.getMessage().getSequenceNumber() == message.getSequenceNumber()) {
165 logger.debug("Removing from sentQueue: {}", queuedSentMessage.getMessage());
166 context.getSentQueue().remove(queuedSentMessage);
171 context.getSentQueueLock().unlock();
175 @SuppressWarnings("resource")
177 public void serialEvent(@Nullable SerialPortEvent event) {
178 if (event != null && event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
179 // We get here if data has been received
180 SerialPort serialPort = context.getSerialPort();
181 if (serialPort == null) {
182 logger.debug("Failed to read available data from null serialPort");
187 InputStream inputStream = serialPort.getInputStream();
188 if (inputStream == null) {
189 logger.debug("Failed to read available data from null inputStream");
193 // Read data from serial device
194 while (inputStream.available() > 0) {
195 int currentByte = inputStream.read();
196 // Plugwise sends ASCII data, but for some unknown reason we sometimes get data with unsigned
197 // byte value >127 which in itself is very strange. We filter these out for the time being
198 if (currentByte < 128) {
199 readBuffer.put((byte) currentByte);
200 if (previousByte == CR && currentByte == LF) {
202 parseAndQueue(readBuffer);
206 previousByte = currentByte;
210 } catch (IOException e) {
211 logger.debug("Error receiving data on serial port {}: {}", context.getConfiguration().getSerialPort(),
217 @SuppressWarnings("resource")
218 public void start() throws PlugwiseInitializationException {
219 SerialPort serialPort = context.getSerialPort();
220 if (serialPort == null) {
221 throw new PlugwiseInitializationException("Failed to add serial port listener because port is null");
225 serialPort.addEventListener(this);
226 } catch (TooManyListenersException e) {
227 throw new PlugwiseInitializationException("Failed to add serial port listener", e);
230 thread = new MessageProcessorThread();
234 @SuppressWarnings("resource")
236 PlugwiseUtils.stopBackgroundThread(thread);
238 SerialPort serialPort = context.getSerialPort();
239 if (serialPort != null) {
240 serialPort.removeEventListener();