]> git.basschouten.com Git - openhab-addons.git/blob
c31ce17a118523779c9180867d8443ec8b76bc89
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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.device;
14
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;
23 import java.util.Map;
24 import java.util.Objects;
25
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.insteon.internal.config.InsteonChannelConfiguration;
29 import org.openhab.binding.insteon.internal.device.DeviceFeatureListener.StateChangeType;
30 import org.openhab.binding.insteon.internal.message.Msg;
31 import org.openhab.binding.insteon.internal.utils.Utils.ParsingException;
32 import org.openhab.core.types.Command;
33 import org.openhab.core.types.State;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38  * A DeviceFeature represents a certain feature (trait) of a given Insteon device, e.g. something
39  * operating under a given InsteonAddress that can be manipulated (relay) or read (sensor).
40  *
41  * The DeviceFeature does the processing of incoming messages, and handles commands for the
42  * particular feature it represents.
43  *
44  * It uses four mechanisms for that:
45  *
46  * 1) MessageDispatcher: makes high level decisions about an incoming message and then runs the
47  * 2) MessageHandler: further processes the message, updates state etc
48  * 3) CommandHandler: translates commands from the openhab bus into an Insteon message.
49  * 4) PollHandler: creates an Insteon message to query the DeviceFeature
50  *
51  * Lastly, DeviceFeatureListeners can register with the DeviceFeature to get notifications when
52  * the state of a feature has changed. In practice, a DeviceFeatureListener corresponds to an
53  * openHAB item.
54  *
55  * The character of a DeviceFeature is thus given by a set of message and command handlers.
56  * A FeatureTemplate captures exactly that: it says what set of handlers make up a DeviceFeature.
57  *
58  * DeviceFeatures are added to a new device by referencing a FeatureTemplate (defined in device_features.xml)
59  * from the Device definition file (device_types.xml).
60  *
61  * @author Daniel Pfrommer - Initial contribution
62  * @author Bernd Pfrommer - openHAB 1 insteonplm binding
63  * @author Rob Nielsen - Port to openHAB 2 insteon binding
64  */
65 @NonNullByDefault
66 public class DeviceFeature {
67     public enum QueryStatus {
68         NEVER_QUERIED,
69         QUERY_PENDING,
70         QUERY_ANSWERED
71     }
72
73     private static final Logger logger = LoggerFactory.getLogger(DeviceFeature.class);
74
75     private static Map<String, FeatureTemplate> features = new HashMap<>();
76
77     private InsteonDevice device = new InsteonDevice();
78     private String name = "INVALID_FEATURE_NAME";
79     private boolean isStatus = false;
80     private int directAckTimeout = 6000;
81     private QueryStatus queryStatus = QueryStatus.NEVER_QUERIED;
82
83     private MessageHandler defaultMsgHandler = new MessageHandler.DefaultMsgHandler(this);
84     private CommandHandler defaultCommandHandler = new CommandHandler.WarnCommandHandler(this);
85     private @Nullable PollHandler pollHandler = null;
86     private @Nullable MessageDispatcher dispatcher = null;
87
88     private Map<Integer, @Nullable MessageHandler> msgHandlers = new HashMap<>();
89     private Map<Class<? extends Command>, @Nullable CommandHandler> commandHandlers = new HashMap<>();
90     private List<DeviceFeatureListener> listeners = new ArrayList<>();
91     private List<DeviceFeature> connectedFeatures = new ArrayList<>();
92
93     /**
94      * Constructor
95      *
96      * @param device Insteon device to which this feature belongs
97      * @param name descriptive name for that feature
98      */
99     public DeviceFeature(InsteonDevice device, String name) {
100         this.name = name;
101         setDevice(device);
102     }
103
104     /**
105      * Constructor
106      *
107      * @param name descriptive name of the feature
108      */
109     public DeviceFeature(String name) {
110         this.name = name;
111     }
112
113     // various simple getters
114     public String getName() {
115         return name;
116     }
117
118     public synchronized QueryStatus getQueryStatus() {
119         return queryStatus;
120     }
121
122     public InsteonDevice getDevice() {
123         return device;
124     }
125
126     public boolean isFeatureGroup() {
127         return !connectedFeatures.isEmpty();
128     }
129
130     public boolean isStatusFeature() {
131         return isStatus;
132     }
133
134     public int getDirectAckTimeout() {
135         return directAckTimeout;
136     }
137
138     public MessageHandler getDefaultMsgHandler() {
139         return defaultMsgHandler;
140     }
141
142     public Map<Integer, @Nullable MessageHandler> getMsgHandlers() {
143         return this.msgHandlers;
144     }
145
146     public List<DeviceFeature> getConnectedFeatures() {
147         return (connectedFeatures);
148     }
149
150     // various simple setters
151     public void setStatusFeature(boolean f) {
152         isStatus = f;
153     }
154
155     public void setPollHandler(@Nullable PollHandler h) {
156         pollHandler = h;
157     }
158
159     public void setDevice(InsteonDevice d) {
160         device = d;
161     }
162
163     public void setMessageDispatcher(@Nullable MessageDispatcher md) {
164         dispatcher = md;
165     }
166
167     public void setDefaultCommandHandler(CommandHandler ch) {
168         defaultCommandHandler = ch;
169     }
170
171     public void setDefaultMsgHandler(MessageHandler mh) {
172         defaultMsgHandler = mh;
173     }
174
175     public synchronized void setQueryStatus(QueryStatus status) {
176         logger.trace("{} set query status to: {}", name, status);
177         queryStatus = status;
178     }
179
180     public void setTimeout(@Nullable String s) {
181         if (s != null && !s.isEmpty()) {
182             try {
183                 directAckTimeout = Integer.parseInt(s);
184                 logger.trace("ack timeout set to {}", directAckTimeout);
185             } catch (NumberFormatException e) {
186                 logger.warn("invalid number for timeout: {}", s);
187             }
188         }
189     }
190
191     /**
192      * Add a listener (item) to a device feature
193      *
194      * @param l the listener
195      */
196     public void addListener(DeviceFeatureListener l) {
197         synchronized (listeners) {
198             for (DeviceFeatureListener m : listeners) {
199                 if (m.getItemName().equals(l.getItemName())) {
200                     return;
201                 }
202             }
203             listeners.add(l);
204         }
205     }
206
207     /**
208      * Adds a connected feature such that this DeviceFeature can
209      * act as a feature group
210      *
211      * @param f the device feature related to this feature
212      */
213     public void addConnectedFeature(DeviceFeature f) {
214         connectedFeatures.add(f);
215     }
216
217     public boolean hasListeners() {
218         if (!listeners.isEmpty()) {
219             return true;
220         }
221         for (DeviceFeature f : connectedFeatures) {
222             if (f.hasListeners()) {
223                 return true;
224             }
225         }
226         return false;
227     }
228
229     /**
230      * removes a DeviceFeatureListener from this feature
231      *
232      * @param aItemName name of the item to remove as listener
233      * @return true if a listener was removed
234      */
235     public boolean removeListener(String aItemName) {
236         boolean listenerRemoved = false;
237         synchronized (listeners) {
238             for (Iterator<DeviceFeatureListener> it = listeners.iterator(); it.hasNext();) {
239                 DeviceFeatureListener fl = it.next();
240                 if (fl.getItemName().equals(aItemName)) {
241                     it.remove();
242                     listenerRemoved = true;
243                 }
244             }
245         }
246         return listenerRemoved;
247     }
248
249     public boolean isReferencedByItem(String aItemName) {
250         synchronized (listeners) {
251             for (DeviceFeatureListener fl : listeners) {
252                 if (fl.getItemName().equals(aItemName)) {
253                     return true;
254                 }
255             }
256         }
257         return false;
258     }
259
260     /**
261      * Called when message is incoming. Dispatches message according to message dispatcher
262      *
263      * @param msg The message to dispatch
264      * @return true if dispatch successful
265      */
266     public boolean handleMessage(Msg msg) {
267         MessageDispatcher dispatcher = this.dispatcher;
268         if (dispatcher == null) {
269             logger.warn("{} no dispatcher for msg {}", name, msg);
270             return false;
271         }
272         return dispatcher.dispatch(msg);
273     }
274
275     /**
276      * Called when an openhab command arrives for this device feature
277      *
278      * @param c the binding config of the item which sends the command
279      * @param cmd the command to be exectued
280      */
281     public void handleCommand(InsteonChannelConfiguration c, Command cmd) {
282         Class<? extends Command> key = cmd.getClass();
283         CommandHandler h = commandHandlers.containsKey(key) ? commandHandlers.get(key) : defaultCommandHandler;
284         if (h != null) {
285             logger.trace("{} uses {} to handle command {} for {}", getName(), h.getClass().getSimpleName(),
286                     key.getSimpleName(), getDevice().getAddress());
287             h.handleCommand(c, cmd, getDevice());
288         }
289     }
290
291     /**
292      * Make a poll message using the configured poll message handler
293      *
294      * @return the poll message
295      */
296     public @Nullable Msg makePollMsg() {
297         PollHandler pollHandler = this.pollHandler;
298         if (pollHandler == null) {
299             return null;
300         }
301         logger.trace("{} making poll msg for {} using handler {}", getName(), getDevice().getAddress(),
302                 pollHandler.getClass().getSimpleName());
303         return pollHandler.makeMsg(device);
304     }
305
306     /**
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.
310      *
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
315      */
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);
321             }
322         }
323     }
324
325     /**
326      * Publish new state to all device feature listeners
327      *
328      * @param newState state to be published
329      * @param changeType what kind of changes to publish
330      */
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);
336             }
337         }
338     }
339
340     /**
341      * Poll all device feature listeners for related devices
342      */
343     public void pollRelatedDevices() {
344         synchronized (listeners) {
345             for (DeviceFeatureListener listener : listeners) {
346                 listener.pollRelatedDevices();
347             }
348         }
349     }
350
351     /**
352      * Adds a message handler to this device feature.
353      *
354      * @param cm1 The insteon cmd1 of the incoming message for which the handler should be used
355      * @param handler the handler to invoke
356      */
357     public void addMessageHandler(int cm1, @Nullable MessageHandler handler) {
358         synchronized (msgHandlers) {
359             msgHandlers.put(cm1, handler);
360         }
361     }
362
363     /**
364      * Adds a command handler to this device feature
365      *
366      * @param c the command for which this handler is invoked
367      * @param handler the handler to call
368      */
369     public void addCommandHandler(Class<? extends Command> c, @Nullable CommandHandler handler) {
370         synchronized (commandHandlers) {
371             commandHandlers.put(c, handler);
372         }
373     }
374
375     /**
376      * Turn DeviceFeature into String
377      */
378     @Override
379     public String toString() {
380         return name + "(" + listeners.size() + ":" + commandHandlers.size() + ":" + msgHandlers.size() + ")";
381     }
382
383     /**
384      * Factory method for creating DeviceFeatures.
385      *
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.
388      */
389     @Nullable
390     public static DeviceFeature makeDeviceFeature(String s) {
391         DeviceFeature f = null;
392         synchronized (features) {
393             FeatureTemplate ft = features.get(s);
394             if (ft != null) {
395                 f = ft.build();
396             } else {
397                 logger.warn("unimplemented feature requested: {}", s);
398             }
399         }
400         return f;
401     }
402
403     /**
404      * Reads the features templates from an input stream and puts them in global map
405      *
406      * @param input the input stream from which to read the feature templates
407      */
408     public static void readFeatureTemplates(InputStream input) {
409         try {
410             List<FeatureTemplate> featureTemplates = FeatureTemplateLoader.readTemplates(input);
411             synchronized (features) {
412                 for (FeatureTemplate f : featureTemplates) {
413                     features.put(f.getName(), f);
414                 }
415             }
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);
420         }
421     }
422
423     /**
424      * Reads the feature templates from a file and adds them to a global map
425      *
426      * @param file name of the file to read from
427      */
428     public static void readFeatureTemplates(String file) {
429         try {
430             FileInputStream fis = new FileInputStream(file);
431             readFeatureTemplates(fis);
432         } catch (FileNotFoundException e) {
433             logger.warn("cannot read feature templates from file {} ", file, e);
434         }
435     }
436
437     /**
438      * static initializer
439      */
440     static {
441         // read features from xml file and store them in a map
442         InputStream input = DeviceFeature.class.getResourceAsStream("/device_features.xml");
443         Objects.requireNonNull(input);
444         readFeatureTemplates(input);
445     }
446 }