]> git.basschouten.com Git - openhab-addons.git/blob
bb01f1c4ef7a8728a2d2687d24de215fec070890
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.openthermgateway.internal;
14
15 import java.io.BufferedReader;
16 import java.io.IOException;
17 import java.io.InputStreamReader;
18 import java.io.PrintWriter;
19 import java.net.InetSocketAddress;
20 import java.net.Socket;
21 import java.util.AbstractMap;
22 import java.util.Map;
23 import java.util.Map.Entry;
24 import java.util.concurrent.ConcurrentHashMap;
25
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.core.library.types.DecimalType;
29 import org.openhab.core.library.types.OnOffType;
30 import org.openhab.core.types.State;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 /**
35  * The {@link OpenThermGatewaySocketConnector} is responsible for handling the socket connection
36  *
37  * @author Arjen Korevaar - Initial contribution
38  * @author Arjan Mels - Improved robustness by re-sending commands, handling all message types (not only Boiler)
39  */
40 @NonNullByDefault
41 public class OpenThermGatewaySocketConnector implements OpenThermGatewayConnector {
42     private static final int COMMAND_RESPONSE_TIME_MILLISECONDS = 100;
43     private static final int COMMAND_TIMEOUT_MILLISECONDS = 5000;
44
45     private final Logger logger = LoggerFactory.getLogger(OpenThermGatewaySocketConnector.class);
46
47     private final OpenThermGatewayCallback callback;
48     private final String ipaddress;
49     private final int port;
50
51     private @Nullable PrintWriter writer;
52
53     private volatile boolean stopping;
54     private boolean connected;
55
56     private Map<String, Entry<Long, GatewayCommand>> pendingCommands = new ConcurrentHashMap<>();
57
58     public OpenThermGatewaySocketConnector(OpenThermGatewayCallback callback, String ipaddress, int port) {
59         this.callback = callback;
60         this.ipaddress = ipaddress;
61         this.port = port;
62     }
63
64     @Override
65     public void run() {
66         stopping = false;
67         connected = false;
68
69         logger.debug("Connecting OpenThermGatewaySocketConnector to {}:{}", this.ipaddress, this.port);
70
71         callback.connecting();
72
73         try (Socket socket = new Socket()) {
74             socket.connect(new InetSocketAddress(this.ipaddress, this.port), COMMAND_TIMEOUT_MILLISECONDS);
75             socket.setSoTimeout(COMMAND_TIMEOUT_MILLISECONDS);
76
77             connected = true;
78
79             callback.connected();
80
81             logger.debug("OpenThermGatewaySocketConnector connected");
82
83             try (BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
84                     PrintWriter wrt = new PrintWriter(socket.getOutputStream(), true)) {
85                 // Make writer accessible on class level
86                 writer = wrt;
87
88                 sendCommand(GatewayCommand.parse(GatewayCommandCode.PrintReport, "A"));
89                 // Set the OTGW to report every message it receives and transmits
90                 sendCommand(GatewayCommand.parse(GatewayCommandCode.PrintSummary, "0"));
91
92                 while (!stopping && !Thread.currentThread().isInterrupted()) {
93                     @Nullable
94                     String message = reader.readLine();
95
96                     if (message != null) {
97                         handleMessage(message);
98                     } else {
99                         logger.debug("Connection closed by OpenTherm Gateway");
100                         break;
101                     }
102                 }
103
104                 logger.debug("Stopping OpenThermGatewaySocketConnector");
105             } finally {
106                 connected = false;
107
108                 logger.debug("OpenThermGatewaySocketConnector disconnected");
109                 callback.disconnected();
110             }
111         } catch (IOException ex) {
112             logger.warn("Unable to connect to the OpenTherm Gateway.", ex);
113         }
114     }
115
116     @Override
117     public void stop() {
118         logger.debug("Stopping OpenThermGatewaySocketConnector");
119         stopping = true;
120     }
121
122     @Override
123     public boolean isConnected() {
124         return connected;
125     }
126
127     @Override
128     public void sendCommand(GatewayCommand command) {
129         @Nullable
130         PrintWriter wrtr = writer;
131
132         String msg = command.toFullString();
133
134         pendingCommands.put(command.getCode(),
135                 new AbstractMap.SimpleImmutableEntry<>(System.currentTimeMillis(), command));
136
137         if (connected) {
138             logger.debug("Sending message: {}", msg);
139             if (wrtr != null) {
140                 wrtr.print(msg + "\r\n");
141                 wrtr.flush();
142             }
143         } else {
144             logger.debug("Unable to send message: {}. OpenThermGatewaySocketConnector is not connected.", msg);
145         }
146     }
147
148     private void handleMessage(String message) {
149         if (message.length() > 2 && message.charAt(2) == ':') {
150             String code = message.substring(0, 2);
151             String value = message.substring(3);
152
153             logger.debug("Received command confirmation: {}: {}", code, value);
154             pendingCommands.remove(code);
155             return;
156         }
157
158         long currentTime = System.currentTimeMillis();
159
160         for (Entry<Long, GatewayCommand> timeAndCommand : pendingCommands.values()) {
161             long responseTime = timeAndCommand.getKey() + COMMAND_RESPONSE_TIME_MILLISECONDS;
162             long timeoutTime = timeAndCommand.getKey() + COMMAND_TIMEOUT_MILLISECONDS;
163
164             if (currentTime > responseTime && currentTime <= timeoutTime) {
165                 logger.debug("Resending command: {}", timeAndCommand.getValue());
166                 sendCommand(timeAndCommand.getValue());
167             } else if (currentTime > timeoutTime) {
168                 pendingCommands.remove(timeAndCommand.getValue().getCode());
169             }
170         }
171
172         Message msg = Message.parse(message);
173
174         if (msg == null) {
175             logger.trace("Received message: {}, (unknown)", message);
176             return;
177         } else {
178             logger.trace("Received message: {}, {} {} {}", message, msg.getID(), msg.getCode(), msg.getMessageType());
179         }
180
181         if (DataItemGroup.dataItemGroups.containsKey(msg.getID())) {
182             DataItem[] dataItems = DataItemGroup.dataItemGroups.get(msg.getID());
183
184             for (DataItem dataItem : dataItems) {
185                 State state = null;
186
187                 switch (dataItem.getDataType()) {
188                     case FLAGS:
189                         state = OnOffType.from(msg.getBit(dataItem.getByteType(), dataItem.getBitPos()));
190                         break;
191                     case UINT8:
192                     case UINT16:
193                         state = new DecimalType(msg.getUInt(dataItem.getByteType()));
194                         break;
195                     case INT8:
196                     case INT16:
197                         state = new DecimalType(msg.getInt(dataItem.getByteType()));
198                         break;
199                     case FLOAT:
200                         state = new DecimalType(msg.getFloat());
201                         break;
202                     case DOWTOD:
203                         break;
204                 }
205
206                 logger.trace("  Data: {} {} {} {}", dataItem.getID(), dataItem.getSubject(), dataItem.getDataType(),
207                         state == null ? "" : state);
208             }
209         }
210
211         if (msg.getMessageType() == MessageType.READACK || msg.getMessageType() == MessageType.WRITEDATA) {
212             receiveMessage(msg);
213         }
214     }
215
216     private void receiveMessage(Message message) {
217         callback.receiveMessage(message);
218     }
219 }