2 * Copyright (c) 2010-2023 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.adorne.internal.hub;
15 import java.io.IOException;
16 import java.io.InputStreamReader;
17 import java.io.PrintStream;
18 import java.net.Socket;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
25 import com.google.gson.JsonElement;
26 import com.google.gson.JsonObject;
27 import com.google.gson.JsonParseException;
28 import com.google.gson.JsonPrimitive;
29 import com.google.gson.JsonStreamParser;
32 * The {@link AdorneHubConnection} manages basic connectivity with the Adorne hub.
34 * @author Mark Theiding - Initial Contribution
37 public class AdorneHubConnection {
38 private final Logger logger = LoggerFactory.getLogger(AdorneHubConnection.class);
40 private final Socket hubSocket;
41 private final PrintStream hubOut;
42 private final InputStreamReader hubInReader;
43 private final JsonStreamParser hubIn;
45 public AdorneHubConnection(String hubHost, int hubPort, int timeout) throws IOException {
46 hubSocket = new Socket(hubHost, hubPort);
47 hubSocket.setSoTimeout(timeout);
48 hubOut = new PrintStream(hubSocket.getOutputStream());
49 hubInReader = new InputStreamReader(hubSocket.getInputStream());
50 hubIn = new JsonStreamParser(hubInReader);
55 hubInReader.close(); // Closes underlying input stream as well
56 } catch (IOException e) {
57 logger.warn("Closing hub input reader failed ({})", e.getMessage());
59 hubOut.close(); // Closes underlying output stream as well
62 } catch (IOException e) {
63 logger.warn("Closing hub controller socket failed ({})", e.getMessage());
67 public void cancel() {
69 hubSocket.shutdownInput();
70 } catch (IOException e) {
71 logger.debug("Couldn't shutdown hub socket");
75 public void putMsg(String cmd) {
79 public @Nullable JsonObject getMsg() throws JsonParseException {
80 JsonElement msg = null;
81 JsonObject msgJsonObject = null;
85 if (msg == null || (msg instanceof JsonPrimitive && msg.getAsCharacter() == 0)) {
86 return null; // Eat empty messages
88 logger.debug("Received message {}", msg);
89 if (msg instanceof JsonObject object) {
90 msgJsonObject = object;