]> git.basschouten.com Git - openhab-addons.git/blob
964c24b3a9e7df954cef3fab6e2a9848830294eb
[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.mqtt.homeassistant.internal.component;
14
15 import java.math.BigDecimal;
16 import java.util.ArrayList;
17 import java.util.Arrays;
18 import java.util.Collections;
19 import java.util.List;
20 import java.util.stream.Collectors;
21
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.openhab.binding.mqtt.generic.ChannelStateUpdateListener;
25 import org.openhab.binding.mqtt.generic.values.OnOffValue;
26 import org.openhab.binding.mqtt.generic.values.PercentageValue;
27 import org.openhab.binding.mqtt.generic.values.TextValue;
28 import org.openhab.binding.mqtt.generic.values.Value;
29 import org.openhab.binding.mqtt.homeassistant.internal.ComponentChannel;
30 import org.openhab.binding.mqtt.homeassistant.internal.config.dto.AbstractChannelConfiguration;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 import com.google.gson.annotations.SerializedName;
35
36 /**
37  * A MQTT vacuum, following the https://www.home-assistant.io/components/vacuum.mqtt/ specification.
38  *
39  * @author Stefan Triller - Initial contribution
40  * @author Anton Kharuzhyi - Make it compilant with the Specification
41  */
42 @NonNullByDefault
43 public class Vacuum extends AbstractComponent<Vacuum.ChannelConfiguration> {
44     public static final String SCHEMA_LEGACY = "legacy";
45     public static final String SCHEMA_STATE = "state";
46
47     public static final String TRUE = "true";
48     public static final String FALSE = "false";
49     public static final String OFF = "off";
50
51     public static final String FEATURE_TURN_ON = "turn_on"; // Begin cleaning
52     public static final String FEATURE_TURN_OFF = "turn_off"; // Turn the Vacuum off
53     public static final String FEATURE_RETURN_HOME = "return_home"; // Return to base/dock
54     public static final String FEATURE_START = "start";
55     public static final String FEATURE_STOP = "stop"; // Stop the Vacuum
56     public static final String FEATURE_CLEAN_SPOT = "clean_spot"; // Initialize a spot cleaning cycle
57     public static final String FEATURE_LOCATE = "locate"; // Locate the vacuum (typically by playing a song)
58     public static final String FEATURE_PAUSE = "pause"; // Pause the vacuum
59     public static final String FEATURE_BATTERY = "battery";
60     public static final String FEATURE_STATUS = "status";
61     public static final String FEATURE_FAN_SPEED = "fan_speed";
62     public static final String FEATURE_SEND_COMMAND = "send_command";
63
64     // State Schema only
65     public static final String STATE_CLEANING = "cleaning";
66     public static final String STATE_DOCKED = "docked";
67     public static final String STATE_PAUSED = "paused";
68     public static final String STATE_IDLE = "idle";
69     public static final String STATE_RETURNING = "returning";
70     public static final String STATE_ERROR = "error";
71
72     public static final String COMMAND_CH_ID = "command";
73     public static final String FAN_SPEED_CH_ID = "fanSpeed";
74     public static final String CUSTOM_COMMAND_CH_ID = "customCommand";
75     public static final String BATTERY_LEVEL_CH_ID = "batteryLevel";
76     public static final String CHARGING_CH_ID = "charging";
77     public static final String CLEANING_CH_ID = "cleaning";
78     public static final String DOCKED_CH_ID = "docked";
79     public static final String ERROR_CH_ID = "error";
80     public static final String JSON_ATTRIBUTES_CH_ID = "jsonAttributes";
81     public static final String STATE_CH_ID = "state";
82
83     public static final List<String> LEGACY_DEFAULT_FEATURES = List.of(FEATURE_TURN_ON, FEATURE_TURN_OFF, FEATURE_STOP,
84             FEATURE_RETURN_HOME, FEATURE_BATTERY, FEATURE_STATUS, FEATURE_CLEAN_SPOT);
85     public static final List<String> LEGACY_SUPPORTED_FEATURES = List.of(FEATURE_TURN_ON, FEATURE_TURN_OFF,
86             FEATURE_PAUSE, FEATURE_STOP, FEATURE_RETURN_HOME, FEATURE_BATTERY, FEATURE_STATUS, FEATURE_LOCATE,
87             FEATURE_CLEAN_SPOT, FEATURE_FAN_SPEED, FEATURE_SEND_COMMAND);
88
89     public static final List<String> STATE_DEFAULT_FEATURES = List.of(FEATURE_START, FEATURE_STOP, FEATURE_RETURN_HOME,
90             FEATURE_STATUS, FEATURE_BATTERY, FEATURE_CLEAN_SPOT);
91     public static final List<String> STATE_SUPPORTED_FEATURES = List.of(FEATURE_START, FEATURE_STOP, FEATURE_PAUSE,
92             FEATURE_RETURN_HOME, FEATURE_BATTERY, FEATURE_STATUS, FEATURE_LOCATE, FEATURE_CLEAN_SPOT, FEATURE_FAN_SPEED,
93             FEATURE_SEND_COMMAND);
94
95     private static final Logger LOGGER = LoggerFactory.getLogger(Vacuum.class);
96
97     /**
98      * Configuration class for MQTT component
99      */
100     static class ChannelConfiguration extends AbstractChannelConfiguration {
101         ChannelConfiguration() {
102             super("MQTT Vacuum");
103         }
104
105         // Legacy and Common MQTT vacuum configuration section.
106
107         @SerializedName("battery_level_template")
108         protected @Nullable String batteryLevelTemplate;
109         @SerializedName("battery_level_topic")
110         protected @Nullable String batteryLevelTopic;
111
112         @SerializedName("charging_template")
113         protected @Nullable String chargingTemplate;
114         @SerializedName("charging_topic")
115         protected @Nullable String chargingTopic;
116
117         @SerializedName("cleaning_template")
118         protected @Nullable String cleaningTemplate;
119         @SerializedName("cleaning_topic")
120         protected @Nullable String cleaningTopic;
121
122         @SerializedName("command_topic")
123         protected @Nullable String commandTopic;
124
125         @SerializedName("docked_template")
126         protected @Nullable String dockedTemplate;
127         @SerializedName("docked_topic")
128         protected @Nullable String dockedTopic;
129
130         @SerializedName("error_template")
131         protected @Nullable String errorTemplate;
132         @SerializedName("error_topic")
133         protected @Nullable String errorTopic;
134
135         @SerializedName("fan_speed_list")
136         protected @Nullable List<String> fanSpeedList;
137         @SerializedName("fan_speed_template")
138         protected @Nullable String fanSpeedTemplate;
139         @SerializedName("fan_speed_topic")
140         protected @Nullable String fanSpeedTopic;
141
142         @SerializedName("payload_clean_spot")
143         protected @Nullable String payloadCleanSpot = "clean_spot";
144         @SerializedName("payload_locate")
145         protected @Nullable String payloadLocate = "locate";
146         @SerializedName("payload_return_to_base")
147         protected @Nullable String payloadReturnToBase = "return_to_base";
148         @SerializedName("payload_start_pause")
149         protected @Nullable String payloadStartPause = "start_pause"; // Legacy only
150         @SerializedName("payload_stop")
151         protected @Nullable String payloadStop = "stop";
152         @SerializedName("payload_turn_off")
153         protected @Nullable String payloadTurnOff = "turn_off";
154         @SerializedName("payload_turn_on")
155         protected @Nullable String payloadTurnOn = "turn_on";
156
157         @SerializedName("schema")
158         protected Schema schema = Schema.LEGACY;
159
160         @SerializedName("send_command_topic")
161         protected @Nullable String sendCommandTopic;
162
163         @SerializedName("set_fan_speed_topic")
164         protected @Nullable String setFanSpeedTopic;
165
166         @SerializedName("supported_features")
167         protected @Nullable List<String> supportedFeatures;
168
169         // State MQTT vacuum configuration section.
170
171         // Start/Pause replaced by 2 payloads
172         @SerializedName("payload_pause")
173         protected @Nullable String payloadPause = "pause";
174         @SerializedName("payload_start")
175         protected @Nullable String payloadStart = "start";
176
177         @SerializedName("state_topic")
178         protected @Nullable String stateTopic;
179
180         @SerializedName("json_attributes_template")
181         protected @Nullable String jsonAttributesTemplate;
182         @SerializedName("json_attributes_topic")
183         protected @Nullable String jsonAttributesTopic;
184     }
185
186     /**
187      * Creates component based on generic configuration and component configuration type.
188      *
189      * @param componentConfiguration generic componentConfiguration with not parsed JSON config
190      */
191     public Vacuum(ComponentFactory.ComponentConfiguration componentConfiguration) {
192         super(componentConfiguration, ChannelConfiguration.class);
193         final ChannelStateUpdateListener updateListener = componentConfiguration.getUpdateListener();
194
195         final var allowedSupportedFeatures = channelConfiguration.schema == Schema.LEGACY ? LEGACY_SUPPORTED_FEATURES
196                 : STATE_SUPPORTED_FEATURES;
197         final var supportedFeatures = channelConfiguration.supportedFeatures;
198         final var configSupportedFeatures = supportedFeatures == null
199                 ? channelConfiguration.schema == Schema.LEGACY ? LEGACY_DEFAULT_FEATURES : STATE_DEFAULT_FEATURES
200                 : supportedFeatures;
201         List<String> deviceSupportedFeatures = Collections.emptyList();
202
203         if (!configSupportedFeatures.isEmpty()) {
204             deviceSupportedFeatures = allowedSupportedFeatures.stream().filter(configSupportedFeatures::contains)
205                     .collect(Collectors.toList());
206         }
207         if (deviceSupportedFeatures.size() != configSupportedFeatures.size()) {
208             LOGGER.warn("Vacuum discovery config has unsupported or duplicated features. Supported: {}, provided: {}",
209                     Arrays.toString(allowedSupportedFeatures.toArray()),
210                     Arrays.toString(configSupportedFeatures.toArray()));
211         }
212
213         final List<String> commands = new ArrayList<>();
214         addPayloadToList(deviceSupportedFeatures, FEATURE_CLEAN_SPOT, channelConfiguration.payloadCleanSpot, commands);
215         addPayloadToList(deviceSupportedFeatures, FEATURE_LOCATE, channelConfiguration.payloadLocate, commands);
216         addPayloadToList(deviceSupportedFeatures, FEATURE_RETURN_HOME, channelConfiguration.payloadReturnToBase,
217                 commands);
218         addPayloadToList(deviceSupportedFeatures, FEATURE_STOP, channelConfiguration.payloadStop, commands);
219         addPayloadToList(deviceSupportedFeatures, FEATURE_TURN_OFF, channelConfiguration.payloadTurnOff, commands);
220         addPayloadToList(deviceSupportedFeatures, FEATURE_TURN_ON, channelConfiguration.payloadTurnOn, commands);
221
222         if (channelConfiguration.schema == Schema.LEGACY) {
223             addPayloadToList(deviceSupportedFeatures, FEATURE_PAUSE, channelConfiguration.payloadStartPause, commands);
224         } else {
225             addPayloadToList(deviceSupportedFeatures, FEATURE_PAUSE, channelConfiguration.payloadPause, commands);
226             addPayloadToList(deviceSupportedFeatures, FEATURE_START, channelConfiguration.payloadStart, commands);
227         }
228
229         buildOptionalChannel(COMMAND_CH_ID, new TextValue(commands.toArray(new String[0])), updateListener, null,
230                 channelConfiguration.commandTopic, null, null);
231
232         final var fanSpeedList = channelConfiguration.fanSpeedList;
233         if (deviceSupportedFeatures.contains(FEATURE_FAN_SPEED) && fanSpeedList != null && !fanSpeedList.isEmpty()) {
234             if (!fanSpeedList.contains(OFF)) {
235                 fanSpeedList.add(OFF); // Off value is used when cleaning if OFF
236             }
237             var fanSpeedValue = new TextValue(fanSpeedList.toArray(new String[0]));
238             if (channelConfiguration.schema == Schema.LEGACY) {
239                 buildOptionalChannel(FAN_SPEED_CH_ID, fanSpeedValue, updateListener, null,
240                         channelConfiguration.setFanSpeedTopic, channelConfiguration.fanSpeedTemplate,
241                         channelConfiguration.fanSpeedTopic);
242             } else if (deviceSupportedFeatures.contains(FEATURE_STATUS)) {
243                 buildOptionalChannel(FAN_SPEED_CH_ID, fanSpeedValue, updateListener, null,
244                         channelConfiguration.setFanSpeedTopic, "{{ value_json.fan_speed }}",
245                         channelConfiguration.stateTopic);
246             } else {
247                 LOGGER.info("Status feature is disabled, unable to get fan speed.");
248                 buildOptionalChannel(FAN_SPEED_CH_ID, fanSpeedValue, updateListener, null,
249                         channelConfiguration.setFanSpeedTopic, null, null);
250             }
251         }
252
253         if (deviceSupportedFeatures.contains(FEATURE_SEND_COMMAND)) {
254             buildOptionalChannel(CUSTOM_COMMAND_CH_ID, new TextValue(), updateListener, null,
255                     channelConfiguration.sendCommandTopic, null, null);
256         }
257
258         if (channelConfiguration.schema == Schema.LEGACY) {
259             // I assume, that if these topics defined in config, then we don't need to check features
260             buildOptionalChannel(BATTERY_LEVEL_CH_ID,
261                     new PercentageValue(BigDecimal.ZERO, BigDecimal.valueOf(100), BigDecimal.ONE, null, null),
262                     updateListener, null, null, channelConfiguration.batteryLevelTemplate,
263                     channelConfiguration.batteryLevelTopic);
264             buildOptionalChannel(CHARGING_CH_ID, new OnOffValue(TRUE, FALSE), updateListener, null, null,
265                     channelConfiguration.chargingTemplate, channelConfiguration.chargingTopic);
266             buildOptionalChannel(CLEANING_CH_ID, new OnOffValue(TRUE, FALSE), updateListener, null, null,
267                     channelConfiguration.cleaningTemplate, channelConfiguration.cleaningTopic);
268             buildOptionalChannel(DOCKED_CH_ID, new OnOffValue(TRUE, FALSE), updateListener, null, null,
269                     channelConfiguration.dockedTemplate, channelConfiguration.dockedTopic);
270             buildOptionalChannel(ERROR_CH_ID, new TextValue(), updateListener, null, null,
271                     channelConfiguration.errorTemplate, channelConfiguration.errorTopic);
272         } else {
273             if (deviceSupportedFeatures.contains(FEATURE_STATUS)) {
274                 // state key is mandatory
275                 buildOptionalChannel(STATE_CH_ID,
276                         new TextValue(new String[] { STATE_CLEANING, STATE_DOCKED, STATE_PAUSED, STATE_IDLE,
277                                 STATE_RETURNING, STATE_ERROR }),
278                         updateListener, null, null, "{{ value_json.state }}", channelConfiguration.stateTopic);
279                 if (deviceSupportedFeatures.contains(FEATURE_BATTERY)) {
280                     buildOptionalChannel(BATTERY_LEVEL_CH_ID,
281                             new PercentageValue(BigDecimal.ZERO, BigDecimal.valueOf(100), BigDecimal.ONE, null, null),
282                             updateListener, null, null, "{{ value_json.battery_level }}",
283                             channelConfiguration.stateTopic);
284                 }
285             }
286         }
287
288         buildOptionalChannel(JSON_ATTRIBUTES_CH_ID, new TextValue(), updateListener, null, null,
289                 channelConfiguration.jsonAttributesTemplate, channelConfiguration.jsonAttributesTopic);
290     }
291
292     @Nullable
293     private ComponentChannel buildOptionalChannel(String channelId, Value valueState,
294             ChannelStateUpdateListener channelStateUpdateListener, @Nullable String commandTemplate,
295             @Nullable String commandTopic, @Nullable String stateTemplate, @Nullable String stateTopic) {
296         if ((commandTopic != null && !commandTopic.isBlank()) || (stateTopic != null && !stateTopic.isBlank())) {
297             return buildChannel(channelId, valueState, getName(), channelStateUpdateListener)
298                     .stateTopic(stateTopic, stateTemplate, channelConfiguration.getValueTemplate())
299                     .commandTopic(commandTopic, channelConfiguration.isRetain(), channelConfiguration.getQos(),
300                             commandTemplate)
301                     .build();
302         }
303         return null;
304     }
305
306     private void addPayloadToList(List<String> supportedFeatures, String feature, @Nullable String payload,
307             List<String> list) {
308         if (supportedFeatures.contains(feature) && payload != null && !payload.isEmpty()) {
309             list.add(payload);
310         }
311     }
312
313     public enum Schema {
314         @SerializedName("legacy")
315         LEGACY,
316         @SerializedName("state")
317         STATE
318     }
319 }