2 * Copyright (c) 2010-2024 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.util.concurrent.CompletableFuture;
16 import java.util.concurrent.ExecutionException;
17 import java.util.concurrent.ScheduledExecutorService;
18 import java.util.concurrent.TimeUnit;
19 import java.util.concurrent.TimeoutException;
20 import java.util.stream.Collectors;
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.openhab.binding.knx.internal.handler.KNXBridgeBaseThingHandler.CommandExtensionData;
24 import org.openhab.core.io.transport.serial.SerialPortIdentifier;
25 import org.openhab.core.io.transport.serial.SerialPortManager;
26 import org.openhab.core.thing.ThingUID;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
30 import tuwien.auto.calimero.Connection.BlockingMode;
31 import tuwien.auto.calimero.KNXException;
32 import tuwien.auto.calimero.link.KNXNetworkLink;
33 import tuwien.auto.calimero.link.KNXNetworkLinkFT12;
34 import tuwien.auto.calimero.link.medium.TPSettings;
35 import tuwien.auto.calimero.serial.FT12Connection;
38 * Serial specific {@link AbstractKNXClient} implementation.
40 * @author Simon Kaufmann - initial contribution and API.
44 public class SerialClient extends AbstractKNXClient {
46 private static final String CALIMERO_ERROR_CANNOT_OPEN_PORT = "failed to open serial port";
48 private final Logger logger = LoggerFactory.getLogger(SerialClient.class);
50 private final SerialPortManager serialPortManager;
51 private final String serialPort;
52 private final boolean useCemi;
54 public SerialClient(int autoReconnectPeriod, ThingUID thingUID, int responseTimeout, int readingPause,
55 int readRetriesLimit, ScheduledExecutorService knxScheduler, String serialPort, boolean useCemi,
56 SerialPortManager serialPortManager, CommandExtensionData commandExtensionData,
57 StatusUpdateCallback statusUpdateCallback) {
58 super(autoReconnectPeriod, thingUID, responseTimeout, readingPause, readRetriesLimit, knxScheduler,
59 commandExtensionData, statusUpdateCallback);
60 this.serialPortManager = serialPortManager;
61 this.serialPort = serialPort;
62 this.useCemi = useCemi;
66 * try automatic detection of cEMI devices via the PEI identification frame
68 * @implNote This is based on an vendor specific extension and may not work for other devices.
70 protected boolean detectCemi() throws InterruptedException {
71 final byte[] peiIdentifyReqFrame = { (byte) 0xa7 };
72 final byte peiIdentifyCon = (byte) 0xa8;
73 final byte peiWzIdentFrameLength = 11;
75 logger.trace("Checking for cEMI support");
77 try (FT12Connection serialConnection = new FT12Connection(serialPort)) {
78 final CompletableFuture<byte[]> frameListener = new CompletableFuture<>();
79 serialConnection.addConnectionListener(frameReceived -> {
80 final byte[] content = frameReceived.getFrameBytes();
81 if ((content.length > 0) && (content[0] == peiIdentifyCon)) {
82 logger.trace("Received PEI confirmation of {} bytes", content.length);
83 frameListener.complete(content);
87 serialConnection.send(peiIdentifyReqFrame, BlockingMode.NonBlocking);
88 byte[] content = frameListener.get(1, TimeUnit.SECONDS);
90 if (peiWzIdentFrameLength == content.length) {
91 // standard emi2 frame contain 9 bytes,
92 // content[1..2] physical address
93 // content[3..8] serial no
95 // Weinzierl adds 2 extra bytes, 0x0004 for capability cEMI,
96 // see "Weinzierl KNX BAOS Starter Kit, User Guide"
97 if (0 == content[9] && 4 == content[10]) {
98 logger.debug("Detected device with cEMI support");
102 } catch (final ExecutionException | TimeoutException | KNXException na) {
103 if (logger.isTraceEnabled()) {
104 logger.trace("Exception detecting cEMI: ", na);
108 logger.trace("Did not detect device with cEMI support");
113 protected KNXNetworkLink establishConnection() throws KNXException, InterruptedException {
115 boolean useCemiL = useCemi;
117 useCemiL = detectCemi();
119 logger.debug("Establishing connection to KNX bus through FT1.2 on serial port {}{}{}", serialPort,
120 (useCemiL ? " using cEMI" : ""), ((useCemiL != useCemi) ? " (autodetected)" : ""));
121 // CEMI support by Calimero library, useful for newer serial devices like KNX RF sticks, kBerry,
122 // etc.; default is still old EMI frame format
124 return KNXNetworkLinkFT12.newCemiLink(serialPort, new TPSettings());
127 return new KNXNetworkLinkFT12(serialPort, new TPSettings());
129 } catch (NoClassDefFoundError e) {
130 throw new KNXException(
131 "The serial FT1.2 KNX connection requires the serial libraries to be available, but they could not be found!",
133 } catch (KNXException e) {
134 final String msg = e.getMessage();
135 // TODO add a test for this string match; error message might change in later version of Calimero library
136 if ((msg != null) && (msg.startsWith(CALIMERO_ERROR_CANNOT_OPEN_PORT))) {
137 String availablePorts = serialPortManager.getIdentifiers().map(SerialPortIdentifier::getName)
138 .collect(Collectors.joining("\n"));
139 if (!availablePorts.isEmpty()) {
140 availablePorts = " Available ports are:\n" + availablePorts;
142 throw new KNXException("Serial port '" + serialPort + "' could not be opened." + availablePorts);