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;
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.openhab.binding.insteon.internal.config.InsteonChannelConfiguration;
24 import org.openhab.binding.insteon.internal.device.DeviceFeatureListener.StateChangeType;
25 import org.openhab.binding.insteon.internal.message.Msg;
26 import org.openhab.binding.insteon.internal.utils.Utils.ParsingException;
27 import org.openhab.core.types.Command;
28 import org.openhab.core.types.State;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
33 * A DeviceFeature represents a certain feature (trait) of a given Insteon device, e.g. something
34 * operating under a given InsteonAddress that can be manipulated (relay) or read (sensor).
36 * The DeviceFeature does the processing of incoming messages, and handles commands for the
37 * particular feature it represents.
39 * It uses four mechanisms for that:
41 * 1) MessageDispatcher: makes high level decisions about an incoming message and then runs the
42 * 2) MessageHandler: further processes the message, updates state etc
43 * 3) CommandHandler: translates commands from the openhab bus into an Insteon message.
44 * 4) PollHandler: creates an Insteon message to query the DeviceFeature
46 * Lastly, DeviceFeatureListeners can register with the DeviceFeature to get notifications when
47 * the state of a feature has changed. In practice, a DeviceFeatureListener corresponds to an
50 * The character of a DeviceFeature is thus given by a set of message and command handlers.
51 * A FeatureTemplate captures exactly that: it says what set of handlers make up a DeviceFeature.
53 * DeviceFeatures are added to a new device by referencing a FeatureTemplate (defined in device_features.xml)
54 * from the Device definition file (device_types.xml).
56 * @author Daniel Pfrommer - Initial contribution
57 * @author Bernd Pfrommer - openHAB 1 insteonplm binding
58 * @author Rob Nielsen - Port to openHAB 2 insteon binding
61 public class DeviceFeature {
62 public static enum QueryStatus {
68 private static final Logger logger = LoggerFactory.getLogger(DeviceFeature.class);
70 private static Map<String, FeatureTemplate> features = new HashMap<>();
72 private InsteonDevice device = new InsteonDevice();
73 private String name = "INVALID_FEATURE_NAME";
74 private boolean isStatus = false;
75 private int directAckTimeout = 6000;
76 private QueryStatus queryStatus = QueryStatus.NEVER_QUERIED;
78 private MessageHandler defaultMsgHandler = new MessageHandler.DefaultMsgHandler(this);
79 private CommandHandler defaultCommandHandler = new CommandHandler.WarnCommandHandler(this);
80 private @Nullable PollHandler pollHandler = null;
81 private @Nullable MessageDispatcher dispatcher = null;
83 private Map<Integer, @Nullable MessageHandler> msgHandlers = new HashMap<>();
84 private Map<Class<? extends Command>, @Nullable CommandHandler> commandHandlers = new HashMap<>();
85 private List<DeviceFeatureListener> listeners = new ArrayList<>();
86 private List<DeviceFeature> connectedFeatures = new ArrayList<>();
91 * @param device Insteon device to which this feature belongs
92 * @param name descriptive name for that feature
94 public DeviceFeature(InsteonDevice device, String name) {
102 * @param name descriptive name of the feature
104 public DeviceFeature(String name) {
108 // various simple getters
109 public String getName() {
113 public synchronized QueryStatus getQueryStatus() {
117 public InsteonDevice getDevice() {
121 public boolean isFeatureGroup() {
122 return !connectedFeatures.isEmpty();
125 public boolean isStatusFeature() {
129 public int getDirectAckTimeout() {
130 return directAckTimeout;
133 public MessageHandler getDefaultMsgHandler() {
134 return defaultMsgHandler;
137 public Map<Integer, @Nullable MessageHandler> getMsgHandlers() {
138 return this.msgHandlers;
141 public List<DeviceFeature> getConnectedFeatures() {
142 return (connectedFeatures);
145 // various simple setters
146 public void setStatusFeature(boolean f) {
150 public void setPollHandler(@Nullable PollHandler h) {
154 public void setDevice(InsteonDevice d) {
158 public void setMessageDispatcher(@Nullable MessageDispatcher md) {
162 public void setDefaultCommandHandler(CommandHandler ch) {
163 defaultCommandHandler = ch;
166 public void setDefaultMsgHandler(MessageHandler mh) {
167 defaultMsgHandler = mh;
170 public synchronized void setQueryStatus(QueryStatus status) {
171 logger.trace("{} set query status to: {}", name, status);
172 queryStatus = status;
175 public void setTimeout(@Nullable String s) {
176 if (s != null && !s.isEmpty()) {
178 directAckTimeout = Integer.parseInt(s);
179 logger.trace("ack timeout set to {}", directAckTimeout);
180 } catch (NumberFormatException e) {
181 logger.warn("invalid number for timeout: {}", s);
187 * Add a listener (item) to a device feature
189 * @param l the listener
191 public void addListener(DeviceFeatureListener l) {
192 synchronized (listeners) {
193 for (DeviceFeatureListener m : listeners) {
194 if (m.getItemName().equals(l.getItemName())) {
203 * Adds a connected feature such that this DeviceFeature can
204 * act as a feature group
206 * @param f the device feature related to this feature
208 public void addConnectedFeature(DeviceFeature f) {
209 connectedFeatures.add(f);
212 public boolean hasListeners() {
213 if (!listeners.isEmpty()) {
216 for (DeviceFeature f : connectedFeatures) {
217 if (f.hasListeners()) {
225 * removes a DeviceFeatureListener from this feature
227 * @param aItemName name of the item to remove as listener
228 * @return true if a listener was removed
230 public boolean removeListener(String aItemName) {
231 boolean listenerRemoved = false;
232 synchronized (listeners) {
233 for (Iterator<DeviceFeatureListener> it = listeners.iterator(); it.hasNext();) {
234 DeviceFeatureListener fl = it.next();
235 if (fl.getItemName().equals(aItemName)) {
237 listenerRemoved = true;
241 return listenerRemoved;
244 public boolean isReferencedByItem(String aItemName) {
245 synchronized (listeners) {
246 for (DeviceFeatureListener fl : listeners) {
247 if (fl.getItemName().equals(aItemName)) {
256 * Called when message is incoming. Dispatches message according to message dispatcher
258 * @param msg The message to dispatch
259 * @return true if dispatch successful
261 public boolean handleMessage(Msg msg) {
262 MessageDispatcher dispatcher = this.dispatcher;
263 if (dispatcher == null) {
264 logger.warn("{} no dispatcher for msg {}", name, msg);
267 return dispatcher.dispatch(msg);
271 * Called when an openhab command arrives for this device feature
273 * @param c the binding config of the item which sends the command
274 * @param cmd the command to be exectued
276 public void handleCommand(InsteonChannelConfiguration c, Command cmd) {
277 Class<? extends Command> key = cmd.getClass();
278 CommandHandler h = commandHandlers.containsKey(key) ? commandHandlers.get(key) : defaultCommandHandler;
280 logger.trace("{} uses {} to handle command {} for {}", getName(), h.getClass().getSimpleName(),
281 key.getSimpleName(), getDevice().getAddress());
282 h.handleCommand(c, cmd, getDevice());
287 * Make a poll message using the configured poll message handler
289 * @return the poll message
291 public @Nullable Msg makePollMsg() {
292 PollHandler pollHandler = this.pollHandler;
293 if (pollHandler == null) {
296 logger.trace("{} making poll msg for {} using handler {}", getName(), getDevice().getAddress(),
297 pollHandler.getClass().getSimpleName());
298 Msg m = pollHandler.makeMsg(device);
303 * Publish new state to all device feature listeners, but give them
304 * additional dataKey and dataValue information so they can decide
305 * whether to publish the data to the bus.
307 * @param newState state to be published
308 * @param changeType what kind of changes to publish
309 * @param dataKey the key on which to filter
310 * @param dataValue the value that must be matched
312 public void publish(State newState, StateChangeType changeType, String dataKey, String dataValue) {
313 logger.debug("{}:{} publishing: {}", this.getDevice().getAddress(), getName(), newState);
314 synchronized (listeners) {
315 for (DeviceFeatureListener listener : listeners) {
316 listener.stateChanged(newState, changeType, dataKey, dataValue);
322 * Publish new state to all device feature listeners
324 * @param newState state to be published
325 * @param changeType what kind of changes to publish
327 public void publish(State newState, StateChangeType changeType) {
328 logger.debug("{}:{} publishing: {}", this.getDevice().getAddress(), getName(), newState);
329 synchronized (listeners) {
330 for (DeviceFeatureListener listener : listeners) {
331 listener.stateChanged(newState, changeType);
337 * Poll all device feature listeners for related devices
339 public void pollRelatedDevices() {
340 synchronized (listeners) {
341 for (DeviceFeatureListener listener : listeners) {
342 listener.pollRelatedDevices();
348 * Adds a message handler to this device feature.
350 * @param cm1 The insteon cmd1 of the incoming message for which the handler should be used
351 * @param handler the handler to invoke
353 public void addMessageHandler(int cm1, @Nullable MessageHandler handler) {
354 synchronized (msgHandlers) {
355 msgHandlers.put(cm1, handler);
360 * Adds a command handler to this device feature
362 * @param c the command for which this handler is invoked
363 * @param handler the handler to call
365 public void addCommandHandler(Class<? extends Command> c, @Nullable CommandHandler handler) {
366 synchronized (commandHandlers) {
367 commandHandlers.put(c, handler);
372 * Turn DeviceFeature into String
375 public String toString() {
376 return name + "(" + listeners.size() + ":" + commandHandlers.size() + ":" + msgHandlers.size() + ")";
380 * Factory method for creating DeviceFeatures.
382 * @param s The name of the device feature to create.
383 * @return The newly created DeviceFeature, or null if requested DeviceFeature does not exist.
386 public static DeviceFeature makeDeviceFeature(String s) {
387 DeviceFeature f = null;
388 synchronized (features) {
389 FeatureTemplate ft = features.get(s);
393 logger.warn("unimplemented feature requested: {}", s);
400 * Reads the features templates from an input stream and puts them in global map
402 * @param input the input stream from which to read the feature templates
404 public static void readFeatureTemplates(InputStream input) {
406 List<FeatureTemplate> featureTemplates = FeatureTemplateLoader.readTemplates(input);
407 synchronized (features) {
408 for (FeatureTemplate f : featureTemplates) {
409 features.put(f.getName(), f);
412 } catch (IOException e) {
413 logger.warn("IOException while reading device features", e);
414 } catch (ParsingException e) {
415 logger.warn("Parsing exception while reading device features", e);
420 * Reads the feature templates from a file and adds them to a global map
422 * @param file name of the file to read from
424 public static void readFeatureTemplates(String file) {
426 FileInputStream fis = new FileInputStream(file);
427 readFeatureTemplates(fis);
428 } catch (FileNotFoundException e) {
429 logger.warn("cannot read feature templates from file {} ", file, e);
437 // read features from xml file and store them in a map
438 InputStream input = DeviceFeature.class.getResourceAsStream("/device_features.xml");
439 Objects.requireNonNull(input);
440 readFeatureTemplates(input);