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.lcn.internal;
15 import java.util.HashMap;
16 import java.util.LinkedList;
17 import java.util.List;
19 import java.util.Queue;
21 import java.util.concurrent.ConcurrentHashMap;
22 import java.util.concurrent.ConcurrentLinkedQueue;
23 import java.util.concurrent.ScheduledFuture;
24 import java.util.concurrent.TimeUnit;
25 import java.util.regex.Matcher;
26 import java.util.regex.Pattern;
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.openhab.binding.lcn.internal.common.LcnAddrMod;
31 import org.openhab.binding.lcn.internal.connection.Connection;
32 import org.openhab.binding.lcn.internal.subhandler.LcnModuleMetaAckSubHandler;
33 import org.openhab.binding.lcn.internal.subhandler.LcnModuleMetaFirmwareSubHandler;
34 import org.openhab.core.config.discovery.AbstractDiscoveryService;
35 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
36 import org.openhab.core.config.discovery.DiscoveryService;
37 import org.openhab.core.thing.Thing;
38 import org.openhab.core.thing.ThingTypeUID;
39 import org.openhab.core.thing.ThingUID;
40 import org.openhab.core.thing.binding.ThingHandler;
41 import org.openhab.core.thing.binding.ThingHandlerService;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
46 * Scans all LCN segments for LCN modules.
49 * 1. Send "Leerkomando" to the broadcast address with request for Ack set
50 * 2. For every received Ack, send the following requests to the module:
51 * - serial number request (SN)
52 * - module's name first part request (NM1)
53 * - module's name second part request (NM2)
54 * 3. When all three messages have been received, fire thingDiscovered()
56 * @author Fabian Wolter - Initial Contribution
59 public class LcnModuleDiscoveryService extends AbstractDiscoveryService
60 implements DiscoveryService, ThingHandlerService {
61 private final Logger logger = LoggerFactory.getLogger(LcnModuleDiscoveryService.class);
62 private static final Pattern NAME_PATTERN = Pattern
63 .compile("=M(?<segId>\\d{3})(?<modId>\\d{3}).N(?<part>[1-2]{1})(?<name>.*)");
64 private static final String SEGMENT_ID = "segmentId";
65 private static final String MODULE_ID = "moduleId";
66 private static final int MODULE_NAME_PART_COUNT = 2;
67 private static final int DISCOVERY_TIMEOUT_SEC = 90;
68 private static final int ACK_TIMEOUT_MS = 1000;
69 private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(LcnBindingConstants.THING_TYPE_MODULE);
70 private @Nullable PckGatewayHandler bridgeHandler;
71 private final Map<LcnAddrMod, @Nullable Map<Integer, String>> moduleNames = new HashMap<>();
72 private final Map<LcnAddrMod, DiscoveryResultBuilder> discoveryResultBuilders = new ConcurrentHashMap<>();
73 private final List<LcnAddrMod> successfullyDiscovered = new LinkedList<>();
74 private final Queue<@Nullable LcnAddrMod> serialNumberRequestQueue = new ConcurrentLinkedQueue<>();
75 private final Queue<@Nullable LcnAddrMod> moduleNameRequestQueue = new ConcurrentLinkedQueue<>();
76 private @Nullable volatile ScheduledFuture<?> queueProcessor;
77 private @Nullable ScheduledFuture<?> builderTask;
79 public LcnModuleDiscoveryService() {
80 super(SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIMEOUT_SEC, false);
84 public void setThingHandler(@Nullable ThingHandler handler) {
85 if (handler instanceof PckGatewayHandler) {
86 this.bridgeHandler = (PckGatewayHandler) handler;
91 public @Nullable ThingHandler getThingHandler() {
96 public void deactivate() {
102 protected void startScan() {
103 synchronized (this) {
104 PckGatewayHandler localBridgeHandler = bridgeHandler;
105 if (localBridgeHandler == null) {
106 logger.warn("Bridge handler not set");
110 ScheduledFuture<?> localBuilderTask = builderTask;
111 if (localBridgeHandler.getConnection() == null && localBuilderTask != null) {
112 localBuilderTask.cancel(true);
115 localBridgeHandler.registerPckListener(data -> {
118 if ((matcher = LcnModuleMetaAckSubHandler.PATTERN_POS.matcher(data)).matches()
119 || (matcher = LcnModuleMetaFirmwareSubHandler.PATTERN.matcher(data)).matches()
120 || (matcher = NAME_PATTERN.matcher(data)).matches()) {
121 synchronized (LcnModuleDiscoveryService.this) {
122 Connection connection = localBridgeHandler.getConnection();
124 if (connection == null) {
128 LcnAddrMod addr = new LcnAddrMod(
129 localBridgeHandler.toLogicalSegmentId(Integer.parseInt(matcher.group("segId"))),
130 Integer.parseInt(matcher.group("modId")));
132 if (matcher.pattern() == LcnModuleMetaAckSubHandler.PATTERN_POS) {
133 // Received an ACK frame
135 // The module could send an Ack with a response to another command. So, ignore the Ack, when
136 // we received our data already.
137 if (!discoveryResultBuilders.containsKey(addr)) {
138 serialNumberRequestQueue.add(addr);
139 rescheduleQueueProcessor(); // delay request of serial until all modules finished ACKing
142 Map<Integer, String> localNameParts = moduleNames.get(addr);
143 if (localNameParts == null || localNameParts.size() != MODULE_NAME_PART_COUNT) {
144 moduleNameRequestQueue.add(addr);
145 rescheduleQueueProcessor(); // delay request of names until all modules finished ACKing
147 } else if (matcher.pattern() == LcnModuleMetaFirmwareSubHandler.PATTERN) {
148 // Received a firmware version info frame
150 ThingUID bridgeUid = localBridgeHandler.getThing().getUID();
151 String serialNumber = matcher.group("sn");
153 String thingID = String.format("S%03dM%03d", addr.getSegmentId(), addr.getModuleId());
155 ThingUID thingUid = new ThingUID(LcnBindingConstants.THING_TYPE_MODULE, bridgeUid, thingID);
157 Map<String, Object> properties = new HashMap<>(3);
158 properties.put(SEGMENT_ID, addr.getSegmentId());
159 properties.put(MODULE_ID, addr.getModuleId());
160 properties.put(Thing.PROPERTY_SERIAL_NUMBER, serialNumber);
162 DiscoveryResultBuilder discoveryResult = DiscoveryResultBuilder.create(thingUid)
163 .withProperties(properties).withRepresentationProperty(Thing.PROPERTY_SERIAL_NUMBER)
164 .withBridge(bridgeUid);
166 discoveryResultBuilders.put(addr, discoveryResult);
167 } else if (matcher.pattern() == NAME_PATTERN) {
168 // Received part of a module's name frame
170 final int part = Integer.parseInt(matcher.group("part")) - 1;
171 final String name = matcher.group("name");
173 moduleNames.compute(addr, (partNumber, namePart) -> {
174 Map<Integer, String> namePartMapping = namePart;
175 if (namePartMapping == null) {
176 namePartMapping = new HashMap<>();
179 namePartMapping.put(part, name);
181 return namePartMapping;
188 builderTask = scheduler.scheduleWithFixedDelay(() -> {
189 synchronized (LcnModuleDiscoveryService.this) {
190 discoveryResultBuilders.entrySet().stream().filter(e -> {
191 Map<Integer, String> localNameParts = moduleNames.get(e.getKey());
192 return localNameParts != null && localNameParts.size() == MODULE_NAME_PART_COUNT;
193 }).filter(e -> !successfullyDiscovered.contains(e.getKey())).forEach(e -> {
194 StringBuilder thingName = new StringBuilder();
195 if (e.getKey().getSegmentId() != 0) {
196 thingName.append("Segment " + e.getKey().getSegmentId() + " ");
199 thingName.append("Module " + e.getKey().getModuleId() + ": ");
200 Map<Integer, String> localNameParts = moduleNames.get(e.getKey());
201 if (localNameParts != null) {
202 thingName.append(localNameParts.get(0));
203 thingName.append(localNameParts.get(1));
205 thingDiscovered(e.getValue().withLabel(thingName.toString()).build());
206 successfullyDiscovered.add(e.getKey());
210 }, 500, 500, TimeUnit.MILLISECONDS);
212 localBridgeHandler.sendModuleDiscoveryCommand();
216 private synchronized void rescheduleQueueProcessor() {
217 // delay serial number and module name requests to not clog the bus
218 ScheduledFuture<?> localQueueProcessor = queueProcessor;
219 if (localQueueProcessor != null) {
220 localQueueProcessor.cancel(true);
222 queueProcessor = scheduler.scheduleWithFixedDelay(() -> {
223 PckGatewayHandler localBridgeHandler = bridgeHandler;
224 if (localBridgeHandler != null) {
225 LcnAddrMod serial = serialNumberRequestQueue.poll();
226 if (serial != null) {
227 localBridgeHandler.sendSerialNumberRequest(serial);
230 LcnAddrMod name = moduleNameRequestQueue.poll();
232 localBridgeHandler.sendModuleNameRequest(name);
235 // stop scan when all LCN modules have been requested
236 if (serial == null && name == null) {
237 scheduler.schedule(this::stopScan, ACK_TIMEOUT_MS, TimeUnit.MILLISECONDS);
240 }, ACK_TIMEOUT_MS, ACK_TIMEOUT_MS, TimeUnit.MILLISECONDS);
244 public synchronized void stopScan() {
245 ScheduledFuture<?> localBuilderTask = builderTask;
246 if (localBuilderTask != null) {
247 localBuilderTask.cancel(true);
249 ScheduledFuture<?> localQueueProcessor = queueProcessor;
250 if (localQueueProcessor != null) {
251 localQueueProcessor.cancel(true);
253 PckGatewayHandler localBridgeHandler = bridgeHandler;
254 if (localBridgeHandler != null) {
255 localBridgeHandler.removeAllPckListeners();
257 successfullyDiscovered.clear();