]> git.basschouten.com Git - openhab-addons.git/blob
bc3f0d646deee32e8d4d0999edc75de70ac57b97
[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.lcn.internal;
14
15 import java.util.HashMap;
16 import java.util.LinkedList;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.Queue;
20 import java.util.Set;
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;
27
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;
44
45 /**
46  * Scans all LCN segments for LCN modules.
47  *
48  * Scan approach:
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()
55  *
56  * @author Fabian Wolter - Initial Contribution
57  */
58 @NonNullByDefault
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;
78
79     public LcnModuleDiscoveryService() {
80         super(SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIMEOUT_SEC, false);
81     }
82
83     @Override
84     public void setThingHandler(@Nullable ThingHandler handler) {
85         if (handler instanceof PckGatewayHandler) {
86             this.bridgeHandler = (PckGatewayHandler) handler;
87         }
88     }
89
90     @Override
91     public @Nullable ThingHandler getThingHandler() {
92         return bridgeHandler;
93     }
94
95     @Override
96     public void deactivate() {
97         stopScan();
98         super.deactivate();
99     }
100
101     @Override
102     protected void startScan() {
103         synchronized (this) {
104             PckGatewayHandler localBridgeHandler = bridgeHandler;
105             if (localBridgeHandler == null) {
106                 logger.warn("Bridge handler not set");
107                 return;
108             }
109
110             ScheduledFuture<?> localBuilderTask = builderTask;
111             if (localBridgeHandler.getConnection() == null && localBuilderTask != null) {
112                 localBuilderTask.cancel(true);
113             }
114
115             localBridgeHandler.registerPckListener(data -> {
116                 Matcher matcher;
117
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();
123
124                         if (connection == null) {
125                             return;
126                         }
127
128                         LcnAddrMod addr = new LcnAddrMod(
129                                 localBridgeHandler.toLogicalSegmentId(Integer.parseInt(matcher.group("segId"))),
130                                 Integer.parseInt(matcher.group("modId")));
131
132                         if (matcher.pattern() == LcnModuleMetaAckSubHandler.PATTERN_POS) {
133                             // Received an ACK frame
134
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
140                             }
141
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
146                             }
147                         } else if (matcher.pattern() == LcnModuleMetaFirmwareSubHandler.PATTERN) {
148                             // Received a firmware version info frame
149
150                             ThingUID bridgeUid = localBridgeHandler.getThing().getUID();
151                             String serialNumber = matcher.group("sn");
152
153                             String thingID = String.format("S%03dM%03d", addr.getSegmentId(), addr.getModuleId());
154
155                             ThingUID thingUid = new ThingUID(LcnBindingConstants.THING_TYPE_MODULE, bridgeUid, thingID);
156
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);
161
162                             DiscoveryResultBuilder discoveryResult = DiscoveryResultBuilder.create(thingUid)
163                                     .withProperties(properties).withRepresentationProperty(Thing.PROPERTY_SERIAL_NUMBER)
164                                     .withBridge(bridgeUid);
165
166                             discoveryResultBuilders.put(addr, discoveryResult);
167                         } else if (matcher.pattern() == NAME_PATTERN) {
168                             // Received part of a module's name frame
169
170                             final int part = Integer.parseInt(matcher.group("part")) - 1;
171                             final String name = matcher.group("name");
172
173                             moduleNames.compute(addr, (partNumber, namePart) -> {
174                                 Map<Integer, String> namePartMapping = namePart;
175                                 if (namePartMapping == null) {
176                                     namePartMapping = new HashMap<>();
177                                 }
178
179                                 namePartMapping.put(part, name);
180
181                                 return namePartMapping;
182                             });
183                         }
184                     }
185                 }
186             });
187
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() + " ");
197                         }
198
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));
204
205                             thingDiscovered(e.getValue().withLabel(thingName.toString()).build());
206                             successfullyDiscovered.add(e.getKey());
207                         }
208                     });
209                 }
210             }, 500, 500, TimeUnit.MILLISECONDS);
211
212             localBridgeHandler.sendModuleDiscoveryCommand();
213         }
214     }
215
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);
221         }
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);
228                 }
229
230                 LcnAddrMod name = moduleNameRequestQueue.poll();
231                 if (name != null) {
232                     localBridgeHandler.sendModuleNameRequest(name);
233                 }
234
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);
238                 }
239             }
240         }, ACK_TIMEOUT_MS, ACK_TIMEOUT_MS, TimeUnit.MILLISECONDS);
241     }
242
243     @Override
244     public synchronized void stopScan() {
245         ScheduledFuture<?> localBuilderTask = builderTask;
246         if (localBuilderTask != null) {
247             localBuilderTask.cancel(true);
248         }
249         ScheduledFuture<?> localQueueProcessor = queueProcessor;
250         if (localQueueProcessor != null) {
251             localQueueProcessor.cancel(true);
252         }
253         PckGatewayHandler localBridgeHandler = bridgeHandler;
254         if (localBridgeHandler != null) {
255             localBridgeHandler.removeAllPckListeners();
256         }
257         successfullyDiscovered.clear();
258         moduleNames.clear();
259
260         super.stopScan();
261     }
262 }