2 * Copyright (c) 2010-2022 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.heos.internal.resources;
15 import java.io.IOException;
17 import org.openhab.binding.heos.internal.json.HeosJsonParser;
18 import org.openhab.binding.heos.internal.json.dto.HeosResponseObject;
19 import org.openhab.binding.heos.internal.resources.Telnet.ReadException;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
24 * The {@link HeosSendCommand} is responsible to send a command
27 * @author Johannes Einig - Initial contribution
29 public class HeosSendCommand {
30 private final Logger logger = LoggerFactory.getLogger(HeosSendCommand.class);
32 private final Telnet client;
33 private final HeosJsonParser parser = new HeosJsonParser();
35 public HeosSendCommand(Telnet client) {
39 public <T> HeosResponseObject<T> send(String command, Class<T> clazz) throws IOException, ReadException {
40 HeosResponseObject<T> result;
43 boolean send = client.send(command);
47 String line = client.readLine();
49 throw new IOException("No valid input was received");
51 result = parser.parseResponse(line, clazz);
53 while (!result.isFinished() && attempt < 3) {
55 logger.trace("Retrying \"{}\" (attempt {})", command, attempt);
56 line = client.readLine(15000);
59 result = parser.parseResponse(line, clazz);
63 if (attempt >= 3 && !result.isFinished()) {
64 throw new IOException("No valid input was received after multiple attempts");
69 throw new IOException("Not connected");
73 public boolean isHostReachable() {
74 return client.isHostReachable();
77 public boolean isConnected() {
78 return client.isConnected();
81 public void stopInputListener(String registerChangeEventOFF) {
82 logger.debug("Stopping HEOS event line listener");
83 client.stopInputListener();
85 if (client.isConnected()) {
87 client.send(registerChangeEventOFF);
88 } catch (IOException e) {
89 logger.debug("Failure during closing connection to HEOS with message: {}", e.getMessage());
94 public void disconnect() {
95 if (client.isConnected()) {
100 logger.debug("Disconnecting HEOS command line");
102 } catch (IOException e) {
103 logger.debug("Failure during closing connection to HEOS with message: {}", e.getMessage());
106 logger.debug("Connection to HEOS system closed");
109 public void startInputListener(String command) throws IOException, ReadException {
110 HeosResponseObject<Void> response = send(command, Void.class);
111 if (response.result) {
112 client.startInputListener();