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.openwebnet.internal.handler;
15 import static org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants.*;
17 import java.util.Collection;
18 import java.util.Collections;
21 import java.util.concurrent.ConcurrentHashMap;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants;
28 import org.openhab.binding.openwebnet.internal.discovery.OpenWebNetDeviceDiscoveryService;
29 import org.openhab.binding.openwebnet.internal.handler.config.OpenWebNetBusBridgeConfig;
30 import org.openhab.binding.openwebnet.internal.handler.config.OpenWebNetZigBeeBridgeConfig;
31 import org.openhab.core.config.core.status.ConfigStatusMessage;
32 import org.openhab.core.thing.Bridge;
33 import org.openhab.core.thing.ChannelUID;
34 import org.openhab.core.thing.Thing;
35 import org.openhab.core.thing.ThingStatus;
36 import org.openhab.core.thing.ThingStatusDetail;
37 import org.openhab.core.thing.ThingTypeUID;
38 import org.openhab.core.thing.binding.ConfigStatusBridgeHandler;
39 import org.openhab.core.thing.binding.ThingHandlerService;
40 import org.openhab.core.types.Command;
41 import org.openhab.core.types.RefreshType;
42 import org.openwebnet4j.BUSGateway;
43 import org.openwebnet4j.GatewayListener;
44 import org.openwebnet4j.OpenDeviceType;
45 import org.openwebnet4j.OpenGateway;
46 import org.openwebnet4j.USBGateway;
47 import org.openwebnet4j.communication.OWNAuthException;
48 import org.openwebnet4j.communication.OWNException;
49 import org.openwebnet4j.message.Automation;
50 import org.openwebnet4j.message.BaseOpenMessage;
51 import org.openwebnet4j.message.EnergyManagement;
52 import org.openwebnet4j.message.FrameException;
53 import org.openwebnet4j.message.GatewayMgmt;
54 import org.openwebnet4j.message.Lighting;
55 import org.openwebnet4j.message.OpenMessage;
56 import org.openwebnet4j.message.Thermoregulation;
57 import org.openwebnet4j.message.What;
58 import org.openwebnet4j.message.Where;
59 import org.openwebnet4j.message.WhereZigBee;
60 import org.openwebnet4j.message.Who;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
65 * The {@link OpenWebNetBridgeHandler} is responsible for handling communication with gateways and handling events.
67 * @author Massimo Valla - Initial contribution
68 * @author Andrea Conte - Energy management, Thermoregulation
69 * @author Gilberto Cocchi - Thermoregulation
72 public class OpenWebNetBridgeHandler extends ConfigStatusBridgeHandler implements GatewayListener {
74 private final Logger logger = LoggerFactory.getLogger(OpenWebNetBridgeHandler.class);
76 private static final int GATEWAY_ONLINE_TIMEOUT_SEC = 20; // Time to wait for the gateway to become connected
78 private static final int REFRESH_ALL_DEVICES_DELAY_MSEC = 500; // Delay to wait before sending all devices refresh
79 // request after a connect/reconnect
81 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = OpenWebNetBindingConstants.BRIDGE_SUPPORTED_THING_TYPES;
83 // ConcurrentHashMap of devices registered to this BridgeHandler
84 // association is: ownId (String) -> OpenWebNetThingHandler, with ownId = WHO.WHERE
85 private Map<String, @Nullable OpenWebNetThingHandler> registeredDevices = new ConcurrentHashMap<>();
86 private Map<String, Long> discoveringDevices = new ConcurrentHashMap<>();
88 protected @Nullable OpenGateway gateway;
89 private boolean isBusGateway = false;
91 private boolean isGatewayConnected = false;
93 public @Nullable OpenWebNetDeviceDiscoveryService deviceDiscoveryService;
94 private boolean reconnecting = false; // we are trying to reconnect to gateway
95 private @Nullable ScheduledFuture<?> refreshSchedule;
97 private boolean scanIsActive = false; // a device scan has been activated by OpenWebNetDeviceDiscoveryService;
98 private boolean discoveryByActivation;
100 public OpenWebNetBridgeHandler(Bridge bridge) {
104 public boolean isBusGateway() {
109 public void initialize() {
110 ThingTypeUID thingType = getThing().getThingTypeUID();
112 if (thingType.equals(THING_TYPE_ZB_GATEWAY)) {
113 gw = initZigBeeGateway();
115 gw = initBusGateway();
121 if (gw.isConnected()) { // gateway is already connected, device can go ONLINE
122 isGatewayConnected = true;
123 updateStatus(ThingStatus.ONLINE);
125 updateStatus(ThingStatus.UNKNOWN);
126 logger.debug("Trying to connect gateway {}... ", gw);
129 scheduler.schedule(() -> {
130 // if status is still UNKNOWN after timer ends, set the device as OFFLINE
131 if (thing.getStatus().equals(ThingStatus.UNKNOWN)) {
132 logger.info("status still UNKNOWN. Setting device={} to OFFLINE", thing.getUID());
133 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
134 "@text/offline.comm-error-timeout");
136 }, GATEWAY_ONLINE_TIMEOUT_SEC, TimeUnit.SECONDS);
137 logger.debug("bridge {} initialization completed", thing.getUID());
138 } catch (OWNException e) {
139 logger.debug("gw.connect() returned OWNException: {}", e.getMessage());
140 // status is updated by callback onConnectionError()
147 * Init a ZigBee gateway based on config
149 private @Nullable OpenGateway initZigBeeGateway() {
150 logger.debug("Initializing ZigBee USB Gateway");
151 OpenWebNetZigBeeBridgeConfig zbBridgeConfig = getConfigAs(OpenWebNetZigBeeBridgeConfig.class);
152 String serialPort = zbBridgeConfig.getSerialPort();
153 if (serialPort == null || serialPort.isEmpty()) {
154 logger.warn("Cannot connect ZigBee USB Gateway. No serial port has been provided in Bridge configuration.");
155 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
156 "@text/offline.conf-error-no-serial-port");
159 return new USBGateway(serialPort);
164 * Init a BUS gateway based on config
166 private @Nullable OpenGateway initBusGateway() {
167 logger.debug("Initializing BUS gateway");
168 OpenWebNetBusBridgeConfig busBridgeConfig = getConfigAs(OpenWebNetBusBridgeConfig.class);
169 String host = busBridgeConfig.getHost();
170 if (host == null || host.isEmpty()) {
171 logger.warn("Cannot connect to BUS Gateway. No host/IP has been provided in Bridge configuration.");
172 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
173 "@text/offline.conf-error-no-ip-address");
176 int port = busBridgeConfig.getPort().intValue();
177 String passwd = busBridgeConfig.getPasswd();
179 if (passwd.length() >= 4) {
180 passwdMasked = "******" + passwd.substring(passwd.length() - 3, passwd.length());
182 passwdMasked = "******";
184 discoveryByActivation = busBridgeConfig.getDiscoveryByActivation();
185 logger.debug("Creating new BUS gateway with config properties: {}:{}, pwd={}, discoveryByActivation={}",
186 host, port, passwdMasked, discoveryByActivation);
187 return new BUSGateway(host, port, passwd);
192 public void handleCommand(ChannelUID channelUID, Command command) {
193 logger.debug("handleCommand (command={} - channel={})", command, channelUID);
194 OpenGateway gw = gateway;
195 if (gw == null || !gw.isConnected()) {
196 logger.warn("Gateway is NOT connected, skipping command");
199 if (command instanceof RefreshType) {
202 logger.warn("Command or channel not supported: channel={} command={}", channelUID, command);
208 public Collection<ConfigStatusMessage> getConfigStatus() {
209 return Collections.emptyList();
213 public void handleRemoval() {
215 super.handleRemoval();
219 public void dispose() {
220 ScheduledFuture<?> rSc = refreshSchedule;
228 private void disconnectGateway() {
229 OpenGateway gw = gateway;
231 gw.closeConnection();
232 gw.unsubscribe(this);
233 logger.debug("Gateway {} connection closed and unsubscribed", gw.toString());
236 reconnecting = false;
240 public Collection<Class<? extends ThingHandlerService>> getServices() {
241 return Collections.singleton(OpenWebNetDeviceDiscoveryService.class);
245 * Search for devices connected to this bridge handler's gateway
247 * @param listener to receive device found notifications
249 public synchronized void searchDevices() {
251 logger.debug("------$$ scanIsActive={}", scanIsActive);
252 OpenGateway gw = gateway;
254 if (!gw.isDiscovering()) {
255 if (!gw.isConnected()) {
256 logger.debug("------$$ Gateway '{}' is NOT connected, cannot search for devices", gw);
259 logger.info("------$$ STARTED active SEARCH for devices on bridge '{}'", thing.getUID());
261 gw.discoverDevices();
262 } catch (OWNException e) {
263 logger.warn("------$$ OWNException while discovering devices on bridge '{}': {}", thing.getUID(),
267 logger.debug("------$$ Searching devices on bridge '{}' already activated", thing.getUID());
271 logger.warn("------$$ Cannot search devices: no gateway associated to this handler");
276 public void onNewDevice(@Nullable Where w, @Nullable OpenDeviceType deviceType, @Nullable BaseOpenMessage message) {
277 OpenWebNetDeviceDiscoveryService discService = deviceDiscoveryService;
278 if (discService != null) {
279 if (w != null && deviceType != null) {
280 discService.newDiscoveryResult(w, deviceType, message);
282 logger.warn("onNewDevice with null where/deviceType, msg={}", message);
285 logger.warn("onNewDevice but null deviceDiscoveryService");
290 public void onDiscoveryCompleted() {
291 logger.info("------$$ FINISHED active SEARCH for devices on bridge '{}'", thing.getUID());
295 * Notifies that the scan has been stopped/aborted by OpenWebNetDeviceDiscoveryService
297 public void scanStopped() {
298 scanIsActive = false;
299 logger.debug("------$$ scanIsActive={}", scanIsActive);
302 private void discoverByActivation(BaseOpenMessage baseMsg) {
303 logger.debug("discoverByActivation: msg={}", baseMsg);
304 OpenWebNetDeviceDiscoveryService discService = deviceDiscoveryService;
305 if (discService == null) {
306 logger.warn("discoverByActivation: null OpenWebNetDeviceDiscoveryService, ignoring msg={}", baseMsg);
309 // we support these types only
310 if (baseMsg instanceof Lighting || baseMsg instanceof Automation || baseMsg instanceof EnergyManagement
311 || baseMsg instanceof Thermoregulation) {
312 BaseOpenMessage bmsg = baseMsg;
313 if (baseMsg instanceof Lighting) {
314 What what = baseMsg.getWhat();
315 if (Lighting.WhatLighting.OFF.equals(what)) { // skipping OFF msg: cannot distinguish dimmer/switch
316 logger.debug("discoverByActivation: skipping OFF msg: cannot distinguish dimmer/switch");
319 if (Lighting.WhatLighting.ON.equals(what)) { // if not already done just now, request light status to
320 // distinguish dimmer from switch
321 if (discoveringDevices.containsKey(ownIdFromMessage(baseMsg))) {
323 "discoverByActivation: we just requested status for this device and it's ON -> it's a switch");
325 OpenGateway gw = gateway;
328 discoveringDevices.put(ownIdFromMessage(baseMsg),
329 Long.valueOf(System.currentTimeMillis()));
330 gw.send(Lighting.requestStatus(baseMsg.getWhere().value()));
332 } catch (OWNException e) {
333 logger.warn("discoverByActivation: Exception while requesting light state: {}",
340 discoveringDevices.remove(ownIdFromMessage(baseMsg));
342 OpenDeviceType type = null;
344 type = bmsg.detectDeviceType();
345 } catch (FrameException e) {
346 logger.warn("Exception while detecting device type: {}", e.getMessage());
349 discService.newDiscoveryResult(bmsg.getWhere(), type, bmsg);
351 logger.debug("discoverByActivation: no device type detected from msg: {}", bmsg);
357 * Register a device ThingHandler to this BridgHandler
359 * @param ownId the device OpenWebNet id
360 * @param thingHandler the thing handler to be registered
362 protected void registerDevice(String ownId, OpenWebNetThingHandler thingHandler) {
363 if (registeredDevices.containsKey(ownId)) {
364 logger.warn("registering device with an existing ownId={}", ownId);
366 registeredDevices.put(ownId, thingHandler);
367 logger.debug("registered device ownId={}, thing={}", ownId, thingHandler.getThing().getUID());
371 * Un-register a device from this bridge handler
373 * @param ownId the device OpenWebNet id
375 protected void unregisterDevice(String ownId) {
376 if (registeredDevices.remove(ownId) != null) {
377 logger.debug("un-registered device ownId={}", ownId);
379 logger.warn("could not un-register ownId={} (not found)", ownId);
384 * Get an already registered device on this bridge handler
386 * @param ownId the device OpenWebNet id
387 * @return the registered device Thing handler or null if the id cannot be found
389 public @Nullable OpenWebNetThingHandler getRegisteredDevice(String ownId) {
390 return registeredDevices.get(ownId);
393 private void refreshAllDevices() {
394 logger.debug("Refreshing all devices for bridge {}", thing.getUID());
395 for (Thing ownThing : getThing().getThings()) {
396 OpenWebNetThingHandler hndlr = (OpenWebNetThingHandler) ownThing.getHandler();
398 hndlr.refreshDevice(true);
404 public void onEventMessage(@Nullable OpenMessage msg) {
405 logger.trace("RECEIVED <<<<< {}", msg);
407 logger.warn("received event msg is null");
410 if (msg.isACK() || msg.isNACK()) {
411 return; // we ignore ACKS/NACKS
413 // GATEWAY MANAGEMENT
414 if (msg instanceof GatewayMgmt) {
419 BaseOpenMessage baseMsg = (BaseOpenMessage) msg;
420 // let's try to get the Thing associated with this message...
421 if (baseMsg instanceof Lighting || baseMsg instanceof Automation || baseMsg instanceof EnergyManagement
422 || baseMsg instanceof Thermoregulation) {
423 String ownId = ownIdFromMessage(baseMsg);
424 logger.debug("ownIdFromMessage({}) --> {}", baseMsg, ownId);
425 OpenWebNetThingHandler deviceHandler = registeredDevices.get(ownId);
426 if (deviceHandler == null) {
427 OpenGateway gw = gateway;
428 if (isBusGateway && ((gw != null && !gw.isDiscovering() && scanIsActive)
429 || (discoveryByActivation && !scanIsActive))) {
430 discoverByActivation(baseMsg);
432 logger.debug("ownId={} has NO DEVICE associated, ignoring it", ownId);
435 deviceHandler.handleMessage(baseMsg);
438 logger.debug("BridgeHandler ignoring frame {}. WHO={} is not supported by this binding", baseMsg,
444 public void onConnected() {
445 isGatewayConnected = true;
446 Map<String, String> properties = editProperties();
447 boolean propertiesChanged = false;
448 OpenGateway gw = gateway;
450 logger.warn("received onConnected() but gateway is null");
453 if (gw instanceof USBGateway) {
454 logger.info("---- CONNECTED to ZigBee USB gateway bridge '{}' (serialPort: {})", thing.getUID(),
455 ((USBGateway) gw).getSerialPortName());
457 logger.info("---- CONNECTED to BUS gateway bridge '{}' ({}:{})", thing.getUID(),
458 ((BUSGateway) gw).getHost(), ((BUSGateway) gw).getPort());
459 // update serial number property (with MAC address)
460 if (properties.get(PROPERTY_SERIAL_NO) != gw.getMACAddr().toUpperCase()) {
461 properties.put(PROPERTY_SERIAL_NO, gw.getMACAddr().toUpperCase());
462 propertiesChanged = true;
463 logger.debug("updated property gw serialNumber: {}", properties.get(PROPERTY_SERIAL_NO));
466 if (properties.get(PROPERTY_FIRMWARE_VERSION) != gw.getFirmwareVersion()) {
467 properties.put(PROPERTY_FIRMWARE_VERSION, gw.getFirmwareVersion());
468 propertiesChanged = true;
469 logger.debug("updated property gw firmware version: {}", properties.get(PROPERTY_FIRMWARE_VERSION));
471 if (propertiesChanged) {
472 updateProperties(properties);
473 logger.info("properties updated for bridge '{}'", thing.getUID());
475 updateStatus(ThingStatus.ONLINE);
476 // schedule a refresh for all devices
477 refreshSchedule = scheduler.schedule(this::refreshAllDevices, REFRESH_ALL_DEVICES_DELAY_MSEC,
478 TimeUnit.MILLISECONDS);
482 public void onConnectionError(@Nullable OWNException error) {
485 errMsg = "unknown error";
487 errMsg = error.getMessage();
489 logger.info("---- ON CONNECTION ERROR for gateway {}: {}", gateway, errMsg);
490 isGatewayConnected = false;
491 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
492 "@text/offline.comm-error-connection" + " (onConnectionError - " + errMsg + ")");
493 tryReconnectGateway();
497 public void onConnectionClosed() {
498 isGatewayConnected = false;
499 logger.debug("onConnectionClosed() - isGatewayConnected={}", isGatewayConnected);
500 // NOTE: cannot change to OFFLINE here because we are already in REMOVING state
504 public void onDisconnected(@Nullable OWNException e) {
505 isGatewayConnected = false;
508 errMsg = "unknown error";
510 errMsg = e.getMessage();
512 logger.info("---- DISCONNECTED from gateway {}. OWNException: {}", gateway, errMsg);
513 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
514 "@text/offline.comm-error-disconnected" + " (onDisconnected - " + errMsg + ")");
515 tryReconnectGateway();
518 private void tryReconnectGateway() {
519 OpenGateway gw = gateway;
523 logger.info("---- Starting RECONNECT cycle to gateway {}", gw);
526 } catch (OWNAuthException e) {
527 logger.info("---- AUTH error from gateway. Stopping re-connect");
528 reconnecting = false;
529 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
530 "@text/offline.conf-error-auth" + " (" + e + ")");
533 logger.debug("---- reconnecting=true");
536 logger.warn("---- cannot start RECONNECT, gateway is null");
541 public void onReconnected() {
542 reconnecting = false;
543 OpenGateway gw = gateway;
544 logger.info("---- RE-CONNECTED to bridge {}", thing.getUID());
546 updateStatus(ThingStatus.ONLINE);
547 if (gw.getFirmwareVersion() != null) {
548 this.updateProperty(PROPERTY_FIRMWARE_VERSION, gw.getFirmwareVersion());
549 logger.debug("gw firmware version: {}", gw.getFirmwareVersion());
552 // schedule a refresh for all devices
553 refreshSchedule = scheduler.schedule(this::refreshAllDevices, REFRESH_ALL_DEVICES_DELAY_MSEC,
554 TimeUnit.MILLISECONDS);
559 * Return a ownId string (=WHO.WHERE) from the device Where address and handler
561 * @param where the Where address (to be normalized)
562 * @param handler the device handler
563 * @return the ownId String
565 protected String ownIdFromDeviceWhere(Where where, OpenWebNetThingHandler handler) {
566 return handler.ownIdPrefix() + "." + normalizeWhere(where);
570 * Returns a ownId string (=WHO.WHERE) from a Who and Where address
573 * @param where the Where address (to be normalized)
574 * @return the ownId String
576 public String ownIdFromWhoWhere(Who who, Where where) {
577 return who.value() + "." + normalizeWhere(where);
581 * Return a ownId string (=WHO.WHERE) from a BaseOpenMessage
583 * @param baseMsg the BaseOpenMessage
584 * @return the ownId String
586 public String ownIdFromMessage(BaseOpenMessage baseMsg) {
587 return baseMsg.getWho().value() + "." + normalizeWhere(baseMsg.getWhere());
591 * Transform a Where address into a Thing id string
593 * @param where the Where address
594 * @return the thing Id string
596 public String thingIdFromWhere(Where where) {
597 return normalizeWhere(where); // '#' cannot be used in ThingUID;
601 * Normalize a Where address
603 * @param where the Where address
604 * @return the normalized address as String
606 public String normalizeWhere(Where where) {
607 String str = where.value();
608 if (where instanceof WhereZigBee) {
609 str = ((WhereZigBee) where).valueWithUnit(WhereZigBee.UNIT_ALL); // 76543210X#9 --> 765432100#9
611 if (str.indexOf("#4#") == -1) { // skip APL#4#bus case
612 if (str.indexOf('#') == 0) { // Thermo central unit (#0) or zone via central unit (#Z, Z=[1-99]) --> Z
613 str = str.substring(1);
614 } else if (str.indexOf('#') > 0) { // Thermo zone Z and actuator N (Z#N, Z=[1-99], N=[1-9]) --> Z
615 str = str.substring(0, str.indexOf('#'));
619 return str.replace('#', 'h');