]> git.basschouten.com Git - openhab-addons.git/blob
2533b90f8ce385370ad2f9c4cc5f00e65ecb8fe0
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.loxone.internal.controls;
14
15 import java.io.IOException;
16 import java.lang.reflect.Type;
17 import java.util.ArrayList;
18 import java.util.HashMap;
19 import java.util.HashSet;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Objects;
23 import java.util.Set;
24
25 import org.openhab.binding.loxone.internal.LxServerHandlerApi;
26 import org.openhab.binding.loxone.internal.types.LxCategory;
27 import org.openhab.binding.loxone.internal.types.LxConfig;
28 import org.openhab.binding.loxone.internal.types.LxContainer;
29 import org.openhab.binding.loxone.internal.types.LxState;
30 import org.openhab.binding.loxone.internal.types.LxUuid;
31 import org.openhab.core.library.types.DecimalType;
32 import org.openhab.core.library.types.OnOffType;
33 import org.openhab.core.library.types.StringType;
34 import org.openhab.core.thing.Channel;
35 import org.openhab.core.thing.ChannelUID;
36 import org.openhab.core.thing.binding.builder.ChannelBuilder;
37 import org.openhab.core.thing.type.ChannelTypeUID;
38 import org.openhab.core.types.Command;
39 import org.openhab.core.types.State;
40 import org.openhab.core.types.StateDescriptionFragment;
41 import org.openhab.core.types.UnDefType;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 import com.google.gson.Gson;
46 import com.google.gson.JsonArray;
47 import com.google.gson.JsonDeserializationContext;
48 import com.google.gson.JsonDeserializer;
49 import com.google.gson.JsonElement;
50 import com.google.gson.JsonObject;
51 import com.google.gson.JsonParseException;
52 import com.google.gson.reflect.TypeToken;
53
54 /**
55  * A control of Loxone Miniserver.
56  * <p>
57  * It represents a control object on the Miniserver. Controls can represent an input, functional block or an output of
58  * the Miniserver, that is marked as visible in the Loxone UI. Controls can belong to a {@link LxContainer} room and a
59  * {@link LxCategory} category.
60  *
61  * @author Pawel Pieczul - initial contribution
62  *
63  */
64 public class LxControl {
65
66     /**
67      * This class contains static configuration of the control and is used to make the fields transparent to the child
68      * classes that implement specific controls.
69      *
70      * @author Pawel Pieczul - initial contribution
71      *
72      */
73     public static class LxControlConfig {
74         private final LxServerHandlerApi thingHandler;
75         private final LxContainer room;
76         private final LxCategory category;
77
78         LxControlConfig(LxControlConfig config) {
79             this(config.thingHandler, config.room, config.category);
80         }
81
82         public LxControlConfig(LxServerHandlerApi thingHandler, LxContainer room, LxCategory category) {
83             this.room = room;
84             this.category = category;
85             this.thingHandler = thingHandler;
86         }
87     }
88
89     /**
90      * This class is used to instantiate a particular control object by the {@link LxControlFactory}
91      *
92      * @author Pawel Pieczul - initial contribution
93      *
94      */
95     abstract static class LxControlInstance {
96         /**
97          * Creates an instance of a particular control class.
98          *
99          * @param uuid UUID of the control object to be created
100          * @return a newly created control object
101          */
102         abstract LxControl create(LxUuid uuid);
103
104         /**
105          * Return a type name for this control.
106          *
107          * @return type name (as used on the Miniserver)
108          */
109         abstract String getType();
110     }
111
112     /**
113      * This class describes additional parameters of a control received from the Miniserver and is used during JSON
114      * deserialization.
115      *
116      * @author Pawel Pieczul - initial contribution
117      *
118      */
119     class LxControlDetails {
120         Double min;
121         Double max;
122         Double step;
123         String format;
124         String actualFormat;
125         String totalFormat;
126         Boolean increaseOnly;
127         String allOff;
128         String url;
129         String urlHd;
130         Map<String, String> outputs;
131         Boolean presenceConnected;
132         Integer connectedInputs;
133     }
134
135     /**
136      * A callback that should be implemented by child classes to process received commands. This callback can be
137      * provided for each channel created by the controls.
138      *
139      * @author Pawel Pieczul - initial contribution
140      *
141      */
142     @FunctionalInterface
143     interface CommandCallback {
144         abstract void handleCommand(Command cmd) throws IOException;
145     }
146
147     /**
148      * A callback that should be implemented by child classes to return current channel state. This callback can be
149      * provided for each channel created by the controls.
150      *
151      * @author Pawel Pieczul - initial contribution
152      *
153      */
154     @FunctionalInterface
155     interface StateCallback {
156         abstract State getChannelState();
157     }
158
159     /**
160      * A set of callbacks registered per each channel by the child classes.
161      *
162      * @author Pawel Pieczul - initial contribution
163      *
164      */
165     private class Callbacks {
166         private CommandCallback commandCallback;
167         private StateCallback stateCallback;
168
169         private Callbacks(CommandCallback cC, StateCallback sC) {
170             commandCallback = cC;
171             stateCallback = sC;
172         }
173     }
174
175     /*
176      * Parameters parsed from the JSON configuration file during deserialization
177      */
178     LxUuid uuid;
179     LxControlDetails details;
180     private String name;
181     private LxUuid roomUuid;
182     private Boolean isSecured;
183     private LxUuid categoryUuid;
184     private Map<LxUuid, LxControl> subControls;
185     private final Map<String, LxState> states;
186
187     /*
188      * Parameters set when finalizing {@link LxConfig} object setup. They will be null right after constructing object.
189      */
190     transient String defaultChannelLabel;
191     private transient LxControlConfig config;
192
193     /*
194      * Parameters set when object is connected to the openHAB by the binding handler
195      */
196     final transient Set<String> tags = new HashSet<>();
197     private final transient List<Channel> channels = new ArrayList<>();
198     private final transient Map<ChannelUID, Callbacks> callbacks = new HashMap<>();
199
200     private final transient Logger logger;
201     private int numberOfChannels = 0;
202
203     /*
204      * JSON deserialization routine, called during parsing configuration by the GSON library
205      */
206     public static final JsonDeserializer<LxControl> DESERIALIZER = new JsonDeserializer<LxControl>() {
207         @Override
208         public LxControl deserialize(JsonElement json, Type type, JsonDeserializationContext context)
209                 throws JsonParseException {
210             JsonObject parent = json.getAsJsonObject();
211             String controlName = LxConfig.deserializeString(parent, "name");
212             String controlType = LxConfig.deserializeString(parent, "type");
213             LxUuid uuid = LxConfig.deserializeObject(parent, "uuidAction", LxUuid.class, context);
214             if (controlName == null || controlType == null || uuid == null) {
215                 throw new JsonParseException("Control name/type/uuid is null.");
216             }
217             LxControl control = LxControlFactory.createControl(uuid, controlType);
218             if (control == null) {
219                 return null;
220             }
221             control.name = controlName;
222             control.isSecured = LxConfig.deserializeObject(parent, "isSecured", Boolean.class, context);
223             control.roomUuid = LxConfig.deserializeObject(parent, "room", LxUuid.class, context);
224             control.categoryUuid = LxConfig.deserializeObject(parent, "cat", LxUuid.class, context);
225             control.details = LxConfig.deserializeObject(parent, "details", LxControlDetails.class, context);
226             control.subControls = LxConfig.deserializeObject(parent, "subControls",
227                     new TypeToken<Map<LxUuid, LxControl>>() {
228                     }.getType(), context);
229
230             JsonObject states = parent.getAsJsonObject("states");
231             if (states != null) {
232                 states.entrySet().forEach(entry -> {
233                     // temperature state of intelligent home controller object is the only
234                     // one that has state represented as an array, as this is not implemented
235                     // yet, we will skip this state
236                     JsonElement element = entry.getValue();
237                     if (element != null && !(element instanceof JsonArray)) {
238                         String value = element.getAsString();
239                         if (value != null) {
240                             String name = entry.getKey().toLowerCase();
241                             control.states.put(name, new LxState(new LxUuid(value), name, control));
242                         }
243                     }
244                 });
245             }
246             return control;
247         }
248     };
249
250     LxControl(LxUuid uuid) {
251         logger = LoggerFactory.getLogger(LxControl.class);
252         this.uuid = uuid;
253         states = new HashMap<>();
254     }
255
256     /**
257      * A method that executes commands by the control. It delegates command execution to a registered callback method.
258      *
259      * @param channelId channel Id for the command
260      * @param command value of the command to perform
261      * @throws IOException in case of communication error with the Miniserver
262      */
263     public final void handleCommand(ChannelUID channelId, Command command) throws IOException {
264         Callbacks c = callbacks.get(channelId);
265         if (c != null && c.commandCallback != null) {
266             c.commandCallback.handleCommand(command);
267         }
268     }
269
270     /**
271      * Provides actual state value for the specified channel. It delegates execution to a registered callback method.
272      *
273      * @param channelId channel ID to get state for
274      * @return state if the channel value or null if no value available
275      */
276     public final State getChannelState(ChannelUID channelId) {
277         Callbacks c = callbacks.get(channelId);
278         if (c != null && c.stateCallback != null) {
279             try {
280                 return c.stateCallback.getChannelState();
281             } catch (NumberFormatException e) {
282                 return UnDefType.UNDEF;
283             }
284         }
285         return null;
286     }
287
288     /**
289      * Obtain control's name
290      *
291      * @return Human readable name of control
292      */
293     public String getName() {
294         return name;
295     }
296
297     /**
298      * Get control's UUID as defined on the Miniserver
299      *
300      * @return UUID of the control
301      */
302     public LxUuid getUuid() {
303         return uuid;
304     }
305
306     /**
307      * Get subcontrols of this control
308      *
309      * @return subcontrols of the control
310      */
311     public Map<LxUuid, LxControl> getSubControls() {
312         return subControls;
313     }
314
315     /**
316      * Get control's channels
317      *
318      * @return channels
319      */
320     public List<Channel> getChannels() {
321         return channels;
322     }
323
324     /**
325      * Get control's and its subcontrols' channels
326      *
327      * @return channels
328      */
329     public List<Channel> getChannelsWithSubcontrols() {
330         final List<Channel> list = new ArrayList<>(channels);
331         subControls.values().forEach(c -> list.addAll(c.getChannelsWithSubcontrols()));
332         return list;
333     }
334
335     /**
336      * Get control's Miniserver states
337      *
338      * @return control's Miniserver states
339      */
340     public Map<String, LxState> getStates() {
341         return states;
342     }
343
344     /**
345      * Gets information is password is required to operate on this control object
346      *
347      * @return true is control is secured
348      */
349     public Boolean isSecured() {
350         return isSecured != null && isSecured;
351     }
352
353     /**
354      * Compare UUID's of two controls -
355      *
356      * @param object Object to compare with
357      * @return true if UUID of two objects are equal
358      */
359     @Override
360     public boolean equals(Object object) {
361         if (this == object) {
362             return true;
363         }
364         if (object == null) {
365             return false;
366         }
367         if (object.getClass() != getClass()) {
368             return false;
369         }
370         LxControl c = (LxControl) object;
371         return Objects.equals(c.uuid, uuid);
372     }
373
374     /**
375      * Hash code of the control is equal to its UUID's hash code
376      */
377     @Override
378     public int hashCode() {
379         return uuid.hashCode();
380     }
381
382     /**
383      * Initialize Miniserver's control in runtime. Each class that implements {@link LxControl} should override this
384      * method and call it as a first step in the overridden implementation. Then it should add all runtime data, like
385      * channels and any fields that derive their value from the parsed JSON configuration.
386      * Before this method is called during configuration parsing, the control object must not be used.
387      *
388      * @param configToSet control's configuration
389      */
390     public void initialize(LxControlConfig configToSet) {
391         logger.debug("Initializing LxControl: {}", uuid);
392
393         if (config != null) {
394             logger.error("Error, attempt to initialize control that is already initialized: {}", uuid);
395             return;
396         }
397         config = configToSet;
398
399         if (subControls == null) {
400             subControls = new HashMap<>();
401         } else {
402             subControls.values().removeIf(Objects::isNull);
403         }
404
405         if (config.room != null) {
406             config.room.addControl(this);
407         }
408
409         if (config.category != null) {
410             config.category.addControl(this);
411         }
412
413         String label = getLabel();
414         if (label == null) {
415             // Each control on a Miniserver must have a name defined, but in case this is a subject
416             // of some malicious data attack, we'll prevent null pointer exception
417             label = "Undefined name";
418         }
419         String roomName = config.room != null ? config.room.getName() : null;
420         if (roomName != null) {
421             label = roomName + " / " + label;
422         }
423         defaultChannelLabel = label;
424
425         // Propagate to all subcontrols of this control object
426         subControls.values().forEach(c -> c.initialize(config));
427     }
428
429     /**
430      * This method will be called from {@link LxState}, when Miniserver state value is updated.
431      * By default it will query all channels of the control and update their state accordingly.
432      * This method will not handle channel state descriptions, as they must be prepared individually.
433      * It can be overridden in child class to handle particular states differently.
434      *
435      * @param state changed Miniserver state or null if not specified (any/all)
436      */
437     public void onStateChange(LxState state) {
438         if (config == null) {
439             logger.error("Attempt to change state with not finalized configuration!: {}", state.getUuid());
440         } else {
441             channels.forEach(channel -> {
442                 ChannelUID channelId = channel.getUID();
443                 State channelState = getChannelState(channelId);
444                 if (channelState != null) {
445                     config.thingHandler.setChannelState(channelId, channelState);
446                 }
447             });
448         }
449     }
450
451     /**
452      * Gets room UUID after it was deserialized by GSON
453      *
454      * @return room UUID
455      */
456     public LxUuid getRoomUuid() {
457         return roomUuid;
458     }
459
460     /**
461      * Gets category UUID after it was deserialized by GSON
462      *
463      * @return category UUID
464      */
465     public LxUuid getCategoryUuid() {
466         return categoryUuid;
467     }
468
469     /**
470      * Gets a GSON object for reuse
471      *
472      * @return GSON object
473      */
474     Gson getGson() {
475         if (config == null) {
476             logger.error("Attempt to get GSON from not finalized configuration!");
477             return null;
478         }
479         return config.thingHandler.getGson();
480     }
481
482     /**
483      * Adds a new control in the framework. Called when a control is dynamically created based on some control's state
484      * changes from the Miniserver.
485      *
486      * @param control a new control to be created
487      */
488     static void addControl(LxControl control) {
489         control.config.thingHandler.addControl(control);
490     }
491
492     /**
493      * Removes a control from the framework. Called when a control is dynamically deleted based on some control's state
494      * changes from the Miniserver.
495      *
496      * @param control a control to be removed
497      */
498     static void removeControl(LxControl control) {
499         control.config.thingHandler.removeControl(control);
500         control.dispose();
501     }
502
503     /**
504      * Gets control's configuration
505      *
506      * @return configuration
507      */
508     LxControlConfig getConfig() {
509         return config;
510     }
511
512     /**
513      * Get control's room.
514      *
515      * @return control's room object
516      */
517     LxContainer getRoom() {
518         return config.room;
519     }
520
521     /**
522      * Get control's category.
523      *
524      * @return control's category object
525      */
526     LxCategory getCategory() {
527         return config.category;
528     }
529
530     /**
531      * Changes the channel state in the framework.
532      *
533      * @param id channel ID
534      * @param state new state value
535      */
536     void setChannelState(ChannelUID id, State state) {
537         if (config == null) {
538             logger.error("Attempt to set channel state with not finalized configuration!: {}", id);
539         } else {
540             if (state != null) {
541                 config.thingHandler.setChannelState(id, state);
542             }
543         }
544     }
545
546     /**
547      * Returns control label that will be used for building channel name. This allows for customizing the label per
548      * control by overriding this method, but keeping {@link LxControl#getName()} intact.
549      *
550      * @return control channel label
551      */
552     String getLabel() {
553         return name;
554     }
555
556     /**
557      * Gets value of a state object of given name, if exists
558      *
559      * @param name name of state object
560      * @return state object's value
561      */
562     Double getStateDoubleValue(String name) {
563         LxState state = states.get(name);
564         if (state != null) {
565             Object value = state.getStateValue();
566             if (value instanceof Double) {
567                 return (Double) value;
568             }
569         }
570         return null;
571     }
572
573     /**
574      * Gets value of a state object of given name, if exists, and converts it to decimal type value.
575      *
576      * @param name state name
577      * @return state value
578      */
579     State getStateDecimalValue(String name) {
580         Double value = getStateDoubleValue(name);
581         if (value != null) {
582             return new DecimalType(value);
583         }
584         return null;
585     }
586
587     /**
588      * Gets text value of a state object of given name, if exists
589      *
590      * @param name name of state object
591      * @return state object's text value
592      */
593     String getStateTextValue(String name) {
594         LxState state = states.get(name);
595         if (state != null) {
596             Object value = state.getStateValue();
597             if (value instanceof String) {
598                 return (String) value;
599             }
600         }
601         return null;
602     }
603
604     /**
605      * Gets text value of a state object of given name, if exists and converts it to string type
606      *
607      * @param name name of state object
608      * @return state object's text value
609      */
610     State getStateStringValue(String name) {
611         String value = getStateTextValue(name);
612         if (value != null) {
613             return new StringType(value);
614         }
615         return null;
616     }
617
618     /**
619      * Gets double value of a state object of given name, if exists and converts it to switch type
620      *
621      * @param name name of state object
622      * @return state object's text value
623      */
624     State getStateOnOffValue(String name) {
625         Double value = getStateDoubleValue(name);
626         if (value != null) {
627             if (value == 1.0) {
628                 return OnOffType.ON;
629             }
630             return OnOffType.OFF;
631         }
632         return null;
633     }
634
635     /**
636      * Create a new channel and add it to the control. Channel ID is assigned automatically in the order of calls to
637      * this method, see (@link LxControl#getChannelId}.
638      *
639      * @param itemType item type for the channel
640      * @param typeId channel type ID for the channel
641      * @param channelLabel channel label
642      * @param channelDescription channel description
643      * @param tags tags for the channel or null if no tags needed
644      * @param commandCallback {@link LxControl} child class method that will be called when command is received
645      * @param stateCallback {@link LxControl} child class method that will be called to get state value
646      * @return channel ID of the added channel (can be used to later set state description to it)
647      */
648     ChannelUID addChannel(String itemType, ChannelTypeUID typeId, String channelLabel, String channelDescription,
649             Set<String> tags, CommandCallback commandCallback, StateCallback stateCallback) {
650         if (channelLabel == null || channelDescription == null) {
651             logger.error("Attempt to add channel with not finalized configuration!: {}", channelLabel);
652             return null;
653         }
654         ChannelUID channelId = getChannelId(numberOfChannels++);
655         ChannelBuilder builder = ChannelBuilder.create(channelId, itemType).withType(typeId).withLabel(channelLabel)
656                 .withDescription(channelDescription + " : " + channelLabel);
657         if (tags != null) {
658             builder.withDefaultTags(tags);
659         }
660         channels.add(builder.build());
661         if (commandCallback != null || stateCallback != null) {
662             callbacks.put(channelId, new Callbacks(commandCallback, stateCallback));
663         }
664         return channelId;
665     }
666
667     /**
668      * Adds a new {@link StateDescriptionFragment} for a channel that has multiple options to select from or a custom
669      * format string.
670      *
671      * @param channelId channel ID to add the description for
672      * @param descriptionFragment channel state description fragment
673      */
674     void addChannelStateDescriptionFragment(ChannelUID channelId, StateDescriptionFragment descriptionFragment) {
675         if (config == null) {
676             logger.error("Attempt to set channel state description with not finalized configuration!: {}", channelId);
677         } else {
678             if (channelId != null && descriptionFragment != null) {
679                 config.thingHandler.setChannelStateDescription(channelId, descriptionFragment.toStateDescription());
680             }
681         }
682     }
683
684     /**
685      * Sends an action command to the Miniserver using active socket connection
686      *
687      * @param action string with action command
688      * @throws IOException when communication error with Miniserver occurs
689      */
690     void sendAction(String action) throws IOException {
691         if (config == null) {
692             logger.error("Attempt to send command with not finalized configuration!: {}", action);
693         } else {
694             config.thingHandler.sendAction(uuid, action);
695         }
696     }
697
698     /**
699      * Remove all channels from the control. This method is used by child classes that may decide to stop exposing any
700      * channels, for example by {@link LxControlMood}, which is based on {@link LxControlSwitch}, but sometime does not
701      * expose anything to the user.
702      */
703     void removeAllChannels() {
704         channels.clear();
705         callbacks.clear();
706     }
707
708     /**
709      * Call when control is no more needed - unlink it from containers
710      */
711     private void dispose() {
712         if (config.room != null) {
713             config.room.removeControl(this);
714         }
715         if (config.category != null) {
716             config.category.removeControl(this);
717         }
718         subControls.values().forEach(control -> control.dispose());
719     }
720
721     /**
722      * Build channel ID for the control, based on control's UUID, thing's UUID and index of the channel for the control
723      *
724      * @param index index of a channel within control (0 for primary channel) all indexes greater than 0 will have
725      *            -index added to the channel ID
726      * @return channel ID for the control and index
727      */
728     private ChannelUID getChannelId(int index) {
729         if (config == null) {
730             logger.error("Attempt to get control's channel ID with not finalized configuration!: {}", index);
731             return null;
732         }
733         String controlId = uuid.toString();
734         if (index > 0) {
735             controlId += "-" + index;
736         }
737         return new ChannelUID(config.thingHandler.getThingId(), controlId);
738     }
739 }