]> git.basschouten.com Git - openhab-addons.git/blob
2c7f5baed164c6b2df3509f2dc95e93182fee162
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.dsmr.internal.discovery;
14
15 import static org.openhab.binding.dsmr.internal.DSMRBindingConstants.*;
16
17 import java.util.HashMap;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.stream.Stream;
21
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;
46
47 /**
48  * This implements the discovery service for detecting new DSMR Meters.
49  *
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).
55  *
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.
58  *
59  * If there are communication problems the service will give an warning and give up
60  *
61  * @author M. Volaart - Initial contribution
62  * @author Hilbrand Bouwkamp - Refactored code to detect meters during actual discovery phase.
63  */
64 @NonNullByDefault
65 @Component(service = DiscoveryService.class, configurationPid = "discovery.dsmr")
66 public class DSMRBridgeDiscoveryService extends DSMRDiscoveryService implements DSMREventListener {
67
68     /**
69      * The timeout used to switch baudrate if no valid data is received within that time frame.
70      */
71     private static final int BAUDRATE_SWITCH_TIMEOUT_SECONDS = 25;
72
73     private final Logger logger = LoggerFactory.getLogger(DSMRBridgeDiscoveryService.class);
74
75     /**
76      * Serial Port Manager.
77      */
78     private final SerialPortManager serialPortManager;
79
80     /**
81      * DSMR Device that is scanned when discovery process in progress.
82      */
83     private @Nullable DSMRDeviceRunnable currentScannedDevice;
84
85     /**
86      * Name of the serial port that is scanned when discovery process in progress.
87      */
88     private String currentScannedPortName = "";
89
90     /**
91      * Keeps a boolean during time discovery process in progress.
92      */
93     private boolean scanning;
94
95     @Activate
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;
101     }
102
103     /**
104      * Starts a new discovery scan.
105      *
106      * All available Serial Ports are scanned for P1 telegrams.
107      */
108     @Override
109     protected void startScan() {
110         logger.debug("Started DSMR discovery scan");
111         scanning = true;
112         Stream<SerialPortIdentifier> portEnum = serialPortManager.getIdentifiers();
113
114         // Traverse each available serial port
115         portEnum.forEach(portIdentifier -> {
116             if (scanning) {
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);
125                     }
126                 } else {
127                     logger.debug("Start discovery on serial port: {}", currentScannedPortName);
128                     //
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();
136                 }
137             }
138         });
139     }
140
141     @Override
142     protected synchronized void stopScan() {
143         scanning = false;
144         stopSerialPortScan();
145         super.stopScan();
146         logger.debug("Stop DSMR discovery scan");
147     }
148
149     /**
150      * Stops the serial port device.
151      */
152     private void stopSerialPortScan() {
153         logger.debug("Stop discovery scan on port [{}].", currentScannedPortName);
154         if (currentScannedDevice != null) {
155             currentScannedDevice.stop();
156         }
157         currentScannedDevice = null;
158         currentScannedPortName = "";
159     }
160
161     /**
162      * Handle if telegrams are received.
163      *
164      * If there are cosem objects received a new bridge will we discovered.
165      *
166      * @param telegram the received telegram
167      */
168     @Override
169     public void handleTelegramReceived(P1Telegram telegram) {
170         List<CosemObject> cosemObjects = telegram.getCosemObjects();
171
172         if (logger.isDebugEnabled()) {
173             logger.debug("[{}] Received {} cosemObjects", currentScannedPortName, cosemObjects.size());
174         }
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();
182         }
183     }
184
185     /**
186      * Creates a bridge.
187      *
188      * @return The {@link ThingUID} of the newly created bridge
189      */
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");
194
195         // Construct the configuration for this meter
196         Map<String, Object> properties = new HashMap<>();
197         properties.put(CONFIGURATION_SERIAL_PORT, currentScannedPortName);
198         if (smarty) {
199             properties.put(CONFIGURATION_DECRYPTION_KEY, CONFIGURATION_DECRYPTION_KEY_EMPTY);
200         }
201         DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(bridgeThingTypeUID)
202                 .withProperties(properties).withLabel(label).build();
203
204         logger.debug("[{}] discovery result:{}", currentScannedPortName, discoveryResult);
205
206         thingDiscovered(discoveryResult);
207         return thingUID;
208     }
209
210     @Override
211     public void handleErrorEvent(DSMRConnectorErrorEvent portEvent) {
212         logger.debug("[{}] Error on port during discovery: {}", currentScannedPortName, portEvent);
213         stopSerialPortScan();
214     }
215 }