2 * Copyright (c) 2010-2020 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;
16 import java.util.concurrent.CopyOnWriteArraySet;
17 import java.util.concurrent.LinkedBlockingQueue;
18 import java.util.concurrent.ScheduledExecutorService;
19 import java.util.concurrent.ScheduledFuture;
20 import java.util.concurrent.TimeUnit;
21 import java.util.function.Consumer;
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.openhab.binding.knx.internal.KNXTypeMapper;
26 import org.openhab.binding.knx.internal.dpt.KNXCoreTypeMapper;
27 import org.openhab.binding.knx.internal.handler.GroupAddressListener;
28 import org.openhab.core.thing.ThingStatus;
29 import org.openhab.core.thing.ThingStatusDetail;
30 import org.openhab.core.thing.ThingUID;
31 import org.openhab.core.types.Type;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
35 import tuwien.auto.calimero.CloseEvent;
36 import tuwien.auto.calimero.DetachEvent;
37 import tuwien.auto.calimero.FrameEvent;
38 import tuwien.auto.calimero.GroupAddress;
39 import tuwien.auto.calimero.IndividualAddress;
40 import tuwien.auto.calimero.KNXException;
41 import tuwien.auto.calimero.datapoint.CommandDP;
42 import tuwien.auto.calimero.datapoint.Datapoint;
43 import tuwien.auto.calimero.device.ProcessCommunicationResponder;
44 import tuwien.auto.calimero.link.KNXNetworkLink;
45 import tuwien.auto.calimero.link.NetworkLinkListener;
46 import tuwien.auto.calimero.mgmt.Destination;
47 import tuwien.auto.calimero.mgmt.ManagementClient;
48 import tuwien.auto.calimero.mgmt.ManagementClientImpl;
49 import tuwien.auto.calimero.mgmt.ManagementProcedures;
50 import tuwien.auto.calimero.mgmt.ManagementProceduresImpl;
51 import tuwien.auto.calimero.process.ProcessCommunicationBase;
52 import tuwien.auto.calimero.process.ProcessCommunicator;
53 import tuwien.auto.calimero.process.ProcessCommunicatorImpl;
54 import tuwien.auto.calimero.process.ProcessEvent;
55 import tuwien.auto.calimero.process.ProcessListener;
58 * KNX Client which encapsulates the communication with the KNX bus via the calimero libary.
60 * @author Simon Kaufmann - initial contribution and API.
64 public abstract class AbstractKNXClient implements NetworkLinkListener, KNXClient {
66 private static final int MAX_SEND_ATTEMPTS = 2;
68 private final Logger logger = LoggerFactory.getLogger(AbstractKNXClient.class);
69 private final KNXTypeMapper typeHelper = new KNXCoreTypeMapper();
71 private final ThingUID thingUID;
72 private final int responseTimeout;
73 private final int readingPause;
74 private final int autoReconnectPeriod;
75 private final int readRetriesLimit;
76 private final StatusUpdateCallback statusUpdateCallback;
77 private final ScheduledExecutorService knxScheduler;
79 private @Nullable ProcessCommunicator processCommunicator;
80 private @Nullable ProcessCommunicationResponder responseCommunicator;
81 private @Nullable ManagementProcedures managementProcedures;
82 private @Nullable ManagementClient managementClient;
83 private @Nullable KNXNetworkLink link;
84 private @Nullable DeviceInfoClient deviceInfoClient;
85 private @Nullable ScheduledFuture<?> busJob;
86 private @Nullable ScheduledFuture<?> connectJob;
88 private final Set<GroupAddressListener> groupAddressListeners = new CopyOnWriteArraySet<>();
89 private final LinkedBlockingQueue<ReadDatapoint> readDatapoints = new LinkedBlockingQueue<>();
92 private interface ListenerNotification {
93 void apply(BusMessageListener listener, IndividualAddress source, GroupAddress destination, byte[] asdu);
97 private final ProcessListener processListener = new ProcessListener() {
100 public void detached(DetachEvent e) {
101 logger.debug("The KNX network link was detached from the process communicator");
105 public void groupWrite(ProcessEvent e) {
106 processEvent("Group Write", e, (listener, source, destination, asdu) -> {
107 listener.onGroupWrite(AbstractKNXClient.this, source, destination, asdu);
112 public void groupReadRequest(ProcessEvent e) {
113 processEvent("Group Read Request", e, (listener, source, destination, asdu) -> {
114 listener.onGroupRead(AbstractKNXClient.this, source, destination, asdu);
119 public void groupReadResponse(ProcessEvent e) {
120 processEvent("Group Read Response", e, (listener, source, destination, asdu) -> {
121 listener.onGroupReadResponse(AbstractKNXClient.this, source, destination, asdu);
126 public AbstractKNXClient(int autoReconnectPeriod, ThingUID thingUID, int responseTimeout, int readingPause,
127 int readRetriesLimit, ScheduledExecutorService knxScheduler, StatusUpdateCallback statusUpdateCallback) {
128 this.autoReconnectPeriod = autoReconnectPeriod;
129 this.thingUID = thingUID;
130 this.responseTimeout = responseTimeout;
131 this.readingPause = readingPause;
132 this.readRetriesLimit = readRetriesLimit;
133 this.knxScheduler = knxScheduler;
134 this.statusUpdateCallback = statusUpdateCallback;
137 public void initialize() {
138 if (!scheduleReconnectJob()) {
143 private boolean scheduleReconnectJob() {
144 if (autoReconnectPeriod > 0) {
145 connectJob = knxScheduler.schedule(this::connect, autoReconnectPeriod, TimeUnit.SECONDS);
152 private void cancelReconnectJob() {
153 ScheduledFuture<?> currentReconnectJob = connectJob;
154 if (currentReconnectJob != null) {
155 currentReconnectJob.cancel(true);
160 protected abstract KNXNetworkLink establishConnection() throws KNXException, InterruptedException;
162 private synchronized boolean connectIfNotAutomatic() {
163 if (!isConnected()) {
164 return connectJob != null ? false : connect();
169 private synchronized boolean connect() {
176 logger.debug("Bridge {} is connecting to the KNX bus", thingUID);
178 KNXNetworkLink link = establishConnection();
181 managementProcedures = new ManagementProceduresImpl(link);
183 ManagementClient managementClient = new ManagementClientImpl(link);
184 managementClient.setResponseTimeout(responseTimeout);
185 this.managementClient = managementClient;
187 deviceInfoClient = new DeviceInfoClientImpl(managementClient);
189 ProcessCommunicator processCommunicator = new ProcessCommunicatorImpl(link);
190 processCommunicator.setResponseTimeout(responseTimeout);
191 processCommunicator.addProcessListener(processListener);
192 this.processCommunicator = processCommunicator;
194 ProcessCommunicationResponder responseCommunicator = new ProcessCommunicationResponder(link);
195 this.responseCommunicator = responseCommunicator;
197 link.addLinkListener(this);
199 busJob = knxScheduler.scheduleWithFixedDelay(() -> readNextQueuedDatapoint(), 0, readingPause,
200 TimeUnit.MILLISECONDS);
202 statusUpdateCallback.updateStatus(ThingStatus.ONLINE);
205 } catch (KNXException | InterruptedException e) {
206 logger.debug("Error connecting to the bus: {}", e.getMessage(), e);
208 scheduleReconnectJob();
213 private void disconnect(@Nullable Exception e) {
216 String message = e.getLocalizedMessage();
217 statusUpdateCallback.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
218 message != null ? message : "");
220 statusUpdateCallback.updateStatus(ThingStatus.OFFLINE);
224 @SuppressWarnings("null")
225 private void releaseConnection() {
226 logger.debug("Bridge {} is disconnecting from the KNX bus", thingUID);
227 readDatapoints.clear();
228 busJob = nullify(busJob, j -> j.cancel(true));
229 deviceInfoClient = null;
230 managementProcedures = nullify(managementProcedures, mp -> mp.detach());
231 managementClient = nullify(managementClient, mc -> mc.detach());
232 link = nullify(link, l -> l.close());
233 processCommunicator = nullify(processCommunicator, pc -> {
234 pc.removeProcessListener(processListener);
237 responseCommunicator = nullify(responseCommunicator, rc -> {
238 rc.removeProcessListener(processListener);
243 private <T> T nullify(T target, @Nullable Consumer<T> lastWill) {
244 if (target != null && lastWill != null) {
245 lastWill.accept(target);
250 private void processEvent(String task, ProcessEvent event, ListenerNotification action) {
251 GroupAddress destination = event.getDestination();
252 IndividualAddress source = event.getSourceAddr();
253 byte[] asdu = event.getASDU();
254 logger.trace("Received a {} telegram from '{}' to '{}' with value '{}'", task, source, destination, asdu);
255 for (GroupAddressListener listener : groupAddressListeners) {
256 if (listener.listensTo(destination)) {
257 knxScheduler.schedule(() -> action.apply(listener, source, destination, asdu), 0, TimeUnit.SECONDS);
263 * Transforms a {@link Type} into a datapoint type value for the KNX bus.
265 * @param type the {@link Type} to transform
266 * @param dpt the datapoint type to which should be converted
267 * @return the corresponding KNX datapoint type value as a string
270 private String toDPTValue(Type type, String dpt) {
271 return typeHelper.toDPTValue(type, dpt);
274 @SuppressWarnings("null")
275 private void readNextQueuedDatapoint() {
276 if (!connectIfNotAutomatic()) {
279 ProcessCommunicator processCommunicator = this.processCommunicator;
280 if (processCommunicator == null) {
283 ReadDatapoint datapoint = readDatapoints.poll();
284 if (datapoint != null) {
285 datapoint.incrementRetries();
287 logger.trace("Sending a Group Read Request telegram for {}", datapoint.getDatapoint().getMainAddress());
288 processCommunicator.read(datapoint.getDatapoint());
289 } catch (KNXException e) {
290 if (datapoint.getRetries() < datapoint.getLimit()) {
291 readDatapoints.add(datapoint);
292 logger.debug("Could not read value for datapoint {}: {}. Going to retry.",
293 datapoint.getDatapoint().getMainAddress(), e.getMessage());
295 logger.warn("Giving up reading datapoint {}, the number of maximum retries ({}) is reached.",
296 datapoint.getDatapoint().getMainAddress(), datapoint.getLimit());
298 } catch (InterruptedException e) {
299 logger.debug("Interrupted sending KNX read request");
305 public void dispose() {
306 cancelReconnectJob();
311 public void linkClosed(@Nullable CloseEvent closeEvent) {
312 KNXNetworkLink link = this.link;
313 if (link == null || closeEvent == null) {
316 if (!link.isOpen() && CloseEvent.USER_REQUEST != closeEvent.getInitiator()) {
317 statusUpdateCallback.updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
318 closeEvent.getReason());
319 logger.debug("KNX link has been lost (reason: {} on object {})", closeEvent.getReason(),
320 closeEvent.getSource().toString());
321 scheduleReconnectJob();
326 public void indication(@Nullable FrameEvent e) {
331 public void confirmation(@Nullable FrameEvent e) {
336 public final synchronized boolean isReachable(@Nullable IndividualAddress address) throws KNXException {
337 ManagementProcedures managementProcedures = this.managementProcedures;
338 if (managementProcedures == null || address == null) {
342 return managementProcedures.isAddressOccupied(address);
343 } catch (InterruptedException e) {
344 logger.debug("Interrupted pinging KNX device '{}'", address);
350 public final synchronized void restartNetworkDevice(@Nullable IndividualAddress address) {
351 ManagementClient managementClient = this.managementClient;
352 if (address == null || managementClient == null) {
355 Destination destination = null;
357 destination = managementClient.createDestination(address, true);
358 managementClient.restart(destination);
359 } catch (KNXException e) {
360 logger.warn("Could not reset device with address '{}': {}", address, e.getMessage());
361 } catch (InterruptedException e) { // ignored as in Calimero pre-2.4.0
363 if (destination != null) {
364 destination.destroy();
370 public void readDatapoint(Datapoint datapoint) {
371 synchronized (this) {
372 ReadDatapoint retryDatapoint = new ReadDatapoint(datapoint, readRetriesLimit);
373 if (!readDatapoints.contains(retryDatapoint)) {
374 readDatapoints.add(retryDatapoint);
380 public final boolean registerGroupAddressListener(GroupAddressListener listener) {
381 return groupAddressListeners.add(listener);
385 public final boolean unregisterGroupAddressListener(GroupAddressListener listener) {
386 return groupAddressListeners.remove(listener);
390 public boolean isConnected() {
391 return link != null && link.isOpen();
395 public DeviceInfoClient getDeviceInfoClient() {
396 DeviceInfoClient deviceInfoClient = this.deviceInfoClient;
397 if (deviceInfoClient != null) {
398 return deviceInfoClient;
400 throw new IllegalStateException();
405 public void writeToKNX(OutboundSpec commandSpec) throws KNXException {
406 ProcessCommunicator processCommunicator = this.processCommunicator;
407 KNXNetworkLink link = this.link;
408 if (processCommunicator == null || link == null) {
409 logger.debug("Cannot write to the KNX bus (processCommuicator: {}, link: {})",
410 processCommunicator == null ? "Not OK" : "OK",
411 link == null ? "Not OK" : (link.isOpen() ? "Open" : "Closed"));
414 GroupAddress groupAddress = commandSpec.getGroupAddress();
416 logger.trace("writeToKNX groupAddress '{}', commandSpec '{}'", groupAddress, commandSpec);
418 if (groupAddress != null) {
419 sendToKNX(processCommunicator, link, groupAddress, commandSpec.getDPT(), commandSpec.getType());
424 public void respondToKNX(OutboundSpec responseSpec) throws KNXException {
425 ProcessCommunicationResponder responseCommunicator = this.responseCommunicator;
426 KNXNetworkLink link = this.link;
427 if (responseCommunicator == null || link == null) {
428 logger.debug("Cannot write to the KNX bus (responseCommunicator: {}, link: {})",
429 responseCommunicator == null ? "Not OK" : "OK",
430 link == null ? "Not OK" : (link.isOpen() ? "Open" : "Closed"));
433 GroupAddress groupAddress = responseSpec.getGroupAddress();
435 logger.trace("respondToKNX groupAddress '{}', responseSpec '{}'", groupAddress, responseSpec);
437 if (groupAddress != null) {
438 sendToKNX(responseCommunicator, link, groupAddress, responseSpec.getDPT(), responseSpec.getType());
442 private void sendToKNX(ProcessCommunicationBase communicator, KNXNetworkLink link, GroupAddress groupAddress,
443 String dpt, Type type) throws KNXException {
444 if (!connectIfNotAutomatic()) {
448 Datapoint datapoint = new CommandDP(groupAddress, thingUID.toString(), 0, dpt);
449 String mappedValue = toDPTValue(type, dpt);
451 logger.trace("sendToKNX mappedValue: '{}' groupAddress: '{}'", mappedValue, groupAddress);
453 if (mappedValue == null) {
454 logger.debug("Value '{}' cannot be mapped to datapoint '{}'", type, datapoint);
457 for (int i = 0; i < MAX_SEND_ATTEMPTS; i++) {
459 communicator.write(datapoint, mappedValue);
460 logger.debug("Wrote value '{}' to datapoint '{}' ({}. attempt).", type, datapoint, i);
462 } catch (KNXException e) {
463 if (i < MAX_SEND_ATTEMPTS - 1) {
464 logger.debug("Value '{}' could not be sent to the KNX bus using datapoint '{}': {}. Will retry.",
465 type, datapoint, e.getLocalizedMessage());
467 logger.warn("Value '{}' could not be sent to the KNX bus using datapoint '{}': {}. Giving up now.",
468 type, datapoint, e.getLocalizedMessage());