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.insteon.internal.device;
15 import java.io.FileInputStream;
16 import java.io.FileNotFoundException;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.util.ArrayList;
20 import java.util.HashMap;
21 import java.util.Iterator;
22 import java.util.List;
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.binding.insteon.internal.config.InsteonChannelConfiguration;
28 import org.openhab.binding.insteon.internal.device.DeviceFeatureListener.StateChangeType;
29 import org.openhab.binding.insteon.internal.message.Msg;
30 import org.openhab.binding.insteon.internal.utils.Utils.ParsingException;
31 import org.openhab.core.types.Command;
32 import org.openhab.core.types.State;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
37 * A DeviceFeature represents a certain feature (trait) of a given Insteon device, e.g. something
38 * operating under a given InsteonAddress that can be manipulated (relay) or read (sensor).
40 * The DeviceFeature does the processing of incoming messages, and handles commands for the
41 * particular feature it represents.
43 * It uses four mechanisms for that:
45 * 1) MessageDispatcher: makes high level decisions about an incoming message and then runs the
46 * 2) MessageHandler: further processes the message, updates state etc
47 * 3) CommandHandler: translates commands from the openhab bus into an Insteon message.
48 * 4) PollHandler: creates an Insteon message to query the DeviceFeature
50 * Lastly, DeviceFeatureListeners can register with the DeviceFeature to get notifications when
51 * the state of a feature has changed. In practice, a DeviceFeatureListener corresponds to an
54 * The character of a DeviceFeature is thus given by a set of message and command handlers.
55 * A FeatureTemplate captures exactly that: it says what set of handlers make up a DeviceFeature.
57 * DeviceFeatures are added to a new device by referencing a FeatureTemplate (defined in device_features.xml)
58 * from the Device definition file (device_types.xml).
60 * @author Daniel Pfrommer - Initial contribution
61 * @author Bernd Pfrommer - openHAB 1 insteonplm binding
62 * @author Rob Nielsen - Port to openHAB 2 insteon binding
65 public class DeviceFeature {
66 public static enum QueryStatus {
72 private static final Logger logger = LoggerFactory.getLogger(DeviceFeature.class);
74 private static Map<String, FeatureTemplate> features = new HashMap<>();
76 private InsteonDevice device = new InsteonDevice();
77 private String name = "INVALID_FEATURE_NAME";
78 private boolean isStatus = false;
79 private int directAckTimeout = 6000;
80 private QueryStatus queryStatus = QueryStatus.NEVER_QUERIED;
82 private MessageHandler defaultMsgHandler = new MessageHandler.DefaultMsgHandler(this);
83 private CommandHandler defaultCommandHandler = new CommandHandler.WarnCommandHandler(this);
84 private @Nullable PollHandler pollHandler = null;
85 private @Nullable MessageDispatcher dispatcher = null;
87 private Map<Integer, @Nullable MessageHandler> msgHandlers = new HashMap<>();
88 private Map<Class<? extends Command>, @Nullable CommandHandler> commandHandlers = new HashMap<>();
89 private List<DeviceFeatureListener> listeners = new ArrayList<>();
90 private List<DeviceFeature> connectedFeatures = new ArrayList<>();
95 * @param device Insteon device to which this feature belongs
96 * @param name descriptive name for that feature
98 public DeviceFeature(InsteonDevice device, String name) {
106 * @param name descriptive name of the feature
108 public DeviceFeature(String name) {
112 // various simple getters
113 public String getName() {
117 public synchronized QueryStatus getQueryStatus() {
121 public InsteonDevice getDevice() {
125 public boolean isFeatureGroup() {
126 return !connectedFeatures.isEmpty();
129 public boolean isStatusFeature() {
133 public int getDirectAckTimeout() {
134 return directAckTimeout;
137 public MessageHandler getDefaultMsgHandler() {
138 return defaultMsgHandler;
141 public Map<Integer, @Nullable MessageHandler> getMsgHandlers() {
142 return this.msgHandlers;
145 public List<DeviceFeature> getConnectedFeatures() {
146 return (connectedFeatures);
149 // various simple setters
150 public void setStatusFeature(boolean f) {
154 public void setPollHandler(@Nullable PollHandler h) {
158 public void setDevice(InsteonDevice d) {
162 public void setMessageDispatcher(@Nullable MessageDispatcher md) {
166 public void setDefaultCommandHandler(CommandHandler ch) {
167 defaultCommandHandler = ch;
170 public void setDefaultMsgHandler(MessageHandler mh) {
171 defaultMsgHandler = mh;
174 public synchronized void setQueryStatus(QueryStatus status) {
175 logger.trace("{} set query status to: {}", name, status);
176 queryStatus = status;
179 public void setTimeout(@Nullable String s) {
180 if (s != null && !s.isEmpty()) {
182 directAckTimeout = Integer.parseInt(s);
183 logger.trace("ack timeout set to {}", directAckTimeout);
184 } catch (NumberFormatException e) {
185 logger.warn("invalid number for timeout: {}", s);
191 * Add a listener (item) to a device feature
193 * @param l the listener
195 public void addListener(DeviceFeatureListener l) {
196 synchronized (listeners) {
197 for (DeviceFeatureListener m : listeners) {
198 if (m.getItemName().equals(l.getItemName())) {
207 * Adds a connected feature such that this DeviceFeature can
208 * act as a feature group
210 * @param f the device feature related to this feature
212 public void addConnectedFeature(DeviceFeature f) {
213 connectedFeatures.add(f);
216 public boolean hasListeners() {
217 if (!listeners.isEmpty()) {
220 for (DeviceFeature f : connectedFeatures) {
221 if (f.hasListeners()) {
229 * removes a DeviceFeatureListener from this feature
231 * @param aItemName name of the item to remove as listener
232 * @return true if a listener was removed
234 public boolean removeListener(String aItemName) {
235 boolean listenerRemoved = false;
236 synchronized (listeners) {
237 for (Iterator<DeviceFeatureListener> it = listeners.iterator(); it.hasNext();) {
238 DeviceFeatureListener fl = it.next();
239 if (fl.getItemName().equals(aItemName)) {
241 listenerRemoved = true;
245 return listenerRemoved;
248 public boolean isReferencedByItem(String aItemName) {
249 synchronized (listeners) {
250 for (DeviceFeatureListener fl : listeners) {
251 if (fl.getItemName().equals(aItemName)) {
260 * Called when message is incoming. Dispatches message according to message dispatcher
262 * @param msg The message to dispatch
263 * @return true if dispatch successful
265 public boolean handleMessage(Msg msg) {
266 MessageDispatcher dispatcher = this.dispatcher;
267 if (dispatcher == null) {
268 logger.warn("{} no dispatcher for msg {}", name, msg);
271 return dispatcher.dispatch(msg);
275 * Called when an openhab command arrives for this device feature
277 * @param c the binding config of the item which sends the command
278 * @param cmd the command to be exectued
280 public void handleCommand(InsteonChannelConfiguration c, Command cmd) {
281 Class<? extends Command> key = cmd.getClass();
282 CommandHandler h = commandHandlers.containsKey(key) ? commandHandlers.get(key) : defaultCommandHandler;
284 logger.trace("{} uses {} to handle command {} for {}", getName(), h.getClass().getSimpleName(),
285 key.getSimpleName(), getDevice().getAddress());
286 h.handleCommand(c, cmd, getDevice());
291 * Make a poll message using the configured poll message handler
293 * @return the poll message
295 public @Nullable Msg makePollMsg() {
296 PollHandler pollHandler = this.pollHandler;
297 if (pollHandler == null) {
300 logger.trace("{} making poll msg for {} using handler {}", getName(), getDevice().getAddress(),
301 pollHandler.getClass().getSimpleName());
302 Msg m = pollHandler.makeMsg(device);
307 * Publish new state to all device feature listeners, but give them
308 * additional dataKey and dataValue information so they can decide
309 * whether to publish the data to the bus.
311 * @param newState state to be published
312 * @param changeType what kind of changes to publish
313 * @param dataKey the key on which to filter
314 * @param dataValue the value that must be matched
316 public void publish(State newState, StateChangeType changeType, String dataKey, String dataValue) {
317 logger.debug("{}:{} publishing: {}", this.getDevice().getAddress(), getName(), newState);
318 synchronized (listeners) {
319 for (DeviceFeatureListener listener : listeners) {
320 listener.stateChanged(newState, changeType, dataKey, dataValue);
326 * Publish new state to all device feature listeners
328 * @param newState state to be published
329 * @param changeType what kind of changes to publish
331 public void publish(State newState, StateChangeType changeType) {
332 logger.debug("{}:{} publishing: {}", this.getDevice().getAddress(), getName(), newState);
333 synchronized (listeners) {
334 for (DeviceFeatureListener listener : listeners) {
335 listener.stateChanged(newState, changeType);
341 * Poll all device feature listeners for related devices
343 public void pollRelatedDevices() {
344 synchronized (listeners) {
345 for (DeviceFeatureListener listener : listeners) {
346 listener.pollRelatedDevices();
352 * Adds a message handler to this device feature.
354 * @param cm1 The insteon cmd1 of the incoming message for which the handler should be used
355 * @param handler the handler to invoke
357 public void addMessageHandler(int cm1, @Nullable MessageHandler handler) {
358 synchronized (msgHandlers) {
359 msgHandlers.put(cm1, handler);
364 * Adds a command handler to this device feature
366 * @param c the command for which this handler is invoked
367 * @param handler the handler to call
369 public void addCommandHandler(Class<? extends Command> c, @Nullable CommandHandler handler) {
370 synchronized (commandHandlers) {
371 commandHandlers.put(c, handler);
376 * Turn DeviceFeature into String
379 public String toString() {
380 return name + "(" + listeners.size() + ":" + commandHandlers.size() + ":" + msgHandlers.size() + ")";
384 * Factory method for creating DeviceFeatures.
386 * @param s The name of the device feature to create.
387 * @return The newly created DeviceFeature, or null if requested DeviceFeature does not exist.
390 public static DeviceFeature makeDeviceFeature(String s) {
391 DeviceFeature f = null;
392 synchronized (features) {
393 FeatureTemplate ft = features.get(s);
397 logger.warn("unimplemented feature requested: {}", s);
404 * Reads the features templates from an input stream and puts them in global map
406 * @param input the input stream from which to read the feature templates
408 public static void readFeatureTemplates(InputStream input) {
410 List<FeatureTemplate> featureTemplates = FeatureTemplateLoader.readTemplates(input);
411 synchronized (features) {
412 for (FeatureTemplate f : featureTemplates) {
413 features.put(f.getName(), f);
416 } catch (IOException e) {
417 logger.warn("IOException while reading device features", e);
418 } catch (ParsingException e) {
419 logger.warn("Parsing exception while reading device features", e);
424 * Reads the feature templates from a file and adds them to a global map
426 * @param file name of the file to read from
428 public static void readFeatureTemplates(String file) {
430 FileInputStream fis = new FileInputStream(file);
431 readFeatureTemplates(fis);
432 } catch (FileNotFoundException e) {
433 logger.warn("cannot read feature templates from file {} ", file, e);
441 // read features from xml file and store them in a map
442 InputStream input = DeviceFeature.class.getResourceAsStream("/device_features.xml");
444 readFeatureTemplates(input);