]> git.basschouten.com Git - openhab-addons.git/blob
397d777fe8870d6e09740ffe03cdd6b953b202ee
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.core.thing.ThingStatus;
32 import org.openhab.core.thing.ThingStatusDetail;
33 import org.openhab.core.thing.ThingUID;
34 import org.openhab.core.types.Type;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 import tuwien.auto.calimero.CloseEvent;
39 import tuwien.auto.calimero.DetachEvent;
40 import tuwien.auto.calimero.FrameEvent;
41 import tuwien.auto.calimero.GroupAddress;
42 import tuwien.auto.calimero.IndividualAddress;
43 import tuwien.auto.calimero.KNXException;
44 import tuwien.auto.calimero.KNXIllegalArgumentException;
45 import tuwien.auto.calimero.datapoint.CommandDP;
46 import tuwien.auto.calimero.datapoint.Datapoint;
47 import tuwien.auto.calimero.device.ProcessCommunicationResponder;
48 import tuwien.auto.calimero.link.KNXNetworkLink;
49 import tuwien.auto.calimero.link.NetworkLinkListener;
50 import tuwien.auto.calimero.mgmt.Destination;
51 import tuwien.auto.calimero.mgmt.ManagementClient;
52 import tuwien.auto.calimero.mgmt.ManagementClientImpl;
53 import tuwien.auto.calimero.mgmt.ManagementProcedures;
54 import tuwien.auto.calimero.mgmt.ManagementProceduresImpl;
55 import tuwien.auto.calimero.process.ProcessCommunication;
56 import tuwien.auto.calimero.process.ProcessCommunicator;
57 import tuwien.auto.calimero.process.ProcessCommunicatorImpl;
58 import tuwien.auto.calimero.process.ProcessEvent;
59 import tuwien.auto.calimero.process.ProcessListener;
60 import tuwien.auto.calimero.secure.KnxSecureException;
61 import tuwien.auto.calimero.secure.SecureApplicationLayer;
62 import tuwien.auto.calimero.secure.Security;
63
64 /**
65  * KNX Client which encapsulates the communication with the KNX bus via the calimero libary.
66  *
67  * @author Simon Kaufmann - initial contribution and API.
68  *
69  */
70 @NonNullByDefault
71 public abstract class AbstractKNXClient implements NetworkLinkListener, KNXClient {
72     public enum ClientState {
73         INIT,
74         RUNNING,
75         INTERRUPTED,
76         DISPOSE
77     }
78
79     private ClientState state = ClientState.INIT;
80
81     private static final int MAX_SEND_ATTEMPTS = 2;
82
83     private final Logger logger = LoggerFactory.getLogger(AbstractKNXClient.class);
84     private final KNXTypeMapper typeHelper = new KNXCoreTypeMapper();
85
86     private final ThingUID thingUID;
87     private final int responseTimeout;
88     private final int readingPause;
89     private final int autoReconnectPeriod;
90     private final int readRetriesLimit;
91     private final StatusUpdateCallback statusUpdateCallback;
92     private final ScheduledExecutorService knxScheduler;
93
94     private @Nullable ProcessCommunicator processCommunicator;
95     private @Nullable ProcessCommunicationResponder responseCommunicator;
96     private @Nullable ManagementProcedures managementProcedures;
97     private @Nullable ManagementClient managementClient;
98     private @Nullable KNXNetworkLink link;
99     private @Nullable DeviceInfoClient deviceInfoClient;
100     private @Nullable ScheduledFuture<?> busJob;
101     private @Nullable ScheduledFuture<?> connectJob;
102
103     private final Set<GroupAddressListener> groupAddressListeners = new CopyOnWriteArraySet<>();
104     private final LinkedBlockingQueue<ReadDatapoint> readDatapoints = new LinkedBlockingQueue<>();
105
106     @FunctionalInterface
107     private interface ListenerNotification {
108         void apply(BusMessageListener listener, IndividualAddress source, GroupAddress destination, byte[] asdu);
109     }
110
111     @NonNullByDefault({})
112     private final ProcessListener processListener = new ProcessListener() {
113
114         @Override
115         public void detached(DetachEvent e) {
116             logger.debug("The KNX network link was detached from the process communicator");
117         }
118
119         @Override
120         public void groupWrite(ProcessEvent e) {
121             processEvent("Group Write", e, (listener, source, destination, asdu) -> {
122                 listener.onGroupWrite(AbstractKNXClient.this, source, destination, asdu);
123             });
124         }
125
126         @Override
127         public void groupReadRequest(ProcessEvent e) {
128             processEvent("Group Read Request", e, (listener, source, destination, asdu) -> {
129                 listener.onGroupRead(AbstractKNXClient.this, source, destination, asdu);
130             });
131         }
132
133         @Override
134         public void groupReadResponse(ProcessEvent e) {
135             processEvent("Group Read Response", e, (listener, source, destination, asdu) -> {
136                 listener.onGroupReadResponse(AbstractKNXClient.this, source, destination, asdu);
137             });
138         }
139     };
140
141     public AbstractKNXClient(int autoReconnectPeriod, ThingUID thingUID, int responseTimeout, int readingPause,
142             int readRetriesLimit, ScheduledExecutorService knxScheduler, StatusUpdateCallback statusUpdateCallback) {
143         this.autoReconnectPeriod = autoReconnectPeriod;
144         this.thingUID = thingUID;
145         this.responseTimeout = responseTimeout;
146         this.readingPause = readingPause;
147         this.readRetriesLimit = readRetriesLimit;
148         this.knxScheduler = knxScheduler;
149         this.statusUpdateCallback = statusUpdateCallback;
150     }
151
152     public void initialize() {
153         if (!scheduleReconnectJob()) {
154             connect();
155         }
156     }
157
158     private boolean scheduleReconnectJob() {
159         if (autoReconnectPeriod > 0) {
160             // schedule connect job, for the first connection ignore autoReconnectPeriod and use 1 sec
161             final long reconnectDelayS = (state == ClientState.INIT) ? 1 : autoReconnectPeriod;
162             final String prefix = (state == ClientState.INIT) ? "re" : "";
163             logger.debug("Bridge {} scheduling {}connect in {}s", thingUID, prefix, reconnectDelayS);
164             connectJob = knxScheduler.schedule(this::connect, reconnectDelayS, TimeUnit.SECONDS);
165             return true;
166         } else {
167             return false;
168         }
169     }
170
171     private void cancelReconnectJob() {
172         final ScheduledFuture<?> currentReconnectJob = connectJob;
173         if (currentReconnectJob != null) {
174             currentReconnectJob.cancel(true);
175             connectJob = null;
176         }
177     }
178
179     protected abstract KNXNetworkLink establishConnection() throws KNXException, InterruptedException;
180
181     private synchronized boolean connectIfNotAutomatic() {
182         if (!isConnected()) {
183             return connectJob != null ? false : connect();
184         }
185         return true;
186     }
187
188     private synchronized boolean connect() {
189         if (state == ClientState.INIT) {
190             state = ClientState.RUNNING;
191         } else if (state == ClientState.DISPOSE) {
192             logger.trace("connect() ignored, closing down");
193             return false;
194         }
195
196         if (isConnected()) {
197             return true;
198         }
199         try {
200             // We have a valid "connection" object, this is ensured by IPClient.java.
201             // "releaseConnection" is actually removing all registered users of this connection and stopping
202             // all threads.
203             // Note that this will also kill this function in the following call to sleep in case of a
204             // connection loss -> restart is via triggered via scheduledReconnect in handler for InterruptedException.
205             releaseConnection();
206             Thread.sleep(1000);
207             logger.debug("Bridge {} is connecting to KNX bus", thingUID);
208
209             // now establish (possibly encrypted) connection, according to settings (tunnel, routing, secure...)
210             KNXNetworkLink link = establishConnection();
211             this.link = link;
212
213             // ManagementProcedures provided by Calimero: allow managing other KNX devices, e.g. check if an address is
214             // reachable.
215             // Note for KNX Secure: ManagmentProcedueresImpl currently does not provide a ctor with external SAL,
216             // it internally creates an instance of ManagementClientImpl, which uses
217             // Security.defaultInstallation().deviceToolKeys()
218             // Protected ctor using given ManagementClientImpl is avalable (custom class to be inherited)
219             managementProcedures = new ManagementProceduresImpl(link);
220
221             // ManagementClient provided by Calimero: allow reading device info, etc.
222             // Note for KNX Secure: ManagementClientImpl does not provide a ctor with external SAL in Calimero 2.5,
223             // is uses global Security.defaultInstalltion().deviceToolKeys()
224             // Current main branch includes a protected ctor (custom class to be inherited)
225             // TODO Calimero>2.5: check if there is a new way to provide security info, there is a new protected ctor
226             // TODO check if we can avoid creating another ManagementClient and re-use this from ManagemntProcedures
227             ManagementClient managementClient = new ManagementClientImpl(link);
228             managementClient.responseTimeout(Duration.ofSeconds(responseTimeout));
229             this.managementClient = managementClient;
230
231             // OH helper for reading device info, based on managementClient above
232             deviceInfoClient = new DeviceInfoClientImpl(managementClient);
233
234             // ProcessCommunicator provides main KNX communication (Calimero).
235             // Note for KNX Secure: SAL to be provided
236             ProcessCommunicator processCommunicator = new ProcessCommunicatorImpl(link);
237             processCommunicator.responseTimeout(Duration.ofSeconds(responseTimeout));
238             processCommunicator.addProcessListener(processListener);
239             this.processCommunicator = processCommunicator;
240
241             // ProcessCommunicationResponder provides responses to requests from KNX bus (Calimero).
242             // Note for KNX Secure: SAL to be provided
243             ProcessCommunicationResponder responseCommunicator = new ProcessCommunicationResponder(link,
244                     new SecureApplicationLayer(link, Security.defaultInstallation()));
245             this.responseCommunicator = responseCommunicator;
246
247             // register this class, callbacks will be triggered
248             link.addLinkListener(this);
249
250             // create a job carrying out read requests
251             busJob = knxScheduler.scheduleWithFixedDelay(() -> readNextQueuedDatapoint(), 0, readingPause,
252                     TimeUnit.MILLISECONDS);
253
254             statusUpdateCallback.updateStatus(ThingStatus.ONLINE);
255             connectJob = null;
256
257             logger.info("Bridge {} connected to KNX bus", thingUID);
258
259             state = ClientState.RUNNING;
260             return true;
261         } catch (InterruptedException e) {
262             final var lastState = state;
263             state = ClientState.INTERRUPTED;
264
265             logger.trace("Bridge {}, connection interrupted", thingUID);
266
267             disconnect(e);
268             if (lastState != ClientState.DISPOSE) {
269                 scheduleReconnectJob();
270             }
271
272             return false;
273         } catch (KNXException | KnxSecureException e) {
274             logger.debug("Bridge {} cannot connect: {}", thingUID, e.getMessage());
275             disconnect(e);
276             scheduleReconnectJob();
277             return false;
278         } catch (KNXIllegalArgumentException e) {
279             logger.debug("Bridge {} cannot connect: {}", thingUID, e.getMessage());
280             disconnect(e, Optional.of(ThingStatusDetail.CONFIGURATION_ERROR));
281             return false;
282         }
283     }
284
285     private void disconnect(@Nullable Exception e) {
286         disconnect(e, Optional.empty());
287     }
288
289     private synchronized void disconnect(@Nullable Exception e, Optional<ThingStatusDetail> detail) {
290         releaseConnection();
291         if (e != null) {
292             final String message = e.getLocalizedMessage();
293             statusUpdateCallback.updateStatus(ThingStatus.OFFLINE, detail.orElse(ThingStatusDetail.COMMUNICATION_ERROR),
294                     message != null ? message : "");
295         } else {
296             statusUpdateCallback.updateStatus(ThingStatus.OFFLINE);
297         }
298     }
299
300     @SuppressWarnings("null")
301     protected void releaseConnection() {
302         logger.debug("Bridge {} is disconnecting from KNX bus", thingUID);
303         var tmplink = link;
304         if (tmplink != null) {
305             link.removeLinkListener(this);
306         }
307         busJob = nullify(busJob, j -> j.cancel(true));
308         readDatapoints.clear();
309         responseCommunicator = nullify(responseCommunicator, rc -> {
310             rc.removeProcessListener(processListener);
311             rc.detach();
312         });
313         processCommunicator = nullify(processCommunicator, pc -> {
314             pc.removeProcessListener(processListener);
315             pc.detach();
316         });
317         deviceInfoClient = null;
318         managementClient = nullify(managementClient, mc -> mc.detach());
319         managementProcedures = nullify(managementProcedures, mp -> mp.detach());
320         link = nullify(link, l -> l.close());
321         logger.trace("Bridge {} disconnected from KNX bus", thingUID);
322     }
323
324     private <T> @Nullable T nullify(T target, @Nullable Consumer<T> lastWill) {
325         if (target != null && lastWill != null) {
326             lastWill.accept(target);
327         }
328         return null;
329     }
330
331     private void processEvent(String task, ProcessEvent event, ListenerNotification action) {
332         GroupAddress destination = event.getDestination();
333         IndividualAddress source = event.getSourceAddr();
334         byte[] asdu = event.getASDU();
335         logger.trace("Received a {} telegram from '{}' to '{}' with value '{}'", task, source, destination, asdu);
336         for (GroupAddressListener listener : groupAddressListeners) {
337             if (listener.listensTo(destination)) {
338                 knxScheduler.schedule(() -> action.apply(listener, source, destination, asdu), 0, TimeUnit.SECONDS);
339             }
340         }
341     }
342
343     /**
344      * Transforms a {@link Type} into a datapoint type value for the KNX bus.
345      *
346      * @param type the {@link Type} to transform
347      * @param dpt the datapoint type to which should be converted
348      * @return the corresponding KNX datapoint type value as a string
349      */
350     @Nullable
351     private String toDPTValue(Type type, String dpt) {
352         return typeHelper.toDPTValue(type, dpt);
353     }
354
355     // datapoint is null at end of the list, warning is misleading
356     @SuppressWarnings("null")
357     private void readNextQueuedDatapoint() {
358         if (!connectIfNotAutomatic()) {
359             return;
360         }
361         ProcessCommunicator processCommunicator = this.processCommunicator;
362         if (processCommunicator == null) {
363             return;
364         }
365         ReadDatapoint datapoint = readDatapoints.poll();
366         if (datapoint != null) {
367             datapoint.incrementRetries();
368             try {
369                 logger.trace("Sending a Group Read Request telegram for {}", datapoint.getDatapoint().getMainAddress());
370                 processCommunicator.read(datapoint.getDatapoint());
371             } catch (KNXException e) {
372                 // Note: KnxException does not cover KnxRuntimeException and subclasses KnxSecureException,
373                 // KnxIllegArgumentException
374                 if (datapoint.getRetries() < datapoint.getLimit()) {
375                     readDatapoints.add(datapoint);
376                     logger.debug("Could not read value for datapoint {}: {}. Going to retry.",
377                             datapoint.getDatapoint().getMainAddress(), e.getMessage());
378                 } else {
379                     logger.warn("Giving up reading datapoint {}, the number of maximum retries ({}) is reached.",
380                             datapoint.getDatapoint().getMainAddress(), datapoint.getLimit());
381                 }
382             } catch (InterruptedException | CancellationException e) {
383                 logger.debug("Interrupted sending KNX read request");
384                 return;
385             } catch (Exception e) {
386                 // Any other exception: Fail gracefully, i.e. notify user and continue reading next DP.
387                 // Not catching this would end the scheduled read for all DPs in case of an error.
388                 // Severity is warning as this is likely caused by a configuration error.
389                 logger.warn("Error reading datapoint {}: {}", datapoint.getDatapoint().getMainAddress(),
390                         e.getMessage());
391             }
392         }
393     }
394
395     public void dispose() {
396         state = ClientState.DISPOSE;
397
398         cancelReconnectJob();
399         disconnect(null);
400     }
401
402     @Override
403     public void linkClosed(@Nullable CloseEvent closeEvent) {
404         KNXNetworkLink link = this.link;
405         if (link == null || closeEvent == null) {
406             return;
407         }
408         if (!link.isOpen() && CloseEvent.USER_REQUEST != closeEvent.getInitiator()) {
409             statusUpdateCallback.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
410                     closeEvent.getReason());
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 }