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.handler;
15 import static org.openhab.binding.openwebnet.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.OpenWebNetBindingConstants;
28 import org.openhab.binding.openwebnet.handler.config.OpenWebNetBusBridgeConfig;
29 import org.openhab.binding.openwebnet.handler.config.OpenWebNetZigBeeBridgeConfig;
30 import org.openhab.binding.openwebnet.internal.discovery.OpenWebNetDeviceDiscoveryService;
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.What;
57 import org.openwebnet4j.message.Where;
58 import org.openwebnet4j.message.WhereZigBee;
59 import org.openwebnet4j.message.Who;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
64 * The {@link OpenWebNetBridgeHandler} is responsible for handling communication with gateways and handling events.
66 * @author Massimo Valla - Initial contribution
67 * @author Andrea Conte - Energy management
70 public class OpenWebNetBridgeHandler extends ConfigStatusBridgeHandler implements GatewayListener {
72 private final Logger logger = LoggerFactory.getLogger(OpenWebNetBridgeHandler.class);
74 private static final int GATEWAY_ONLINE_TIMEOUT_SEC = 20; // Time to wait for the gateway to become connected
76 private static final int REFRESH_ALL_DEVICES_DELAY_MSEC = 500; // Delay to wait before sending all devices refresh
77 // request after a connect/reconnect
79 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = OpenWebNetBindingConstants.BRIDGE_SUPPORTED_THING_TYPES;
81 // ConcurrentHashMap of devices registered to this BridgeHandler
82 // association is: ownId (String) -> OpenWebNetThingHandler, with ownId = WHO.WHERE
83 private Map<String, @Nullable OpenWebNetThingHandler> registeredDevices = new ConcurrentHashMap<>();
84 private Map<String, Long> discoveringDevices = new ConcurrentHashMap<>();
86 protected @Nullable OpenGateway gateway;
87 private boolean isBusGateway = false;
89 private boolean isGatewayConnected = false;
91 public @Nullable OpenWebNetDeviceDiscoveryService deviceDiscoveryService;
92 private boolean reconnecting = false; // we are trying to reconnect to gateway
93 private @Nullable ScheduledFuture<?> refreshSchedule;
95 private boolean scanIsActive = false; // a device scan has been activated by OpenWebNetDeviceDiscoveryService;
96 private boolean discoveryByActivation;
98 public OpenWebNetBridgeHandler(Bridge bridge) {
102 public boolean isBusGateway() {
107 public void initialize() {
108 ThingTypeUID thingType = getThing().getThingTypeUID();
110 if (thingType.equals(THING_TYPE_ZB_GATEWAY)) {
111 gw = initZigBeeGateway();
113 gw = initBusGateway();
119 if (gw.isConnected()) { // gateway is already connected, device can go ONLINE
120 isGatewayConnected = true;
121 updateStatus(ThingStatus.ONLINE);
123 updateStatus(ThingStatus.UNKNOWN);
124 logger.debug("Trying to connect gateway {}... ", gw);
127 scheduler.schedule(() -> {
128 // if status is still UNKNOWN after timer ends, set the device as OFFLINE
129 if (thing.getStatus().equals(ThingStatus.UNKNOWN)) {
130 logger.info("status still UNKNOWN. Setting device={} to OFFLINE", thing.getUID());
131 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
132 "@text/offline.comm-error-timeout");
134 }, GATEWAY_ONLINE_TIMEOUT_SEC, TimeUnit.SECONDS);
135 logger.debug("bridge {} initialization completed", thing.getUID());
136 } catch (OWNException e) {
137 logger.debug("gw.connect() returned OWNException: {}", e.getMessage());
138 // status is updated by callback onConnectionError()
145 * Init a ZigBee gateway based on config
147 private @Nullable OpenGateway initZigBeeGateway() {
148 logger.debug("Initializing ZigBee USB Gateway");
149 OpenWebNetZigBeeBridgeConfig zbBridgeConfig = getConfigAs(OpenWebNetZigBeeBridgeConfig.class);
150 String serialPort = zbBridgeConfig.getSerialPort();
151 if (serialPort == null || serialPort.isEmpty()) {
152 logger.warn("Cannot connect ZigBee USB Gateway. No serial port has been provided in Bridge configuration.");
153 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
154 "@text/offline.conf-error-no-serial-port");
157 return new USBGateway(serialPort);
162 * Init a BUS gateway based on config
164 private @Nullable OpenGateway initBusGateway() {
165 logger.debug("Initializing BUS gateway");
166 OpenWebNetBusBridgeConfig busBridgeConfig = getConfigAs(OpenWebNetBusBridgeConfig.class);
167 String host = busBridgeConfig.getHost();
168 if (host == null || host.isEmpty()) {
169 logger.warn("Cannot connect to BUS Gateway. No host/IP has been provided in Bridge configuration.");
170 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
171 "@text/offline.conf-error-no-ip-address");
174 int port = busBridgeConfig.getPort().intValue();
175 String passwd = busBridgeConfig.getPasswd();
177 if (passwd.length() >= 4) {
178 passwdMasked = "******" + passwd.substring(passwd.length() - 3, passwd.length());
180 passwdMasked = "******";
182 discoveryByActivation = busBridgeConfig.getDiscoveryByActivation();
183 logger.debug("Creating new BUS gateway with config properties: {}:{}, pwd={}, discoveryByActivation={}",
184 host, port, passwdMasked, discoveryByActivation);
185 return new BUSGateway(host, port, passwd);
190 public void handleCommand(ChannelUID channelUID, Command command) {
191 logger.debug("handleCommand (command={} - channel={})", command, channelUID);
192 OpenGateway gw = gateway;
193 if (gw == null || !gw.isConnected()) {
194 logger.warn("Gateway is NOT connected, skipping command");
197 if (command instanceof RefreshType) {
200 logger.warn("Command or channel not supported: channel={} command={}", channelUID, command);
206 public Collection<ConfigStatusMessage> getConfigStatus() {
207 return Collections.emptyList();
211 public void handleRemoval() {
213 super.handleRemoval();
217 public void dispose() {
218 ScheduledFuture<?> rSc = refreshSchedule;
226 private void disconnectGateway() {
227 OpenGateway gw = gateway;
229 gw.closeConnection();
230 gw.unsubscribe(this);
231 logger.debug("Gateway {} connection closed and unsubscribed", gw.toString());
234 reconnecting = false;
238 public Collection<Class<? extends ThingHandlerService>> getServices() {
239 return Collections.singleton(OpenWebNetDeviceDiscoveryService.class);
243 * Search for devices connected to this bridge handler's gateway
245 * @param listener to receive device found notifications
247 public synchronized void searchDevices() {
249 logger.debug("------$$ scanIsActive={}", scanIsActive);
250 OpenGateway gw = gateway;
252 if (!gw.isDiscovering()) {
253 if (!gw.isConnected()) {
254 logger.debug("------$$ Gateway '{}' is NOT connected, cannot search for devices", gw);
257 logger.info("------$$ STARTED active SEARCH for devices on bridge '{}'", thing.getUID());
259 gw.discoverDevices();
260 } catch (OWNException e) {
261 logger.warn("------$$ OWNException while discovering devices on bridge '{}': {}", thing.getUID(),
265 logger.debug("------$$ Searching devices on bridge '{}' already activated", thing.getUID());
269 logger.warn("------$$ Cannot search devices: no gateway associated to this handler");
274 public void onNewDevice(@Nullable Where w, @Nullable OpenDeviceType deviceType, @Nullable BaseOpenMessage message) {
275 OpenWebNetDeviceDiscoveryService discService = deviceDiscoveryService;
276 if (discService != null) {
277 if (w != null && deviceType != null) {
278 discService.newDiscoveryResult(w, deviceType, message);
280 logger.warn("onNewDevice with null where/deviceType, msg={}", message);
283 logger.warn("onNewDevice but null deviceDiscoveryService");
288 public void onDiscoveryCompleted() {
289 logger.info("------$$ FINISHED active SEARCH for devices on bridge '{}'", thing.getUID());
293 * Notifies that the scan has been stopped/aborted by OpenWebNetDeviceDiscoveryService
295 public void scanStopped() {
296 scanIsActive = false;
297 logger.debug("------$$ scanIsActive={}", scanIsActive);
300 private void discoverByActivation(BaseOpenMessage baseMsg) {
301 logger.debug("discoverByActivation: msg={}", baseMsg);
302 OpenWebNetDeviceDiscoveryService discService = deviceDiscoveryService;
303 if (discService == null) {
304 logger.warn("discoverByActivation: null OpenWebNetDeviceDiscoveryService, ignoring msg={}", baseMsg);
307 if (baseMsg instanceof Lighting || baseMsg instanceof Automation || baseMsg instanceof EnergyManagement) { // we
312 BaseOpenMessage bmsg = baseMsg;
313 if (baseMsg instanceof Lighting) {
314 What what = baseMsg.getWhat();
315 if (Lighting.WHAT.OFF.equals(what)) { // skipping OFF msg: cannot distinguish dimmer/switch
316 logger.debug("discoverByActivation: skipping OFF msg: cannot distinguish dimmer/switch");
319 if (Lighting.WHAT.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 String ownId = ownIdFromMessage(baseMsg);
423 logger.debug("ownIdFromMessage({}) --> {}", baseMsg, ownId);
424 OpenWebNetThingHandler deviceHandler = registeredDevices.get(ownId);
425 if (deviceHandler == null) {
426 OpenGateway gw = gateway;
427 if (isBusGateway && ((gw != null && !gw.isDiscovering() && scanIsActive)
428 || (discoveryByActivation && !scanIsActive))) {
429 discoverByActivation(baseMsg);
431 logger.debug("ownId={} has NO DEVICE associated, ignoring it", ownId);
434 deviceHandler.handleMessage(baseMsg);
437 logger.debug("BridgeHandler ignoring frame {}. WHO={} is not supported by this binding", baseMsg,
443 public void onConnected() {
444 isGatewayConnected = true;
445 Map<String, String> properties = editProperties();
446 boolean propertiesChanged = false;
447 OpenGateway gw = gateway;
449 logger.warn("received onConnected() but gateway is null");
452 if (gw instanceof USBGateway) {
453 logger.info("---- CONNECTED to ZigBee USB gateway bridge '{}' (serialPort: {})", thing.getUID(),
454 ((USBGateway) gw).getSerialPortName());
456 logger.info("---- CONNECTED to BUS gateway bridge '{}' ({}:{})", thing.getUID(),
457 ((BUSGateway) gw).getHost(), ((BUSGateway) gw).getPort());
458 // update serial number property (with MAC address)
459 if (properties.get(PROPERTY_SERIAL_NO) != gw.getMACAddr().toUpperCase()) {
460 properties.put(PROPERTY_SERIAL_NO, gw.getMACAddr().toUpperCase());
461 propertiesChanged = true;
462 logger.debug("updated property gw serialNumber: {}", properties.get(PROPERTY_SERIAL_NO));
465 if (properties.get(PROPERTY_FIRMWARE_VERSION) != gw.getFirmwareVersion()) {
466 properties.put(PROPERTY_FIRMWARE_VERSION, gw.getFirmwareVersion());
467 propertiesChanged = true;
468 logger.debug("updated property gw firmware version: {}", properties.get(PROPERTY_FIRMWARE_VERSION));
470 if (propertiesChanged) {
471 updateProperties(properties);
472 logger.info("properties updated for bridge '{}'", thing.getUID());
474 updateStatus(ThingStatus.ONLINE);
475 // schedule a refresh for all devices
476 refreshSchedule = scheduler.schedule(this::refreshAllDevices, REFRESH_ALL_DEVICES_DELAY_MSEC,
477 TimeUnit.MILLISECONDS);
481 public void onConnectionError(@Nullable OWNException error) {
484 errMsg = "unknown error";
486 errMsg = error.getMessage();
488 logger.info("---- ON CONNECTION ERROR for gateway {}: {}", gateway, errMsg);
489 isGatewayConnected = false;
490 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
491 "@text/offline.comm-error-connection" + " (onConnectionError - " + errMsg + ")");
492 tryReconnectGateway();
496 public void onConnectionClosed() {
497 isGatewayConnected = false;
498 logger.debug("onConnectionClosed() - isGatewayConnected={}", isGatewayConnected);
499 // NOTE: cannot change to OFFLINE here because we are already in REMOVING state
503 public void onDisconnected(@Nullable OWNException e) {
504 isGatewayConnected = false;
507 errMsg = "unknown error";
509 errMsg = e.getMessage();
511 logger.info("---- DISCONNECTED from gateway {}. OWNException: {}", gateway, errMsg);
512 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
513 "@text/offline.comm-error-disconnected" + " (onDisconnected - " + errMsg + ")");
514 tryReconnectGateway();
517 private void tryReconnectGateway() {
518 OpenGateway gw = gateway;
522 logger.info("---- Starting RECONNECT cycle to gateway {}", gw);
525 } catch (OWNAuthException e) {
526 logger.info("---- AUTH error from gateway. Stopping re-connect");
527 reconnecting = false;
528 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR,
529 "@text/offline.conf-error-auth" + " (" + e + ")");
532 logger.debug("---- reconnecting=true");
535 logger.warn("---- cannot start RECONNECT, gateway is null");
540 public void onReconnected() {
541 reconnecting = false;
542 OpenGateway gw = gateway;
543 logger.info("---- RE-CONNECTED to bridge {}", thing.getUID());
545 updateStatus(ThingStatus.ONLINE);
546 if (gw.getFirmwareVersion() != null) {
547 this.updateProperty(PROPERTY_FIRMWARE_VERSION, gw.getFirmwareVersion());
548 logger.debug("gw firmware version: {}", gw.getFirmwareVersion());
551 // schedule a refresh for all devices
552 refreshSchedule = scheduler.schedule(this::refreshAllDevices, REFRESH_ALL_DEVICES_DELAY_MSEC,
553 TimeUnit.MILLISECONDS);
558 * Return a ownId string (=WHO.WHERE) from the device Where address and handler
560 * @param where the Where address (to be normalized)
561 * @param handler the device handler
562 * @return the ownId String
564 protected String ownIdFromDeviceWhere(Where where, OpenWebNetThingHandler handler) {
565 return handler.ownIdPrefix() + "." + normalizeWhere(where);
569 * Returns a ownId string (=WHO.WHERE) from a Who and Where address
572 * @param where the Where address (to be normalized)
573 * @return the ownId String
575 public String ownIdFromWhoWhere(Who who, Where where) {
576 return who.value() + "." + normalizeWhere(where);
580 * Return a ownId string (=WHO.WHERE) from a BaseOpenMessage
582 * @param baseMsg the BaseOpenMessage
583 * @return the ownId String
585 public String ownIdFromMessage(BaseOpenMessage baseMsg) {
586 return baseMsg.getWho().value() + "." + normalizeWhere(baseMsg.getWhere());
590 * Transform a Where address into a Thing id string
592 * @param where the Where address
593 * @return the thing Id string
595 public String thingIdFromWhere(Where where) {
596 return normalizeWhere(where); // '#' cannot be used in ThingUID;
600 * Normalize a Where address
602 * @param where the Where address
603 * @return the normalized address as String
605 public String normalizeWhere(Where where) {
606 String str = where.value();
607 if (where instanceof WhereZigBee) {
608 str = ((WhereZigBee) where).valueWithUnit(WhereZigBee.UNIT_ALL); // 76543210X#9 --> 765432100#9
610 if (str.indexOf("#4#") == -1) { // skip APL#4#bus case
611 if (str.indexOf('#') == 0) { // Thermo central unit (#0) or zone via central unit (#Z, Z=[1-99]) --> Z
612 str = str.substring(1);
613 } else if (str.indexOf('#') > 0) { // Thermo zone Z and actuator N (Z#N, Z=[1-99], N=[1-9]) --> Z
614 str = str.substring(0, str.indexOf('#'));
618 return str.replace('#', 'h');