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.hyperion.internal.connection;
15 import java.io.BufferedReader;
16 import java.io.DataOutputStream;
17 import java.io.IOException;
18 import java.io.InputStreamReader;
19 import java.io.Reader;
20 import java.net.InetAddress;
21 import java.net.Socket;
22 import java.net.UnknownHostException;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
28 * The {@link JsonTcpConnection} class is responsible for handling
29 * the communication with the Hyperion json server.
31 * @author Daniel Walters - Initial contribution
33 public class JsonTcpConnection {
35 private final Logger logger = LoggerFactory.getLogger(JsonTcpConnection.class);
36 private InetAddress address;
38 private Socket hyperionServerSocket;
40 public JsonTcpConnection(InetAddress address, int port) {
41 this.setAddress(address);
45 public JsonTcpConnection(String sAddress, int port) throws UnknownHostException {
46 this(InetAddress.getByName(sAddress), port);
49 public int getPort() {
53 public InetAddress getAddress() {
57 public void setAddress(InetAddress address) {
58 this.address = address;
61 public String send(String json) throws IOException {
62 String response = null;
63 try (Socket hyperionServer = new Socket(address, port);
64 DataOutputStream outToServer = new DataOutputStream(hyperionServer.getOutputStream());
65 Reader isr = new InputStreamReader(hyperionServer.getInputStream());
66 BufferedReader inFromServer = new BufferedReader(isr)) {
67 logger.debug("Sending: {}", json);
68 outToServer.writeBytes(json + System.lineSeparator());
70 response = inFromServer.readLine();
72 logger.debug("Received: {}", response);
76 public void connect() throws IOException {
77 if (hyperionServerSocket == null || !hyperionServerSocket.isConnected()) {
78 hyperionServerSocket = new Socket(address, port);
82 public void close() throws IOException {
83 if (hyperionServerSocket != null && hyperionServerSocket.isConnected()) {
84 hyperionServerSocket.close();
88 public boolean isConnected() {
89 return hyperionServerSocket != null && hyperionServerSocket.isConnected();