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.yamahareceiver.internal.protocol;
16 import java.io.FileNotFoundException;
17 import java.io.FileOutputStream;
18 import java.io.IOException;
20 import org.openhab.core.OpenHAB;
21 import org.slf4j.Logger;
22 import org.slf4j.LoggerFactory;
25 * Represents a connection to the AVR. Is implemented by the XMLConnection and JSONConnection.
27 * @author David Graeff - Initial contribution
28 * @author Tomasz Maruszak - Refactoring
30 public abstract class AbstractConnection {
31 private Logger logger = LoggerFactory.getLogger(AbstractConnection.class);
33 protected String host;
34 protected boolean protocolSnifferEnabled;
35 protected FileOutputStream debugOutStream;
38 * Creates a connection with the given host.
39 * Enables sniffing of the communication to the AVR if the logger level is set to trace
40 * when the addon is being loaded.
44 public AbstractConnection(String host) {
46 setProtocolSnifferEnable(logger.isTraceEnabled());
49 public void setHost(String host) {
53 public String getHost() {
57 public void setProtocolSnifferEnable(boolean enable) {
59 File pathWithoutFilename = new File(OpenHAB.getUserDataFolder());
60 pathWithoutFilename.mkdirs();
61 File file = new File(pathWithoutFilename, "yamaha_trace.log");
65 logger.warn("Protocol sniffing for Yamaha Receiver Addon is enabled. Performance may suffer! Writing to {}",
66 file.getAbsolutePath());
68 debugOutStream = new FileOutputStream(file);
69 } catch (FileNotFoundException e) {
70 debugOutStream = null;
71 logger.trace("Protocol log file not found!!", e);
73 } else if (protocolSnifferEnabled) {
74 // Close stream if protocol sniffing will be disabled
76 debugOutStream.close();
77 } catch (Exception e) {
79 debugOutStream = null;
81 this.protocolSnifferEnabled = enable;
84 protected void writeTraceFile(String message) {
85 if (protocolSnifferEnabled && debugOutStream != null) {
87 debugOutStream.write(message.replace('\n', ' ').getBytes());
88 debugOutStream.write('\n');
89 debugOutStream.write('\n');
90 debugOutStream.flush();
91 } catch (IOException e) {
92 logger.trace("Writing trace file failed", e);
98 * Implement this for a pure send.
100 * @param message The message to send. Must be xml or json already.
101 * @throws IOException
103 public abstract void send(String message) throws IOException;
106 * Implement this for a send/receive.
108 * @param message The message to send. Must be xml or json already.
109 * @throws IOException
111 public abstract String sendReceive(String message) throws IOException;