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.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.insteon.internal.driver.IOStream;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
33 * Implements IOStream for a Hub 2014 device
35 * @author Daniel Pfrommer - Initial contribution
36 * @author Rob Nielsen - Port to openHAB 2 insteon binding
40 @SuppressWarnings("null")
41 public class HubIOStream extends IOStream implements Runnable {
42 private final Logger logger = LoggerFactory.getLogger(HubIOStream.class);
44 private static final String BS_START = "<BS>";
45 private static final String BS_END = "</BS>";
47 /** time between polls (in milliseconds */
48 private int pollTime = 1000;
50 private String baseUrl;
51 private @Nullable String auth = null;
53 private @Nullable Thread pollThread = null;
55 // index of the last byte we have read in the buffer
56 private int bufferIdx = -1;
58 private boolean polling;
61 * Constructor for HubIOStream
63 * @param host host name of hub device
64 * @param port port to connect to
65 * @param pollTime time between polls (in milliseconds)
66 * @param user hub user name
67 * @param pass hub password
69 public HubIOStream(String host, int port, int pollTime, @Nullable String user, @Nullable String pass) {
70 this.pollTime = pollTime;
72 StringBuilder s = new StringBuilder();
76 s.append(":").append(port);
78 baseUrl = s.toString();
80 if (user != null && pass != null) {
81 auth = "Basic " + Base64.getEncoder().encodeToString((user + ":" + pass).getBytes(StandardCharsets.UTF_8));
86 public boolean open() {
89 } catch (IOException e) {
90 logger.warn("open failed: {}", e.getMessage());
94 in = new HubInputStream();
95 out = new HubOutputStream();
98 pollThread = new Thread(this);
99 pollThread.setName("Insteon Hub Poller");
100 pollThread.setDaemon(true);
107 public void close() {
110 if (pollThread != null) {
117 } catch (IOException e) {
118 logger.warn("failed to close input stream", e);
126 } catch (IOException e) {
127 logger.warn("failed to close output stream", e);
134 * Fetches the latest status buffer from the Hub
136 * @return string with status buffer
137 * @throws IOException
139 private synchronized String bufferStatus() throws IOException {
140 String result = getURL("/buffstatus.xml");
142 int start = result.indexOf(BS_START);
144 throw new IOException("malformed bufferstatus.xml");
146 start += BS_START.length();
148 int end = result.indexOf(BS_END, start);
150 throw new IOException("malformed bufferstatus.xml");
153 return result.substring(start, end).trim();
157 * Sends command to Hub to clear the status buffer
159 * @throws IOException
161 private synchronized void clearBuffer() throws IOException {
162 logger.trace("clearing buffer");
168 * Sends Insteon message (byte array) as a readable ascii string to the Hub
170 * @param msg byte array representing the Insteon message
171 * @throws IOException in case of I/O error
173 public synchronized void write(ByteBuffer msg) throws IOException {
174 poll(); // fetch the status buffer before we send out commands
176 StringBuilder b = new StringBuilder();
177 while (msg.remaining() > 0) {
178 b.append(String.format("%02x", msg.get()));
180 String hexMSG = b.toString();
181 logger.trace("writing a message");
182 getURL("/3?" + hexMSG + "=I=3");
187 * Polls the Hub web interface to fetch the status buffer
189 * @throws IOException if something goes wrong with I/O
191 public synchronized void poll() throws IOException {
192 String buffer = bufferStatus(); // fetch via http call
193 logger.trace("poll: {}", buffer);
195 // The Hub maintains a ring buffer where the last two digits (in hex!) represent
196 // the position of the last byte read.
198 String data = buffer.substring(0, buffer.length() - 2); // pure data w/o index pointer
202 nIdx = Integer.parseInt(buffer.substring(buffer.length() - 2, buffer.length()), 16);
203 } catch (NumberFormatException e) {
205 logger.warn("invalid buffer size received in line: {}", buffer);
209 if (bufferIdx == -1) {
210 // this is the first call or first call after error, no need for buffer copying
212 return; // XXX why return here????
215 if (allZeros(data)) {
216 logger.trace("skip cleared buffer");
221 StringBuilder msg = new StringBuilder();
222 if (nIdx < bufferIdx) {
223 String msgStart = data.substring(bufferIdx, data.length());
224 String msgEnd = data.substring(0, nIdx);
225 if (allZeros(msgStart)) {
226 logger.trace("discard cleared buffer wrap around msg start");
230 msg.append(msgStart + msgEnd);
231 logger.trace("wrap around: copying new data on: {}", msg.toString());
233 msg.append(data.substring(bufferIdx, nIdx));
234 logger.trace("no wrap: appending new data: {}", msg.toString());
236 if (msg.length() != 0) {
237 ByteBuffer buf = ByteBuffer.wrap(hexStringToByteArray(msg.toString()));
238 ((HubInputStream) in).handle(buf);
243 private boolean allZeros(String s) {
244 return "0".repeat(s.length()).equals(s);
248 * Helper method to fetch url from http server
250 * @param resource the url
251 * @return contents returned by http server
252 * @throws IOException
254 private String getURL(String resource) throws IOException {
255 String url = baseUrl + resource;
257 HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
259 connection.setConnectTimeout(30000);
260 connection.setUseCaches(false);
261 connection.setDoInput(true);
262 connection.setDoOutput(false);
264 connection.setRequestProperty("Authorization", auth);
267 logger.debug("getting {}", url);
269 int responseCode = connection.getResponseCode();
270 if (responseCode != 200) {
271 if (responseCode == 401) {
273 "Bad username or password. See the label on the bottom of the hub for the correct login information.");
274 throw new IOException("login credentials are incorrect");
276 String message = url + " failed with the response code: " + responseCode;
277 logger.warn(message);
278 throw new IOException(message);
282 return getData(connection.getInputStream());
284 connection.disconnect();
288 private String getData(InputStream is) throws IOException {
289 BufferedInputStream bis = new BufferedInputStream(is);
291 ByteArrayOutputStream baos = new ByteArrayOutputStream();
292 byte[] buffer = new byte[1024];
294 while ((length = bis.read(buffer)) != -1) {
295 baos.write(buffer, 0, length);
298 String s = baos.toString();
306 * Entry point for thread
313 } catch (IOException e) {
314 logger.warn("got exception while polling: {}", e.toString());
317 Thread.sleep(pollTime);
318 } catch (InterruptedException e) {
325 * Helper function to convert an ascii hex string (received from hub)
328 * @param s string received from hub
329 * @return simple byte array
331 public static byte[] hexStringToByteArray(String s) {
332 int len = s.length();
333 byte[] bytes = new byte[len / 2];
334 for (int i = 0; i < len; i += 2) {
335 bytes[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
342 * Implements an InputStream for the Hub 2014
344 * @author Daniel Pfrommer - Initial contribution
348 public class HubInputStream extends InputStream {
350 // A buffer to keep bytes while we are waiting for the inputstream to read
351 private ReadByteBuffer buffer = new ReadByteBuffer(1024);
353 public HubInputStream() {
356 public void handle(ByteBuffer b) throws IOException {
357 // Make sure we cleanup as much space as possible
358 buffer.makeCompact();
359 buffer.add(b.array());
363 public int read() throws IOException {
368 public int read(byte @Nullable [] b, int off, int len) throws IOException {
369 return buffer.get(b, off, len);
373 public void close() throws IOException {
379 * Implements an OutputStream for the Hub 2014
381 * @author Daniel Pfrommer - Initial contribution
385 public class HubOutputStream extends OutputStream {
386 private ByteArrayOutputStream out = new ByteArrayOutputStream();
389 public void write(int b) {
395 public void write(byte @Nullable [] b, int off, int len) {
396 out.write(b, off, len);
400 private void flushBuffer() {
401 ByteBuffer buffer = ByteBuffer.wrap(out.toByteArray());
403 HubIOStream.this.write(buffer);
404 } catch (IOException e) {
405 logger.warn("failed to write to hub: {}", e.toString());