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.dsmr.internal.discovery;
15 import static org.openhab.binding.dsmr.internal.DSMRBindingConstants.*;
17 import java.util.HashMap;
18 import java.util.List;
20 import java.util.stream.Stream;
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.openhab.binding.dsmr.internal.device.DSMRDeviceRunnable;
25 import org.openhab.binding.dsmr.internal.device.DSMREventListener;
26 import org.openhab.binding.dsmr.internal.device.DSMRSerialAutoDevice;
27 import org.openhab.binding.dsmr.internal.device.DSMRTelegramListener;
28 import org.openhab.binding.dsmr.internal.device.connector.DSMRConnectorErrorEvent;
29 import org.openhab.binding.dsmr.internal.device.cosem.CosemObject;
30 import org.openhab.binding.dsmr.internal.device.p1telegram.P1Telegram;
31 import org.openhab.binding.dsmr.internal.device.p1telegram.P1Telegram.TelegramState;
32 import org.openhab.core.config.discovery.DiscoveryResult;
33 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
34 import org.openhab.core.config.discovery.DiscoveryService;
35 import org.openhab.core.i18n.LocaleProvider;
36 import org.openhab.core.i18n.TranslationProvider;
37 import org.openhab.core.io.transport.serial.SerialPortIdentifier;
38 import org.openhab.core.io.transport.serial.SerialPortManager;
39 import org.openhab.core.thing.ThingTypeUID;
40 import org.openhab.core.thing.ThingUID;
41 import org.osgi.service.component.annotations.Activate;
42 import org.osgi.service.component.annotations.Component;
43 import org.osgi.service.component.annotations.Reference;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
48 * This implements the discovery service for detecting new DSMR Meters.
50 * The service will iterate over the available serial ports and open the given serial port and wait for telegrams. If
51 * the port is already owned because it's already detected this service will ignore it. But it will report a warning in
52 * case the port was locked due to a crash.
53 * After {@link #BAUDRATE_SWITCH_TIMEOUT_SECONDS} seconds it will switch the baud rate and wait again for telegrams.
54 * When that doesn't produce any results the service will give up (assuming no DSMR Bridge is present).
56 * If a telegram is received with at least 1 Cosem Object a bridge is assumed available and a Thing is added (regardless
57 * if there were problems receiving the telegram) and the discovery is stopped.
59 * If there are communication problems the service will give an warning and give up
61 * @author M. Volaart - Initial contribution
62 * @author Hilbrand Bouwkamp - Refactored code to detect meters during actual discovery phase.
65 @Component(service = DiscoveryService.class, configurationPid = "discovery.dsmr")
66 public class DSMRBridgeDiscoveryService extends DSMRDiscoveryService implements DSMREventListener {
69 * The timeout used to switch baudrate if no valid data is received within that time frame.
71 private static final int BAUDRATE_SWITCH_TIMEOUT_SECONDS = 25;
73 private final Logger logger = LoggerFactory.getLogger(DSMRBridgeDiscoveryService.class);
76 * Serial Port Manager.
78 private final SerialPortManager serialPortManager;
81 * DSMR Device that is scanned when discovery process in progress.
83 private @Nullable DSMRDeviceRunnable currentScannedDevice;
86 * Name of the serial port that is scanned when discovery process in progress.
88 private String currentScannedPortName = "";
91 * Keeps a boolean during time discovery process in progress.
93 private boolean scanning;
96 public DSMRBridgeDiscoveryService(final @Reference TranslationProvider i18nProvider,
97 final @Reference LocaleProvider localeProvider, final @Reference SerialPortManager serialPortManager) {
98 this.i18nProvider = i18nProvider;
99 this.localeProvider = localeProvider;
100 this.serialPortManager = serialPortManager;
104 * Starts a new discovery scan.
106 * All available Serial Ports are scanned for P1 telegrams.
109 protected void startScan() {
110 logger.debug("Started DSMR discovery scan");
112 Stream<SerialPortIdentifier> portEnum = serialPortManager.getIdentifiers();
114 // Traverse each available serial port
115 portEnum.forEach(portIdentifier -> {
117 currentScannedPortName = portIdentifier.getName();
118 if (portIdentifier.isCurrentlyOwned()) {
119 logger.trace("Possible port to check:{}, owned:{} by:{}", currentScannedPortName,
120 portIdentifier.isCurrentlyOwned(), portIdentifier.getCurrentOwner());
121 if (DSMR_PORT_NAME.equals(portIdentifier.getCurrentOwner())) {
122 logger.debug("The port {} is owned by this binding. If no DSMR meters will be found it "
123 + "might indicate the port is locked by an older instance of this binding. "
124 + "Restart the system to unlock the port.", currentScannedPortName);
127 logger.debug("Start discovery on serial port: {}", currentScannedPortName);
129 final DSMRTelegramListener telegramListener = new DSMRTelegramListener("");
130 final DSMRSerialAutoDevice device = new DSMRSerialAutoDevice(serialPortManager,
131 portIdentifier.getName(), this, telegramListener, scheduler,
132 BAUDRATE_SWITCH_TIMEOUT_SECONDS);
133 device.setLenientMode(true);
134 currentScannedDevice = new DSMRDeviceRunnable(device, this);
135 currentScannedDevice.run();
142 protected synchronized void stopScan() {
144 stopSerialPortScan();
146 logger.debug("Stop DSMR discovery scan");
150 * Stops the serial port device.
152 private void stopSerialPortScan() {
153 logger.debug("Stop discovery scan on port [{}].", currentScannedPortName);
154 if (currentScannedDevice != null) {
155 currentScannedDevice.stop();
157 currentScannedDevice = null;
158 currentScannedPortName = "";
162 * Handle if telegrams are received.
164 * If there are cosem objects received a new bridge will we discovered.
166 * @param telegram the received telegram
169 public void handleTelegramReceived(P1Telegram telegram) {
170 List<CosemObject> cosemObjects = telegram.getCosemObjects();
172 if (logger.isDebugEnabled()) {
173 logger.debug("[{}] Received {} cosemObjects", currentScannedPortName, cosemObjects.size());
175 if (telegram.getTelegramState() == TelegramState.INVALID_ENCRYPTION_KEY) {
176 bridgeDiscovered(THING_TYPE_SMARTY_BRIDGE);
177 stopSerialPortScan();
178 } else if (!cosemObjects.isEmpty()) {
179 ThingUID bridgeThingUID = bridgeDiscovered(THING_TYPE_DSMR_BRIDGE);
180 meterDetector.detectMeters(telegram).getKey().forEach(m -> meterDiscovered(m, bridgeThingUID));
181 stopSerialPortScan();
188 * @return The {@link ThingUID} of the newly created bridge
190 private ThingUID bridgeDiscovered(ThingTypeUID bridgeThingTypeUID) {
191 ThingUID thingUID = new ThingUID(bridgeThingTypeUID, Integer.toHexString(currentScannedPortName.hashCode()));
192 final boolean smarty = THING_TYPE_SMARTY_BRIDGE.equals(bridgeThingTypeUID);
193 final String label = String.format("@text/thing-type.dsmr.%s.label", smarty ? "smartyBridge" : "dsmrBridge");
195 // Construct the configuration for this meter
196 Map<String, Object> properties = new HashMap<>();
197 properties.put(CONFIGURATION_SERIAL_PORT, currentScannedPortName);
199 properties.put(CONFIGURATION_DECRYPTION_KEY, CONFIGURATION_DECRYPTION_KEY_EMPTY);
201 DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(bridgeThingTypeUID)
202 .withProperties(properties).withLabel(label).build();
204 logger.debug("[{}] discovery result:{}", currentScannedPortName, discoveryResult);
206 thingDiscovered(discoveryResult);
211 public void handleErrorEvent(DSMRConnectorErrorEvent portEvent) {
212 logger.debug("[{}] Error on port during discovery: {}", currentScannedPortName, portEvent);
213 stopSerialPortScan();