2 * Copyright (c) 2010-2020 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.caddx.internal.handler;
15 import static org.openhab.binding.caddx.internal.CaddxBindingConstants.SEND_COMMAND;
17 import java.io.IOException;
18 import java.math.BigDecimal;
19 import java.util.Collection;
20 import java.util.HashSet;
23 import java.util.TooManyListenersException;
24 import java.util.concurrent.ConcurrentHashMap;
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;
60 * The bridge handler for the Caddx RS232 Serial interface.
62 * @author Georgios Moutsos - Initial contribution
65 public class CaddxBridgeHandler extends BaseBridgeHandler implements CaddxPanelListener {
66 private final Logger logger = LoggerFactory.getLogger(CaddxBridgeHandler.class);
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 };
83 private final SerialPortManager portManager;
84 private @Nullable CaddxDiscoveryService discoveryService = null;
85 private CaddxProtocol protocol = CaddxProtocol.Binary;
86 private String serialPortName = "";
88 private int maxZoneNumber;
89 private @Nullable CaddxCommunicator communicator = null;
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;
97 public @Nullable CaddxDiscoveryService getDiscoveryService() {
98 return discoveryService;
101 public void setDiscoveryService(CaddxDiscoveryService discoveryService) {
102 this.discoveryService = discoveryService;
105 public CaddxBridgeHandler(SerialPortManager portManager, Bridge bridge) {
108 this.portManager = portManager;
112 public void initialize() {
113 CaddxBridgeConfiguration configuration = getConfigAs(CaddxBridgeConfiguration.class);
115 String portName = configuration.getSerialPort();
116 if (portName == null) {
117 logger.debug("Serial port is not defined in the configuration");
120 serialPortName = portName;
121 protocol = configuration.getProtocol();
122 baudRate = configuration.getBaudrate();
123 maxZoneNumber = configuration.getMaxZoneNumber();
124 updateStatus(ThingStatus.OFFLINE);
126 // create & start panel interface
127 logger.debug("Starting interface at port {} with baudrate {} and protocol {}", serialPortName, baudRate,
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());
139 CaddxCommunicator comm = communicator;
141 comm.addListener(this);
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));
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));
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());
172 public void dispose() {
173 CaddxCommunicator comm = communicator;
179 if (discoveryService != null) {
180 unregisterDiscoveryService();
186 public @Nullable Thing findThing(CaddxThingType caddxThingType, @Nullable Integer partition, @Nullable Integer zone,
187 @Nullable Integer keypad) {
188 switch (caddxThingType) {
190 if (partition != null) {
191 return thingPartitionsMap.get(BigDecimal.valueOf(partition));
195 return thingZonesMap.get(BigDecimal.valueOf(zone));
198 if (keypad != null) {
199 return thingKeypadsMap.get(BigDecimal.valueOf(keypad));
208 public void handleCommand(ChannelUID channelUID, Command command) {
209 logger.trace("handleCommand(), channelUID: {}, command: {}", channelUID, command);
211 switch (channelUID.getId()) {
213 if (!command.toString().isEmpty()) {
214 String[] tokens = command.toString().split("\\|");
216 String cmd = tokens[0];
218 if (tokens.length > 1) {
222 sendCommand(cmd, data);
224 updateState(channelUID, new StringType(""));
228 logger.debug("Unknown command {}", command);
234 * Sends a command to the panel
236 * @param command The command to be send
237 * @param data The associated command data
239 public boolean sendCommand(String command, String data) {
240 logger.trace("sendCommand(): Attempting to send Command: command - {} - data: {}", command, data);
242 CaddxMessage msg = null;
245 case CaddxBindingConstants.ZONE_BYPASSED:
246 msg = new CaddxMessage(CaddxMessageType.ZONE_BYPASS_TOGGLE, data);
248 case CaddxBindingConstants.ZONE_STATUS_REQUEST:
249 msg = new CaddxMessage(CaddxMessageType.ZONE_STATUS_REQUEST, data);
251 case CaddxBindingConstants.ZONE_NAME_REQUEST:
252 msg = new CaddxMessage(CaddxMessageType.ZONE_NAME_REQUEST, data);
254 case CaddxBindingConstants.PARTITION_STATUS_REQUEST:
255 msg = new CaddxMessage(CaddxMessageType.PARTITION_STATUS_REQUEST, data);
257 case CaddxBindingConstants.PARTITION_PRIMARY_COMMAND_WITH_PIN:
258 msg = new CaddxMessage(CaddxMessageType.PRIMARY_KEYPAD_FUNCTION_WITH_PIN, data);
260 case CaddxBindingConstants.PARTITION_SECONDARY_COMMAND:
261 msg = new CaddxMessage(CaddxMessageType.SECONDARY_KEYPAD_FUNCTION, data);
263 case CaddxBindingConstants.PANEL_SYSTEM_STATUS_REQUEST:
264 msg = new CaddxMessage(CaddxMessageType.SYSTEM_STATUS_REQUEST, data);
266 case CaddxBindingConstants.PANEL_INTERFACE_CONFIGURATION_REQUEST:
267 msg = new CaddxMessage(CaddxMessageType.INTERFACE_CONFIGURATION_REQUEST, data);
269 case CaddxBindingConstants.PANEL_LOG_EVENT_REQUEST:
270 msg = new CaddxMessage(CaddxMessageType.LOG_EVENT_REQUEST, data);
272 case CaddxBindingConstants.KEYPAD_TERMINAL_MODE_REQUEST:
273 msg = new CaddxMessage(CaddxMessageType.KEYPAD_TERMINAL_MODE_REQUEST, data);
275 case CaddxBindingConstants.KEYPAD_SEND_KEYPAD_TEXT_MESSAGE:
276 msg = new CaddxMessage(CaddxMessageType.SEND_KEYPAD_TEXT_MESSAGE, data);
279 logger.debug("Unknown command {}", command);
283 CaddxCommunicator comm = communicator;
292 * Register the Discovery Service.
294 * @param discoveryService
296 public void registerDiscoveryService(CaddxDiscoveryService discoveryService) {
297 this.discoveryService = discoveryService;
298 logger.trace("registerDiscoveryService(): Discovery Service Registered!");
302 * Unregister the Discovery Service.
304 public void unregisterDiscoveryService() {
305 logger.trace("unregisterDiscoveryService(): Discovery Service Unregistered!");
306 discoveryService = null;
310 public void caddxMessage(CaddxCommunicator communicator, CaddxMessage caddxMessage) {
311 CaddxSource source = caddxMessage.getSource();
313 if (source != CaddxSource.NONE) {
314 CaddxThingType caddxThingType = null;
316 Integer partition = null;
320 Integer keypad = null;
324 caddxThingType = CaddxThingType.PANEL;
327 caddxThingType = CaddxThingType.PARTITION;
328 partition = Integer.parseInt(caddxMessage.getPropertyById("partition_number")) + 1;
331 caddxThingType = CaddxThingType.ZONE;
332 zone = Integer.parseInt(caddxMessage.getPropertyById("zone_number")) + 1;
335 caddxThingType = CaddxThingType.KEYPAD;
336 keypad = Integer.parseInt(caddxMessage.getPropertyById("keypad_address"));
339 logger.debug("Source has illegal value");
343 CaddxEvent event = new CaddxEvent(caddxMessage, partition, zone, keypad);
346 Thing thing = findThing(caddxThingType, partition, zone, keypad);
347 CaddxDiscoveryService discoveryService = getDiscoveryService();
349 CaddxBaseThingHandler thingHandler = (CaddxBaseThingHandler) thing.getHandler();
350 if (thingHandler != null) {
351 thingHandler.caddxEventReceived(event, thing);
354 if (discoveryService != null) {
355 discoveryService.addThing(getThing(), caddxThingType, event);
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);
370 event = new CaddxEvent(caddxMessage, i, null, null);
371 discoveryService.addThing(getThing(), CaddxThingType.PARTITION, event);
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);
384 event = new CaddxEvent(caddxMessage, null, zoneOffset + i, null);
385 discoveryService.addThing(getThing(), CaddxThingType.ZONE, event);
395 updateStatus(ThingStatus.ONLINE);
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;
414 super.childHandlerInitialized(childHandler, childThing);
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) {
433 super.childHandlerDisposed(childHandler, childThing);
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);
444 public void restart() {
445 // Stop the currently running communicator
446 CaddxCommunicator comm = communicator;