]> git.basschouten.com Git - openhab-addons.git/blob
f30b064c44bad90228353f79d8f185fb1dd0dac6
[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.lutron.internal.handler;
14
15 import java.io.IOException;
16 import java.text.ParseException;
17 import java.text.SimpleDateFormat;
18 import java.util.Date;
19 import java.util.concurrent.BlockingQueue;
20 import java.util.concurrent.LinkedBlockingQueue;
21 import java.util.concurrent.ScheduledFuture;
22 import java.util.concurrent.TimeUnit;
23 import java.util.concurrent.atomic.AtomicBoolean;
24 import java.util.regex.MatchResult;
25 import java.util.regex.Matcher;
26 import java.util.regex.Pattern;
27
28 import org.apache.commons.lang.StringUtils;
29 import org.openhab.binding.lutron.internal.config.IPBridgeConfig;
30 import org.openhab.binding.lutron.internal.discovery.LutronDeviceDiscoveryService;
31 import org.openhab.binding.lutron.internal.net.TelnetSession;
32 import org.openhab.binding.lutron.internal.net.TelnetSessionListener;
33 import org.openhab.binding.lutron.internal.protocol.LutronCommand;
34 import org.openhab.binding.lutron.internal.protocol.LutronCommandType;
35 import org.openhab.binding.lutron.internal.protocol.LutronOperation;
36 import org.openhab.core.thing.Bridge;
37 import org.openhab.core.thing.ChannelUID;
38 import org.openhab.core.thing.Thing;
39 import org.openhab.core.thing.ThingStatus;
40 import org.openhab.core.thing.ThingStatusDetail;
41 import org.openhab.core.thing.binding.BaseBridgeHandler;
42 import org.openhab.core.thing.binding.ThingHandler;
43 import org.openhab.core.types.Command;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * Handler responsible for communicating with the main Lutron control hub.
49  *
50  * @author Allan Tong - Initial contribution
51  * @author Bob Adair - Added reconnect and heartbeat config parameters, moved discovery service registration to
52  *         LutronHandlerFactory
53  */
54 public class IPBridgeHandler extends BaseBridgeHandler {
55     private static final Pattern RESPONSE_REGEX = Pattern
56             .compile("~(OUTPUT|DEVICE|SYSTEM|TIMECLOCK|MODE|SYSVAR),([0-9\\.:/]+),([0-9,\\.:/]*)\\Z");
57
58     private static final String DB_UPDATE_DATE_FORMAT = "MM/dd/yyyy HH:mm:ss";
59
60     private static final Integer MONITOR_PROMPT = 12;
61     private static final Integer MONITOR_SYSVAR = 10;
62     private static final Integer MONITOR_ENABLE = 1;
63     private static final Integer MONITOR_DISABLE = 2;
64
65     private static final Integer SYSTEM_DBEXPORTDATETIME = 10;
66
67     private static final int MAX_LOGIN_ATTEMPTS = 2;
68
69     private static final String PROMPT_GNET = "GNET>";
70     private static final String PROMPT_QNET = "QNET>";
71     private static final String PROMPT_SAFE = "SAFE>";
72     private static final String LOGIN_MATCH_REGEX = "(login:|[GQ]NET>|SAFE>)";
73
74     private static final String DEFAULT_USER = "lutron";
75     private static final String DEFAULT_PASSWORD = "integration";
76     private static final int DEFAULT_RECONNECT_MINUTES = 5;
77     private static final int DEFAULT_HEARTBEAT_MINUTES = 5;
78     private static final long KEEPALIVE_TIMEOUT_SECONDS = 30;
79
80     private final Logger logger = LoggerFactory.getLogger(IPBridgeHandler.class);
81
82     private IPBridgeConfig config;
83     private int reconnectInterval;
84     private int heartbeatInterval;
85     private int sendDelay;
86
87     private TelnetSession session;
88     private BlockingQueue<LutronCommand> sendQueue = new LinkedBlockingQueue<>();
89
90     private Thread messageSender;
91     private ScheduledFuture<?> keepAlive;
92     private ScheduledFuture<?> keepAliveReconnect;
93     private ScheduledFuture<?> connectRetryJob;
94
95     private Date lastDbUpdateDate;
96     private LutronDeviceDiscoveryService discoveryService;
97
98     private final AtomicBoolean requireSysvarMonitoring = new AtomicBoolean(false);
99
100     public void setDiscoveryService(LutronDeviceDiscoveryService discoveryService) {
101         this.discoveryService = discoveryService;
102     }
103
104     public class LutronSafemodeException extends Exception {
105         private static final long serialVersionUID = 1L;
106
107         public LutronSafemodeException(String message) {
108             super(message);
109         }
110     }
111
112     public IPBridgeConfig getIPBridgeConfig() {
113         return config;
114     }
115
116     public IPBridgeHandler(Bridge bridge) {
117         super(bridge);
118
119         this.session = new TelnetSession();
120
121         this.session.addListener(new TelnetSessionListener() {
122             @Override
123             public void inputAvailable() {
124                 parseUpdates();
125             }
126
127             @Override
128             public void error(IOException exception) {
129             }
130         });
131     }
132
133     @Override
134     public void handleCommand(ChannelUID channelUID, Command command) {
135     }
136
137     @Override
138     public void initialize() {
139         this.config = getThing().getConfiguration().as(IPBridgeConfig.class);
140
141         if (validConfiguration(this.config)) {
142             reconnectInterval = (config.reconnect > 0) ? config.reconnect : DEFAULT_RECONNECT_MINUTES;
143             heartbeatInterval = (config.heartbeat > 0) ? config.heartbeat : DEFAULT_HEARTBEAT_MINUTES;
144             sendDelay = (config.delay < 0) ? 0 : config.delay;
145
146             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "Connecting");
147             scheduler.submit(this::connect); // start the async connect task
148         }
149     }
150
151     private boolean validConfiguration(IPBridgeConfig config) {
152         if (config == null) {
153             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "bridge configuration missing");
154
155             return false;
156         }
157
158         if (StringUtils.isEmpty(config.ipAddress)) {
159             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "bridge address not specified");
160
161             return false;
162         }
163
164         return true;
165     }
166
167     private void scheduleConnectRetry(long waitMinutes) {
168         logger.debug("Scheduling connection retry in {} minutes", waitMinutes);
169         connectRetryJob = scheduler.schedule(this::connect, waitMinutes, TimeUnit.MINUTES);
170     }
171
172     private synchronized void connect() {
173         if (this.session.isConnected()) {
174             return;
175         }
176
177         logger.debug("Connecting to bridge at {}", config.ipAddress);
178
179         try {
180             if (!login(config)) {
181                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "invalid username/password");
182
183                 return;
184             }
185         } catch (LutronSafemodeException e) {
186             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "main repeater is in safe mode");
187             disconnect();
188             scheduleConnectRetry(reconnectInterval); // Possibly a temporary problem. Try again later.
189
190             return;
191         } catch (IOException e) {
192             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
193             disconnect();
194             scheduleConnectRetry(reconnectInterval); // Possibly a temporary problem. Try again later.
195
196             return;
197         } catch (InterruptedException e) {
198             Thread.currentThread().interrupt();
199
200             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.HANDLER_INITIALIZING_ERROR, "login interrupted");
201             disconnect();
202
203             return;
204         }
205
206         updateStatus(ThingStatus.ONLINE);
207
208         // Disable prompts
209         sendCommand(new LutronCommand(LutronOperation.EXECUTE, LutronCommandType.MONITORING, -1, MONITOR_PROMPT,
210                 MONITOR_DISABLE));
211
212         if (requireSysvarMonitoring.get()) {
213             setSysvarMonitoring(true);
214         }
215
216         // Check the time device database was last updated. On the initial connect, this will trigger
217         // a scan for paired devices.
218         sendCommand(new LutronCommand(LutronOperation.QUERY, LutronCommandType.SYSTEM, -1, SYSTEM_DBEXPORTDATETIME));
219
220         messageSender = new Thread(this::sendCommandsThread, "Lutron sender");
221         messageSender.start();
222
223         logger.debug("Starting keepAlive job with interval {}", heartbeatInterval);
224         keepAlive = scheduler.scheduleWithFixedDelay(this::sendKeepAlive, heartbeatInterval, heartbeatInterval,
225                 TimeUnit.MINUTES);
226     }
227
228     private void sendCommandsThread() {
229         try {
230             while (!Thread.currentThread().isInterrupted()) {
231                 LutronCommand command = sendQueue.take();
232
233                 logger.debug("Sending command {}", command);
234
235                 try {
236                     session.writeLine(command.toString());
237                 } catch (IOException e) {
238                     logger.warn("Communication error, will try to reconnect. Error: {}", e.getMessage());
239                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
240
241                     sendQueue.add(command); // Requeue command
242
243                     reconnect();
244
245                     // reconnect() will start a new thread; terminate this one
246                     break;
247                 }
248                 if (sendDelay > 0) {
249                     Thread.sleep(sendDelay); // introduce delay to throttle send rate
250                 }
251             }
252         } catch (InterruptedException e) {
253             Thread.currentThread().interrupt();
254         }
255     }
256
257     private synchronized void disconnect() {
258         logger.debug("Disconnecting from bridge");
259
260         if (connectRetryJob != null) {
261             connectRetryJob.cancel(true);
262         }
263
264         if (this.keepAlive != null) {
265             this.keepAlive.cancel(true);
266         }
267
268         if (this.keepAliveReconnect != null) {
269             // This method can be called from the keepAliveReconnect thread. Make sure
270             // we don't interrupt ourselves, as that may prevent the reconnection attempt.
271             this.keepAliveReconnect.cancel(false);
272         }
273
274         if (messageSender != null && messageSender.isAlive()) {
275             messageSender.interrupt();
276         }
277
278         try {
279             this.session.close();
280         } catch (IOException e) {
281             logger.warn("Error disconnecting: {}", e.getMessage());
282         }
283     }
284
285     private synchronized void reconnect() {
286         logger.debug("Keepalive timeout, attempting to reconnect to the bridge");
287
288         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.DUTY_CYCLE);
289         disconnect();
290         connect();
291     }
292
293     private boolean login(IPBridgeConfig config) throws IOException, InterruptedException, LutronSafemodeException {
294         this.session.open(config.ipAddress);
295         this.session.waitFor("login:");
296
297         // Sometimes the Lutron Smart Bridge Pro will request login more than once.
298         for (int attempt = 0; attempt < MAX_LOGIN_ATTEMPTS; attempt++) {
299             this.session.writeLine(config.user != null ? config.user : DEFAULT_USER);
300             this.session.waitFor("password:");
301             this.session.writeLine(config.password != null ? config.password : DEFAULT_PASSWORD);
302
303             MatchResult matchResult = this.session.waitFor(LOGIN_MATCH_REGEX);
304
305             if (PROMPT_GNET.equals(matchResult.group()) || PROMPT_QNET.equals(matchResult.group())) {
306                 return true;
307             } else if (PROMPT_SAFE.equals(matchResult.group())) {
308                 logger.warn("Lutron repeater is in safe mode. Unable to connect.");
309                 throw new LutronSafemodeException("Lutron repeater in safe mode");
310             }
311
312             else {
313                 logger.debug("got another login prompt, logging in again");
314                 // we already got the login prompt so go straight to sending user
315             }
316         }
317         return false;
318     }
319
320     void sendCommand(LutronCommand command) {
321         this.sendQueue.add(command);
322     }
323
324     private LutronHandler findThingHandler(int integrationId) {
325         for (Thing thing : getThing().getThings()) {
326             if (thing.getHandler() instanceof LutronHandler) {
327                 LutronHandler handler = (LutronHandler) thing.getHandler();
328
329                 try {
330                     if (handler != null && handler.getIntegrationId() == integrationId) {
331                         return handler;
332                     }
333                 } catch (IllegalStateException e) {
334                     logger.trace("Handler for id {} not initialized", integrationId);
335                 }
336             }
337         }
338
339         return null;
340     }
341
342     private void parseUpdates() {
343         String paramString;
344         String scrubbedLine;
345
346         for (String line : this.session.readLines()) {
347             if (line.trim().equals("")) {
348                 // Sometimes we get an empty line (possibly only when prompts are disabled). Ignore them.
349                 continue;
350             }
351
352             logger.debug("Received message {}", line);
353
354             // System is alive, cancel reconnect task.
355             if (this.keepAliveReconnect != null) {
356                 this.keepAliveReconnect.cancel(true);
357             }
358
359             Matcher matcher = RESPONSE_REGEX.matcher(line);
360             boolean responseMatched = matcher.find();
361
362             if (!responseMatched) {
363                 // In some cases with Caseta a CLI prompt may be embedded within a received response line.
364                 if (line.contains("NET>")) {
365                     // Try to remove it and re-attempt the regex match.
366                     scrubbedLine = line.replaceAll("[GQ]NET> ", "");
367                     matcher = RESPONSE_REGEX.matcher(scrubbedLine);
368                     responseMatched = matcher.find();
369                     if (responseMatched) {
370                         line = scrubbedLine;
371                         logger.debug("Cleaned response line: {}", scrubbedLine);
372                     }
373                 }
374             }
375
376             if (!responseMatched) {
377                 logger.debug("Ignoring message {}", line);
378                 continue;
379             } else {
380                 // We have a good response message
381                 LutronCommandType type = LutronCommandType.valueOf(matcher.group(1));
382
383                 if (type == LutronCommandType.SYSTEM) {
384                     // SYSTEM messages are assumed to be a response to the SYSTEM_DBEXPORTDATETIME
385                     // query. The response returns the last time the device database was updated.
386                     setDbUpdateDate(matcher.group(2), matcher.group(3));
387
388                     continue;
389                 }
390
391                 Integer integrationId;
392
393                 try {
394                     integrationId = Integer.valueOf(matcher.group(2));
395                 } catch (NumberFormatException e1) {
396                     logger.warn("Integer conversion error parsing update: {}", line);
397                     continue;
398                 }
399                 paramString = matcher.group(3);
400
401                 // Now dispatch update to the proper thing handler
402                 LutronHandler handler = findThingHandler(integrationId);
403
404                 if (handler != null) {
405                     try {
406                         handler.handleUpdate(type, paramString.split(","));
407                     } catch (NumberFormatException e) {
408                         logger.warn("Number format exception parsing update: {}", line);
409                     } catch (RuntimeException e) {
410                         logger.warn("Runtime exception while processing update: {}", line, e);
411                     }
412                 } else {
413                     logger.debug("No thing configured for integration ID {}", integrationId);
414                 }
415             }
416         }
417     }
418
419     private void sendKeepAlive() {
420         logger.debug("Scheduling keepalive reconnect job");
421
422         // Reconnect if no response is received within 30 seconds.
423         keepAliveReconnect = scheduler.schedule(this::reconnect, KEEPALIVE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
424
425         logger.trace("Sending keepalive query");
426         sendCommand(new LutronCommand(LutronOperation.QUERY, LutronCommandType.SYSTEM, -1, SYSTEM_DBEXPORTDATETIME));
427     }
428
429     private void setDbUpdateDate(String dateString, String timeString) {
430         try {
431             Date date = new SimpleDateFormat(DB_UPDATE_DATE_FORMAT).parse(dateString + " " + timeString);
432
433             if (this.lastDbUpdateDate == null || date.after(this.lastDbUpdateDate)) {
434                 scanForDevices();
435
436                 this.lastDbUpdateDate = date;
437             }
438         } catch (ParseException e) {
439             logger.warn("Failed to parse DB update date {} {}", dateString, timeString);
440         }
441     }
442
443     private void scanForDevices() {
444         try {
445             if (discoveryService != null) {
446                 logger.debug("Initiating discovery scan for devices");
447                 discoveryService.startScan(null);
448             } else {
449                 logger.debug("Unable to initiate discovery because discoveryService is null");
450             }
451         } catch (Exception e) {
452             logger.warn("Error scanning for paired devices: {}", e.getMessage(), e);
453         }
454     }
455
456     private void setSysvarMonitoring(boolean enable) {
457         Integer setting = (enable) ? MONITOR_ENABLE : MONITOR_DISABLE;
458         sendCommand(
459                 new LutronCommand(LutronOperation.EXECUTE, LutronCommandType.MONITORING, -1, MONITOR_SYSVAR, setting));
460     }
461
462     @Override
463     public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
464         // enable sysvar monitoring the first time a sysvar child thing initializes
465         if (childHandler instanceof SysvarHandler) {
466             if (requireSysvarMonitoring.compareAndSet(false, true)) {
467                 setSysvarMonitoring(true);
468             }
469         }
470     }
471
472     @Override
473     public void thingUpdated(Thing thing) {
474         IPBridgeConfig newConfig = thing.getConfiguration().as(IPBridgeConfig.class);
475         boolean validConfig = validConfiguration(newConfig);
476         boolean needsReconnect = validConfig && !this.config.sameConnectionParameters(newConfig);
477
478         if (!validConfig || needsReconnect) {
479             dispose();
480         }
481
482         this.thing = thing;
483         this.config = newConfig;
484
485         if (needsReconnect) {
486             initialize();
487         }
488     }
489
490     @Override
491     public void dispose() {
492         disconnect();
493     }
494 }