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.loxone.internal.controls;
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;
22 import java.util.Objects;
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;
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;
55 * A control of Loxone Miniserver.
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.
61 * @author Pawel Pieczul - initial contribution
64 public class LxControl {
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.
70 * @author Pawel Pieczul - initial contribution
73 public static class LxControlConfig {
74 private final LxServerHandlerApi thingHandler;
75 private final LxContainer room;
76 private final LxCategory category;
78 LxControlConfig(LxControlConfig config) {
79 this(config.thingHandler, config.room, config.category);
82 public LxControlConfig(LxServerHandlerApi thingHandler, LxContainer room, LxCategory category) {
84 this.category = category;
85 this.thingHandler = thingHandler;
90 * This class is used to instantiate a particular control object by the {@link LxControlFactory}
92 * @author Pawel Pieczul - initial contribution
95 abstract static class LxControlInstance {
97 * Creates an instance of a particular control class.
99 * @param uuid UUID of the control object to be created
100 * @return a newly created control object
102 abstract LxControl create(LxUuid uuid);
105 * Return a type name for this control.
107 * @return type name (as used on the Miniserver)
109 abstract String getType();
113 * This class describes additional parameters of a control received from the Miniserver and is used during JSON
116 * @author Pawel Pieczul - initial contribution
119 class LxControlDetails {
126 Boolean increaseOnly;
130 Map<String, String> outputs;
131 Boolean presenceConnected;
132 Integer connectedInputs;
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.
139 * @author Pawel Pieczul - initial contribution
143 interface CommandCallback {
144 abstract void handleCommand(Command cmd) throws IOException;
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.
151 * @author Pawel Pieczul - initial contribution
155 interface StateCallback {
156 abstract State getChannelState();
160 * A set of callbacks registered per each channel by the child classes.
162 * @author Pawel Pieczul - initial contribution
165 private class Callbacks {
166 private CommandCallback commandCallback;
167 private StateCallback stateCallback;
169 private Callbacks(CommandCallback cC, StateCallback sC) {
170 commandCallback = cC;
176 * Parameters parsed from the JSON configuration file during deserialization
179 LxControlDetails details;
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;
188 * Parameters set when finalizing {@link LxConfig} object setup. They will be null right after constructing object.
190 transient String defaultChannelLabel;
191 private transient LxControlConfig config;
194 * Parameters set when object is connected to the openHAB by the binding handler
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<>();
200 private final transient Logger logger;
201 private int numberOfChannels = 0;
204 * JSON deserialization routine, called during parsing configuration by the GSON library
206 public static final JsonDeserializer<LxControl> DESERIALIZER = new JsonDeserializer<LxControl>() {
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.");
217 LxControl control = LxControlFactory.createControl(uuid, controlType);
218 if (control == null) {
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);
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();
240 String name = entry.getKey().toLowerCase();
241 control.states.put(name, new LxState(new LxUuid(value), name, control));
250 LxControl(LxUuid uuid) {
251 logger = LoggerFactory.getLogger(LxControl.class);
253 states = new HashMap<>();
257 * A method that executes commands by the control. It delegates command execution to a registered callback method.
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
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);
271 * Provides actual state value for the specified channel. It delegates execution to a registered callback method.
273 * @param channelId channel ID to get state for
274 * @return state if the channel value or null if no value available
276 public final State getChannelState(ChannelUID channelId) {
277 Callbacks c = callbacks.get(channelId);
278 if (c != null && c.stateCallback != null) {
280 return c.stateCallback.getChannelState();
281 } catch (NumberFormatException e) {
282 return UnDefType.UNDEF;
289 * Obtain control's name
291 * @return Human readable name of control
293 public String getName() {
298 * Get control's UUID as defined on the Miniserver
300 * @return UUID of the control
302 public LxUuid getUuid() {
307 * Get subcontrols of this control
309 * @return subcontrols of the control
311 public Map<LxUuid, LxControl> getSubControls() {
316 * Get control's channels
320 public List<Channel> getChannels() {
325 * Get control's and its subcontrols' channels
329 public List<Channel> getChannelsWithSubcontrols() {
330 final List<Channel> list = new ArrayList<>(channels);
331 subControls.values().forEach(c -> list.addAll(c.getChannelsWithSubcontrols()));
336 * Get control's Miniserver states
338 * @return control's Miniserver states
340 public Map<String, LxState> getStates() {
345 * Gets information is password is required to operate on this control object
347 * @return true is control is secured
349 public Boolean isSecured() {
350 return isSecured != null && isSecured;
354 * Compare UUID's of two controls -
356 * @param object Object to compare with
357 * @return true if UUID of two objects are equal
360 public boolean equals(Object object) {
361 if (this == object) {
364 if (object == null) {
367 if (object.getClass() != getClass()) {
370 LxControl c = (LxControl) object;
371 return Objects.equals(c.uuid, uuid);
375 * Hash code of the control is equal to its UUID's hash code
378 public int hashCode() {
379 return uuid.hashCode();
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.
388 * @param configToSet control's configuration
390 public void initialize(LxControlConfig configToSet) {
391 logger.debug("Initializing LxControl: {}", uuid);
393 if (config != null) {
394 logger.error("Error, attempt to initialize control that is already initialized: {}", uuid);
397 config = configToSet;
399 if (subControls == null) {
400 subControls = new HashMap<>();
402 subControls.values().removeIf(Objects::isNull);
405 if (config.room != null) {
406 config.room.addControl(this);
409 if (config.category != null) {
410 config.category.addControl(this);
413 String label = getLabel();
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";
419 String roomName = config.room != null ? config.room.getName() : null;
420 if (roomName != null) {
421 label = roomName + " / " + label;
423 defaultChannelLabel = label;
425 // Propagate to all subcontrols of this control object
426 subControls.values().forEach(c -> c.initialize(config));
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.
435 * @param state changed Miniserver state or null if not specified (any/all)
437 public void onStateChange(LxState state) {
438 if (config == null) {
439 logger.error("Attempt to change state with not finalized configuration!: {}", state.getUuid());
441 channels.forEach(channel -> {
442 ChannelUID channelId = channel.getUID();
443 State channelState = getChannelState(channelId);
444 if (channelState != null) {
445 config.thingHandler.setChannelState(channelId, channelState);
452 * Gets room UUID after it was deserialized by GSON
456 public LxUuid getRoomUuid() {
461 * Gets category UUID after it was deserialized by GSON
463 * @return category UUID
465 public LxUuid getCategoryUuid() {
470 * Gets a GSON object for reuse
472 * @return GSON object
475 if (config == null) {
476 logger.error("Attempt to get GSON from not finalized configuration!");
479 return config.thingHandler.getGson();
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.
486 * @param control a new control to be created
488 static void addControl(LxControl control) {
489 control.config.thingHandler.addControl(control);
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.
496 * @param control a control to be removed
498 static void removeControl(LxControl control) {
499 control.config.thingHandler.removeControl(control);
504 * Gets control's configuration
506 * @return configuration
508 LxControlConfig getConfig() {
513 * Get control's room.
515 * @return control's room object
517 LxContainer getRoom() {
522 * Get control's category.
524 * @return control's category object
526 LxCategory getCategory() {
527 return config.category;
531 * Changes the channel state in the framework.
533 * @param id channel ID
534 * @param state new state value
536 void setChannelState(ChannelUID id, State state) {
537 if (config == null) {
538 logger.error("Attempt to set channel state with not finalized configuration!: {}", id);
541 config.thingHandler.setChannelState(id, state);
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.
550 * @return control channel label
557 * Gets value of a state object of given name, if exists
559 * @param name name of state object
560 * @return state object's value
562 Double getStateDoubleValue(String name) {
563 LxState state = states.get(name);
565 Object value = state.getStateValue();
566 if (value instanceof Double) {
567 return (Double) value;
574 * Gets value of a state object of given name, if exists, and converts it to decimal type value.
576 * @param name state name
577 * @return state value
579 State getStateDecimalValue(String name) {
580 Double value = getStateDoubleValue(name);
582 return new DecimalType(value);
588 * Gets text value of a state object of given name, if exists
590 * @param name name of state object
591 * @return state object's text value
593 String getStateTextValue(String name) {
594 LxState state = states.get(name);
596 Object value = state.getStateValue();
597 if (value instanceof String) {
598 return (String) value;
605 * Gets text value of a state object of given name, if exists and converts it to string type
607 * @param name name of state object
608 * @return state object's text value
610 State getStateStringValue(String name) {
611 String value = getStateTextValue(name);
613 return new StringType(value);
619 * Gets double value of a state object of given name, if exists and converts it to switch type
621 * @param name name of state object
622 * @return state object's text value
624 State getStateOnOffValue(String name) {
625 Double value = getStateDoubleValue(name);
630 return OnOffType.OFF;
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}.
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)
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);
654 ChannelUID channelId = getChannelId(numberOfChannels++);
655 ChannelBuilder builder = ChannelBuilder.create(channelId, itemType).withType(typeId).withLabel(channelLabel)
656 .withDescription(channelDescription + " : " + channelLabel);
658 builder.withDefaultTags(tags);
660 channels.add(builder.build());
661 if (commandCallback != null || stateCallback != null) {
662 callbacks.put(channelId, new Callbacks(commandCallback, stateCallback));
668 * Adds a new {@link StateDescriptionFragment} for a channel that has multiple options to select from or a custom
671 * @param channelId channel ID to add the description for
672 * @param descriptionFragment channel state description fragment
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);
678 if (channelId != null && descriptionFragment != null) {
679 config.thingHandler.setChannelStateDescription(channelId, descriptionFragment.toStateDescription());
685 * Sends an action command to the Miniserver using active socket connection
687 * @param action string with action command
688 * @throws IOException when communication error with Miniserver occurs
690 void sendAction(String action) throws IOException {
691 if (config == null) {
692 logger.error("Attempt to send command with not finalized configuration!: {}", action);
694 config.thingHandler.sendAction(uuid, action);
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.
703 void removeAllChannels() {
709 * Call when control is no more needed - unlink it from containers
711 private void dispose() {
712 if (config.room != null) {
713 config.room.removeControl(this);
715 if (config.category != null) {
716 config.category.removeControl(this);
718 subControls.values().forEach(control -> control.dispose());
722 * Build channel ID for the control, based on control's UUID, thing's UUID and index of the channel for the control
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
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);
733 String controlId = uuid.toString();
735 controlId += "-" + index;
737 return new ChannelUID(config.thingHandler.getThingId(), controlId);