]> git.basschouten.com Git - openhab-addons.git/blob
2ef00e9aa713e33955e71e3b8d005c582c3ca9b6
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.knx.internal.client;
14
15 import java.time.Duration;
16 import java.util.Optional;
17 import java.util.Set;
18 import java.util.concurrent.CancellationException;
19 import java.util.concurrent.CopyOnWriteArraySet;
20 import java.util.concurrent.LinkedBlockingQueue;
21 import java.util.concurrent.ScheduledExecutorService;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
24 import java.util.function.Consumer;
25
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.knx.internal.KNXTypeMapper;
29 import org.openhab.binding.knx.internal.dpt.KNXCoreTypeMapper;
30 import org.openhab.binding.knx.internal.handler.GroupAddressListener;
31 import org.openhab.binding.knx.internal.i18n.KNXTranslationProvider;
32 import org.openhab.core.thing.ThingStatus;
33 import org.openhab.core.thing.ThingStatusDetail;
34 import org.openhab.core.thing.ThingUID;
35 import org.openhab.core.types.Type;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 import tuwien.auto.calimero.CloseEvent;
40 import tuwien.auto.calimero.DetachEvent;
41 import tuwien.auto.calimero.FrameEvent;
42 import tuwien.auto.calimero.GroupAddress;
43 import tuwien.auto.calimero.IndividualAddress;
44 import tuwien.auto.calimero.KNXException;
45 import tuwien.auto.calimero.KNXIllegalArgumentException;
46 import tuwien.auto.calimero.datapoint.CommandDP;
47 import tuwien.auto.calimero.datapoint.Datapoint;
48 import tuwien.auto.calimero.device.ProcessCommunicationResponder;
49 import tuwien.auto.calimero.link.KNXNetworkLink;
50 import tuwien.auto.calimero.link.NetworkLinkListener;
51 import tuwien.auto.calimero.mgmt.Destination;
52 import tuwien.auto.calimero.mgmt.ManagementClient;
53 import tuwien.auto.calimero.mgmt.ManagementClientImpl;
54 import tuwien.auto.calimero.mgmt.ManagementProcedures;
55 import tuwien.auto.calimero.mgmt.ManagementProceduresImpl;
56 import tuwien.auto.calimero.process.ProcessCommunication;
57 import tuwien.auto.calimero.process.ProcessCommunicator;
58 import tuwien.auto.calimero.process.ProcessCommunicatorImpl;
59 import tuwien.auto.calimero.process.ProcessEvent;
60 import tuwien.auto.calimero.process.ProcessListener;
61 import tuwien.auto.calimero.secure.KnxSecureException;
62 import tuwien.auto.calimero.secure.SecureApplicationLayer;
63 import tuwien.auto.calimero.secure.Security;
64
65 /**
66  * KNX Client which encapsulates the communication with the KNX bus via the calimero libary.
67  *
68  * @author Simon Kaufmann - initial contribution and API.
69  *
70  */
71 @NonNullByDefault
72 public abstract class AbstractKNXClient implements NetworkLinkListener, KNXClient {
73     public enum ClientState {
74         INIT,
75         RUNNING,
76         INTERRUPTED,
77         DISPOSE
78     }
79
80     private ClientState state = ClientState.INIT;
81
82     private static final int MAX_SEND_ATTEMPTS = 2;
83
84     private final Logger logger = LoggerFactory.getLogger(AbstractKNXClient.class);
85     private final KNXTypeMapper typeHelper = new KNXCoreTypeMapper();
86
87     private final ThingUID thingUID;
88     private final int responseTimeout;
89     private final int readingPause;
90     private final int autoReconnectPeriod;
91     private final int readRetriesLimit;
92     private final StatusUpdateCallback statusUpdateCallback;
93     private final ScheduledExecutorService knxScheduler;
94
95     private @Nullable ProcessCommunicator processCommunicator;
96     private @Nullable ProcessCommunicationResponder responseCommunicator;
97     private @Nullable ManagementProcedures managementProcedures;
98     private @Nullable ManagementClient managementClient;
99     private @Nullable KNXNetworkLink link;
100     private @Nullable DeviceInfoClient deviceInfoClient;
101     private @Nullable ScheduledFuture<?> busJob;
102     private @Nullable ScheduledFuture<?> connectJob;
103
104     private final Set<GroupAddressListener> groupAddressListeners = new CopyOnWriteArraySet<>();
105     private final LinkedBlockingQueue<ReadDatapoint> readDatapoints = new LinkedBlockingQueue<>();
106
107     @FunctionalInterface
108     private interface ListenerNotification {
109         void apply(BusMessageListener listener, IndividualAddress source, GroupAddress destination, byte[] asdu);
110     }
111
112     @NonNullByDefault({})
113     private final ProcessListener processListener = new ProcessListener() {
114
115         @Override
116         public void detached(DetachEvent e) {
117             logger.debug("The KNX network link was detached from the process communicator");
118         }
119
120         @Override
121         public void groupWrite(ProcessEvent e) {
122             processEvent("Group Write", e, (listener, source, destination, asdu) -> {
123                 listener.onGroupWrite(AbstractKNXClient.this, source, destination, asdu);
124             });
125         }
126
127         @Override
128         public void groupReadRequest(ProcessEvent e) {
129             processEvent("Group Read Request", e, (listener, source, destination, asdu) -> {
130                 listener.onGroupRead(AbstractKNXClient.this, source, destination, asdu);
131             });
132         }
133
134         @Override
135         public void groupReadResponse(ProcessEvent e) {
136             processEvent("Group Read Response", e, (listener, source, destination, asdu) -> {
137                 listener.onGroupReadResponse(AbstractKNXClient.this, source, destination, asdu);
138             });
139         }
140     };
141
142     public AbstractKNXClient(int autoReconnectPeriod, ThingUID thingUID, int responseTimeout, int readingPause,
143             int readRetriesLimit, ScheduledExecutorService knxScheduler, StatusUpdateCallback statusUpdateCallback) {
144         this.autoReconnectPeriod = autoReconnectPeriod;
145         this.thingUID = thingUID;
146         this.responseTimeout = responseTimeout;
147         this.readingPause = readingPause;
148         this.readRetriesLimit = readRetriesLimit;
149         this.knxScheduler = knxScheduler;
150         this.statusUpdateCallback = statusUpdateCallback;
151     }
152
153     public void initialize() {
154         if (!scheduleReconnectJob()) {
155             connect();
156         }
157     }
158
159     private boolean scheduleReconnectJob() {
160         if (autoReconnectPeriod > 0) {
161             // schedule connect job, for the first connection ignore autoReconnectPeriod and use 1 sec
162             final long reconnectDelayS = (state == ClientState.INIT) ? 1 : autoReconnectPeriod;
163             final String prefix = (state == ClientState.INIT) ? "re" : "";
164             logger.debug("Bridge {} scheduling {}connect in {}s", thingUID, prefix, reconnectDelayS);
165             connectJob = knxScheduler.schedule(this::connect, reconnectDelayS, TimeUnit.SECONDS);
166             return true;
167         } else {
168             return false;
169         }
170     }
171
172     private void cancelReconnectJob() {
173         final ScheduledFuture<?> currentReconnectJob = connectJob;
174         if (currentReconnectJob != null) {
175             currentReconnectJob.cancel(true);
176             connectJob = null;
177         }
178     }
179
180     protected abstract KNXNetworkLink establishConnection() throws KNXException, InterruptedException;
181
182     private synchronized boolean connectIfNotAutomatic() {
183         if (!isConnected()) {
184             return connectJob != null ? false : connect();
185         }
186         return true;
187     }
188
189     private synchronized boolean connect() {
190         if (state == ClientState.INIT) {
191             state = ClientState.RUNNING;
192         } else if (state == ClientState.DISPOSE) {
193             logger.trace("connect() ignored, closing down");
194             return false;
195         }
196
197         if (isConnected()) {
198             return true;
199         }
200         try {
201             // We have a valid "connection" object, this is ensured by IPClient.java.
202             // "releaseConnection" is actually removing all registered users of this connection and stopping
203             // all threads.
204             // Note that this will also kill this function in the following call to sleep in case of a
205             // connection loss -> restart is via triggered via scheduledReconnect in handler for InterruptedException.
206             releaseConnection();
207             Thread.sleep(1000);
208             logger.debug("Bridge {} is connecting to KNX bus", thingUID);
209
210             // now establish (possibly encrypted) connection, according to settings (tunnel, routing, secure...)
211             KNXNetworkLink link = establishConnection();
212             this.link = link;
213
214             // ManagementProcedures provided by Calimero: allow managing other KNX devices, e.g. check if an address is
215             // reachable.
216             // Note for KNX Secure: ManagmentProcedueresImpl currently does not provide a ctor with external SAL,
217             // it internally creates an instance of ManagementClientImpl, which uses
218             // Security.defaultInstallation().deviceToolKeys()
219             // Protected ctor using given ManagementClientImpl is avalable (custom class to be inherited)
220             managementProcedures = new ManagementProceduresImpl(link);
221
222             // ManagementClient provided by Calimero: allow reading device info, etc.
223             // Note for KNX Secure: ManagementClientImpl does not provide a ctor with external SAL in Calimero 2.5,
224             // is uses global Security.defaultInstalltion().deviceToolKeys()
225             // Current main branch includes a protected ctor (custom class to be inherited)
226             // TODO Calimero>2.5: check if there is a new way to provide security info, there is a new protected ctor
227             // TODO check if we can avoid creating another ManagementClient and re-use this from ManagemntProcedures
228             ManagementClient managementClient = new ManagementClientImpl(link);
229             managementClient.responseTimeout(Duration.ofSeconds(responseTimeout));
230             this.managementClient = managementClient;
231
232             // OH helper for reading device info, based on managementClient above
233             deviceInfoClient = new DeviceInfoClientImpl(managementClient);
234
235             // ProcessCommunicator provides main KNX communication (Calimero).
236             // Note for KNX Secure: SAL to be provided
237             ProcessCommunicator processCommunicator = new ProcessCommunicatorImpl(link);
238             processCommunicator.responseTimeout(Duration.ofSeconds(responseTimeout));
239             processCommunicator.addProcessListener(processListener);
240             this.processCommunicator = processCommunicator;
241
242             // ProcessCommunicationResponder provides responses to requests from KNX bus (Calimero).
243             // Note for KNX Secure: SAL to be provided
244             ProcessCommunicationResponder responseCommunicator = new ProcessCommunicationResponder(link,
245                     new SecureApplicationLayer(link, Security.defaultInstallation()));
246             this.responseCommunicator = responseCommunicator;
247
248             // register this class, callbacks will be triggered
249             link.addLinkListener(this);
250
251             // create a job carrying out read requests
252             busJob = knxScheduler.scheduleWithFixedDelay(() -> readNextQueuedDatapoint(), 0, readingPause,
253                     TimeUnit.MILLISECONDS);
254
255             statusUpdateCallback.updateStatus(ThingStatus.ONLINE);
256             connectJob = null;
257
258             logger.info("Bridge {} connected to KNX bus", thingUID);
259
260             state = ClientState.RUNNING;
261             return true;
262         } catch (InterruptedException e) {
263             final var lastState = state;
264             state = ClientState.INTERRUPTED;
265
266             logger.trace("Bridge {}, connection interrupted", thingUID);
267
268             disconnect(e);
269             if (lastState != ClientState.DISPOSE) {
270                 scheduleReconnectJob();
271             }
272
273             return false;
274         } catch (KNXException | KnxSecureException e) {
275             logger.debug("Bridge {} cannot connect: {}", thingUID, e.getMessage());
276             disconnect(e);
277             scheduleReconnectJob();
278             return false;
279         } catch (KNXIllegalArgumentException e) {
280             logger.debug("Bridge {} cannot connect: {}", thingUID, e.getMessage());
281             disconnect(e, Optional.of(ThingStatusDetail.CONFIGURATION_ERROR));
282             return false;
283         }
284     }
285
286     private void disconnect(@Nullable Exception e) {
287         disconnect(e, Optional.empty());
288     }
289
290     private synchronized void disconnect(@Nullable Exception e, Optional<ThingStatusDetail> detail) {
291         releaseConnection();
292         if (e != null) {
293             statusUpdateCallback.updateStatus(ThingStatus.OFFLINE, detail.orElse(ThingStatusDetail.COMMUNICATION_ERROR),
294                     KNXTranslationProvider.I18N.getLocalizedException(e));
295         } else {
296             statusUpdateCallback.updateStatus(ThingStatus.OFFLINE);
297         }
298     }
299
300     protected void releaseConnection() {
301         logger.debug("Bridge {} is disconnecting from KNX bus", thingUID);
302         var tmplink = link;
303         if (tmplink != null) {
304             tmplink.removeLinkListener(this);
305         }
306         busJob = nullify(busJob, j -> j.cancel(true));
307         readDatapoints.clear();
308         responseCommunicator = nullify(responseCommunicator, rc -> {
309             rc.removeProcessListener(processListener);
310             rc.detach();
311         });
312         processCommunicator = nullify(processCommunicator, pc -> {
313             pc.removeProcessListener(processListener);
314             pc.detach();
315         });
316         deviceInfoClient = null;
317         managementClient = nullify(managementClient, mc -> mc.detach());
318         managementProcedures = nullify(managementProcedures, mp -> mp.detach());
319         link = nullify(link, l -> l.close());
320         logger.trace("Bridge {} disconnected from KNX bus", thingUID);
321     }
322
323     private <T> @Nullable T nullify(@Nullable T target, @Nullable Consumer<T> lastWill) {
324         if (target != null && lastWill != null) {
325             lastWill.accept(target);
326         }
327         return null;
328     }
329
330     private void processEvent(String task, ProcessEvent event, ListenerNotification action) {
331         GroupAddress destination = event.getDestination();
332         IndividualAddress source = event.getSourceAddr();
333         byte[] asdu = event.getASDU();
334         logger.trace("Received a {} telegram from '{}' to '{}' with value '{}'", task, source, destination, asdu);
335         for (GroupAddressListener listener : groupAddressListeners) {
336             if (listener.listensTo(destination)) {
337                 knxScheduler.schedule(() -> action.apply(listener, source, destination, asdu), 0, TimeUnit.SECONDS);
338             }
339         }
340     }
341
342     /**
343      * Transforms a {@link Type} into a datapoint type value for the KNX bus.
344      *
345      * @param type the {@link Type} to transform
346      * @param dpt the datapoint type to which should be converted
347      * @return the corresponding KNX datapoint type value as a string
348      */
349     @Nullable
350     private String toDPTValue(Type type, String dpt) {
351         return typeHelper.toDPTValue(type, dpt);
352     }
353
354     // datapoint is null at end of the list, warning is misleading
355     @SuppressWarnings("null")
356     private void readNextQueuedDatapoint() {
357         if (!connectIfNotAutomatic()) {
358             return;
359         }
360         ProcessCommunicator processCommunicator = this.processCommunicator;
361         if (processCommunicator == null) {
362             return;
363         }
364         ReadDatapoint datapoint = readDatapoints.poll();
365         if (datapoint != null) {
366             datapoint.incrementRetries();
367             try {
368                 logger.trace("Sending a Group Read Request telegram for {}", datapoint.getDatapoint().getMainAddress());
369                 processCommunicator.read(datapoint.getDatapoint());
370             } catch (KNXException e) {
371                 // Note: KnxException does not cover KnxRuntimeException and subclasses KnxSecureException,
372                 // KnxIllegArgumentException
373                 if (datapoint.getRetries() < datapoint.getLimit()) {
374                     readDatapoints.add(datapoint);
375                     logger.debug("Could not read value for datapoint {}: {}. Going to retry.",
376                             datapoint.getDatapoint().getMainAddress(), e.getMessage());
377                 } else {
378                     logger.warn("Giving up reading datapoint {}, the number of maximum retries ({}) is reached.",
379                             datapoint.getDatapoint().getMainAddress(), datapoint.getLimit());
380                 }
381             } catch (InterruptedException | CancellationException e) {
382                 logger.debug("Interrupted sending KNX read request");
383                 return;
384             } catch (Exception e) {
385                 // Any other exception: Fail gracefully, i.e. notify user and continue reading next DP.
386                 // Not catching this would end the scheduled read for all DPs in case of an error.
387                 // Severity is warning as this is likely caused by a configuration error.
388                 logger.warn("Error reading datapoint {}: {}", datapoint.getDatapoint().getMainAddress(),
389                         e.getMessage());
390             }
391         }
392     }
393
394     public void dispose() {
395         state = ClientState.DISPOSE;
396
397         cancelReconnectJob();
398         disconnect(null);
399     }
400
401     @Override
402     public void linkClosed(@Nullable CloseEvent closeEvent) {
403         KNXNetworkLink link = this.link;
404         if (link == null || closeEvent == null) {
405             return;
406         }
407         if (!link.isOpen() && CloseEvent.USER_REQUEST != closeEvent.getInitiator()) {
408             final String reason = closeEvent.getReason();
409             statusUpdateCallback.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
410                     KNXTranslationProvider.I18N.get(reason));
411             logger.debug("KNX link has been lost (reason: {} on object {})", closeEvent.getReason(),
412                     closeEvent.getSource().toString());
413             scheduleReconnectJob();
414         }
415     }
416
417     @Override
418     public void indication(@Nullable FrameEvent e) {
419         // no-op
420     }
421
422     @Override
423     public void confirmation(@Nullable FrameEvent e) {
424         // no-op
425     }
426
427     @Override
428     public final synchronized boolean isReachable(@Nullable IndividualAddress address) throws KNXException {
429         ManagementProcedures managementProcedures = this.managementProcedures;
430         if (managementProcedures == null || address == null) {
431             return false;
432         }
433         try {
434             return managementProcedures.isAddressOccupied(address);
435         } catch (InterruptedException e) {
436             logger.debug("Interrupted pinging KNX device '{}'", address);
437         }
438         return false;
439     }
440
441     @Override
442     public final synchronized void restartNetworkDevice(@Nullable IndividualAddress address) {
443         ManagementClient managementClient = this.managementClient;
444         if (address == null || managementClient == null) {
445             return;
446         }
447         Destination destination = null;
448         try {
449             destination = managementClient.createDestination(address, true);
450             managementClient.restart(destination);
451         } catch (KNXException e) {
452             logger.warn("Could not reset device with address '{}': {}", address, e.getMessage());
453         } catch (InterruptedException e) { // ignored as in Calimero pre-2.4.0
454         } finally {
455             if (destination != null) {
456                 destination.destroy();
457             }
458         }
459     }
460
461     @Override
462     public void readDatapoint(Datapoint datapoint) {
463         synchronized (this) {
464             ReadDatapoint retryDatapoint = new ReadDatapoint(datapoint, readRetriesLimit);
465             if (!readDatapoints.contains(retryDatapoint)) {
466                 readDatapoints.add(retryDatapoint);
467             }
468         }
469     }
470
471     @Override
472     public final boolean registerGroupAddressListener(GroupAddressListener listener) {
473         return groupAddressListeners.add(listener);
474     }
475
476     @Override
477     public final boolean unregisterGroupAddressListener(GroupAddressListener listener) {
478         return groupAddressListeners.remove(listener);
479     }
480
481     @Override
482     public boolean isConnected() {
483         final var tmpLink = link;
484         return tmpLink != null && tmpLink.isOpen();
485     }
486
487     @Override
488     public DeviceInfoClient getDeviceInfoClient() {
489         DeviceInfoClient deviceInfoClient = this.deviceInfoClient;
490         if (deviceInfoClient != null) {
491             return deviceInfoClient;
492         } else {
493             throw new IllegalStateException();
494         }
495     }
496
497     @Override
498     public void writeToKNX(OutboundSpec commandSpec) throws KNXException {
499         ProcessCommunicator processCommunicator = this.processCommunicator;
500         KNXNetworkLink link = this.link;
501         if (processCommunicator == null || link == null) {
502             logger.debug("Cannot write to KNX bus (processCommuicator: {}, link: {})",
503                     processCommunicator == null ? "Not OK" : "OK",
504                     link == null ? "Not OK" : (link.isOpen() ? "Open" : "Closed"));
505             return;
506         }
507         GroupAddress groupAddress = commandSpec.getGroupAddress();
508
509         logger.trace("writeToKNX groupAddress '{}', commandSpec '{}'", groupAddress, commandSpec);
510
511         if (groupAddress != null) {
512             sendToKNX(processCommunicator, link, groupAddress, commandSpec.getDPT(), commandSpec.getType());
513         }
514     }
515
516     @Override
517     public void respondToKNX(OutboundSpec responseSpec) throws KNXException {
518         ProcessCommunicationResponder responseCommunicator = this.responseCommunicator;
519         KNXNetworkLink link = this.link;
520         if (responseCommunicator == null || link == null) {
521             logger.debug("Cannot write to KNX bus (responseCommunicator: {}, link: {})",
522                     responseCommunicator == null ? "Not OK" : "OK",
523                     link == null ? "Not OK" : (link.isOpen() ? "Open" : "Closed"));
524             return;
525         }
526         GroupAddress groupAddress = responseSpec.getGroupAddress();
527
528         logger.trace("respondToKNX groupAddress '{}', responseSpec '{}'", groupAddress, responseSpec);
529
530         if (groupAddress != null) {
531             sendToKNX(responseCommunicator, link, groupAddress, responseSpec.getDPT(), responseSpec.getType());
532         }
533     }
534
535     private void sendToKNX(ProcessCommunication communicator, KNXNetworkLink link, GroupAddress groupAddress,
536             String dpt, Type type) throws KNXException {
537         if (!connectIfNotAutomatic()) {
538             return;
539         }
540
541         Datapoint datapoint = new CommandDP(groupAddress, thingUID.toString(), 0, dpt);
542         String mappedValue = toDPTValue(type, dpt);
543
544         logger.trace("sendToKNX mappedValue: '{}' groupAddress: '{}'", mappedValue, groupAddress);
545
546         if (mappedValue == null) {
547             logger.debug("Value '{}' cannot be mapped to datapoint '{}'", type, datapoint);
548             return;
549         }
550         for (int i = 0; i < MAX_SEND_ATTEMPTS; i++) {
551             try {
552                 communicator.write(datapoint, mappedValue);
553                 logger.debug("Wrote value '{}' to datapoint '{}' ({}. attempt).", type, datapoint, i);
554                 break;
555             } catch (KNXException e) {
556                 if (i < MAX_SEND_ATTEMPTS - 1) {
557                     logger.debug("Value '{}' could not be sent to KNX bus using datapoint '{}': {}. Will retry.", type,
558                             datapoint, e.getLocalizedMessage());
559                 } else {
560                     logger.warn("Value '{}' could not be sent to KNX bus using datapoint '{}': {}. Giving up now.",
561                             type, datapoint, e.getLocalizedMessage());
562                     throw e;
563                 }
564             }
565         }
566     }
567 }