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 java.time.Duration;
16 import java.util.Optional;
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;
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;
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;
66 * KNX Client which encapsulates the communication with the KNX bus via the calimero libary.
68 * @author Simon Kaufmann - initial contribution and API.
72 public abstract class AbstractKNXClient implements NetworkLinkListener, KNXClient {
73 public enum ClientState {
80 private ClientState state = ClientState.INIT;
82 private static final int MAX_SEND_ATTEMPTS = 2;
84 private final Logger logger = LoggerFactory.getLogger(AbstractKNXClient.class);
85 private final KNXTypeMapper typeHelper = new KNXCoreTypeMapper();
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;
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;
104 private final Set<GroupAddressListener> groupAddressListeners = new CopyOnWriteArraySet<>();
105 private final LinkedBlockingQueue<ReadDatapoint> readDatapoints = new LinkedBlockingQueue<>();
108 private interface ListenerNotification {
109 void apply(BusMessageListener listener, IndividualAddress source, GroupAddress destination, byte[] asdu);
112 @NonNullByDefault({})
113 private final ProcessListener processListener = new ProcessListener() {
116 public void detached(DetachEvent e) {
117 logger.debug("The KNX network link was detached from the process communicator");
121 public void groupWrite(ProcessEvent e) {
122 processEvent("Group Write", e, (listener, source, destination, asdu) -> {
123 listener.onGroupWrite(AbstractKNXClient.this, source, destination, asdu);
128 public void groupReadRequest(ProcessEvent e) {
129 processEvent("Group Read Request", e, (listener, source, destination, asdu) -> {
130 listener.onGroupRead(AbstractKNXClient.this, source, destination, asdu);
135 public void groupReadResponse(ProcessEvent e) {
136 processEvent("Group Read Response", e, (listener, source, destination, asdu) -> {
137 listener.onGroupReadResponse(AbstractKNXClient.this, source, destination, asdu);
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;
153 public void initialize() {
154 if (!scheduleReconnectJob()) {
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);
172 private void cancelReconnectJob() {
173 final ScheduledFuture<?> currentReconnectJob = connectJob;
174 if (currentReconnectJob != null) {
175 currentReconnectJob.cancel(true);
180 protected abstract KNXNetworkLink establishConnection() throws KNXException, InterruptedException;
182 private synchronized boolean connectIfNotAutomatic() {
183 if (!isConnected()) {
184 return connectJob != null ? false : connect();
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");
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
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.
208 logger.debug("Bridge {} is connecting to KNX bus", thingUID);
210 // now establish (possibly encrypted) connection, according to settings (tunnel, routing, secure...)
211 KNXNetworkLink link = establishConnection();
214 // ManagementProcedures provided by Calimero: allow managing other KNX devices, e.g. check if an address is
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);
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;
232 // OH helper for reading device info, based on managementClient above
233 deviceInfoClient = new DeviceInfoClientImpl(managementClient);
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;
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;
248 // register this class, callbacks will be triggered
249 link.addLinkListener(this);
251 // create a job carrying out read requests
252 busJob = knxScheduler.scheduleWithFixedDelay(() -> readNextQueuedDatapoint(), 0, readingPause,
253 TimeUnit.MILLISECONDS);
255 statusUpdateCallback.updateStatus(ThingStatus.ONLINE);
258 logger.info("Bridge {} connected to KNX bus", thingUID);
260 state = ClientState.RUNNING;
262 } catch (InterruptedException e) {
263 final var lastState = state;
264 state = ClientState.INTERRUPTED;
266 logger.trace("Bridge {}, connection interrupted", thingUID);
269 if (lastState != ClientState.DISPOSE) {
270 scheduleReconnectJob();
274 } catch (KNXException | KnxSecureException e) {
275 logger.debug("Bridge {} cannot connect: {}", thingUID, e.getMessage());
277 scheduleReconnectJob();
279 } catch (KNXIllegalArgumentException e) {
280 logger.debug("Bridge {} cannot connect: {}", thingUID, e.getMessage());
281 disconnect(e, Optional.of(ThingStatusDetail.CONFIGURATION_ERROR));
286 private void disconnect(@Nullable Exception e) {
287 disconnect(e, Optional.empty());
290 private synchronized void disconnect(@Nullable Exception e, Optional<ThingStatusDetail> detail) {
293 statusUpdateCallback.updateStatus(ThingStatus.OFFLINE, detail.orElse(ThingStatusDetail.COMMUNICATION_ERROR),
294 KNXTranslationProvider.I18N.getLocalizedException(e));
296 statusUpdateCallback.updateStatus(ThingStatus.OFFLINE);
300 protected void releaseConnection() {
301 logger.debug("Bridge {} is disconnecting from KNX bus", thingUID);
303 if (tmplink != null) {
304 tmplink.removeLinkListener(this);
306 busJob = nullify(busJob, j -> j.cancel(true));
307 readDatapoints.clear();
308 responseCommunicator = nullify(responseCommunicator, rc -> {
309 rc.removeProcessListener(processListener);
312 processCommunicator = nullify(processCommunicator, pc -> {
313 pc.removeProcessListener(processListener);
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);
323 private <T> @Nullable T nullify(@Nullable T target, @Nullable Consumer<T> lastWill) {
324 if (target != null && lastWill != null) {
325 lastWill.accept(target);
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);
343 * Transforms a {@link Type} into a datapoint type value for the KNX bus.
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
350 private String toDPTValue(Type type, String dpt) {
351 return typeHelper.toDPTValue(type, dpt);
354 // datapoint is null at end of the list, warning is misleading
355 @SuppressWarnings("null")
356 private void readNextQueuedDatapoint() {
357 if (!connectIfNotAutomatic()) {
360 ProcessCommunicator processCommunicator = this.processCommunicator;
361 if (processCommunicator == null) {
364 ReadDatapoint datapoint = readDatapoints.poll();
365 if (datapoint != null) {
366 datapoint.incrementRetries();
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());
378 logger.warn("Giving up reading datapoint {}, the number of maximum retries ({}) is reached.",
379 datapoint.getDatapoint().getMainAddress(), datapoint.getLimit());
381 } catch (InterruptedException | CancellationException e) {
382 logger.debug("Interrupted sending KNX read request");
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(),
394 public void dispose() {
395 state = ClientState.DISPOSE;
397 cancelReconnectJob();
402 public void linkClosed(@Nullable CloseEvent closeEvent) {
403 KNXNetworkLink link = this.link;
404 if (link == null || closeEvent == null) {
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();
418 public void indication(@Nullable FrameEvent e) {
423 public void confirmation(@Nullable FrameEvent e) {
428 public final synchronized boolean isReachable(@Nullable IndividualAddress address) throws KNXException {
429 ManagementProcedures managementProcedures = this.managementProcedures;
430 if (managementProcedures == null || address == null) {
434 return managementProcedures.isAddressOccupied(address);
435 } catch (InterruptedException e) {
436 logger.debug("Interrupted pinging KNX device '{}'", address);
442 public final synchronized void restartNetworkDevice(@Nullable IndividualAddress address) {
443 ManagementClient managementClient = this.managementClient;
444 if (address == null || managementClient == null) {
447 Destination destination = null;
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
455 if (destination != null) {
456 destination.destroy();
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);
472 public final boolean registerGroupAddressListener(GroupAddressListener listener) {
473 return groupAddressListeners.add(listener);
477 public final boolean unregisterGroupAddressListener(GroupAddressListener listener) {
478 return groupAddressListeners.remove(listener);
482 public boolean isConnected() {
483 final var tmpLink = link;
484 return tmpLink != null && tmpLink.isOpen();
488 public DeviceInfoClient getDeviceInfoClient() {
489 DeviceInfoClient deviceInfoClient = this.deviceInfoClient;
490 if (deviceInfoClient != null) {
491 return deviceInfoClient;
493 throw new IllegalStateException();
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"));
507 GroupAddress groupAddress = commandSpec.getGroupAddress();
509 logger.trace("writeToKNX groupAddress '{}', commandSpec '{}'", groupAddress, commandSpec);
511 if (groupAddress != null) {
512 sendToKNX(processCommunicator, link, groupAddress, commandSpec.getDPT(), commandSpec.getType());
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"));
526 GroupAddress groupAddress = responseSpec.getGroupAddress();
528 logger.trace("respondToKNX groupAddress '{}', responseSpec '{}'", groupAddress, responseSpec);
530 if (groupAddress != null) {
531 sendToKNX(responseCommunicator, link, groupAddress, responseSpec.getDPT(), responseSpec.getType());
535 private void sendToKNX(ProcessCommunication communicator, KNXNetworkLink link, GroupAddress groupAddress,
536 String dpt, Type type) throws KNXException {
537 if (!connectIfNotAutomatic()) {
541 Datapoint datapoint = new CommandDP(groupAddress, thingUID.toString(), 0, dpt);
542 String mappedValue = toDPTValue(type, dpt);
544 logger.trace("sendToKNX mappedValue: '{}' groupAddress: '{}'", mappedValue, groupAddress);
546 if (mappedValue == null) {
547 logger.debug("Value '{}' cannot be mapped to datapoint '{}'", type, datapoint);
550 for (int i = 0; i < MAX_SEND_ATTEMPTS; i++) {
552 communicator.write(datapoint, mappedValue);
553 logger.debug("Wrote value '{}' to datapoint '{}' ({}. attempt).", type, datapoint, i);
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());
560 logger.warn("Value '{}' could not be sent to KNX bus using datapoint '{}': {}. Giving up now.",
561 type, datapoint, e.getLocalizedMessage());