]> git.basschouten.com Git - openhab-addons.git/blob
7d0af16f9b3acebe04c2c34891b0c3408dd51e98
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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.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;
21
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;
29
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;
36
37 /**
38  * Serial specific {@link AbstractKNXClient} implementation.
39  *
40  * @author Simon Kaufmann - initial contribution and API.
41  *
42  */
43 @NonNullByDefault
44 public class SerialClient extends AbstractKNXClient {
45
46     private static final String CALIMERO_ERROR_CANNOT_OPEN_PORT = "failed to open serial port";
47
48     private final Logger logger = LoggerFactory.getLogger(SerialClient.class);
49
50     private final SerialPortManager serialPortManager;
51     private final String serialPort;
52     private final boolean useCemi;
53
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;
63     }
64
65     /**
66      * try automatic detection of cEMI devices via the PEI identification frame
67      *
68      * @implNote This is based on an vendor specific extension and may not work for other devices.
69      */
70     protected boolean detectCemi() throws InterruptedException {
71         final byte[] peiIdentifyReqFrame = { (byte) 0xa7 };
72         final byte peiIdentifyCon = (byte) 0xa8;
73         final byte peiWzIdentFrameLength = 11;
74
75         logger.trace("Checking for cEMI support");
76
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);
84                 }
85             });
86
87             serialConnection.send(peiIdentifyReqFrame, BlockingMode.NonBlocking);
88             byte[] content = frameListener.get(1, TimeUnit.SECONDS);
89
90             if (peiWzIdentFrameLength == content.length) {
91                 // standard emi2 frame contain 9 bytes,
92                 // content[1..2] physical address
93                 // content[3..8] serial no
94                 //
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");
99                     return true;
100                 }
101             }
102         } catch (final ExecutionException | TimeoutException | KNXException na) {
103             if (logger.isTraceEnabled()) {
104                 logger.trace("Exception detecting cEMI: ", na);
105             }
106         }
107
108         logger.trace("Did not detect device with cEMI support");
109         return false;
110     }
111
112     @Override
113     protected KNXNetworkLink establishConnection() throws KNXException, InterruptedException {
114         try {
115             boolean useCemiL = useCemi;
116             if (!useCemiL) {
117                 useCemiL = detectCemi();
118             }
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
123             if (useCemiL) {
124                 return KNXNetworkLinkFT12.newCemiLink(serialPort, new TPSettings());
125             }
126
127             return new KNXNetworkLinkFT12(serialPort, new TPSettings());
128
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!",
132                     e);
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;
141                 }
142                 throw new KNXException("Serial port '" + serialPort + "' could not be opened." + availablePorts);
143             } else {
144                 throw e;
145             }
146         }
147     }
148 }