2 * Copyright (c) 2010-2021 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.rfxcom.internal.handler;
15 import java.io.IOException;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.List;
19 import java.util.Queue;
20 import java.util.concurrent.CopyOnWriteArrayList;
21 import java.util.concurrent.LinkedBlockingQueue;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.openhab.binding.rfxcom.internal.DeviceMessageListener;
27 import org.openhab.binding.rfxcom.internal.config.RFXComBridgeConfiguration;
28 import org.openhab.binding.rfxcom.internal.connector.RFXComConnectorInterface;
29 import org.openhab.binding.rfxcom.internal.connector.RFXComEventListener;
30 import org.openhab.binding.rfxcom.internal.connector.RFXComJD2XXConnector;
31 import org.openhab.binding.rfxcom.internal.connector.RFXComSerialConnector;
32 import org.openhab.binding.rfxcom.internal.connector.RFXComTcpConnector;
33 import org.openhab.binding.rfxcom.internal.discovery.RFXComDeviceDiscoveryService;
34 import org.openhab.binding.rfxcom.internal.exceptions.RFXComException;
35 import org.openhab.binding.rfxcom.internal.exceptions.RFXComMessageNotImplementedException;
36 import org.openhab.binding.rfxcom.internal.messages.RFXComBaseMessage;
37 import org.openhab.binding.rfxcom.internal.messages.RFXComDeviceMessage;
38 import org.openhab.binding.rfxcom.internal.messages.RFXComInterfaceControlMessage;
39 import org.openhab.binding.rfxcom.internal.messages.RFXComInterfaceMessage;
40 import org.openhab.binding.rfxcom.internal.messages.RFXComInterfaceMessage.Commands;
41 import org.openhab.binding.rfxcom.internal.messages.RFXComInterfaceMessage.SubType;
42 import org.openhab.binding.rfxcom.internal.messages.RFXComMessage;
43 import org.openhab.binding.rfxcom.internal.messages.RFXComMessageFactory;
44 import org.openhab.binding.rfxcom.internal.messages.RFXComTransmitterMessage;
45 import org.openhab.core.io.transport.serial.SerialPortManager;
46 import org.openhab.core.thing.Bridge;
47 import org.openhab.core.thing.ChannelUID;
48 import org.openhab.core.thing.Thing;
49 import org.openhab.core.thing.ThingStatus;
50 import org.openhab.core.thing.ThingStatusDetail;
51 import org.openhab.core.thing.binding.BaseBridgeHandler;
52 import org.openhab.core.thing.binding.ThingHandlerService;
53 import org.openhab.core.types.Command;
54 import org.openhab.core.util.HexUtils;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
59 * {@link RFXComBridgeHandler} is the handler for a RFXCOM transceivers. All
60 * {@link RFXComHandler}s use the {@link RFXComBridgeHandler} to execute the
63 * @author Pauli Anttila - Initial contribution
65 public class RFXComBridgeHandler extends BaseBridgeHandler {
66 private Logger logger = LoggerFactory.getLogger(RFXComBridgeHandler.class);
68 private RFXComConnectorInterface connector = null;
69 private MessageListener eventListener = new MessageListener();
71 private List<DeviceMessageListener> deviceStatusListeners = new CopyOnWriteArrayList<>();
73 private RFXComBridgeConfiguration configuration = null;
74 private ScheduledFuture<?> connectorTask;
76 private SerialPortManager serialPortManager;
78 private class TransmitQueue {
79 private Queue<RFXComBaseMessage> queue = new LinkedBlockingQueue<>();
81 public synchronized void enqueue(RFXComBaseMessage msg) throws IOException {
82 boolean wasEmpty = queue.isEmpty();
83 if (queue.offer(msg)) {
88 logger.error("Transmit queue overflow. Lost message: {}", msg);
92 public synchronized void sendNext() throws IOException {
97 public synchronized void send() throws IOException {
98 while (!queue.isEmpty()) {
99 RFXComBaseMessage msg = queue.peek();
102 logger.debug("Transmitting message '{}'", msg);
103 byte[] data = msg.decodeMessage();
104 connector.sendMessage(data);
106 } catch (RFXComException rfxe) {
107 logger.error("Error during send of {}", msg, rfxe);
114 private TransmitQueue transmitQueue = new TransmitQueue();
116 public RFXComBridgeHandler(@NonNull Bridge br, SerialPortManager serialPortManager) {
118 this.serialPortManager = serialPortManager;
122 public Collection<Class<? extends ThingHandlerService>> getServices() {
123 return Collections.singleton(RFXComDeviceDiscoveryService.class);
127 public void handleCommand(ChannelUID channelUID, Command command) {
128 logger.debug("Bridge commands not supported.");
132 public synchronized void dispose() {
133 logger.debug("Handler disposed.");
135 for (DeviceMessageListener deviceStatusListener : deviceStatusListeners) {
136 unregisterDeviceStatusListener(deviceStatusListener);
139 if (connector != null) {
140 connector.removeEventListener(eventListener);
141 connector.disconnect();
145 if (connectorTask != null && !connectorTask.isCancelled()) {
146 connectorTask.cancel(true);
147 connectorTask = null;
154 public void initialize() {
155 logger.debug("Initializing RFXCOM bridge handler");
156 updateStatus(ThingStatus.OFFLINE);
158 configuration = getConfigAs(RFXComBridgeConfiguration.class);
160 if (configuration.serialPort != null && configuration.serialPort.startsWith("rfc2217")) {
161 logger.debug("Please use the Transceiver over TCP/IP bridge type for a serial over IP connection.");
162 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
163 "Please use the Transceiver over TCP/IP bridge type for a serial over IP connection.");
167 if (connectorTask == null || connectorTask.isCancelled()) {
168 connectorTask = scheduler.scheduleWithFixedDelay(() -> {
169 logger.trace("Checking RFXCOM transceiver connection, thing status = {}", thing.getStatus());
170 if (thing.getStatus() != ThingStatus.ONLINE) {
173 }, 0, 60, TimeUnit.SECONDS);
177 private synchronized void connect() {
178 logger.debug("Connecting to RFXCOM transceiver");
181 String readerThreadName = "OH-binding-" + getThing().getUID().getAsString();
182 if (configuration.serialPort != null) {
183 if (connector == null) {
184 connector = new RFXComSerialConnector(serialPortManager, readerThreadName);
186 } else if (configuration.bridgeId != null) {
187 if (connector == null) {
188 connector = new RFXComJD2XXConnector(readerThreadName);
190 } else if (configuration.host != null) {
191 if (connector == null) {
192 connector = new RFXComTcpConnector(readerThreadName);
196 if (connector != null) {
197 connector.disconnect();
198 connector.connect(configuration);
200 logger.debug("Reset controller");
201 connector.sendMessage(RFXComMessageFactory.CMD_RESET);
203 // controller does not response immediately after reset,
207 connector.addEventListener(eventListener);
209 logger.debug("Get status of controller");
210 connector.sendMessage(RFXComMessageFactory.CMD_GET_STATUS);
212 } catch (IOException e) {
213 logger.error("Connection to RFXCOM transceiver failed", e);
214 if ("device not opened (3)".equalsIgnoreCase(e.getMessage())) {
215 if (connector instanceof RFXComJD2XXConnector) {
216 logger.info("Automatically Discovered RFXCOM bridges use FTDI chip driver (D2XX)."
217 + " Reason for this error normally is related to operating system native FTDI drivers,"
218 + " which prevent D2XX driver to open device."
219 + " To solve this problem, uninstall OS FTDI native drivers or add manually universal bridge 'RFXCOM USB Transceiver',"
220 + " which use normal serial port driver rather than D2XX.");
223 } catch (Exception e) {
224 logger.error("Connection to RFXCOM transceiver failed", e);
225 } catch (UnsatisfiedLinkError e) {
226 logger.error("Error occurred when trying to load native library for OS '{}' version '{}', processor '{}'",
227 System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch"), e);
231 public void sendMessage(RFXComMessage msg) {
233 RFXComBaseMessage baseMsg = (RFXComBaseMessage) msg;
234 transmitQueue.enqueue(baseMsg);
235 } catch (IOException e) {
236 logger.error("I/O Error", e);
237 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
241 private class MessageListener implements RFXComEventListener {
244 public void packetReceived(byte[] packet) {
246 RFXComMessage message = RFXComMessageFactory.createMessage(packet);
247 logger.debug("Message received: {}", message);
249 if (message instanceof RFXComInterfaceMessage) {
250 RFXComInterfaceMessage msg = (RFXComInterfaceMessage) message;
251 if (msg.subType == SubType.RESPONSE) {
252 if (msg.command == Commands.GET_STATUS) {
253 logger.debug("RFXCOM transceiver/receiver type: {}, hw version: {}.{}, fw version: {}",
254 msg.transceiverType, msg.hardwareVersion1, msg.hardwareVersion2,
255 msg.firmwareVersion);
256 if (msg.firmwareVersion < 1000) {
258 * Versions before 1000 had some different behaviour, so lets encourage upgrading.
259 * 1001 was released in Feb 2016!
262 "RFXCOM device using outdated firmware (version {}), consider flashing with more a more recent version",
263 msg.firmwareVersion);
265 thing.setProperty(Thing.PROPERTY_HARDWARE_VERSION,
266 msg.hardwareVersion1 + "." + msg.hardwareVersion2);
267 thing.setProperty(Thing.PROPERTY_FIRMWARE_VERSION, Integer.toString(msg.firmwareVersion));
269 if (configuration.ignoreConfig) {
270 logger.debug("Ignoring transceiver configuration");
272 byte[] setMode = null;
274 if (configuration.setMode != null && !configuration.setMode.isEmpty()) {
276 setMode = HexUtils.hexToBytes(configuration.setMode);
277 if (setMode.length != 14) {
278 logger.warn("Invalid RFXCOM transceiver mode configuration");
281 } catch (IllegalArgumentException ee) {
282 logger.warn("Failed to parse setMode data", ee);
285 RFXComInterfaceControlMessage modeMsg = new RFXComInterfaceControlMessage(
286 msg.transceiverType, configuration);
287 setMode = modeMsg.decodeMessage();
290 if (setMode != null) {
291 if (logger.isDebugEnabled()) {
292 logger.debug("Setting RFXCOM mode using: {}", HexUtils.bytesToHex(setMode));
294 connector.sendMessage(setMode);
298 // No need to wait for a response to any set mode. We start
299 // regardless of whether it fails and the RFXCOM's buffer
300 // is big enough to queue up the command.
301 logger.debug("Start receiver");
302 connector.sendMessage(RFXComMessageFactory.CMD_START_RECEIVER);
304 } else if (msg.subType == SubType.START_RECEIVER) {
305 updateStatus(ThingStatus.ONLINE);
306 logger.debug("Start TX of any queued messages");
307 transmitQueue.send();
309 logger.debug("Interface response received: {}", msg);
310 transmitQueue.sendNext();
312 } else if (message instanceof RFXComTransmitterMessage) {
313 RFXComTransmitterMessage resp = (RFXComTransmitterMessage) message;
315 logger.debug("Transmitter response received: {}", resp);
317 transmitQueue.sendNext();
318 } else if (message instanceof RFXComDeviceMessage) {
319 for (DeviceMessageListener deviceStatusListener : deviceStatusListeners) {
321 deviceStatusListener.onDeviceMessageReceived(getThing().getUID(),
322 (RFXComDeviceMessage) message);
323 } catch (Exception e) {
324 // catch all exceptions give all handlers a fair chance of handling the messages
325 logger.error("An exception occurred while calling the DeviceStatusListener", e);
329 logger.warn("The received message cannot be processed, please create an "
330 + "issue at the relevant tracker. Received message: {}", message);
332 } catch (RFXComMessageNotImplementedException e) {
333 logger.debug("Message not supported, data: {}", HexUtils.bytesToHex(packet));
334 } catch (RFXComException e) {
335 logger.error("Error occurred during packet receiving, data: {}", HexUtils.bytesToHex(packet), e);
336 } catch (IOException e) {
337 errorOccurred("I/O error");
342 public void errorOccurred(String error) {
343 logger.error("Error occurred: {}", error);
344 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
348 public boolean registerDeviceStatusListener(DeviceMessageListener deviceStatusListener) {
349 if (deviceStatusListener == null) {
350 throw new IllegalArgumentException("It's not allowed to pass a null deviceStatusListener.");
352 return !deviceStatusListeners.contains(deviceStatusListener) && deviceStatusListeners.add(deviceStatusListener);
355 public boolean unregisterDeviceStatusListener(DeviceMessageListener deviceStatusListener) {
356 if (deviceStatusListener == null) {
357 throw new IllegalArgumentException("It's not allowed to pass a null deviceStatusListener.");
359 return deviceStatusListeners.remove(deviceStatusListener);
362 public RFXComBridgeConfiguration getConfiguration() {
363 return configuration;