]> git.basschouten.com Git - openhab-addons.git/blob
7cfbbdd7569e2444336556cbbed26d1ba314fc98
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.regoheatpump.internal.protocol;
14
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.io.OutputStream;
18
19 import org.openhab.core.io.transport.serial.PortInUseException;
20 import org.openhab.core.io.transport.serial.SerialPort;
21 import org.openhab.core.io.transport.serial.SerialPortIdentifier;
22 import org.openhab.core.io.transport.serial.UnsupportedCommOperationException;
23
24 /**
25  * The {@link SerialRegoConnection} is responsible for creating serial connections to clients.
26  *
27  * @author Boris Krivonog - Initial contribution
28  */
29 public class SerialRegoConnection implements RegoConnection {
30     private final int baudRate;
31     private final String portName;
32     private SerialPort serialPort;
33     private final SerialPortIdentifier serialPortIdentifier;
34
35     public SerialRegoConnection(SerialPortIdentifier serialPortIdentifier, int baudRate) {
36         this.serialPortIdentifier = serialPortIdentifier;
37         this.portName = serialPortIdentifier.getName();
38         this.baudRate = baudRate;
39     }
40
41     @Override
42     public void connect() throws IOException {
43         try {
44             serialPort = serialPortIdentifier.open(SerialRegoConnection.class.getCanonicalName(), 2000);
45             serialPort.enableReceiveTimeout(100);
46             serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
47                     SerialPort.PARITY_NONE);
48         } catch (PortInUseException e) {
49             throw new IOException("Serial port already used: " + portName, e);
50         } catch (UnsupportedCommOperationException e) {
51             throw new IOException("Unsupported operation on '" + portName + "': " + e.getMessage(), e);
52         }
53     }
54
55     @Override
56     public boolean isConnected() {
57         return serialPort != null;
58     }
59
60     @Override
61     public void close() {
62         if (serialPort != null) {
63             serialPort.close();
64             serialPort = null;
65         }
66     }
67
68     @Override
69     public OutputStream outputStream() throws IOException {
70         return serialPort.getOutputStream();
71     }
72
73     @Override
74     public InputStream inputStream() throws IOException {
75         return serialPort.getInputStream();
76     }
77 }