2 * Copyright (c) 2010-2024 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 gatewayHandler) {
86 this.bridgeHandler = gatewayHandler;
91 public @Nullable ThingHandler getThingHandler() {
96 public void deactivate() {
102 @SuppressWarnings("PMD.CompareObjectsWithEquals")
103 protected void startScan() {
104 synchronized (this) {
105 PckGatewayHandler localBridgeHandler = bridgeHandler;
106 if (localBridgeHandler == null) {
107 logger.warn("Bridge handler not set");
111 ScheduledFuture<?> localBuilderTask = builderTask;
112 if (localBridgeHandler.getConnection() == null && localBuilderTask != null) {
113 localBuilderTask.cancel(true);
116 localBridgeHandler.registerPckListener(data -> {
119 if ((matcher = LcnModuleMetaAckSubHandler.PATTERN_POS.matcher(data)).matches()
120 || (matcher = LcnModuleMetaFirmwareSubHandler.PATTERN.matcher(data)).matches()
121 || (matcher = NAME_PATTERN.matcher(data)).matches()) {
122 synchronized (LcnModuleDiscoveryService.this) {
123 Connection connection = localBridgeHandler.getConnection();
125 if (connection == null) {
129 LcnAddrMod addr = new LcnAddrMod(
130 localBridgeHandler.toLogicalSegmentId(Integer.parseInt(matcher.group("segId"))),
131 Integer.parseInt(matcher.group("modId")));
133 if (matcher.pattern() == LcnModuleMetaAckSubHandler.PATTERN_POS) {
134 // Received an ACK frame
136 // The module could send an Ack with a response to another command. So, ignore the Ack, when
137 // we received our data already.
138 if (!discoveryResultBuilders.containsKey(addr)) {
139 serialNumberRequestQueue.add(addr);
140 rescheduleQueueProcessor(); // delay request of serial until all modules finished ACKing
143 Map<Integer, String> localNameParts = moduleNames.get(addr);
144 if (localNameParts == null || localNameParts.size() != MODULE_NAME_PART_COUNT) {
145 moduleNameRequestQueue.add(addr);
146 rescheduleQueueProcessor(); // delay request of names until all modules finished ACKing
148 } else if (matcher.pattern() == LcnModuleMetaFirmwareSubHandler.PATTERN) {
149 // Received a firmware version info frame
151 ThingUID bridgeUid = localBridgeHandler.getThing().getUID();
152 String serialNumber = matcher.group("sn");
154 String thingID = String.format("S%03dM%03d", addr.getSegmentId(), addr.getModuleId());
156 ThingUID thingUid = new ThingUID(LcnBindingConstants.THING_TYPE_MODULE, bridgeUid, thingID);
158 Map<String, Object> properties = new HashMap<>(3);
159 properties.put(SEGMENT_ID, addr.getSegmentId());
160 properties.put(MODULE_ID, addr.getModuleId());
161 properties.put(Thing.PROPERTY_SERIAL_NUMBER, serialNumber);
163 DiscoveryResultBuilder discoveryResult = DiscoveryResultBuilder.create(thingUid)
164 .withProperties(properties).withRepresentationProperty(Thing.PROPERTY_SERIAL_NUMBER)
165 .withBridge(bridgeUid);
167 discoveryResultBuilders.put(addr, discoveryResult);
168 } else if (matcher.pattern() == NAME_PATTERN) {
169 // Received part of a module's name frame
171 final int part = Integer.parseInt(matcher.group("part")) - 1;
172 final String name = matcher.group("name");
174 moduleNames.compute(addr, (partNumber, namePart) -> {
175 Map<Integer, String> namePartMapping = namePart;
176 if (namePartMapping == null) {
177 namePartMapping = new HashMap<>();
180 namePartMapping.put(part, name);
182 return namePartMapping;
189 builderTask = scheduler.scheduleWithFixedDelay(() -> {
190 synchronized (LcnModuleDiscoveryService.this) {
191 discoveryResultBuilders.entrySet().stream().filter(e -> {
192 Map<Integer, String> localNameParts = moduleNames.get(e.getKey());
193 return localNameParts != null && localNameParts.size() == MODULE_NAME_PART_COUNT;
194 }).filter(e -> !successfullyDiscovered.contains(e.getKey())).forEach(e -> {
195 StringBuilder thingName = new StringBuilder();
196 if (e.getKey().getSegmentId() != 0) {
197 thingName.append("Segment " + e.getKey().getSegmentId() + " ");
200 thingName.append("Module " + e.getKey().getModuleId() + ": ");
201 Map<Integer, String> localNameParts = moduleNames.get(e.getKey());
202 if (localNameParts != null) {
203 thingName.append(localNameParts.get(0));
204 thingName.append(localNameParts.get(1));
206 thingDiscovered(e.getValue().withLabel(thingName.toString()).build());
207 successfullyDiscovered.add(e.getKey());
211 }, 500, 500, TimeUnit.MILLISECONDS);
213 localBridgeHandler.sendModuleDiscoveryCommand();
217 private synchronized void rescheduleQueueProcessor() {
218 // delay serial number and module name requests to not clog the bus
219 ScheduledFuture<?> localQueueProcessor = queueProcessor;
220 if (localQueueProcessor != null) {
221 localQueueProcessor.cancel(true);
223 queueProcessor = scheduler.scheduleWithFixedDelay(() -> {
224 PckGatewayHandler localBridgeHandler = bridgeHandler;
225 if (localBridgeHandler != null) {
226 LcnAddrMod serial = serialNumberRequestQueue.poll();
227 if (serial != null) {
228 localBridgeHandler.sendSerialNumberRequest(serial);
231 LcnAddrMod name = moduleNameRequestQueue.poll();
233 localBridgeHandler.sendModuleNameRequest(name);
236 // stop scan when all LCN modules have been requested
237 if (serial == null && name == null) {
238 scheduler.schedule(this::stopScan, ACK_TIMEOUT_MS, TimeUnit.MILLISECONDS);
241 }, ACK_TIMEOUT_MS, ACK_TIMEOUT_MS, TimeUnit.MILLISECONDS);
245 public synchronized void stopScan() {
246 ScheduledFuture<?> localBuilderTask = builderTask;
247 if (localBuilderTask != null) {
248 localBuilderTask.cancel(true);
250 ScheduledFuture<?> localQueueProcessor = queueProcessor;
251 if (localQueueProcessor != null) {
252 localQueueProcessor.cancel(true);
254 PckGatewayHandler localBridgeHandler = bridgeHandler;
255 if (localBridgeHandler != null) {
256 localBridgeHandler.removeAllPckListeners();
258 successfullyDiscovered.clear();