2 * Copyright (c) 2010-2023 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.knx.internal.client;
15 import static org.openhab.binding.knx.internal.dpt.DPTUtil.NORMALIZED_DPT;
17 import java.time.Duration;
18 import java.util.Optional;
20 import java.util.concurrent.CancellationException;
21 import java.util.concurrent.CopyOnWriteArraySet;
22 import java.util.concurrent.LinkedBlockingQueue;
23 import java.util.concurrent.ScheduledExecutorService;
24 import java.util.concurrent.ScheduledFuture;
25 import java.util.concurrent.TimeUnit;
26 import java.util.function.Consumer;
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.openhab.binding.knx.internal.dpt.ValueEncoder;
31 import org.openhab.binding.knx.internal.handler.GroupAddressListener;
32 import org.openhab.binding.knx.internal.handler.KNXBridgeBaseThingHandler.CommandExtensionData;
33 import org.openhab.binding.knx.internal.i18n.KNXTranslationProvider;
34 import org.openhab.core.thing.ThingStatus;
35 import org.openhab.core.thing.ThingStatusDetail;
36 import org.openhab.core.thing.ThingUID;
37 import org.openhab.core.types.Type;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
41 import tuwien.auto.calimero.CloseEvent;
42 import tuwien.auto.calimero.DetachEvent;
43 import tuwien.auto.calimero.FrameEvent;
44 import tuwien.auto.calimero.GroupAddress;
45 import tuwien.auto.calimero.IndividualAddress;
46 import tuwien.auto.calimero.KNXException;
47 import tuwien.auto.calimero.KNXIllegalArgumentException;
48 import tuwien.auto.calimero.datapoint.CommandDP;
49 import tuwien.auto.calimero.datapoint.Datapoint;
50 import tuwien.auto.calimero.device.ProcessCommunicationResponder;
51 import tuwien.auto.calimero.link.KNXNetworkLink;
52 import tuwien.auto.calimero.link.NetworkLinkListener;
53 import tuwien.auto.calimero.mgmt.Destination;
54 import tuwien.auto.calimero.mgmt.ManagementClient;
55 import tuwien.auto.calimero.mgmt.ManagementClientImpl;
56 import tuwien.auto.calimero.mgmt.ManagementProcedures;
57 import tuwien.auto.calimero.mgmt.ManagementProceduresImpl;
58 import tuwien.auto.calimero.process.ProcessCommunication;
59 import tuwien.auto.calimero.process.ProcessCommunicator;
60 import tuwien.auto.calimero.process.ProcessCommunicatorImpl;
61 import tuwien.auto.calimero.process.ProcessEvent;
62 import tuwien.auto.calimero.process.ProcessListener;
63 import tuwien.auto.calimero.secure.KnxSecureException;
64 import tuwien.auto.calimero.secure.SecureApplicationLayer;
65 import tuwien.auto.calimero.secure.Security;
68 * KNX Client which encapsulates the communication with the KNX bus via the calimero libary.
70 * @author Simon Kaufmann - initial contribution and API.
74 public abstract class AbstractKNXClient implements NetworkLinkListener, KNXClient {
75 public enum ClientState {
82 private ClientState state = ClientState.INIT;
84 private static final int MAX_SEND_ATTEMPTS = 2;
86 private final Logger logger = LoggerFactory.getLogger(AbstractKNXClient.class);
88 private final ThingUID thingUID;
89 private final int responseTimeout;
90 private final int readingPause;
91 private final int autoReconnectPeriod;
92 private final int readRetriesLimit;
93 private final StatusUpdateCallback statusUpdateCallback;
94 private final ScheduledExecutorService knxScheduler;
95 private final CommandExtensionData commandExtensionData;
97 private @Nullable ProcessCommunicator processCommunicator;
98 private @Nullable ProcessCommunicationResponder responseCommunicator;
99 private @Nullable ManagementProcedures managementProcedures;
100 private @Nullable ManagementClient managementClient;
101 private @Nullable KNXNetworkLink link;
102 private @Nullable DeviceInfoClient deviceInfoClient;
103 private @Nullable ScheduledFuture<?> busJob;
104 private @Nullable ScheduledFuture<?> connectJob;
106 private final Set<GroupAddressListener> groupAddressListeners = new CopyOnWriteArraySet<>();
107 private final LinkedBlockingQueue<ReadDatapoint> readDatapoints = new LinkedBlockingQueue<>();
110 private interface ListenerNotification {
111 void apply(BusMessageListener listener, IndividualAddress source, GroupAddress destination, byte[] asdu);
114 @NonNullByDefault({})
115 private final ProcessListener processListener = new ProcessListener() {
118 public void detached(DetachEvent e) {
119 logger.debug("The KNX network link was detached from the process communicator");
123 public void groupWrite(ProcessEvent e) {
124 processEvent("Group Write", e, (listener, source, destination, asdu) -> listener
125 .onGroupWrite(AbstractKNXClient.this, source, destination, asdu));
129 public void groupReadRequest(ProcessEvent e) {
130 processEvent("Group Read Request", e, (listener, source, destination, asdu) -> listener
131 .onGroupRead(AbstractKNXClient.this, source, destination, asdu));
135 public void groupReadResponse(ProcessEvent e) {
136 processEvent("Group Read Response", e, (listener, source, destination, asdu) -> listener
137 .onGroupReadResponse(AbstractKNXClient.this, source, destination, asdu));
141 public AbstractKNXClient(int autoReconnectPeriod, ThingUID thingUID, int responseTimeout, int readingPause,
142 int readRetriesLimit, ScheduledExecutorService knxScheduler, CommandExtensionData commandExtensionData,
143 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 this.commandExtensionData = commandExtensionData;
154 public void initialize() {
158 private void 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);
168 private void cancelReconnectJob() {
169 final ScheduledFuture<?> currentReconnectJob = connectJob;
170 if (currentReconnectJob != null) {
171 currentReconnectJob.cancel(true);
176 protected abstract KNXNetworkLink establishConnection() throws KNXException, InterruptedException;
178 private synchronized boolean connectIfNotAutomatic() {
179 if (!isConnected()) {
180 return connectJob == null && connect();
185 private synchronized boolean connect() {
186 if (state == ClientState.INIT) {
187 state = ClientState.RUNNING;
188 } else if (state == ClientState.DISPOSE) {
189 logger.trace("connect() ignored, closing down");
197 // We have a valid "connection" object, this is ensured by IPClient.java.
198 // "releaseConnection" is actually removing all registered users of this connection and stopping
200 // Note that this will also kill this function in the following call to sleep in case of a
201 // connection loss -> restart is via triggered via scheduledReconnect in handler for InterruptedException.
204 logger.debug("Bridge {} is connecting to KNX bus", thingUID);
206 // now establish (possibly encrypted) connection, according to settings (tunnel, routing, secure...)
207 KNXNetworkLink link = establishConnection();
210 // ManagementProcedures provided by Calimero: allow managing other KNX devices, e.g. check if an address is
212 // Note for KNX Secure: ManagmentProcedueresImpl currently does not provide a ctor with external SAL,
213 // it internally creates an instance of ManagementClientImpl, which uses
214 // Security.defaultInstallation().deviceToolKeys()
215 // Protected ctor using given ManagementClientImpl is avalable (custom class to be inherited)
216 managementProcedures = new ManagementProceduresImpl(link);
218 // ManagementClient provided by Calimero: allow reading device info, etc.
219 // Note for KNX Secure: ManagementClientImpl does not provide a ctor with external SAL in Calimero 2.5,
220 // is uses global Security.defaultInstalltion().deviceToolKeys()
221 // Current main branch includes a protected ctor (custom class to be inherited)
222 // TODO Calimero>2.5: check if there is a new way to provide security info, there is a new protected ctor
223 // TODO check if we can avoid creating another ManagementClient and re-use this from ManagemntProcedures
224 ManagementClient managementClient = new ManagementClientImpl(link);
225 managementClient.responseTimeout(Duration.ofSeconds(responseTimeout));
226 this.managementClient = managementClient;
228 // OH helper for reading device info, based on managementClient above
229 deviceInfoClient = new DeviceInfoClientImpl(managementClient);
231 // ProcessCommunicator provides main KNX communication (Calimero).
232 // Note for KNX Secure: SAL to be provided
233 ProcessCommunicator processCommunicator = new ProcessCommunicatorImpl(link);
234 processCommunicator.responseTimeout(Duration.ofSeconds(responseTimeout));
235 processCommunicator.addProcessListener(processListener);
236 this.processCommunicator = processCommunicator;
238 // ProcessCommunicationResponder provides responses to requests from KNX bus (Calimero).
239 // Note for KNX Secure: SAL to be provided
240 this.responseCommunicator = new ProcessCommunicationResponder(link,
241 new SecureApplicationLayer(link, Security.defaultInstallation()));
243 // register this class, callbacks will be triggered
244 link.addLinkListener(this);
246 // create a job carrying out read requests
247 busJob = knxScheduler.scheduleWithFixedDelay(this::readNextQueuedDatapoint, 0, readingPause,
248 TimeUnit.MILLISECONDS);
250 statusUpdateCallback.updateStatus(ThingStatus.ONLINE);
253 logger.info("Bridge {} connected to KNX bus", thingUID);
255 state = ClientState.RUNNING;
257 } catch (InterruptedException e) {
258 ClientState lastState = state;
259 state = ClientState.INTERRUPTED;
261 logger.trace("Bridge {}, connection interrupted", thingUID);
264 if (lastState != ClientState.DISPOSE) {
265 scheduleReconnectJob();
269 } catch (KNXException | KnxSecureException e) {
270 logger.debug("Bridge {} cannot connect: {}", thingUID, e.getMessage());
272 scheduleReconnectJob();
274 } catch (KNXIllegalArgumentException e) {
275 logger.debug("Bridge {} cannot connect: {}", thingUID, e.getMessage());
276 disconnect(e, Optional.of(ThingStatusDetail.CONFIGURATION_ERROR));
281 private void disconnect(@Nullable Exception e) {
282 disconnect(e, Optional.empty());
285 private synchronized void disconnect(@Nullable Exception e, Optional<ThingStatusDetail> detail) {
288 statusUpdateCallback.updateStatus(ThingStatus.OFFLINE, detail.orElse(ThingStatusDetail.COMMUNICATION_ERROR),
289 KNXTranslationProvider.I18N.getLocalizedException(e));
291 statusUpdateCallback.updateStatus(ThingStatus.OFFLINE);
295 protected void releaseConnection() {
296 logger.debug("Bridge {} is disconnecting from KNX bus", thingUID);
298 if (tmplink != null) {
299 tmplink.removeLinkListener(this);
301 busJob = nullify(busJob, j -> j.cancel(true));
302 readDatapoints.clear();
303 responseCommunicator = nullify(responseCommunicator, rc -> {
304 rc.removeProcessListener(processListener);
307 processCommunicator = nullify(processCommunicator, pc -> {
308 pc.removeProcessListener(processListener);
311 deviceInfoClient = null;
312 managementClient = nullify(managementClient, ManagementClient::detach);
313 managementProcedures = nullify(managementProcedures, ManagementProcedures::detach);
314 link = nullify(link, KNXNetworkLink::close);
315 logger.trace("Bridge {} disconnected from KNX bus", thingUID);
318 private <T> @Nullable T nullify(@Nullable T target, @Nullable Consumer<T> lastWill) {
319 if (target != null && lastWill != null) {
320 lastWill.accept(target);
325 private void processEvent(String task, ProcessEvent event, ListenerNotification action) {
326 GroupAddress destination = event.getDestination();
327 IndividualAddress source = event.getSourceAddr();
328 byte[] asdu = event.getASDU();
329 logger.trace("Received a {} telegram from '{}' to '{}' with value '{}'", task, source, destination, asdu);
330 boolean isHandled = false;
331 for (GroupAddressListener listener : groupAddressListeners) {
332 if (listener.listensTo(destination)) {
334 knxScheduler.schedule(() -> action.apply(listener, source, destination, asdu), 0, TimeUnit.SECONDS);
337 // Store information about unhandled GAs, can be shown on console using knx:list-unknown-ga.
338 // The idea is to store GA, message type, and size as key. The value counts the number of packets.
340 logger.trace("Address '{}' is not configured in openHAB", destination);
341 final String type = switch (event.getServiceCode()) {
342 case 0x80 -> " GROUP_WRITE(";
343 case 0x40 -> " GROUP_RESPONSE(";
344 case 0x00 -> " GROUP_READ(";
347 final String key = destination.toString() + type + event.getASDU().length + ")";
348 commandExtensionData.unknownGA().compute(key, (k, v) -> v == null ? 1 : v + 1);
352 // datapoint is null at end of the list, warning is misleading
353 @SuppressWarnings("null")
354 private void readNextQueuedDatapoint() {
355 if (!connectIfNotAutomatic()) {
358 ProcessCommunicator processCommunicator = this.processCommunicator;
359 if (processCommunicator == null) {
362 ReadDatapoint datapoint = readDatapoints.poll();
363 if (datapoint != null) {
364 datapoint.incrementRetries();
366 logger.trace("Sending a Group Read Request telegram for {}", datapoint.getDatapoint().getMainAddress());
367 processCommunicator.read(datapoint.getDatapoint());
368 } catch (KNXException e) {
369 // Note: KnxException does not cover KnxRuntimeException and subclasses KnxSecureException,
370 // KnxIllegArgumentException
371 if (datapoint.getRetries() < datapoint.getLimit()) {
372 readDatapoints.add(datapoint);
373 logger.debug("Could not read value for datapoint {}: {}. Going to retry.",
374 datapoint.getDatapoint().getMainAddress(), e.getMessage());
376 logger.warn("Giving up reading datapoint {}, the number of maximum retries ({}) is reached.",
377 datapoint.getDatapoint().getMainAddress(), datapoint.getLimit());
379 } catch (InterruptedException | CancellationException e) {
380 logger.debug("Interrupted sending KNX read request");
381 } catch (Exception e) {
382 // Any other exception: Fail gracefully, i.e. notify user and continue reading next DP.
383 // Not catching this would end the scheduled read for all DPs in case of an error.
384 // Severity is warning as this is likely caused by a configuration error.
385 logger.warn("Error reading datapoint {}: {}", datapoint.getDatapoint().getMainAddress(),
391 public void dispose() {
392 state = ClientState.DISPOSE;
394 cancelReconnectJob();
399 public void linkClosed(@Nullable CloseEvent closeEvent) {
400 KNXNetworkLink link = this.link;
401 if (link == null || closeEvent == null) {
404 if (!link.isOpen() && CloseEvent.USER_REQUEST != closeEvent.getInitiator()) {
405 final String reason = closeEvent.getReason();
406 statusUpdateCallback.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
407 KNXTranslationProvider.I18N.get(reason));
408 logger.debug("KNX link has been lost (reason: {} on object {})", closeEvent.getReason(),
409 closeEvent.getSource().toString());
410 scheduleReconnectJob();
415 public void indication(@Nullable FrameEvent e) {
420 public void confirmation(@Nullable FrameEvent e) {
425 public final synchronized boolean isReachable(@Nullable IndividualAddress address) throws KNXException {
426 ManagementProcedures managementProcedures = this.managementProcedures;
427 if (managementProcedures == null || address == null) {
431 return managementProcedures.isAddressOccupied(address);
432 } catch (InterruptedException e) {
433 logger.debug("Interrupted pinging KNX device '{}'", address);
439 public final synchronized void restartNetworkDevice(@Nullable IndividualAddress address) {
440 ManagementClient managementClient = this.managementClient;
441 if (address == null || managementClient == null) {
444 Destination destination = null;
446 destination = managementClient.createDestination(address, true);
447 managementClient.restart(destination);
448 } catch (KNXException e) {
449 logger.warn("Could not reset device with address '{}': {}", address, e.getMessage());
450 } catch (InterruptedException e) { // ignored as in Calimero pre-2.4.0
452 if (destination != null) {
453 destination.destroy();
459 public void readDatapoint(Datapoint datapoint) {
460 synchronized (this) {
461 ReadDatapoint retryDatapoint = new ReadDatapoint(datapoint, readRetriesLimit);
462 if (!readDatapoints.contains(retryDatapoint)) {
463 readDatapoints.add(retryDatapoint);
469 public final void registerGroupAddressListener(GroupAddressListener listener) {
470 groupAddressListeners.add(listener);
474 public final void unregisterGroupAddressListener(GroupAddressListener listener) {
475 groupAddressListeners.remove(listener);
479 public boolean isConnected() {
480 KNXNetworkLink tmpLink = link;
481 return tmpLink != null && tmpLink.isOpen();
485 public DeviceInfoClient getDeviceInfoClient() {
486 DeviceInfoClient deviceInfoClient = this.deviceInfoClient;
487 if (deviceInfoClient != null) {
488 return deviceInfoClient;
490 throw new IllegalStateException();
495 public void writeToKNX(OutboundSpec commandSpec) throws KNXException {
496 ProcessCommunicator processCommunicator = this.processCommunicator;
497 KNXNetworkLink link = this.link;
498 if (processCommunicator == null || link == null) {
499 logger.debug("Cannot write to KNX bus (processCommunicator: {}, link: {})",
500 processCommunicator == null ? "Not OK" : "OK",
501 link == null ? "Not OK" : (link.isOpen() ? "Open" : "Closed"));
504 GroupAddress groupAddress = commandSpec.getGroupAddress();
506 logger.trace("writeToKNX groupAddress '{}', commandSpec '{}'", groupAddress, commandSpec);
508 sendToKNX(processCommunicator, groupAddress, commandSpec.getDPT(), commandSpec.getValue());
512 public void respondToKNX(OutboundSpec responseSpec) throws KNXException {
513 ProcessCommunicationResponder responseCommunicator = this.responseCommunicator;
514 KNXNetworkLink link = this.link;
515 if (responseCommunicator == null || link == null) {
516 logger.debug("Cannot write to KNX bus (responseCommunicator: {}, link: {})",
517 responseCommunicator == null ? "Not OK" : "OK",
518 link == null ? "Not OK" : (link.isOpen() ? "Open" : "Closed"));
521 GroupAddress groupAddress = responseSpec.getGroupAddress();
523 logger.trace("respondToKNX groupAddress '{}', responseSpec '{}'", groupAddress, responseSpec);
525 sendToKNX(responseCommunicator, groupAddress, responseSpec.getDPT(), responseSpec.getValue());
528 private void sendToKNX(ProcessCommunication communicator, GroupAddress groupAddress, String dpt, Type type)
529 throws KNXException {
530 if (!connectIfNotAutomatic()) {
534 Datapoint datapoint = new CommandDP(groupAddress, thingUID.toString(), 0,
535 NORMALIZED_DPT.getOrDefault(dpt, dpt));
536 String mappedValue = ValueEncoder.encode(type, dpt);
537 if (mappedValue == null) {
538 logger.debug("Value '{}' of type '{}' cannot be mapped to datapoint '{}'", type, type.getClass(),
542 logger.trace("sendToKNX mappedValue: '{}' groupAddress: '{}'", mappedValue, groupAddress);
544 for (int i = 0;; i++) {
546 communicator.write(datapoint, mappedValue);
547 logger.debug("Wrote value '{}' to datapoint '{}' ({}. attempt).", type, datapoint, i);
549 } catch (KNXException e) {
550 if (i < MAX_SEND_ATTEMPTS - 1) {
551 logger.debug("Value '{}' could not be sent to KNX bus using datapoint '{}': {}. Will retry.", type,
552 datapoint, e.getLocalizedMessage());
554 logger.warn("Value '{}' could not be sent to KNX bus using datapoint '{}': {}. Giving up now.",
555 type, datapoint, e.getLocalizedMessage());