]> git.basschouten.com Git - openhab-addons.git/blob
a9bfe980fb8fd05407d74f962a298279664290d7
[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.dscalarm.internal.handler;
14
15 import java.io.BufferedReader;
16 import java.io.IOException;
17 import java.io.InputStreamReader;
18 import java.io.OutputStreamWriter;
19 import java.io.UnsupportedEncodingException;
20 import java.util.TooManyListenersException;
21
22 import org.openhab.binding.dscalarm.internal.config.IT100BridgeConfiguration;
23 import org.openhab.core.io.transport.serial.PortInUseException;
24 import org.openhab.core.io.transport.serial.SerialPort;
25 import org.openhab.core.io.transport.serial.SerialPortEvent;
26 import org.openhab.core.io.transport.serial.SerialPortEventListener;
27 import org.openhab.core.io.transport.serial.SerialPortIdentifier;
28 import org.openhab.core.io.transport.serial.SerialPortManager;
29 import org.openhab.core.io.transport.serial.UnsupportedCommOperationException;
30 import org.openhab.core.thing.Bridge;
31 import org.openhab.core.thing.ThingStatus;
32 import org.openhab.core.thing.ThingStatusDetail;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 /**
37  * The bridge handler for the DSC IT100 RS232 Serial interface.
38  *
39  * @author Russell Stephens - Initial Contribution
40  */
41
42 public class IT100BridgeHandler extends DSCAlarmBaseBridgeHandler implements SerialPortEventListener {
43
44     private final Logger logger = LoggerFactory.getLogger(IT100BridgeHandler.class);
45     private final SerialPortManager serialPortManager;
46
47     private String serialPortName = "";
48     private int baudRate;
49     private SerialPort serialPort = null;
50     private OutputStreamWriter serialOutput = null;
51     private BufferedReader serialInput = null;
52
53     public IT100BridgeHandler(Bridge bridge, SerialPortManager serialPortManager) {
54         super(bridge, DSCAlarmBridgeType.IT100, DSCAlarmProtocol.IT100_API);
55         this.serialPortManager = serialPortManager;
56     }
57
58     @Override
59     public void initialize() {
60         logger.debug("Initializing the DSC IT100 Bridge handler.");
61
62         IT100BridgeConfiguration configuration = getConfigAs(IT100BridgeConfiguration.class);
63
64         if (configuration.serialPort == null || configuration.serialPort.trim().isEmpty()) {
65             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
66                     "Set a serial port in the thing configuration.");
67         } else {
68             serialPortName = configuration.serialPort.trim();
69             baudRate = configuration.baud.intValue();
70             pollPeriod = configuration.pollPeriod.intValue();
71
72             super.initialize();
73
74             logger.debug("IT100 Bridge Handler Initialized.");
75             logger.debug("   Serial Port: {},", serialPortName);
76             logger.debug("   Baud:        {},", baudRate);
77             logger.debug("   PollPeriod:  {},", pollPeriod);
78         }
79     }
80
81     @Override
82     public void openConnection() {
83         logger.debug("openConnection(): Connecting to IT-100");
84
85         SerialPortIdentifier portIdentifier = serialPortManager.getIdentifier(serialPortName);
86         if (portIdentifier == null) {
87             logger.error("openConnection(): No Such Port: {}", serialPort);
88             setConnected(false);
89             return;
90         }
91
92         try {
93             SerialPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
94
95             serialPort = commPort;
96             serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
97                     SerialPort.PARITY_NONE);
98             serialPort.enableReceiveThreshold(1);
99             serialPort.disableReceiveTimeout();
100
101             serialOutput = new OutputStreamWriter(serialPort.getOutputStream(), "US-ASCII");
102             serialInput = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
103
104             setSerialEventHandler(this);
105
106             setConnected(true);
107         } catch (PortInUseException portInUseException) {
108             logger.error("openConnection(): Port in Use Exception: {}", portInUseException.getMessage());
109             setConnected(false);
110         } catch (UnsupportedCommOperationException unsupportedCommOperationException) {
111             logger.error("openConnection(): Unsupported Comm Operation Exception: {}",
112                     unsupportedCommOperationException.getMessage());
113             setConnected(false);
114         } catch (UnsupportedEncodingException unsupportedEncodingException) {
115             logger.error("openConnection(): Unsupported Encoding Exception: {}",
116                     unsupportedEncodingException.getMessage());
117             setConnected(false);
118         } catch (IOException ioException) {
119             logger.error("openConnection(): IO Exception: {}", ioException.getMessage());
120             setConnected(false);
121         }
122     }
123
124     @Override
125     public void write(String writeString, boolean doNotLog) {
126         try {
127             serialOutput.write(writeString);
128             serialOutput.flush();
129             logger.debug("write(): Message Sent: {}", doNotLog ? "***" : writeString);
130         } catch (IOException ioException) {
131             logger.error("write(): {}", ioException.getMessage());
132             setConnected(false);
133         } catch (Exception exception) {
134             logger.error("write(): Unable to write to serial port: {} ", exception.getMessage(), exception);
135             setConnected(false);
136         }
137     }
138
139     @Override
140     public String read() {
141         String message = "";
142
143         try {
144             message = readLine();
145             logger.debug("read(): Message Received: {}", message);
146         } catch (IOException ioException) {
147             logger.error("read(): IO Exception: {} ", ioException.getMessage());
148             setConnected(false);
149         } catch (Exception exception) {
150             logger.error("read(): Exception: {} ", exception.getMessage(), exception);
151             setConnected(false);
152         }
153
154         return message;
155     }
156
157     /**
158      * Read a line from the Input Stream.
159      *
160      * @return
161      * @throws IOException
162      */
163     private String readLine() throws IOException {
164         return serialInput.readLine();
165     }
166
167     @Override
168     public void closeConnection() {
169         logger.debug("closeConnection(): Closing Serial Connection!");
170
171         if (serialPort == null) {
172             setConnected(false);
173             return;
174         }
175
176         serialPort.removeEventListener();
177
178         if (serialInput != null) {
179             try {
180                 serialInput.close();
181             } catch (IOException e) {
182                 logger.debug("Error while closing the input stream: {}", e.getMessage());
183             }
184             serialInput = null;
185         }
186
187         if (serialOutput != null) {
188             try {
189                 serialOutput.close();
190             } catch (IOException e) {
191                 logger.debug("Error while closing the output stream: {}", e.getMessage());
192             }
193             serialOutput = null;
194         }
195
196         serialPort.close();
197         serialPort = null;
198
199         setConnected(false);
200         logger.debug("close(): Serial Connection Closed!");
201     }
202
203     /**
204      * Gets the Serial Port Name of the IT-100
205      *
206      * @return serialPortName
207      */
208     public String getSerialPortName() {
209         return serialPortName;
210     }
211
212     /**
213      * Receives Serial Port Events and reads Serial Port Data.
214      *
215      * @param serialPortEvent
216      */
217     @Override
218     public synchronized void serialEvent(SerialPortEvent serialPortEvent) {
219         if (serialPortEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
220             try {
221                 String messageLine = serialInput.readLine();
222                 handleIncomingMessage(messageLine);
223             } catch (IOException ioException) {
224                 logger.error("serialEvent(): IO Exception: {}", ioException.getMessage());
225             }
226         }
227     }
228
229     /**
230      * Set the serial event handler.
231      *
232      * @param serialPortEventListenser
233      */
234     private void setSerialEventHandler(SerialPortEventListener serialPortEventListenser) {
235         try {
236             // Add the serial port event listener
237             serialPort.addEventListener(serialPortEventListenser);
238             serialPort.notifyOnDataAvailable(true);
239         } catch (TooManyListenersException tooManyListenersException) {
240             logger.error("setSerialEventHandler(): Too Many Listeners Exception: {}",
241                     tooManyListenersException.getMessage());
242         }
243     }
244 }