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.regoheatpump.internal.protocol;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.io.OutputStream;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.openhab.core.io.transport.serial.PortInUseException;
22 import org.openhab.core.io.transport.serial.SerialPort;
23 import org.openhab.core.io.transport.serial.SerialPortIdentifier;
24 import org.openhab.core.io.transport.serial.UnsupportedCommOperationException;
27 * The {@link SerialRegoConnection} is responsible for creating serial connections to clients.
29 * @author Boris Krivonog - Initial contribution
32 public class SerialRegoConnection implements RegoConnection {
33 private final int baudRate;
34 private final String portName;
35 private @Nullable SerialPort serialPort;
36 private final SerialPortIdentifier serialPortIdentifier;
38 public SerialRegoConnection(SerialPortIdentifier serialPortIdentifier, int baudRate) {
39 this.serialPortIdentifier = serialPortIdentifier;
40 this.portName = serialPortIdentifier.getName();
41 this.baudRate = baudRate;
45 public void connect() throws IOException {
47 SerialPort serialPort = serialPortIdentifier.open(SerialRegoConnection.class.getCanonicalName(), 2000);
48 serialPort.enableReceiveTimeout(100);
49 serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
50 SerialPort.PARITY_NONE);
51 this.serialPort = serialPort;
52 } catch (PortInUseException e) {
53 throw new IOException("Serial port already used: " + portName, e);
54 } catch (UnsupportedCommOperationException e) {
55 throw new IOException("Unsupported operation on '" + portName + "': " + e.getMessage(), e);
60 public boolean isConnected() {
61 return serialPort != null;
66 SerialPort serialPort = this.serialPort;
67 this.serialPort = null;
68 if (serialPort != null) {
74 public OutputStream outputStream() throws IOException {
75 OutputStream outputStream = getSerialPort().getOutputStream();
76 if (outputStream == null) {
77 throw new IOException("Sending data is not supported");
83 public InputStream inputStream() throws IOException {
84 InputStream inputStream = getSerialPort().getInputStream();
85 if (inputStream == null) {
86 throw new IOException("Receiving data is not supported");
91 private SerialPort getSerialPort() throws IOException {
92 SerialPort serialPort = this.serialPort;
93 if (serialPort == null) {
94 throw new IOException("Connection closed");