]> git.basschouten.com Git - openhab-addons.git/blob
fc7b126d1297b4fd1d3ebf854497e9f1e232aba4
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.bondhome.internal.api;
14
15 import static java.nio.charset.StandardCharsets.*;
16 import static org.openhab.binding.bondhome.internal.BondHomeBindingConstants.*;
17
18 import java.io.IOException;
19 import java.net.DatagramPacket;
20 import java.net.DatagramSocket;
21 import java.net.InetAddress;
22 import java.net.SocketException;
23 import java.net.SocketTimeoutException;
24 import java.util.concurrent.Executor;
25
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.bondhome.internal.handler.BondBridgeHandler;
29 import org.openhab.core.thing.ThingStatusDetail;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 import com.google.gson.Gson;
34 import com.google.gson.GsonBuilder;
35 import com.google.gson.JsonParseException;
36
37 /**
38  * This Thread is responsible maintaining the Bond Push UDP Protocol
39  *
40  * @author Sara Geleskie Damiano - Initial contribution
41  *
42  */
43 @NonNullByDefault
44 public class BPUPListener implements Runnable {
45
46     private static final int SOCKET_TIMEOUT_MILLISECONDS = 3000;
47     private static final int SOCKET_RETRY_TIMEOUT_MILLISECONDS = 3000;
48
49     private final Logger logger = LoggerFactory.getLogger(BPUPListener.class);
50
51     // To parse the JSON responses
52     private final Gson gsonBuilder;
53
54     // Used for callbacks to handler
55     private final BondBridgeHandler bridgeHandler;
56
57     // UDP socket used to receive status events
58     private @Nullable DatagramSocket socket;
59
60     public @Nullable String lastRequestId;
61     private long timeOfLastKeepAlivePacket;
62     private boolean shutdown;
63
64     private int numberOfKeepAliveTimeouts;
65
66     /**
67      * Constructor of the receiver runnable thread.
68      *
69      * @param bridgeHandler The handler of the Bond Bridge
70      */
71     public BPUPListener(BondBridgeHandler bridgeHandler) {
72         logger.debug("Starting BPUP Listener...");
73
74         this.bridgeHandler = bridgeHandler;
75         this.timeOfLastKeepAlivePacket = -1;
76         this.numberOfKeepAliveTimeouts = 0;
77
78         GsonBuilder gsonBuilder = new GsonBuilder();
79         gsonBuilder.excludeFieldsWithoutExposeAnnotation();
80         Gson gson = gsonBuilder.create();
81         this.gsonBuilder = gson;
82         this.shutdown = true;
83     }
84
85     public boolean isRunning() {
86         return !shutdown;
87     }
88
89     public void start(Executor executor) {
90         shutdown = false;
91         executor.execute(this);
92     }
93
94     /**
95      * Send keep-alive as necessary and listen for push messages
96      */
97     @Override
98     public void run() {
99         receivePackets();
100     }
101
102     /**
103      * Gracefully shutdown thread. Worst case takes TIMEOUT_TO_DATAGRAM_RECEPTION to
104      * shutdown.
105      */
106     public void shutdown() {
107         this.shutdown = true;
108         DatagramSocket s = this.socket;
109         if (s != null) {
110             s.close();
111             logger.debug("Listener closed socket");
112             this.socket = null;
113         }
114     }
115
116     private void sendBPUPKeepAlive() {
117         // Create a buffer and packet for the response
118         byte[] buffer = new byte[256];
119         DatagramPacket inPacket = new DatagramPacket(buffer, buffer.length);
120
121         DatagramSocket sock = this.socket;
122         if (sock != null) {
123             logger.trace("Sending keep-alive request ('\\n')");
124             try {
125                 byte[] outBuffer = { (byte) '\n' };
126                 InetAddress inetAddress = InetAddress.getByName(bridgeHandler.getBridgeIpAddress());
127                 DatagramPacket outPacket = new DatagramPacket(outBuffer, 1, inetAddress, BOND_BPUP_PORT);
128                 sock.send(outPacket);
129                 sock.receive(inPacket);
130                 BPUPUpdate response = transformUpdatePacket(inPacket);
131                 if (response != null) {
132                     @Nullable
133                     String bondId = response.bondId;
134                     if (bondId == null || !bondId.equalsIgnoreCase(bridgeHandler.getBridgeId())) {
135                         logger.trace("Response isn't from expected Bridge! Expected: {} Got: {}",
136                                 bridgeHandler.getBridgeId(), bondId);
137                     } else {
138                         bridgeHandler.setBridgeOnline(inPacket.getAddress().getHostAddress());
139                         numberOfKeepAliveTimeouts = 0;
140                     }
141                 }
142             } catch (SocketTimeoutException e) {
143                 numberOfKeepAliveTimeouts++;
144                 logger.trace("BPUP Socket timeout, number of timeouts: {}", numberOfKeepAliveTimeouts);
145                 if (numberOfKeepAliveTimeouts > 10) {
146                     bridgeHandler.setBridgeOffline(ThingStatusDetail.COMMUNICATION_ERROR,
147                             "@text/offline.comm-error.timeout");
148                 }
149             } catch (IOException e) {
150                 logger.debug("One exception has occurred", e);
151             }
152         }
153     }
154
155     private void receivePackets() {
156         try {
157             DatagramSocket s = new DatagramSocket(null);
158             s.setSoTimeout(SOCKET_TIMEOUT_MILLISECONDS);
159             s.bind(null);
160             socket = s;
161             logger.debug("Listener created UDP socket on port {} with timeout {}", s.getPort(),
162                     SOCKET_TIMEOUT_MILLISECONDS);
163         } catch (SocketException e) {
164             logger.debug("Listener got SocketException", e);
165             datagramSocketHealthRoutine();
166         }
167
168         // Create a buffer and packet for the response
169         byte[] buffer = new byte[256];
170         DatagramPacket inPacket = new DatagramPacket(buffer, buffer.length);
171
172         DatagramSocket sock = this.socket;
173         while (sock != null && !this.shutdown) {
174             // Check if we're due to send something to keep the connection
175             long now = System.nanoTime() / 1000000L;
176             long timePassedFromLastKeepAlive = now - timeOfLastKeepAlivePacket;
177
178             if (timeOfLastKeepAlivePacket == -1 || timePassedFromLastKeepAlive >= 60000L) {
179                 sendBPUPKeepAlive();
180                 timeOfLastKeepAlivePacket = now;
181             }
182
183             try {
184                 sock.receive(inPacket);
185                 processPacket(inPacket);
186             } catch (SocketTimeoutException e) {
187                 // Ignore. Means there was no updates while we waited.
188                 // We'll just loop around and try again after sending a keep alive.
189             } catch (IOException e) {
190                 logger.debug("Listener got IOException waiting for datagram: {}", e.getMessage());
191                 datagramSocketHealthRoutine();
192             }
193         }
194         logger.debug("Listener exiting");
195     }
196
197     private void processPacket(DatagramPacket packet) {
198         logger.trace("Got datagram of length {} from {}", packet.getLength(), packet.getAddress().getHostAddress());
199
200         BPUPUpdate update = transformUpdatePacket(packet);
201         if (update != null) {
202             if (!update.bondId.equalsIgnoreCase(bridgeHandler.getBridgeId())) {
203                 logger.trace("Response isn't from expected Bridge! Expected: {} Got: {}", bridgeHandler.getBridgeId(),
204                         update.bondId);
205             }
206
207             // Check for duplicate packet
208             if (isDuplicate(update)) {
209                 logger.trace("Dropping duplicate packet");
210                 return;
211             }
212
213             // Send the update the the bridge for it to pass on to the devices
214             if (update.topic != null) {
215                 logger.trace("Forwarding message to bridge handler");
216                 bridgeHandler.forwardUpdateToThing(update);
217             } else {
218                 logger.debug("No topic in incoming message!");
219             }
220         }
221     }
222
223     /**
224      * Method that transforms {@link DatagramPacket} to a {@link BPUPUpdate} Object
225      *
226      * @param packet the {@link DatagramPacket}
227      * @return the {@link BPUPUpdate}
228      */
229     public @Nullable BPUPUpdate transformUpdatePacket(final DatagramPacket packet) {
230         String responseJson = new String(packet.getData(), 0, packet.getLength(), UTF_8);
231         logger.debug("Message from {}:{} -> {}", packet.getAddress().getHostAddress(), packet.getPort(), responseJson);
232
233         @Nullable
234         BPUPUpdate response = null;
235         try {
236             response = this.gsonBuilder.fromJson(responseJson, BPUPUpdate.class);
237         } catch (JsonParseException e) {
238             logger.debug("Error parsing json! {}", e.getMessage());
239         }
240         return response;
241     }
242
243     private boolean isDuplicate(BPUPUpdate update) {
244         boolean packetIsDuplicate = false;
245         String newReqestId = update.requestId;
246         String lastRequestId = this.lastRequestId;
247         if (lastRequestId != null && newReqestId != null) {
248             if (lastRequestId.equalsIgnoreCase(newReqestId)) {
249                 packetIsDuplicate = true;
250             }
251         }
252         // Remember this packet for duplicate check
253         lastRequestId = newReqestId;
254         return packetIsDuplicate;
255     }
256
257     private void datagramSocketHealthRoutine() {
258         @Nullable
259         DatagramSocket datagramSocket = this.socket;
260         if (datagramSocket == null || (datagramSocket.isClosed() || !datagramSocket.isConnected())) {
261             logger.trace("Datagram Socket is disconnected or has been closed, reconnecting...");
262             try {
263                 // close the socket before trying to reopen
264                 if (datagramSocket != null) {
265                     datagramSocket.close();
266                 }
267                 logger.trace("Old socket closed.");
268                 try {
269                     Thread.sleep(SOCKET_RETRY_TIMEOUT_MILLISECONDS);
270                 } catch (InterruptedException e) {
271                     Thread.currentThread().interrupt();
272                 }
273                 DatagramSocket s = new DatagramSocket(null);
274                 s.setSoTimeout(SOCKET_TIMEOUT_MILLISECONDS);
275                 s.bind(null);
276                 this.socket = s;
277                 logger.trace("Datagram Socket reconnected using port {}.", s.getPort());
278             } catch (SocketException exception) {
279                 logger.trace("Problem creating new socket : {}", exception.getLocalizedMessage());
280             }
281         }
282     }
283 }