]> git.basschouten.com Git - openhab-addons.git/blob
e220f806570439bd8b5f3922fd0e5b33f52cc15f
[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.insteon.internal;
14
15 import java.io.IOException;
16 import java.util.ArrayList;
17 import java.util.Collections;
18 import java.util.Comparator;
19 import java.util.HashMap;
20 import java.util.HashSet;
21 import java.util.Iterator;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Map.Entry;
25 import java.util.Set;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.ScheduledExecutorService;
28
29 import javax.xml.parsers.ParserConfigurationException;
30
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.openhab.binding.insteon.internal.config.InsteonChannelConfiguration;
34 import org.openhab.binding.insteon.internal.config.InsteonNetworkConfiguration;
35 import org.openhab.binding.insteon.internal.device.DeviceFeature;
36 import org.openhab.binding.insteon.internal.device.DeviceFeatureListener;
37 import org.openhab.binding.insteon.internal.device.DeviceType;
38 import org.openhab.binding.insteon.internal.device.DeviceTypeLoader;
39 import org.openhab.binding.insteon.internal.device.InsteonAddress;
40 import org.openhab.binding.insteon.internal.device.InsteonDevice;
41 import org.openhab.binding.insteon.internal.device.InsteonDevice.DeviceStatus;
42 import org.openhab.binding.insteon.internal.device.RequestQueueManager;
43 import org.openhab.binding.insteon.internal.driver.Driver;
44 import org.openhab.binding.insteon.internal.driver.DriverListener;
45 import org.openhab.binding.insteon.internal.driver.ModemDBEntry;
46 import org.openhab.binding.insteon.internal.driver.Poller;
47 import org.openhab.binding.insteon.internal.driver.Port;
48 import org.openhab.binding.insteon.internal.handler.InsteonDeviceHandler;
49 import org.openhab.binding.insteon.internal.handler.InsteonNetworkHandler;
50 import org.openhab.binding.insteon.internal.message.FieldException;
51 import org.openhab.binding.insteon.internal.message.Msg;
52 import org.openhab.binding.insteon.internal.message.MsgListener;
53 import org.openhab.binding.insteon.internal.utils.Utils;
54 import org.openhab.core.io.transport.serial.SerialPortManager;
55 import org.openhab.core.thing.ChannelUID;
56 import org.openhab.core.types.Command;
57 import org.openhab.core.types.State;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60 import org.xml.sax.SAXException;
61
62 /**
63  * A majority of the code in this file is from the openHAB 1 binding
64  * org.openhab.binding.insteonplm.InsteonPLMActiveBinding. Including the comments below.
65  *
66  * -----------------------------------------------------------------------------------------------
67  *
68  * This class represents the actual implementation of the binding, and controls the high level flow
69  * of messages to and from the InsteonModem.
70  *
71  * Writing this binding has been an odyssey through the quirks of the Insteon protocol
72  * and Insteon devices. A substantial redesign was necessary at some point along the way.
73  * Here are some of the hard learned lessons that should be considered by anyone who wants
74  * to re-architect the binding:
75  *
76  * 1) The entries of the link database of the modem are not reliable. The category/subcategory entries in
77  * particular have junk data. Forget about using the modem database to generate a list of devices.
78  * The database should only be used to verify that a device has been linked.
79  *
80  * 2) Querying devices for their product information does not work either. First of all, battery operated devices
81  * (and there are a lot of those) have their radio switched off, and may generally not respond to product
82  * queries. Even main stream hardwired devices sold presently (like the 2477s switch and the 2477d dimmer)
83  * don't even have a product ID. Although supposedly part of the Insteon protocol, we have yet to
84  * encounter a device that would cough up a product id when queried, even among very recent devices. They
85  * simply return zeros as product id. Lesson: forget about querying devices to generate a device list.
86  *
87  * 3) Polling is a thorny issue: too much traffic on the network, and messages will be dropped left and right,
88  * and not just the poll related ones, but others as well. In particular sending back-to-back messages
89  * seemed to result in the second message simply never getting sent, without flow control back pressure
90  * (NACK) from the modem. For now the work-around is to space out the messages upon sending, and
91  * in general poll as infrequently as acceptable.
92  *
93  * 4) Instantiating and tracking devices when reported by the modem (either from the database, or when
94  * messages are received) leads to complicated state management because there is no guarantee at what
95  * point (if at all) the binding configuration will be available. It gets even more difficult when
96  * items are created, destroyed, and modified while the binding runs.
97  *
98  * For the above reasons, devices are only instantiated when they are referenced by binding information.
99  * As nice as it would be to discover devices and their properties dynamically, we have abandoned that
100  * path because it had led to a complicated and fragile system which due to the technical limitations
101  * above was inherently squirrely.
102  *
103  *
104  * @author Bernd Pfrommer - Initial contribution
105  * @author Daniel Pfrommer - openHAB 1 insteonplm binding
106  * @author Rob Nielsen - Port to openHAB 2 insteon binding
107  */
108 @NonNullByDefault
109 @SuppressWarnings({ "null", "unused" })
110 public class InsteonBinding {
111     private static final int DEAD_DEVICE_COUNT = 10;
112
113     private final Logger logger = LoggerFactory.getLogger(InsteonBinding.class);
114
115     private Driver driver;
116     private ConcurrentHashMap<InsteonAddress, InsteonDevice> devices = new ConcurrentHashMap<>();
117     private ConcurrentHashMap<String, InsteonChannelConfiguration> bindingConfigs = new ConcurrentHashMap<>();
118     private PortListener portListener = new PortListener();
119     private int devicePollIntervalMilliseconds = 300000;
120     private int deadDeviceTimeout = -1;
121     private int messagesReceived = 0;
122     private boolean isActive = false; // state of binding
123     private int x10HouseUnit = -1;
124     private InsteonNetworkHandler handler;
125
126     public InsteonBinding(InsteonNetworkHandler handler, @Nullable InsteonNetworkConfiguration config,
127             @Nullable SerialPortManager serialPortManager, ScheduledExecutorService scheduler) {
128         this.handler = handler;
129
130         String port = config.getPort();
131         logger.debug("port = '{}'", Utils.redactPassword(port));
132
133         driver = new Driver(port, portListener, serialPortManager, scheduler);
134         driver.addMsgListener(portListener);
135
136         Integer devicePollIntervalSeconds = config.getDevicePollIntervalSeconds();
137         if (devicePollIntervalSeconds != null) {
138             devicePollIntervalMilliseconds = devicePollIntervalSeconds * 1000;
139         }
140         logger.debug("device poll interval set to {} seconds", devicePollIntervalMilliseconds / 1000);
141
142         String additionalDevices = config.getAdditionalDevices();
143         if (additionalDevices != null) {
144             try {
145                 DeviceTypeLoader.instance().loadDeviceTypesXML(additionalDevices);
146                 logger.debug("read additional device definitions from {}", additionalDevices);
147             } catch (ParserConfigurationException | SAXException | IOException e) {
148                 logger.warn("error reading additional devices from {}", additionalDevices, e);
149             }
150         }
151
152         String additionalFeatures = config.getAdditionalFeatures();
153         if (additionalFeatures != null) {
154             logger.debug("reading additional feature templates from {}", additionalFeatures);
155             DeviceFeature.readFeatureTemplates(additionalFeatures);
156         }
157
158         deadDeviceTimeout = devicePollIntervalMilliseconds * DEAD_DEVICE_COUNT;
159         logger.debug("dead device timeout set to {} seconds", deadDeviceTimeout / 1000);
160     }
161
162     public Driver getDriver() {
163         return driver;
164     }
165
166     public boolean startPolling() {
167         logger.debug("starting to poll {}", driver.getPortName());
168         driver.start();
169         return driver.isRunning();
170     }
171
172     public void setIsActive(boolean isActive) {
173         this.isActive = isActive;
174     }
175
176     public void sendCommand(String channelName, Command command) {
177         if (!isActive) {
178             logger.debug("not ready to handle commands yet, returning.");
179             return;
180         }
181
182         InsteonChannelConfiguration bindingConfig = bindingConfigs.get(channelName);
183         if (bindingConfig == null) {
184             logger.warn("unable to find binding config for channel {}", channelName);
185             return;
186         }
187
188         InsteonDevice dev = getDevice(bindingConfig.getAddress());
189         if (dev == null) {
190             logger.warn("no device found with insteon address {}", bindingConfig.getAddress());
191             return;
192         }
193
194         dev.processCommand(driver, bindingConfig, command);
195
196         logger.debug("found binding config for channel {}", channelName);
197     }
198
199     public void addFeatureListener(InsteonChannelConfiguration bindingConfig) {
200         logger.debug("adding listener for channel {}", bindingConfig.getChannelName());
201
202         InsteonAddress address = bindingConfig.getAddress();
203         InsteonDevice dev = getDevice(address);
204         @Nullable
205         DeviceFeature f = dev.getFeature(bindingConfig.getFeature());
206         if (f == null || f.isFeatureGroup()) {
207             StringBuilder buf = new StringBuilder();
208             ArrayList<String> names = new ArrayList<>(dev.getFeatures().keySet());
209             Collections.sort(names);
210             for (String name : names) {
211                 DeviceFeature feature = dev.getFeature(name);
212                 if (!feature.isFeatureGroup()) {
213                     if (buf.length() > 0) {
214                         buf.append(", ");
215                     }
216                     buf.append(name);
217                 }
218             }
219
220             logger.warn("channel {} references unknown feature: {}, it will be ignored. Known features for {} are: {}.",
221                     bindingConfig.getChannelName(), bindingConfig.getFeature(), bindingConfig.getProductKey(),
222                     buf.toString());
223             return;
224         }
225
226         DeviceFeatureListener fl = new DeviceFeatureListener(this, bindingConfig.getChannelUID(),
227                 bindingConfig.getChannelName());
228         fl.setParameters(bindingConfig.getParameters());
229         f.addListener(fl);
230
231         bindingConfigs.put(bindingConfig.getChannelName(), bindingConfig);
232     }
233
234     public void removeFeatureListener(ChannelUID channelUID) {
235         String channelName = channelUID.getAsString();
236
237         logger.debug("removing listener for channel {}", channelName);
238
239         for (Iterator<Entry<InsteonAddress, InsteonDevice>> it = devices.entrySet().iterator(); it.hasNext();) {
240             InsteonDevice dev = it.next().getValue();
241             boolean removedListener = dev.removeFeatureListener(channelName);
242             if (removedListener) {
243                 logger.trace("removed feature listener {} from dev {}", channelName, dev);
244             }
245         }
246     }
247
248     public void updateFeatureState(ChannelUID channelUID, State state) {
249         handler.updateState(channelUID, state);
250     }
251
252     public InsteonDevice makeNewDevice(InsteonAddress addr, String productKey,
253             Map<String, @Nullable Object> deviceConfigMap) {
254         DeviceType dt = DeviceTypeLoader.instance().getDeviceType(productKey);
255         InsteonDevice dev = InsteonDevice.makeDevice(dt);
256         dev.setAddress(addr);
257         dev.setProductKey(productKey);
258         dev.setDriver(driver);
259         dev.setIsModem(productKey.equals(InsteonDeviceHandler.PLM_PRODUCT_KEY));
260         dev.setDeviceConfigMap(deviceConfigMap);
261         if (!dev.hasValidPollingInterval()) {
262             dev.setPollInterval(devicePollIntervalMilliseconds);
263         }
264         if (driver.isModemDBComplete() && dev.getStatus() != DeviceStatus.POLLING) {
265             int ndev = checkIfInModemDatabase(dev);
266             if (dev.hasModemDBEntry()) {
267                 dev.setStatus(DeviceStatus.POLLING);
268                 Poller.instance().startPolling(dev, ndev);
269             }
270         }
271         devices.put(addr, dev);
272
273         handler.insteonDeviceWasCreated();
274
275         return (dev);
276     }
277
278     public void removeDevice(InsteonAddress addr) {
279         InsteonDevice dev = devices.remove(addr);
280         if (dev == null) {
281             return;
282         }
283
284         if (dev.getStatus() == DeviceStatus.POLLING) {
285             Poller.instance().stopPolling(dev);
286         }
287     }
288
289     /**
290      * Checks if a device is in the modem link database, and, if the database
291      * is complete, logs a warning if the device is not present
292      *
293      * @param dev The device to search for in the modem database
294      * @return number of devices in modem database
295      */
296     private int checkIfInModemDatabase(InsteonDevice dev) {
297         try {
298             InsteonAddress addr = dev.getAddress();
299             Map<InsteonAddress, @Nullable ModemDBEntry> dbes = driver.lockModemDBEntries();
300             if (dbes.containsKey(addr)) {
301                 if (!dev.hasModemDBEntry()) {
302                     logger.debug("device {} found in the modem database and {}.", addr, getLinkInfo(dbes, addr, true));
303                     dev.setHasModemDBEntry(true);
304                 }
305             } else {
306                 if (driver.isModemDBComplete() && !addr.isX10()) {
307                     logger.warn("device {} not found in the modem database. Did you forget to link?", addr);
308                 }
309             }
310             return dbes.size();
311         } finally {
312             driver.unlockModemDBEntries();
313         }
314     }
315
316     public Map<String, String> getDatabaseInfo() {
317         try {
318             Map<String, String> databaseInfo = new HashMap<>();
319             Map<InsteonAddress, @Nullable ModemDBEntry> dbes = driver.lockModemDBEntries();
320             for (InsteonAddress addr : dbes.keySet()) {
321                 String a = addr.toString();
322                 databaseInfo.put(a, a + ": " + getLinkInfo(dbes, addr, false));
323             }
324
325             return databaseInfo;
326         } finally {
327             driver.unlockModemDBEntries();
328         }
329     }
330
331     public boolean reconnect() {
332         driver.stop();
333         return startPolling();
334     }
335
336     /**
337      * Everything below was copied from Insteon PLM v1
338      */
339
340     /**
341      * Clean up all state.
342      */
343     public void shutdown() {
344         logger.debug("shutting down Insteon bridge");
345         driver.stop();
346         devices.clear();
347         RequestQueueManager.destroyInstance();
348         Poller.instance().stop();
349         isActive = false;
350     }
351
352     /**
353      * Method to find a device by address
354      *
355      * @param aAddr the insteon address to search for
356      * @return reference to the device, or null if not found
357      */
358     public @Nullable InsteonDevice getDevice(@Nullable InsteonAddress aAddr) {
359         InsteonDevice dev = (aAddr == null) ? null : devices.get(aAddr);
360         return (dev);
361     }
362
363     private String getLinkInfo(Map<InsteonAddress, @Nullable ModemDBEntry> dbes, InsteonAddress a, boolean prefix) {
364         ModemDBEntry dbe = dbes.get(a);
365         List<Byte> controls = dbe.getControls();
366         List<Byte> responds = dbe.getRespondsTo();
367
368         Port port = dbe.getPort();
369         String deviceName = port.getDeviceName();
370         String s = deviceName.startsWith("/hub") ? "hub" : "plm";
371         StringBuilder buf = new StringBuilder();
372         if (port.isModem(a)) {
373             if (prefix) {
374                 buf.append("it is the ");
375             }
376             buf.append(s);
377             buf.append(" (");
378             buf.append(Utils.redactPassword(deviceName));
379             buf.append(")");
380         } else {
381             if (prefix) {
382                 buf.append("the ");
383             }
384             buf.append(s);
385             buf.append(" controls groups (");
386             buf.append(toGroupString(controls));
387             buf.append(") and responds to groups (");
388             buf.append(toGroupString(responds));
389             buf.append(")");
390         }
391
392         return buf.toString();
393     }
394
395     private String toGroupString(List<Byte> group) {
396         List<Byte> sorted = new ArrayList<>(group);
397         Collections.sort(sorted, new Comparator<Byte>() {
398             @Override
399             public int compare(Byte b1, Byte b2) {
400                 int i1 = b1 & 0xFF;
401                 int i2 = b2 & 0xFF;
402                 return i1 < i2 ? -1 : i1 == i2 ? 0 : 1;
403             }
404         });
405
406         StringBuilder buf = new StringBuilder();
407         for (Byte b : sorted) {
408             if (buf.length() > 0) {
409                 buf.append(",");
410             }
411             buf.append(b & 0xFF);
412         }
413
414         return buf.toString();
415     }
416
417     public void logDeviceStatistics() {
418         String msg = String.format("devices: %3d configured, %3d polling, msgs received: %5d", devices.size(),
419                 Poller.instance().getSizeOfQueue(), messagesReceived);
420         logger.debug("{}", msg);
421         messagesReceived = 0;
422         for (InsteonDevice dev : devices.values()) {
423             if (dev.isModem()) {
424                 continue;
425             }
426             if (deadDeviceTimeout > 0 && dev.getPollOverDueTime() > deadDeviceTimeout) {
427                 logger.debug("device {} has not responded to polls for {} sec", dev.toString(),
428                         dev.getPollOverDueTime() / 3600);
429             }
430         }
431     }
432
433     /**
434      * Handles messages that come in from the ports.
435      * Will only process one message at a time.
436      */
437     @NonNullByDefault
438     private class PortListener implements MsgListener, DriverListener {
439         @Override
440         public void msg(Msg msg) {
441             if (msg.isEcho() || msg.isPureNack()) {
442                 return;
443             }
444             messagesReceived++;
445             logger.debug("got msg: {}", msg);
446             if (msg.isX10()) {
447                 handleX10Message(msg);
448             } else {
449                 handleInsteonMessage(msg);
450             }
451         }
452
453         @Override
454         public void driverCompletelyInitialized() {
455             List<String> missing = new ArrayList<>();
456             try {
457                 Map<InsteonAddress, @Nullable ModemDBEntry> dbes = driver.lockModemDBEntries();
458                 logger.debug("modem database has {} entries!", dbes.size());
459                 if (dbes.isEmpty()) {
460                     logger.warn("the modem link database is empty!");
461                 }
462                 for (InsteonAddress k : dbes.keySet()) {
463                     logger.debug("modem db entry: {}", k);
464                 }
465                 Set<InsteonAddress> addrs = new HashSet<>();
466                 for (InsteonDevice dev : devices.values()) {
467                     InsteonAddress a = dev.getAddress();
468                     if (!dbes.containsKey(a)) {
469                         if (!a.isX10()) {
470                             logger.warn("device {} not found in the modem database. Did you forget to link?", a);
471                         }
472                     } else {
473                         if (!dev.hasModemDBEntry()) {
474                             addrs.add(a);
475                             logger.debug("device {} found in the modem database and {}.", a,
476                                     getLinkInfo(dbes, a, true));
477                             dev.setHasModemDBEntry(true);
478                         }
479                         if (dev.getStatus() != DeviceStatus.POLLING) {
480                             Poller.instance().startPolling(dev, dbes.size());
481                         }
482                     }
483                 }
484
485                 for (InsteonAddress k : dbes.keySet()) {
486                     if (!addrs.contains(k)) {
487                         logger.debug("device {} found in the modem database, but is not configured as a thing and {}.",
488                                 k, getLinkInfo(dbes, k, true));
489
490                         missing.add(k.toString());
491                     }
492                 }
493             } finally {
494                 driver.unlockModemDBEntries();
495             }
496
497             if (!missing.isEmpty()) {
498                 handler.addMissingDevices(missing);
499             }
500         }
501
502         @Override
503         public void disconnected() {
504             handler.bindingDisconnected();
505         }
506
507         private void handleInsteonMessage(Msg msg) {
508             InsteonAddress toAddr = msg.getAddr("toAddress");
509             if (!msg.isBroadcast() && !driver.isMsgForUs(toAddr)) {
510                 // not for one of our modems, do not process
511                 return;
512             }
513             InsteonAddress fromAddr = msg.getAddr("fromAddress");
514             if (fromAddr == null) {
515                 logger.debug("invalid fromAddress, ignoring msg {}", msg);
516                 return;
517             }
518             handleMessage(fromAddr, msg);
519         }
520
521         private void handleX10Message(Msg msg) {
522             try {
523                 int x10Flag = msg.getByte("X10Flag") & 0xff;
524                 int rawX10 = msg.getByte("rawX10") & 0xff;
525                 if (x10Flag == 0x80) { // actual command
526                     if (x10HouseUnit != -1) {
527                         InsteonAddress fromAddr = new InsteonAddress((byte) x10HouseUnit);
528                         handleMessage(fromAddr, msg);
529                     }
530                 } else if (x10Flag == 0) {
531                     // what unit the next cmd will apply to
532                     x10HouseUnit = rawX10 & 0xFF;
533                 }
534             } catch (FieldException e) {
535                 logger.warn("got bad X10 message: {}", msg, e);
536                 return;
537             }
538         }
539
540         private void handleMessage(InsteonAddress fromAddr, Msg msg) {
541             InsteonDevice dev = getDevice(fromAddr);
542             if (dev == null) {
543                 logger.debug("dropping message from unknown device with address {}", fromAddr);
544             } else {
545                 dev.handleMessage(msg);
546             }
547         }
548     }
549 }