]> git.basschouten.com Git - openhab-addons.git/blob
6d193f0cfc08f764a984004e8cc7ccd475e8cf55
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.caddx.internal.handler;
14
15 import static org.openhab.binding.caddx.internal.CaddxBindingConstants.SEND_COMMAND;
16
17 import java.io.IOException;
18 import java.math.BigDecimal;
19 import java.util.Collection;
20 import java.util.HashSet;
21 import java.util.Map;
22 import java.util.Set;
23 import java.util.TooManyListenersException;
24 import java.util.concurrent.ConcurrentHashMap;
25
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.caddx.internal.CaddxBindingConstants;
29 import org.openhab.binding.caddx.internal.CaddxCommunicator;
30 import org.openhab.binding.caddx.internal.CaddxEvent;
31 import org.openhab.binding.caddx.internal.CaddxMessage;
32 import org.openhab.binding.caddx.internal.CaddxMessageType;
33 import org.openhab.binding.caddx.internal.CaddxPanelListener;
34 import org.openhab.binding.caddx.internal.CaddxProtocol;
35 import org.openhab.binding.caddx.internal.CaddxSource;
36 import org.openhab.binding.caddx.internal.action.CaddxBridgeActions;
37 import org.openhab.binding.caddx.internal.config.CaddxBridgeConfiguration;
38 import org.openhab.binding.caddx.internal.config.CaddxKeypadConfiguration;
39 import org.openhab.binding.caddx.internal.config.CaddxPartitionConfiguration;
40 import org.openhab.binding.caddx.internal.config.CaddxZoneConfiguration;
41 import org.openhab.binding.caddx.internal.discovery.CaddxDiscoveryService;
42 import org.openhab.core.io.transport.serial.PortInUseException;
43 import org.openhab.core.io.transport.serial.SerialPortManager;
44 import org.openhab.core.io.transport.serial.UnsupportedCommOperationException;
45 import org.openhab.core.library.types.StringType;
46 import org.openhab.core.thing.Bridge;
47 import org.openhab.core.thing.Channel;
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.ThingHandler;
54 import org.openhab.core.thing.binding.ThingHandlerService;
55 import org.openhab.core.types.Command;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 /**
60  * The bridge handler for the Caddx RS232 Serial interface.
61  *
62  * @author Georgios Moutsos - Initial contribution
63  */
64 @NonNullByDefault
65 public class CaddxBridgeHandler extends BaseBridgeHandler implements CaddxPanelListener {
66     private final Logger logger = LoggerFactory.getLogger(CaddxBridgeHandler.class);
67
68     static final byte[] DISCOVERY_PARTITION_STATUS_REQUEST_0 = { 0x26, 0x00 };
69     static final byte[] DISCOVERY_ZONES_SNAPSHOT_REQUEST_00 = { 0x25, 0x00 }; // 1 - 16
70     static final byte[] DISCOVERY_ZONES_SNAPSHOT_REQUEST_10 = { 0x25, 0x01 }; // 17 - 32
71     static final byte[] DISCOVERY_ZONES_SNAPSHOT_REQUEST_20 = { 0x25, 0x02 }; // 33 - 48
72     static final byte[] DISCOVERY_ZONES_SNAPSHOT_REQUEST_30 = { 0x25, 0x03 }; // 49 - 64
73     static final byte[] DISCOVERY_ZONES_SNAPSHOT_REQUEST_40 = { 0x25, 0x04 }; // 65 - 80
74     static final byte[] DISCOVERY_ZONES_SNAPSHOT_REQUEST_50 = { 0x25, 0x05 }; // 81 - 96
75     static final byte[] DISCOVERY_ZONES_SNAPSHOT_REQUEST_60 = { 0x25, 0x06 }; // 97 - 112
76     static final byte[] DISCOVERY_ZONES_SNAPSHOT_REQUEST_70 = { 0x25, 0x07 }; // 113 - 64
77     static final byte[] DISCOVERY_ZONES_SNAPSHOT_REQUEST_80 = { 0x25, 0x08 }; // 129 - 144
78     static final byte[] DISCOVERY_ZONES_SNAPSHOT_REQUEST_90 = { 0x25, 0x09 }; // 145 - 160
79     static final byte[] DISCOVERY_ZONES_SNAPSHOT_REQUEST_A0 = { 0x25, 0x0A }; // 161 - 176
80     static final byte[] DISCOVERY_ZONES_SNAPSHOT_REQUEST_B0 = { 0x25, 0x0B }; // 177 - 192
81     static final byte[] DISCOVERY_PARTITIONS_SNAPSHOT_REQUEST = { 0x27 };
82
83     private final SerialPortManager portManager;
84     private @Nullable CaddxDiscoveryService discoveryService = null;
85     private CaddxProtocol protocol = CaddxProtocol.Binary;
86     private String serialPortName = "";
87     private int baudRate;
88     private int maxZoneNumber;
89     private @Nullable CaddxCommunicator communicator = null;
90
91     // Things served by the bridge
92     private Map<BigDecimal, Thing> thingZonesMap = new ConcurrentHashMap<>();
93     private Map<BigDecimal, Thing> thingPartitionsMap = new ConcurrentHashMap<>();
94     private Map<BigDecimal, Thing> thingKeypadsMap = new ConcurrentHashMap<>();
95     private @Nullable Thing thingPanel = null;
96
97     public @Nullable CaddxDiscoveryService getDiscoveryService() {
98         return discoveryService;
99     }
100
101     public void setDiscoveryService(CaddxDiscoveryService discoveryService) {
102         this.discoveryService = discoveryService;
103     }
104
105     public CaddxBridgeHandler(SerialPortManager portManager, Bridge bridge) {
106         super(bridge);
107
108         this.portManager = portManager;
109     }
110
111     @Override
112     public void initialize() {
113         CaddxBridgeConfiguration configuration = getConfigAs(CaddxBridgeConfiguration.class);
114
115         String portName = configuration.getSerialPort();
116         if (portName == null) {
117             logger.debug("Serial port is not defined in the configuration");
118             return;
119         }
120         serialPortName = portName;
121         protocol = configuration.getProtocol();
122         baudRate = configuration.getBaudrate();
123         maxZoneNumber = configuration.getMaxZoneNumber();
124         updateStatus(ThingStatus.OFFLINE);
125
126         // create & start panel interface
127         logger.debug("Starting interface at port {} with baudrate {} and protocol {}", serialPortName, baudRate,
128                 protocol);
129
130         try {
131             communicator = new CaddxCommunicator(portManager, protocol, serialPortName, baudRate);
132         } catch (IOException | TooManyListenersException | UnsupportedCommOperationException | PortInUseException e) {
133             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
134                     "Communication cannot be initialized. " + e.toString());
135
136             return;
137         }
138
139         CaddxCommunicator comm = communicator;
140         if (comm != null) {
141             comm.addListener(this);
142
143             // Send discovery commands for the zones
144             comm.transmit(new CaddxMessage(DISCOVERY_ZONES_SNAPSHOT_REQUEST_00, false));
145             comm.transmit(new CaddxMessage(DISCOVERY_ZONES_SNAPSHOT_REQUEST_10, false));
146             comm.transmit(new CaddxMessage(DISCOVERY_ZONES_SNAPSHOT_REQUEST_20, false));
147             comm.transmit(new CaddxMessage(DISCOVERY_ZONES_SNAPSHOT_REQUEST_30, false));
148             comm.transmit(new CaddxMessage(DISCOVERY_ZONES_SNAPSHOT_REQUEST_40, false));
149             comm.transmit(new CaddxMessage(DISCOVERY_ZONES_SNAPSHOT_REQUEST_50, false));
150             comm.transmit(new CaddxMessage(DISCOVERY_ZONES_SNAPSHOT_REQUEST_60, false));
151             comm.transmit(new CaddxMessage(DISCOVERY_ZONES_SNAPSHOT_REQUEST_70, false));
152             comm.transmit(new CaddxMessage(DISCOVERY_ZONES_SNAPSHOT_REQUEST_80, false));
153             comm.transmit(new CaddxMessage(DISCOVERY_ZONES_SNAPSHOT_REQUEST_90, false));
154             comm.transmit(new CaddxMessage(DISCOVERY_ZONES_SNAPSHOT_REQUEST_A0, false));
155             comm.transmit(new CaddxMessage(DISCOVERY_ZONES_SNAPSHOT_REQUEST_B0, false));
156
157             // Send discovery commands for the partitions
158             comm.transmit(new CaddxMessage(DISCOVERY_PARTITION_STATUS_REQUEST_0, false));
159             comm.transmit(new CaddxMessage(DISCOVERY_PARTITIONS_SNAPSHOT_REQUEST, false));
160         }
161
162         // list all channels
163         if (logger.isTraceEnabled()) {
164             logger.trace("list all {} channels:", getThing().getChannels().size());
165             for (Channel c : getThing().getChannels()) {
166                 logger.trace("Channel Type {} UID {}", c.getChannelTypeUID(), c.getUID());
167             }
168         }
169     }
170
171     @Override
172     public void dispose() {
173         CaddxCommunicator comm = communicator;
174         if (comm != null) {
175             comm.stop();
176             comm = null;
177         }
178
179         if (discoveryService != null) {
180             unregisterDiscoveryService();
181         }
182
183         super.dispose();
184     }
185
186     public @Nullable Thing findThing(CaddxThingType caddxThingType, @Nullable Integer partition, @Nullable Integer zone,
187             @Nullable Integer keypad) {
188         switch (caddxThingType) {
189             case PARTITION:
190                 if (partition != null) {
191                     return thingPartitionsMap.get(BigDecimal.valueOf(partition));
192                 }
193             case ZONE:
194                 if (zone != null) {
195                     return thingZonesMap.get(BigDecimal.valueOf(zone));
196                 }
197             case KEYPAD:
198                 if (keypad != null) {
199                     return thingKeypadsMap.get(BigDecimal.valueOf(keypad));
200                 }
201             case PANEL:
202                 return thingPanel;
203         }
204         return null;
205     }
206
207     @Override
208     public void handleCommand(ChannelUID channelUID, Command command) {
209         logger.trace("handleCommand(), channelUID: {}, command: {}", channelUID, command);
210
211         switch (channelUID.getId()) {
212             case SEND_COMMAND:
213                 if (!command.toString().isEmpty()) {
214                     String[] tokens = command.toString().split("\\|");
215
216                     String cmd = tokens[0];
217                     String data = "";
218                     if (tokens.length > 1) {
219                         data = tokens[1];
220                     }
221
222                     sendCommand(cmd, data);
223
224                     updateState(channelUID, new StringType(""));
225                 }
226                 break;
227             default:
228                 logger.debug("Unknown command {}", command);
229                 break;
230         }
231     }
232
233     /**
234      * Sends a command to the panel
235      *
236      * @param command The command to be send
237      * @param data The associated command data
238      */
239     public boolean sendCommand(String command, String data) {
240         logger.trace("sendCommand(): Attempting to send Command: command - {} - data: {}", command, data);
241
242         CaddxMessage msg = null;
243
244         switch (command) {
245             case CaddxBindingConstants.ZONE_BYPASSED:
246                 msg = new CaddxMessage(CaddxMessageType.ZONE_BYPASS_TOGGLE, data);
247                 break;
248             case CaddxBindingConstants.ZONE_STATUS_REQUEST:
249                 msg = new CaddxMessage(CaddxMessageType.ZONE_STATUS_REQUEST, data);
250                 break;
251             case CaddxBindingConstants.ZONE_NAME_REQUEST:
252                 msg = new CaddxMessage(CaddxMessageType.ZONE_NAME_REQUEST, data);
253                 break;
254             case CaddxBindingConstants.PARTITION_STATUS_REQUEST:
255                 msg = new CaddxMessage(CaddxMessageType.PARTITION_STATUS_REQUEST, data);
256                 break;
257             case CaddxBindingConstants.PARTITION_PRIMARY_COMMAND_WITH_PIN:
258                 msg = new CaddxMessage(CaddxMessageType.PRIMARY_KEYPAD_FUNCTION_WITH_PIN, data);
259                 break;
260             case CaddxBindingConstants.PARTITION_SECONDARY_COMMAND:
261                 msg = new CaddxMessage(CaddxMessageType.SECONDARY_KEYPAD_FUNCTION, data);
262                 break;
263             case CaddxBindingConstants.PANEL_SYSTEM_STATUS_REQUEST:
264                 msg = new CaddxMessage(CaddxMessageType.SYSTEM_STATUS_REQUEST, data);
265                 break;
266             case CaddxBindingConstants.PANEL_INTERFACE_CONFIGURATION_REQUEST:
267                 msg = new CaddxMessage(CaddxMessageType.INTERFACE_CONFIGURATION_REQUEST, data);
268                 break;
269             case CaddxBindingConstants.PANEL_LOG_EVENT_REQUEST:
270                 msg = new CaddxMessage(CaddxMessageType.LOG_EVENT_REQUEST, data);
271                 break;
272             case CaddxBindingConstants.KEYPAD_TERMINAL_MODE_REQUEST:
273                 msg = new CaddxMessage(CaddxMessageType.KEYPAD_TERMINAL_MODE_REQUEST, data);
274                 break;
275             case CaddxBindingConstants.KEYPAD_SEND_KEYPAD_TEXT_MESSAGE:
276                 msg = new CaddxMessage(CaddxMessageType.SEND_KEYPAD_TEXT_MESSAGE, data);
277                 break;
278             default:
279                 logger.debug("Unknown command {}", command);
280                 return false;
281         }
282
283         CaddxCommunicator comm = communicator;
284         if (comm != null) {
285             comm.transmit(msg);
286         }
287
288         return true;
289     }
290
291     /**
292      * Register the Discovery Service.
293      *
294      * @param discoveryService
295      */
296     public void registerDiscoveryService(CaddxDiscoveryService discoveryService) {
297         this.discoveryService = discoveryService;
298         logger.trace("registerDiscoveryService(): Discovery Service Registered!");
299     }
300
301     /**
302      * Unregister the Discovery Service.
303      */
304     public void unregisterDiscoveryService() {
305         logger.trace("unregisterDiscoveryService(): Discovery Service Unregistered!");
306         discoveryService = null;
307     }
308
309     @Override
310     public void caddxMessage(CaddxCommunicator communicator, CaddxMessage caddxMessage) {
311         CaddxSource source = caddxMessage.getSource();
312
313         if (source != CaddxSource.NONE) {
314             CaddxThingType caddxThingType = null;
315             @Nullable
316             Integer partition = null;
317             @Nullable
318             Integer zone = null;
319             @Nullable
320             Integer keypad = null;
321
322             switch (source) {
323                 case PANEL:
324                     caddxThingType = CaddxThingType.PANEL;
325                     break;
326                 case PARTITION:
327                     caddxThingType = CaddxThingType.PARTITION;
328                     partition = Integer.parseInt(caddxMessage.getPropertyById("partition_number")) + 1;
329                     break;
330                 case ZONE:
331                     caddxThingType = CaddxThingType.ZONE;
332                     zone = Integer.parseInt(caddxMessage.getPropertyById("zone_number")) + 1;
333                     break;
334                 case KEYPAD:
335                     caddxThingType = CaddxThingType.KEYPAD;
336                     keypad = Integer.parseInt(caddxMessage.getPropertyById("keypad_address"));
337                     break;
338                 default:
339                     logger.debug("Source has illegal value");
340                     return;
341             }
342
343             CaddxEvent event = new CaddxEvent(caddxMessage, partition, zone, keypad);
344
345             // Find the thing
346             Thing thing = findThing(caddxThingType, partition, zone, keypad);
347             CaddxDiscoveryService discoveryService = getDiscoveryService();
348             if (thing != null) {
349                 CaddxBaseThingHandler thingHandler = (CaddxBaseThingHandler) thing.getHandler();
350                 if (thingHandler != null) {
351                     thingHandler.caddxEventReceived(event, thing);
352                 }
353             } else {
354                 if (discoveryService != null) {
355                     discoveryService.addThing(getThing(), caddxThingType, event);
356                 }
357             }
358
359             // Handle specific messages that add multiple discovered things
360             if (discoveryService != null) {
361                 switch (caddxMessage.getCaddxMessageType()) {
362                     case PARTITIONS_SNAPSHOT_MESSAGE:
363                         for (int i = 1; i <= 8; i++) {
364                             if (caddxMessage.getPropertyById("partition_" + i + "_valid").equals("true")) {
365                                 thing = findThing(CaddxThingType.PARTITION, i, null, null);
366                                 if (thing != null) {
367                                     continue;
368                                 }
369
370                                 event = new CaddxEvent(caddxMessage, i, null, null);
371                                 discoveryService.addThing(getThing(), CaddxThingType.PARTITION, event);
372                             }
373                         }
374                         break;
375                     case ZONES_SNAPSHOT_MESSAGE:
376                         int zoneOffset = Integer.parseInt(caddxMessage.getPropertyById("zone_offset")) * 16;
377                         for (int i = 1; i <= 16; i++) {
378                             if (zoneOffset + i <= maxZoneNumber) {
379                                 thing = findThing(CaddxThingType.ZONE, null, zoneOffset + i, null);
380                                 if (thing != null) {
381                                     continue;
382                                 }
383
384                                 event = new CaddxEvent(caddxMessage, null, zoneOffset + i, null);
385                                 discoveryService.addThing(getThing(), CaddxThingType.ZONE, event);
386                             }
387                         }
388                         break;
389                     default:
390                         break;
391                 }
392             }
393         }
394
395         updateStatus(ThingStatus.ONLINE);
396     }
397
398     @Override
399     public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
400         if (childHandler instanceof ThingHandlerPartition) {
401             BigDecimal id = (BigDecimal) childThing.getConfiguration()
402                     .get(CaddxPartitionConfiguration.PARTITION_NUMBER);
403             thingPartitionsMap.put(id, childThing);
404         } else if (childHandler instanceof ThingHandlerZone) {
405             BigDecimal id = (BigDecimal) childThing.getConfiguration().get(CaddxZoneConfiguration.ZONE_NUMBER);
406             thingZonesMap.put(id, childThing);
407         } else if (childHandler instanceof ThingHandlerKeypad) {
408             BigDecimal id = (BigDecimal) childThing.getConfiguration().get(CaddxKeypadConfiguration.KEYPAD_ADDRESS);
409             thingKeypadsMap.put(id, childThing);
410         } else if (childHandler instanceof ThingHandlerPanel) {
411             thingPanel = childThing;
412         }
413
414         super.childHandlerInitialized(childHandler, childThing);
415     }
416
417     @Override
418     public void childHandlerDisposed(ThingHandler childHandler, Thing childThing) {
419         if (childHandler instanceof ThingHandlerPartition) {
420             BigDecimal id = (BigDecimal) childThing.getConfiguration()
421                     .get(CaddxPartitionConfiguration.PARTITION_NUMBER);
422             thingPartitionsMap.remove(id);
423         } else if (childHandler instanceof ThingHandlerZone) {
424             BigDecimal id = (BigDecimal) childThing.getConfiguration().get(CaddxZoneConfiguration.ZONE_NUMBER);
425             thingZonesMap.remove(id);
426         } else if (childHandler instanceof ThingHandlerKeypad) {
427             BigDecimal id = (BigDecimal) childThing.getConfiguration().get(CaddxKeypadConfiguration.KEYPAD_ADDRESS);
428             thingKeypadsMap.remove(id);
429         } else if (childHandler instanceof ThingHandlerPanel) {
430             thingPanel = null;
431         }
432
433         super.childHandlerDisposed(childHandler, childThing);
434     }
435
436     @Override
437     public Collection<Class<? extends ThingHandlerService>> getServices() {
438         Set<Class<? extends ThingHandlerService>> set = new HashSet<Class<? extends ThingHandlerService>>(2);
439         set.add(CaddxDiscoveryService.class);
440         set.add(CaddxBridgeActions.class);
441         return set;
442     }
443
444     public void restart() {
445         // Stop the currently running communicator
446         CaddxCommunicator comm = communicator;
447         if (comm != null) {
448             comm.stop();
449             comm = null;
450         }
451
452         // Initialize again
453         initialize();
454     }
455 }