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.insteon.internal.driver.hub;
15 import java.io.BufferedInputStream;
16 import java.io.ByteArrayOutputStream;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.io.OutputStream;
20 import java.net.HttpURLConnection;
22 import java.nio.ByteBuffer;
23 import java.nio.charset.StandardCharsets;
24 import java.util.Base64;
26 import org.apache.commons.lang.StringUtils;
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.openhab.binding.insteon.internal.driver.IOStream;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
34 * Implements IOStream for a Hub 2014 device
36 * @author Daniel Pfrommer - Initial contribution
37 * @author Rob Nielsen - Port to openHAB 2 insteon binding
41 @SuppressWarnings("null")
42 public class HubIOStream extends IOStream implements Runnable {
43 private final Logger logger = LoggerFactory.getLogger(HubIOStream.class);
45 private static final String BS_START = "<BS>";
46 private static final String BS_END = "</BS>";
48 /** time between polls (in milliseconds */
49 private int pollTime = 1000;
51 private String baseUrl;
52 private @Nullable String auth = null;
54 private @Nullable Thread pollThread = null;
56 // index of the last byte we have read in the buffer
57 private int bufferIdx = -1;
59 private boolean polling;
62 * Constructor for HubIOStream
64 * @param host host name of hub device
65 * @param port port to connect to
66 * @param pollTime time between polls (in milliseconds)
67 * @param user hub user name
68 * @param pass hub password
70 public HubIOStream(String host, int port, int pollTime, @Nullable String user, @Nullable String pass) {
71 this.pollTime = pollTime;
73 StringBuilder s = new StringBuilder();
77 s.append(":").append(port);
79 baseUrl = s.toString();
81 if (user != null && pass != null) {
82 auth = "Basic " + Base64.getEncoder().encodeToString((user + ":" + pass).getBytes(StandardCharsets.UTF_8));
87 public boolean open() {
90 } catch (IOException e) {
91 logger.warn("open failed: {}", e.getMessage());
95 in = new HubInputStream();
96 out = new HubOutputStream();
99 pollThread = new Thread(this);
100 pollThread.setName("Insteon Hub Poller");
101 pollThread.setDaemon(true);
108 public void close() {
111 if (pollThread != null) {
118 } catch (IOException e) {
119 logger.warn("failed to close input stream", e);
127 } catch (IOException e) {
128 logger.warn("failed to close output stream", e);
135 * Fetches the latest status buffer from the Hub
137 * @return string with status buffer
138 * @throws IOException
140 private synchronized String bufferStatus() throws IOException {
141 String result = getURL("/buffstatus.xml");
143 int start = result.indexOf(BS_START);
145 throw new IOException("malformed bufferstatus.xml");
147 start += BS_START.length();
149 int end = result.indexOf(BS_END, start);
151 throw new IOException("malformed bufferstatus.xml");
154 return result.substring(start, end).trim();
158 * Sends command to Hub to clear the status buffer
160 * @throws IOException
162 private synchronized void clearBuffer() throws IOException {
163 logger.trace("clearing buffer");
169 * Sends Insteon message (byte array) as a readable ascii string to the Hub
171 * @param msg byte array representing the Insteon message
172 * @throws IOException in case of I/O error
174 public synchronized void write(ByteBuffer msg) throws IOException {
175 poll(); // fetch the status buffer before we send out commands
177 StringBuilder b = new StringBuilder();
178 while (msg.remaining() > 0) {
179 b.append(String.format("%02x", msg.get()));
181 String hexMSG = b.toString();
182 logger.trace("writing a message");
183 getURL("/3?" + hexMSG + "=I=3");
188 * Polls the Hub web interface to fetch the status buffer
190 * @throws IOException if something goes wrong with I/O
192 public synchronized void poll() throws IOException {
193 String buffer = bufferStatus(); // fetch via http call
194 logger.trace("poll: {}", buffer);
196 // The Hub maintains a ring buffer where the last two digits (in hex!) represent
197 // the position of the last byte read.
199 String data = buffer.substring(0, buffer.length() - 2); // pure data w/o index pointer
203 nIdx = Integer.parseInt(buffer.substring(buffer.length() - 2, buffer.length()), 16);
204 } catch (NumberFormatException e) {
206 logger.warn("invalid buffer size received in line: {}", buffer);
210 if (bufferIdx == -1) {
211 // this is the first call or first call after error, no need for buffer copying
213 return; // XXX why return here????
216 if (StringUtils.repeat("0", data.length()).equals(data)) {
217 logger.trace("skip cleared buffer");
222 StringBuilder msg = new StringBuilder();
223 if (nIdx < bufferIdx) {
224 String msgStart = data.substring(bufferIdx, data.length());
225 String msgEnd = data.substring(0, nIdx);
226 if (StringUtils.repeat("0", msgStart.length()).equals(msgStart)) {
227 logger.trace("discard cleared buffer wrap around msg start");
231 msg.append(msgStart + msgEnd);
232 logger.trace("wrap around: copying new data on: {}", msg.toString());
234 msg.append(data.substring(bufferIdx, nIdx));
235 logger.trace("no wrap: appending new data: {}", msg.toString());
237 if (msg.length() != 0) {
238 ByteBuffer buf = ByteBuffer.wrap(hexStringToByteArray(msg.toString()));
239 ((HubInputStream) in).handle(buf);
245 * Helper method to fetch url from http server
247 * @param resource the url
248 * @return contents returned by http server
249 * @throws IOException
251 private String getURL(String resource) throws IOException {
252 String url = baseUrl + resource;
254 HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
256 connection.setConnectTimeout(30000);
257 connection.setUseCaches(false);
258 connection.setDoInput(true);
259 connection.setDoOutput(false);
261 connection.setRequestProperty("Authorization", auth);
264 logger.debug("getting {}", url);
266 int responseCode = connection.getResponseCode();
267 if (responseCode != 200) {
268 if (responseCode == 401) {
270 "Bad username or password. See the label on the bottom of the hub for the correct login information.");
271 throw new IOException("login credentials are incorrect");
273 String message = url + " failed with the response code: " + responseCode;
274 logger.warn(message);
275 throw new IOException(message);
279 return getData(connection.getInputStream());
281 connection.disconnect();
285 private String getData(InputStream is) throws IOException {
286 BufferedInputStream bis = new BufferedInputStream(is);
288 ByteArrayOutputStream baos = new ByteArrayOutputStream();
289 byte[] buffer = new byte[1024];
291 while ((length = bis.read(buffer)) != -1) {
292 baos.write(buffer, 0, length);
295 String s = baos.toString();
303 * Entry point for thread
310 } catch (IOException e) {
311 logger.warn("got exception while polling: {}", e.toString());
314 Thread.sleep(pollTime);
315 } catch (InterruptedException e) {
322 * Helper function to convert an ascii hex string (received from hub)
325 * @param s string received from hub
326 * @return simple byte array
328 public static byte[] hexStringToByteArray(String s) {
329 int len = s.length();
330 byte[] bytes = new byte[len / 2];
331 for (int i = 0; i < len; i += 2) {
332 bytes[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
339 * Implements an InputStream for the Hub 2014
341 * @author Daniel Pfrommer - Initial contribution
345 public class HubInputStream extends InputStream {
347 // A buffer to keep bytes while we are waiting for the inputstream to read
348 private ReadByteBuffer buffer = new ReadByteBuffer(1024);
350 public HubInputStream() {
353 public void handle(ByteBuffer b) throws IOException {
354 // Make sure we cleanup as much space as possible
355 buffer.makeCompact();
356 buffer.add(b.array());
360 public int read() throws IOException {
365 public int read(byte @Nullable [] b, int off, int len) throws IOException {
366 return buffer.get(b, off, len);
370 public void close() throws IOException {
376 * Implements an OutputStream for the Hub 2014
378 * @author Daniel Pfrommer - Initial contribution
382 public class HubOutputStream extends OutputStream {
383 private ByteArrayOutputStream out = new ByteArrayOutputStream();
386 public void write(int b) {
392 public void write(byte @Nullable [] b, int off, int len) {
393 out.write(b, off, len);
397 private void flushBuffer() {
398 ByteBuffer buffer = ByteBuffer.wrap(out.toByteArray());
400 HubIOStream.this.write(buffer);
401 } catch (IOException e) {
402 logger.warn("failed to write to hub: {}", e.toString());