]> git.basschouten.com Git - openhab-addons.git/blob
092ebf4364769b7adf692de840b950af1c06d991
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.rfxcom.internal.handler;
14
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;
24
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.RFXComMessageFactoryImpl;
45 import org.openhab.binding.rfxcom.internal.messages.RFXComTransmitterMessage;
46 import org.openhab.core.io.transport.serial.SerialPortManager;
47 import org.openhab.core.thing.Bridge;
48 import org.openhab.core.thing.ChannelUID;
49 import org.openhab.core.thing.Thing;
50 import org.openhab.core.thing.ThingStatus;
51 import org.openhab.core.thing.ThingStatusDetail;
52 import org.openhab.core.thing.binding.BaseBridgeHandler;
53 import org.openhab.core.thing.binding.ThingHandlerService;
54 import org.openhab.core.types.Command;
55 import org.openhab.core.util.HexUtils;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 /**
60  * {@link RFXComBridgeHandler} is the handler for a RFXCOM transceivers. All
61  * {@link RFXComHandler}s use the {@link RFXComBridgeHandler} to execute the
62  * actual commands.
63  *
64  * @author Pauli Anttila - Initial contribution
65  */
66 public class RFXComBridgeHandler extends BaseBridgeHandler {
67     private Logger logger = LoggerFactory.getLogger(RFXComBridgeHandler.class);
68
69     private RFXComConnectorInterface connector = null;
70     private MessageListener eventListener = new MessageListener();
71
72     private List<DeviceMessageListener> deviceStatusListeners = new CopyOnWriteArrayList<>();
73
74     private RFXComBridgeConfiguration configuration = null;
75     private ScheduledFuture<?> connectorTask;
76
77     private SerialPortManager serialPortManager;
78
79     private RFXComMessageFactory messageFactory;
80
81     private class TransmitQueue {
82         private Queue<RFXComBaseMessage> queue = new LinkedBlockingQueue<>();
83
84         public synchronized void enqueue(RFXComBaseMessage msg) throws IOException {
85             boolean wasEmpty = queue.isEmpty();
86             if (queue.offer(msg)) {
87                 if (wasEmpty) {
88                     send();
89                 }
90             } else {
91                 logger.error("Transmit queue overflow. Lost message: {}", msg);
92             }
93         }
94
95         public synchronized void sendNext() throws IOException {
96             queue.poll();
97             send();
98         }
99
100         public synchronized void send() throws IOException {
101             while (!queue.isEmpty()) {
102                 RFXComBaseMessage msg = queue.peek();
103
104                 try {
105                     logger.debug("Transmitting message '{}'", msg);
106                     byte[] data = msg.decodeMessage();
107                     connector.sendMessage(data);
108                     break;
109                 } catch (RFXComException rfxe) {
110                     logger.error("Error during send of {}", msg, rfxe);
111                     queue.poll();
112                 }
113             }
114         }
115     }
116
117     private TransmitQueue transmitQueue = new TransmitQueue();
118
119     public RFXComBridgeHandler(@NonNull Bridge br, SerialPortManager serialPortManager) {
120         super(br);
121         this.serialPortManager = serialPortManager;
122         this.messageFactory = RFXComMessageFactoryImpl.INSTANCE;
123     }
124
125     public RFXComBridgeHandler(@NonNull Bridge br, SerialPortManager serialPortManager,
126             RFXComMessageFactory messageFactory) {
127         super(br);
128         this.serialPortManager = serialPortManager;
129         this.messageFactory = messageFactory;
130     }
131
132     @Override
133     public Collection<Class<? extends ThingHandlerService>> getServices() {
134         return Collections.singleton(RFXComDeviceDiscoveryService.class);
135     }
136
137     @Override
138     public void handleCommand(ChannelUID channelUID, Command command) {
139         logger.debug("Bridge commands not supported.");
140     }
141
142     @Override
143     public synchronized void dispose() {
144         logger.debug("Handler disposed.");
145
146         for (DeviceMessageListener deviceStatusListener : deviceStatusListeners) {
147             unregisterDeviceStatusListener(deviceStatusListener);
148         }
149
150         if (connector != null) {
151             connector.removeEventListener(eventListener);
152             connector.disconnect();
153             connector = null;
154         }
155
156         if (connectorTask != null && !connectorTask.isCancelled()) {
157             connectorTask.cancel(true);
158             connectorTask = null;
159         }
160
161         super.dispose();
162     }
163
164     @Override
165     public void initialize() {
166         logger.debug("Initializing RFXCOM bridge handler");
167         updateStatus(ThingStatus.OFFLINE);
168
169         configuration = getConfigAs(RFXComBridgeConfiguration.class);
170
171         if (configuration.serialPort != null && configuration.serialPort.startsWith("rfc2217")) {
172             logger.debug("Please use the Transceiver over TCP/IP bridge type for a serial over IP connection.");
173             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
174                     "Please use the Transceiver over TCP/IP bridge type for a serial over IP connection.");
175             return;
176         }
177
178         if (connectorTask == null || connectorTask.isCancelled()) {
179             connectorTask = scheduler.scheduleWithFixedDelay(() -> {
180                 logger.trace("Checking RFXCOM transceiver connection, thing status = {}", thing.getStatus());
181                 if (thing.getStatus() != ThingStatus.ONLINE) {
182                     connect();
183                 }
184             }, 0, 60, TimeUnit.SECONDS);
185         }
186     }
187
188     private synchronized void connect() {
189         logger.debug("Connecting to RFXCOM transceiver");
190
191         try {
192             String readerThreadName = "OH-binding-" + getThing().getUID().getAsString();
193             if (configuration.serialPort != null) {
194                 if (connector == null) {
195                     connector = new RFXComSerialConnector(serialPortManager, readerThreadName);
196                 }
197             } else if (configuration.bridgeId != null) {
198                 if (connector == null) {
199                     connector = new RFXComJD2XXConnector(readerThreadName);
200                 }
201             } else if (configuration.host != null) {
202                 if (connector == null) {
203                     connector = new RFXComTcpConnector(readerThreadName);
204                 }
205             }
206
207             if (connector != null) {
208                 connector.disconnect();
209                 connector.connect(configuration);
210
211                 logger.debug("Reset controller");
212                 connector.sendMessage(RFXComInterfaceMessage.CMD_RESET);
213
214                 // controller does not response immediately after reset,
215                 // so wait a while
216                 Thread.sleep(300);
217
218                 connector.addEventListener(eventListener);
219
220                 logger.debug("Get status of controller");
221                 connector.sendMessage(RFXComInterfaceMessage.CMD_GET_STATUS);
222             }
223         } catch (IOException e) {
224             logger.error("Connection to RFXCOM transceiver failed", e);
225             if ("device not opened (3)".equalsIgnoreCase(e.getMessage())) {
226                 if (connector instanceof RFXComJD2XXConnector) {
227                     logger.info("Automatically Discovered RFXCOM bridges use FTDI chip driver (D2XX)."
228                             + " Reason for this error normally is related to operating system native FTDI drivers,"
229                             + " which prevent D2XX driver to open device."
230                             + " To solve this problem, uninstall OS FTDI native drivers or add manually universal bridge 'RFXCOM USB Transceiver',"
231                             + " which use normal serial port driver rather than D2XX.");
232                 }
233             }
234         } catch (Exception e) {
235             logger.error("Connection to RFXCOM transceiver failed", e);
236         } catch (UnsatisfiedLinkError e) {
237             logger.error("Error occurred when trying to load native library for OS '{}' version '{}', processor '{}'",
238                     System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch"), e);
239         }
240     }
241
242     public void sendMessage(RFXComMessage msg) {
243         try {
244             RFXComBaseMessage baseMsg = (RFXComBaseMessage) msg;
245             transmitQueue.enqueue(baseMsg);
246         } catch (IOException e) {
247             logger.error("I/O Error", e);
248             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
249         }
250     }
251
252     private class MessageListener implements RFXComEventListener {
253
254         @Override
255         public void packetReceived(byte[] packet) {
256             try {
257                 RFXComMessage message = messageFactory.createMessage(packet);
258                 logger.debug("Message received: {}", message);
259
260                 if (message instanceof RFXComInterfaceMessage) {
261                     RFXComInterfaceMessage msg = (RFXComInterfaceMessage) message;
262                     if (msg.subType == SubType.RESPONSE) {
263                         if (msg.command == Commands.GET_STATUS) {
264                             logger.debug("RFXCOM transceiver/receiver type: {}, hw version: {}.{}, fw version: {}",
265                                     msg.transceiverType, msg.hardwareVersion1, msg.hardwareVersion2,
266                                     msg.firmwareVersion);
267                             if (msg.firmwareVersion < 1000) {
268                                 /**
269                                  * Versions before 1000 had some different behaviour, so lets encourage upgrading.
270                                  * 1001 was released in Feb 2016!
271                                  */
272                                 logger.warn(
273                                         "RFXCOM device using outdated firmware (version {}), consider flashing with more a more recent version",
274                                         msg.firmwareVersion);
275                             }
276                             thing.setProperty(Thing.PROPERTY_HARDWARE_VERSION,
277                                     msg.hardwareVersion1 + "." + msg.hardwareVersion2);
278                             thing.setProperty(Thing.PROPERTY_FIRMWARE_VERSION, Integer.toString(msg.firmwareVersion));
279
280                             if (configuration.ignoreConfig) {
281                                 logger.debug("Ignoring transceiver configuration");
282                             } else {
283                                 byte[] setMode = null;
284
285                                 if (configuration.setMode != null && !configuration.setMode.isEmpty()) {
286                                     try {
287                                         setMode = HexUtils.hexToBytes(configuration.setMode);
288                                         if (setMode.length != 14) {
289                                             logger.warn("Invalid RFXCOM transceiver mode configuration");
290                                             setMode = null;
291                                         }
292                                     } catch (IllegalArgumentException ee) {
293                                         logger.warn("Failed to parse setMode data", ee);
294                                     }
295                                 } else {
296                                     RFXComInterfaceControlMessage modeMsg = new RFXComInterfaceControlMessage(
297                                             msg.transceiverType, configuration);
298                                     setMode = modeMsg.decodeMessage();
299                                 }
300
301                                 if (setMode != null) {
302                                     if (logger.isDebugEnabled()) {
303                                         logger.debug("Setting RFXCOM mode using: {}", HexUtils.bytesToHex(setMode));
304                                     }
305                                     connector.sendMessage(setMode);
306                                 }
307                             }
308
309                             // No need to wait for a response to any set mode. We start
310                             // regardless of whether it fails and the RFXCOM's buffer
311                             // is big enough to queue up the command.
312                             logger.debug("Start receiver");
313                             connector.sendMessage(RFXComInterfaceMessage.CMD_START_RECEIVER);
314                         }
315                     } else if (msg.subType == SubType.START_RECEIVER) {
316                         updateStatus(ThingStatus.ONLINE);
317                         logger.debug("Start TX of any queued messages");
318                         transmitQueue.send();
319                     } else {
320                         logger.debug("Interface response received: {}", msg);
321                         transmitQueue.sendNext();
322                     }
323                 } else if (message instanceof RFXComTransmitterMessage) {
324                     RFXComTransmitterMessage resp = (RFXComTransmitterMessage) message;
325
326                     logger.debug("Transmitter response received: {}", resp);
327
328                     transmitQueue.sendNext();
329                 } else if (message instanceof RFXComDeviceMessage) {
330                     for (DeviceMessageListener deviceStatusListener : deviceStatusListeners) {
331                         try {
332                             deviceStatusListener.onDeviceMessageReceived(getThing().getUID(),
333                                     (RFXComDeviceMessage) message);
334                         } catch (Exception e) {
335                             // catch all exceptions give all handlers a fair chance of handling the messages
336                             logger.error("An exception occurred while calling the DeviceStatusListener", e);
337                         }
338                     }
339                 } else {
340                     logger.warn("The received message cannot be processed, please create an "
341                             + "issue at the relevant tracker. Received message: {}", message);
342                 }
343             } catch (RFXComMessageNotImplementedException e) {
344                 logger.debug("Message not supported, data: {}", HexUtils.bytesToHex(packet));
345             } catch (RFXComException e) {
346                 logger.error("Error occurred during packet receiving, data: {}", HexUtils.bytesToHex(packet), e);
347             } catch (IOException e) {
348                 errorOccurred("I/O error");
349             }
350         }
351
352         @Override
353         public void errorOccurred(String error) {
354             logger.error("Error occurred: {}", error);
355             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
356         }
357     }
358
359     public boolean registerDeviceStatusListener(DeviceMessageListener deviceStatusListener) {
360         if (deviceStatusListener == null) {
361             throw new IllegalArgumentException("It's not allowed to pass a null deviceStatusListener.");
362         }
363         return !deviceStatusListeners.contains(deviceStatusListener) && deviceStatusListeners.add(deviceStatusListener);
364     }
365
366     public boolean unregisterDeviceStatusListener(DeviceMessageListener deviceStatusListener) {
367         if (deviceStatusListener == null) {
368             throw new IllegalArgumentException("It's not allowed to pass a null deviceStatusListener.");
369         }
370         return deviceStatusListeners.remove(deviceStatusListener);
371     }
372
373     public RFXComBridgeConfiguration getConfiguration() {
374         return configuration;
375     }
376 }