2 * Copyright (c) 2010-2020 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.lutron.internal.handler;
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;
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;
48 * Handler responsible for communicating with the main Lutron control hub.
50 * @author Allan Tong - Initial contribution
51 * @author Bob Adair - Added reconnect and heartbeat config parameters, moved discovery service registration to
52 * LutronHandlerFactory
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");
58 private static final String DB_UPDATE_DATE_FORMAT = "MM/dd/yyyy HH:mm:ss";
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;
65 private static final Integer SYSTEM_DBEXPORTDATETIME = 10;
67 private static final int MAX_LOGIN_ATTEMPTS = 2;
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>)";
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;
80 private final Logger logger = LoggerFactory.getLogger(IPBridgeHandler.class);
82 private IPBridgeConfig config;
83 private int reconnectInterval;
84 private int heartbeatInterval;
85 private int sendDelay;
87 private TelnetSession session;
88 private BlockingQueue<LutronCommand> sendQueue = new LinkedBlockingQueue<>();
90 private Thread messageSender;
91 private ScheduledFuture<?> keepAlive;
92 private ScheduledFuture<?> keepAliveReconnect;
93 private ScheduledFuture<?> connectRetryJob;
95 private Date lastDbUpdateDate;
96 private LutronDeviceDiscoveryService discoveryService;
98 private final AtomicBoolean requireSysvarMonitoring = new AtomicBoolean(false);
100 public void setDiscoveryService(LutronDeviceDiscoveryService discoveryService) {
101 this.discoveryService = discoveryService;
104 public class LutronSafemodeException extends Exception {
105 private static final long serialVersionUID = 1L;
107 public LutronSafemodeException(String message) {
112 public IPBridgeConfig getIPBridgeConfig() {
116 public IPBridgeHandler(Bridge bridge) {
119 this.session = new TelnetSession();
121 this.session.addListener(new TelnetSessionListener() {
123 public void inputAvailable() {
128 public void error(IOException exception) {
134 public void handleCommand(ChannelUID channelUID, Command command) {
138 public void initialize() {
139 this.config = getThing().getConfiguration().as(IPBridgeConfig.class);
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;
146 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "Connecting");
147 scheduler.submit(this::connect); // start the async connect task
151 private boolean validConfiguration(IPBridgeConfig config) {
152 if (config == null) {
153 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "bridge configuration missing");
158 if (StringUtils.isEmpty(config.ipAddress)) {
159 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "bridge address not specified");
167 private void scheduleConnectRetry(long waitMinutes) {
168 logger.debug("Scheduling connection retry in {} minutes", waitMinutes);
169 connectRetryJob = scheduler.schedule(this::connect, waitMinutes, TimeUnit.MINUTES);
172 private synchronized void connect() {
173 if (this.session.isConnected()) {
177 logger.debug("Connecting to bridge at {}", config.ipAddress);
180 if (!login(config)) {
181 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "invalid username/password");
185 } catch (LutronSafemodeException e) {
186 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "main repeater is in safe mode");
188 scheduleConnectRetry(reconnectInterval); // Possibly a temporary problem. Try again later.
191 } catch (IOException e) {
192 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
194 scheduleConnectRetry(reconnectInterval); // Possibly a temporary problem. Try again later.
197 } catch (InterruptedException e) {
198 Thread.currentThread().interrupt();
200 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.HANDLER_INITIALIZING_ERROR, "login interrupted");
206 updateStatus(ThingStatus.ONLINE);
209 sendCommand(new LutronCommand(LutronOperation.EXECUTE, LutronCommandType.MONITORING, -1, MONITOR_PROMPT,
212 if (requireSysvarMonitoring.get()) {
213 setSysvarMonitoring(true);
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));
220 messageSender = new Thread(this::sendCommandsThread, "Lutron sender");
221 messageSender.start();
223 logger.debug("Starting keepAlive job with interval {}", heartbeatInterval);
224 keepAlive = scheduler.scheduleWithFixedDelay(this::sendKeepAlive, heartbeatInterval, heartbeatInterval,
228 private void sendCommandsThread() {
230 while (!Thread.currentThread().isInterrupted()) {
231 LutronCommand command = sendQueue.take();
233 logger.debug("Sending command {}", command);
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);
241 sendQueue.add(command); // Requeue command
245 // reconnect() will start a new thread; terminate this one
249 Thread.sleep(sendDelay); // introduce delay to throttle send rate
252 } catch (InterruptedException e) {
253 Thread.currentThread().interrupt();
257 private synchronized void disconnect() {
258 logger.debug("Disconnecting from bridge");
260 if (connectRetryJob != null) {
261 connectRetryJob.cancel(true);
264 if (this.keepAlive != null) {
265 this.keepAlive.cancel(true);
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);
274 if (messageSender != null && messageSender.isAlive()) {
275 messageSender.interrupt();
279 this.session.close();
280 } catch (IOException e) {
281 logger.warn("Error disconnecting: {}", e.getMessage());
285 private synchronized void reconnect() {
286 logger.debug("Keepalive timeout, attempting to reconnect to the bridge");
288 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.DUTY_CYCLE);
293 private boolean login(IPBridgeConfig config) throws IOException, InterruptedException, LutronSafemodeException {
294 this.session.open(config.ipAddress);
295 this.session.waitFor("login:");
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);
303 MatchResult matchResult = this.session.waitFor(LOGIN_MATCH_REGEX);
305 if (PROMPT_GNET.equals(matchResult.group()) || PROMPT_QNET.equals(matchResult.group())) {
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");
313 logger.debug("got another login prompt, logging in again");
314 // we already got the login prompt so go straight to sending user
320 void sendCommand(LutronCommand command) {
321 this.sendQueue.add(command);
324 private LutronHandler findThingHandler(int integrationId) {
325 for (Thing thing : getThing().getThings()) {
326 if (thing.getHandler() instanceof LutronHandler) {
327 LutronHandler handler = (LutronHandler) thing.getHandler();
330 if (handler != null && handler.getIntegrationId() == integrationId) {
333 } catch (IllegalStateException e) {
334 logger.trace("Handler for id {} not initialized", integrationId);
342 private void parseUpdates() {
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.
352 logger.debug("Received message {}", line);
354 // System is alive, cancel reconnect task.
355 if (this.keepAliveReconnect != null) {
356 this.keepAliveReconnect.cancel(true);
359 Matcher matcher = RESPONSE_REGEX.matcher(line);
360 boolean responseMatched = matcher.find();
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) {
371 logger.debug("Cleaned response line: {}", scrubbedLine);
376 if (!responseMatched) {
377 logger.debug("Ignoring message {}", line);
380 // We have a good response message
381 LutronCommandType type = LutronCommandType.valueOf(matcher.group(1));
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));
391 Integer integrationId;
394 integrationId = Integer.valueOf(matcher.group(2));
395 } catch (NumberFormatException e1) {
396 logger.warn("Integer conversion error parsing update: {}", line);
399 paramString = matcher.group(3);
401 // Now dispatch update to the proper thing handler
402 LutronHandler handler = findThingHandler(integrationId);
404 if (handler != null) {
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);
413 logger.debug("No thing configured for integration ID {}", integrationId);
419 private void sendKeepAlive() {
420 logger.debug("Scheduling keepalive reconnect job");
422 // Reconnect if no response is received within 30 seconds.
423 keepAliveReconnect = scheduler.schedule(this::reconnect, KEEPALIVE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
425 logger.trace("Sending keepalive query");
426 sendCommand(new LutronCommand(LutronOperation.QUERY, LutronCommandType.SYSTEM, -1, SYSTEM_DBEXPORTDATETIME));
429 private void setDbUpdateDate(String dateString, String timeString) {
431 Date date = new SimpleDateFormat(DB_UPDATE_DATE_FORMAT).parse(dateString + " " + timeString);
433 if (this.lastDbUpdateDate == null || date.after(this.lastDbUpdateDate)) {
436 this.lastDbUpdateDate = date;
438 } catch (ParseException e) {
439 logger.warn("Failed to parse DB update date {} {}", dateString, timeString);
443 private void scanForDevices() {
445 if (discoveryService != null) {
446 logger.debug("Initiating discovery scan for devices");
447 discoveryService.startScan(null);
449 logger.debug("Unable to initiate discovery because discoveryService is null");
451 } catch (Exception e) {
452 logger.warn("Error scanning for paired devices: {}", e.getMessage(), e);
456 private void setSysvarMonitoring(boolean enable) {
457 Integer setting = (enable) ? MONITOR_ENABLE : MONITOR_DISABLE;
459 new LutronCommand(LutronOperation.EXECUTE, LutronCommandType.MONITORING, -1, MONITOR_SYSVAR, setting));
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);
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);
478 if (!validConfig || needsReconnect) {
483 this.config = newConfig;
485 if (needsReconnect) {
491 public void dispose() {