]> git.basschouten.com Git - openhab-addons.git/blob
ac4a24720a2a284c73c896447ef7fbde5fcc12b6
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.net.InetSocketAddress;
20 import java.net.Socket;
21 import java.net.SocketAddress;
22 import java.net.SocketException;
23 import java.net.UnknownHostException;
24
25 import org.openhab.binding.dscalarm.internal.config.EnvisalinkBridgeConfiguration;
26 import org.openhab.core.thing.Bridge;
27 import org.openhab.core.thing.ThingStatus;
28 import org.openhab.core.thing.ThingStatusDetail;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 /**
33  * The bridge handler for the EyezOn Envisalink 3/2DS Ethernet interface.
34  *
35  * @author Russell Stephens - Initial Contribution
36  */
37
38 public class EnvisalinkBridgeHandler extends DSCAlarmBaseBridgeHandler {
39
40     private final Logger logger = LoggerFactory.getLogger(EnvisalinkBridgeHandler.class);
41
42     /**
43      * Constructor.
44      *
45      * @param bridge
46      */
47     public EnvisalinkBridgeHandler(Bridge bridge) {
48         super(bridge, DSCAlarmBridgeType.Envisalink, DSCAlarmProtocol.ENVISALINK_TPI);
49     }
50
51     // Variables for TCP connection.
52     private String ipAddress;
53     private int tcpPort;
54     private int connectionTimeout;
55     private Socket tcpSocket = null;
56     private OutputStreamWriter tcpOutput = null;
57     private BufferedReader tcpInput = null;
58
59     @Override
60     public void initialize() {
61         logger.debug("Initializing the Envisalink Bridge handler.");
62
63         EnvisalinkBridgeConfiguration configuration = getConfigAs(EnvisalinkBridgeConfiguration.class);
64
65         if (configuration.ipAddress == null || configuration.ipAddress.trim().isEmpty()) {
66             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
67                     "Set an IP address in the thing configuration.");
68         } else if (configuration.port == null) {
69             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
70                     "Set a TCP port in the thing configuration.");
71         } else {
72             ipAddress = configuration.ipAddress.trim();
73             tcpPort = configuration.port.intValue();
74             setPassword(configuration.password);
75             connectionTimeout = configuration.connectionTimeout.intValue();
76             pollPeriod = configuration.pollPeriod.intValue();
77
78             super.initialize();
79
80             logger.debug("Envisalink Bridge Handler Initialized");
81             logger.debug("   IP Address:         {},", ipAddress);
82             logger.debug("   Port:               {},", tcpPort);
83             logger.debug("   PollPeriod:         {},", pollPeriod);
84             logger.debug("   Connection Timeout: {}.", connectionTimeout);
85         }
86     }
87
88     @Override
89     public void openConnection() {
90         try {
91             closeConnection();
92
93             logger.debug("openConnection(): Connecting to Envisalink ");
94
95             tcpSocket = new Socket();
96             SocketAddress tpiSocketAddress = new InetSocketAddress(ipAddress, tcpPort);
97             tcpSocket.connect(tpiSocketAddress, connectionTimeout);
98             tcpOutput = new OutputStreamWriter(tcpSocket.getOutputStream(), "US-ASCII");
99             tcpInput = new BufferedReader(new InputStreamReader(tcpSocket.getInputStream()));
100
101             Thread tcpListener = new Thread(new TCPListener());
102             tcpListener.start();
103
104             setConnected(true);
105         } catch (UnknownHostException unknownHostException) {
106             logger.error("openConnection(): Unknown Host Exception: {}", unknownHostException.getMessage());
107             setConnected(false);
108         } catch (SocketException socketException) {
109             logger.error("openConnection(): Socket Exception: {}", socketException.getMessage());
110             setConnected(false);
111         } catch (IOException ioException) {
112             logger.error("openConnection(): IO Exception: {}", ioException.getMessage());
113             setConnected(false);
114         } catch (Exception exception) {
115             logger.error("openConnection(): Unable to open a connection: {} ", exception.getMessage(), exception);
116             setConnected(false);
117         }
118     }
119
120     @Override
121     public void write(String writeString, boolean doNotLog) {
122         try {
123             logger.debug("write(): Attempting to Send Message: {}", doNotLog ? "***" : writeString);
124             tcpOutput.write(writeString);
125             tcpOutput.flush();
126         } catch (IOException ioException) {
127             logger.error("write(): {}", ioException.getMessage());
128             setConnected(false);
129         } catch (Exception exception) {
130             logger.error("write(): Unable to write to socket: {} ", exception.getMessage(), exception);
131             setConnected(false);
132         }
133     }
134
135     @Override
136     public String read() {
137         String message = "";
138
139         try {
140             message = tcpInput.readLine();
141             logger.debug("read(): Message Received: {}", message);
142         } catch (IOException ioException) {
143             logger.error("read(): IO Exception: {}", ioException.getMessage());
144             setConnected(false);
145         } catch (Exception exception) {
146             logger.error("read(): Exception: {} ", exception.getMessage(), exception);
147             setConnected(false);
148         }
149
150         return message;
151     }
152
153     @Override
154     public void closeConnection() {
155         try {
156             if (tcpSocket != null) {
157                 logger.debug("closeConnection(): Closing Socket!");
158                 tcpSocket.close();
159                 tcpSocket = null;
160                 tcpInput = null;
161                 tcpOutput = null;
162             }
163             setConnected(false);
164             logger.debug("closeConnection(): Closed TCP Connection!");
165         } catch (IOException ioException) {
166             logger.error("closeConnection(): Unable to close connection - {}", ioException.getMessage());
167         } catch (Exception exception) {
168             logger.error("closeConnection(): Error closing connection - {}", exception.getMessage());
169         }
170     }
171
172     /**
173      * Gets the IP Address of the Envisalink
174      *
175      * @return ipAddress
176      */
177     public String getIPAddress() {
178         return ipAddress;
179     }
180
181     /**
182      * TCPMessageListener: Receives messages from the DSC Alarm Panel API.
183      */
184     private class TCPListener implements Runnable {
185         private final Logger logger = LoggerFactory.getLogger(TCPListener.class);
186
187         /**
188          * Run method. Runs the MessageListener thread
189          */
190         @Override
191         public void run() {
192             String messageLine;
193
194             try {
195                 while (isConnected()) {
196                     if ((messageLine = read()) != null) {
197                         try {
198                             handleIncomingMessage(messageLine);
199                         } catch (Exception e) {
200                             logger.error("TCPListener(): Message not handled by bridge: {}", e.getMessage());
201                         }
202                     } else {
203                         setConnected(false);
204                     }
205                 }
206             } catch (Exception e) {
207                 logger.error("TCPListener(): Unable to read message: {} ", e.getMessage(), e);
208                 closeConnection();
209             }
210         }
211     }
212 }