2 * Copyright (c) 2010-2023 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.sensibo.internal.handler;
15 import static org.openhab.binding.sensibo.internal.SensiboBindingConstants.*;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.HashMap;
20 import java.util.List;
21 import java.util.Locale;
23 import java.util.Objects;
24 import java.util.Optional;
26 import java.util.stream.Collectors;
28 import javax.measure.IncommensurableException;
29 import javax.measure.UnconvertibleException;
30 import javax.measure.Unit;
31 import javax.measure.UnitConverter;
32 import javax.measure.quantity.Temperature;
34 import org.eclipse.jdt.annotation.NonNullByDefault;
35 import org.eclipse.jdt.annotation.Nullable;
36 import org.openhab.binding.sensibo.internal.CallbackChannelsTypeProvider;
37 import org.openhab.binding.sensibo.internal.SensiboBindingConstants;
38 import org.openhab.binding.sensibo.internal.config.SensiboSkyConfiguration;
39 import org.openhab.binding.sensibo.internal.dto.poddetails.TemperatureDTO;
40 import org.openhab.binding.sensibo.internal.model.SensiboModel;
41 import org.openhab.binding.sensibo.internal.model.SensiboSky;
42 import org.openhab.binding.sensibo.internal.util.StringUtils;
43 import org.openhab.core.library.types.DecimalType;
44 import org.openhab.core.library.types.OnOffType;
45 import org.openhab.core.library.types.QuantityType;
46 import org.openhab.core.library.types.StringType;
47 import org.openhab.core.library.unit.SIUnits;
48 import org.openhab.core.library.unit.Units;
49 import org.openhab.core.thing.Channel;
50 import org.openhab.core.thing.ChannelUID;
51 import org.openhab.core.thing.Thing;
52 import org.openhab.core.thing.ThingStatus;
53 import org.openhab.core.thing.ThingStatusDetail;
54 import org.openhab.core.thing.binding.ThingHandlerService;
55 import org.openhab.core.thing.binding.builder.ChannelBuilder;
56 import org.openhab.core.thing.type.ChannelType;
57 import org.openhab.core.thing.type.ChannelTypeBuilder;
58 import org.openhab.core.thing.type.ChannelTypeProvider;
59 import org.openhab.core.thing.type.ChannelTypeUID;
60 import org.openhab.core.thing.type.StateChannelTypeBuilder;
61 import org.openhab.core.types.Command;
62 import org.openhab.core.types.RefreshType;
63 import org.openhab.core.types.StateDescriptionFragmentBuilder;
64 import org.openhab.core.types.StateOption;
65 import org.openhab.core.types.UnDefType;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
70 * The {@link SensiboSkyHandler} is responsible for handling commands, which are
71 * sent to one of the channels.
73 * @author Arne Seime - Initial contribution
76 public class SensiboSkyHandler extends SensiboBaseThingHandler implements ChannelTypeProvider {
77 public static final String SWING_PROPERTY = "swing";
78 public static final String MASTER_SWITCH_PROPERTY = "on";
79 public static final String FAN_LEVEL_PROPERTY = "fanLevel";
80 public static final String MODE_PROPERTY = "mode";
81 public static final String TARGET_TEMPERATURE_PROPERTY = "targetTemperature";
82 public static final String SWING_MODE_LABEL = "Swing Mode";
83 public static final String FAN_LEVEL_LABEL = "Fan Level";
84 public static final String MODE_LABEL = "Mode";
85 public static final String TARGET_TEMPERATURE_LABEL = "Target Temperature";
86 private static final String ITEM_TYPE_STRING = "String";
87 private static final String ITEM_TYPE_NUMBER_TEMPERATURE = "Number:Temperature";
88 private final Logger logger = LoggerFactory.getLogger(SensiboSkyHandler.class);
89 private final Map<ChannelTypeUID, ChannelType> generatedChannelTypes = new HashMap<>();
90 private Optional<SensiboSkyConfiguration> config = Optional.empty();
92 public SensiboSkyHandler(final Thing thing) {
96 private static String beautify(final String camelCaseWording) {
97 final StringBuilder b = new StringBuilder();
98 for (final String s : StringUtils.splitByCharacterType(camelCaseWording)) {
102 final StringBuilder bs = new StringBuilder();
103 for (final String t : b.toString().split("[ ][_]")) {
108 return StringUtils.capitalizeFully(bs.toString()).trim();
111 private String getMacAddress() {
112 if (config.isPresent()) {
113 return config.get().macAddress;
115 throw new IllegalArgumentException("No configuration present");
119 public void handleCommand(final ChannelUID channelUID, final Command command) {
120 handleCommand(channelUID, command, getSensiboModel());
124 * Package private in order to be reachable from unit test
126 void updateAcState(SensiboSky sensiboSky, String property, Object value) {
127 StateChange stateChange = checkStateChangeValid(sensiboSky, property, value);
128 if (stateChange.valid) {
129 getAccountHandler().ifPresent(
130 handler -> handler.updateSensiboSkyAcState(getMacAddress(), property, stateChange.value, this));
132 logger.info("Update command not sent; invalid state change for SensiboSky AC state: {}",
133 stateChange.validationMessage);
137 private void updateTimer(@Nullable Integer secondsFromNowUntilSwitchOff) {
139 .ifPresent(handler -> handler.updateSensiboSkyTimer(getMacAddress(), secondsFromNowUntilSwitchOff));
143 protected void handleCommand(final ChannelUID channelUID, final Command command, final SensiboModel model) {
144 model.findSensiboSkyByMacAddress(getMacAddress()).ifPresent(sensiboSky -> {
145 if (sensiboSky.isAlive()) {
146 if (getThing().getStatus() != ThingStatus.ONLINE) {
147 addDynamicChannelsAndProperties(sensiboSky);
148 updateStatus(ThingStatus.ONLINE); // In case it has been offline
150 switch (channelUID.getId()) {
151 case CHANNEL_CURRENT_HUMIDITY:
152 handleCurrentHumidityCommand(channelUID, command, sensiboSky);
154 case CHANNEL_CURRENT_TEMPERATURE:
155 handleCurrentTemperatureCommand(channelUID, command, sensiboSky);
157 case CHANNEL_MASTER_SWITCH:
158 handleMasterSwitchCommand(channelUID, command, sensiboSky);
160 case CHANNEL_TARGET_TEMPERATURE:
161 handleTargetTemperatureCommand(channelUID, command, sensiboSky);
164 handleModeCommand(channelUID, command, sensiboSky);
166 case CHANNEL_SWING_MODE:
167 handleSwingCommand(channelUID, command, sensiboSky);
169 case CHANNEL_FAN_LEVEL:
170 handleFanLevelCommand(channelUID, command, sensiboSky);
173 handleTimerCommand(channelUID, command, sensiboSky);
176 logger.debug("Received command on unknown channel {}, ignoring", channelUID.getId());
179 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
180 "Unreachable by Sensibo servers");
185 private void handleTimerCommand(ChannelUID channelUID, Command command, SensiboSky sensiboSky) {
186 if (command instanceof RefreshType) {
187 if (sensiboSky.getTimer().isPresent() && sensiboSky.getTimer().get().secondsRemaining > 0) {
188 updateState(channelUID, new DecimalType(sensiboSky.getTimer().get().secondsRemaining));
190 updateState(channelUID, UnDefType.UNDEF);
192 } else if (command instanceof DecimalType newValue) {
193 updateTimer(newValue.intValue());
199 private void handleFanLevelCommand(ChannelUID channelUID, Command command, SensiboSky sensiboSky) {
200 if (command instanceof RefreshType) {
201 if (sensiboSky.getAcState().isPresent() && sensiboSky.getAcState().get().getFanLevel() != null) {
202 updateState(channelUID, new StringType(sensiboSky.getAcState().get().getFanLevel()));
204 updateState(channelUID, UnDefType.UNDEF);
206 } else if (command instanceof StringType newValue) {
207 updateAcState(sensiboSky, FAN_LEVEL_PROPERTY, newValue.toString());
211 private void handleSwingCommand(ChannelUID channelUID, Command command, SensiboSky sensiboSky) {
212 if (command instanceof RefreshType && sensiboSky.getAcState().isPresent()) {
213 if (sensiboSky.getAcState().isPresent() && sensiboSky.getAcState().get().getSwing() != null) {
214 updateState(channelUID, new StringType(sensiboSky.getAcState().get().getSwing()));
216 updateState(channelUID, UnDefType.UNDEF);
218 } else if (command instanceof StringType newValue) {
219 updateAcState(sensiboSky, SWING_PROPERTY, newValue.toString());
223 private void handleModeCommand(ChannelUID channelUID, Command command, SensiboSky sensiboSky) {
224 if (command instanceof RefreshType) {
225 if (sensiboSky.getAcState().isPresent()) {
226 updateState(channelUID, new StringType(sensiboSky.getAcState().get().getMode()));
228 updateState(channelUID, UnDefType.UNDEF);
230 } else if (command instanceof StringType newValue) {
231 updateAcState(sensiboSky, MODE_PROPERTY, newValue.toString());
232 addDynamicChannelsAndProperties(sensiboSky);
236 private void handleTargetTemperatureCommand(ChannelUID channelUID, Command command, SensiboSky sensiboSky) {
237 if (command instanceof RefreshType) {
238 sensiboSky.getAcState().ifPresent(acState -> {
240 Integer targetTemperature = acState.getTargetTemperature();
241 if (targetTemperature != null) {
242 updateState(channelUID, new QuantityType<>(targetTemperature, sensiboSky.getTemperatureUnit()));
244 updateState(channelUID, UnDefType.UNDEF);
247 if (sensiboSky.getAcState().isEmpty()) {
248 updateState(channelUID, UnDefType.UNDEF);
250 } else if (command instanceof QuantityType<?> newValue) {
251 if (!Objects.equals(sensiboSky.getTemperatureUnit(), newValue.getUnit())) {
252 // If quantity is given in celsius when fahrenheit is used or opposite
254 UnitConverter temperatureConverter = newValue.getUnit()
255 .getConverterToAny(sensiboSky.getTemperatureUnit());
256 // No decimals supported
257 long convertedValue = (long) temperatureConverter.convert(newValue.longValue());
258 updateAcState(sensiboSky, TARGET_TEMPERATURE_PROPERTY, new DecimalType(convertedValue));
259 } catch (UnconvertibleException | IncommensurableException e) {
260 logger.info("Could not convert {} to {}: {}", newValue, sensiboSky.getTemperatureUnit(),
264 updateAcState(sensiboSky, TARGET_TEMPERATURE_PROPERTY, new DecimalType(newValue.intValue()));
266 } else if (command instanceof DecimalType) {
267 updateAcState(sensiboSky, TARGET_TEMPERATURE_PROPERTY, command);
271 private void handleMasterSwitchCommand(ChannelUID channelUID, Command command, SensiboSky sensiboSky) {
272 if (command instanceof RefreshType) {
273 sensiboSky.getAcState().ifPresent(e -> updateState(channelUID, OnOffType.from(e.isOn())));
274 } else if (command instanceof OnOffType) {
275 updateAcState(sensiboSky, MASTER_SWITCH_PROPERTY, command == OnOffType.ON);
279 private void handleCurrentTemperatureCommand(ChannelUID channelUID, Command command, SensiboSky sensiboSky) {
280 if (command instanceof RefreshType) {
281 updateState(channelUID, new QuantityType<>(sensiboSky.getTemperature(), SIUnits.CELSIUS));
285 private void handleCurrentHumidityCommand(ChannelUID channelUID, Command command, SensiboSky sensiboSky) {
286 if (command instanceof RefreshType) {
287 updateState(channelUID, new QuantityType<>(sensiboSky.getHumidity(), Units.PERCENT));
292 public Collection<Class<? extends ThingHandlerService>> getServices() {
293 return Set.of(CallbackChannelsTypeProvider.class);
297 public void initialize() {
298 config = Optional.ofNullable(getConfigAs(SensiboSkyConfiguration.class));
299 logger.debug("Initializing SensiboSky using config {}", config);
300 getSensiboModel().findSensiboSkyByMacAddress(getMacAddress()).ifPresent(pod -> {
303 addDynamicChannelsAndProperties(pod);
304 updateStatus(ThingStatus.ONLINE);
306 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
307 "Unreachable by Sensibo servers");
312 private boolean isDynamicChannel(final ChannelTypeUID uid) {
313 return SensiboBindingConstants.DYNAMIC_CHANNEL_TYPES.stream().anyMatch(e -> uid.getId().startsWith(e));
316 private void addDynamicChannelsAndProperties(final SensiboSky sensiboSky) {
317 logger.debug("Updating dynamic channels for {}", sensiboSky.getId());
318 final List<Channel> newChannels = new ArrayList<>();
319 for (final Channel channel : getThing().getChannels()) {
320 final ChannelTypeUID channelTypeUID = channel.getChannelTypeUID();
321 if (channelTypeUID != null && !isDynamicChannel(channelTypeUID)) {
322 newChannels.add(channel);
326 newChannels.addAll(createDynamicChannels(sensiboSky));
327 Map<String, String> properties = sensiboSky.getThingProperties();
328 updateThing(editThing().withChannels(newChannels).withProperties(properties).build());
331 public List<Channel> createDynamicChannels(final SensiboSky sensiboSky) {
332 final List<Channel> newChannels = new ArrayList<>();
333 generatedChannelTypes.clear();
335 sensiboSky.getCurrentModeCapabilities().ifPresent(capabilities -> {
336 // Not all modes have swing and fan level
337 final ChannelTypeUID swingModeChannelType = addChannelType(SensiboBindingConstants.CHANNEL_TYPE_SWING_MODE,
338 SWING_MODE_LABEL, ITEM_TYPE_STRING, capabilities.swingModes, null, null);
341 .create(new ChannelUID(getThing().getUID(), SensiboBindingConstants.CHANNEL_SWING_MODE),
343 .withLabel(SWING_MODE_LABEL).withType(swingModeChannelType).build());
345 final ChannelTypeUID fanLevelChannelType = addChannelType(SensiboBindingConstants.CHANNEL_TYPE_FAN_LEVEL,
346 FAN_LEVEL_LABEL, ITEM_TYPE_STRING, capabilities.fanLevels, null, null);
347 newChannels.add(ChannelBuilder
348 .create(new ChannelUID(getThing().getUID(), SensiboBindingConstants.CHANNEL_FAN_LEVEL),
350 .withLabel(FAN_LEVEL_LABEL).withType(fanLevelChannelType).build());
353 final ChannelTypeUID modeChannelType = addChannelType(SensiboBindingConstants.CHANNEL_TYPE_MODE, MODE_LABEL,
354 ITEM_TYPE_STRING, sensiboSky.getRemoteCapabilities().keySet(), null, null);
355 newChannels.add(ChannelBuilder
356 .create(new ChannelUID(getThing().getUID(), SensiboBindingConstants.CHANNEL_MODE), ITEM_TYPE_STRING)
357 .withLabel(MODE_LABEL).withType(modeChannelType).build());
359 final ChannelTypeUID targetTemperatureChannelType = addChannelType(
360 SensiboBindingConstants.CHANNEL_TYPE_TARGET_TEMPERATURE, TARGET_TEMPERATURE_LABEL,
361 ITEM_TYPE_NUMBER_TEMPERATURE, sensiboSky.getTargetTemperatures(), "%d %unit%",
362 Set.of("Setpoint", "Temperature"));
363 newChannels.add(ChannelBuilder
364 .create(new ChannelUID(getThing().getUID(), SensiboBindingConstants.CHANNEL_TARGET_TEMPERATURE),
365 ITEM_TYPE_NUMBER_TEMPERATURE)
366 .withLabel(TARGET_TEMPERATURE_LABEL).withType(targetTemperatureChannelType).build());
371 private ChannelTypeUID addChannelType(final String channelTypePrefix, final String label, final String itemType,
372 final Collection<?> options, @Nullable final String pattern, @Nullable final Set<String> tags) {
373 final ChannelTypeUID channelTypeUID = new ChannelTypeUID(SensiboBindingConstants.BINDING_ID,
374 channelTypePrefix + getThing().getUID().getId());
375 final List<StateOption> stateOptions = options.stream()
376 .map(e -> new StateOption(e.toString(), e instanceof String s ? beautify(s) : e.toString()))
377 .collect(Collectors.toList());
379 StateDescriptionFragmentBuilder stateDescription = StateDescriptionFragmentBuilder.create().withReadOnly(false)
380 .withOptions(stateOptions);
381 if (pattern != null) {
382 stateDescription = stateDescription.withPattern(pattern);
384 final StateChannelTypeBuilder builder = ChannelTypeBuilder.state(channelTypeUID, label, itemType)
385 .withStateDescriptionFragment(stateDescription.build());
386 if (tags != null && !tags.isEmpty()) {
387 builder.withTags(tags);
389 final ChannelType channelType = builder.build();
391 generatedChannelTypes.put(channelTypeUID, channelType);
393 return channelTypeUID;
397 public Collection<ChannelType> getChannelTypes(@Nullable final Locale locale) {
398 return generatedChannelTypes.values();
402 public @Nullable ChannelType getChannelType(final ChannelTypeUID channelTypeUID, @Nullable final Locale locale) {
403 return generatedChannelTypes.get(channelTypeUID);
407 * Package private in order to be reachable from unit test
409 StateChange checkStateChangeValid(SensiboSky sensiboSky, String property, Object newPropertyValue) {
410 StateChange stateChange = new StateChange(newPropertyValue);
412 sensiboSky.getCurrentModeCapabilities().ifPresent(currentModeCapabilities -> {
414 case TARGET_TEMPERATURE_PROPERTY:
415 Unit<Temperature> temperatureUnit = sensiboSky.getTemperatureUnit();
416 TemperatureDTO validTemperatures = currentModeCapabilities.temperatures
417 .get(SIUnits.CELSIUS.equals(temperatureUnit) ? "C" : "F");
418 DecimalType rawValue = (DecimalType) newPropertyValue;
419 stateChange.updateValue(rawValue.intValue());
420 if (!validTemperatures.validValues.contains(rawValue.intValue())) {
421 stateChange.addError(String.format(
422 "Cannot change targetTemperature to '%d', valid targetTemperatures are one of %s",
424 String.join(",", validTemperatures.validValues.stream().map(Object::toString)
425 .collect(Collectors.toUnmodifiableList()).toArray(new String[0]))));
429 if (!sensiboSky.getRemoteCapabilities().containsKey(newPropertyValue)) {
430 stateChange.addError(String.format("Cannot change mode to %s, valid modes are %s",
431 newPropertyValue, String.join(",", sensiboSky.getRemoteCapabilities().keySet())));
434 case FAN_LEVEL_PROPERTY:
435 if (!currentModeCapabilities.fanLevels.contains(newPropertyValue)) {
436 stateChange.addError(
437 String.format("Cannot change fanLevel to %s, valid fanLevels are %s", newPropertyValue,
438 String.join(",", currentModeCapabilities.fanLevels.toArray(new String[0]))));
441 case MASTER_SWITCH_PROPERTY:
445 if (!currentModeCapabilities.swingModes.contains(newPropertyValue)) {
446 stateChange.addError(
447 String.format("Cannot change swing to %s, valid swings are %s", newPropertyValue,
448 String.join(",", currentModeCapabilities.swingModes.toArray(new String[0]))));
452 stateChange.addError(String.format("No such ac state property %s", property));
454 logger.debug("State change request {}", stateChange);
460 public class StateChange {
463 boolean valid = true;
465 String validationMessage;
467 public StateChange(Object value) {
471 public void updateValue(Object updatedValue) {
472 value = updatedValue;
475 public void addError(String validationMessage) {
477 this.validationMessage = validationMessage;
481 public String toString() {
482 return "StateChange [valid=" + valid + ", validationMessage=" + validationMessage + ", value=" + value
483 + ", value Class=" + value.getClass() + "]";