2 * Copyright (c) 2010-2021 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.homeconnect.internal.handler;
15 import static java.util.Collections.emptyList;
16 import static org.openhab.binding.homeconnect.internal.HomeConnectBindingConstants.*;
17 import static org.openhab.binding.homeconnect.internal.client.model.EventType.*;
18 import static org.openhab.core.library.unit.ImperialUnits.FAHRENHEIT;
19 import static org.openhab.core.library.unit.SIUnits.CELSIUS;
20 import static org.openhab.core.library.unit.Units.*;
21 import static org.openhab.core.thing.ThingStatus.*;
23 import java.time.Duration;
24 import java.util.Collections;
25 import java.util.List;
27 import java.util.Optional;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.ScheduledFuture;
30 import java.util.concurrent.TimeUnit;
31 import java.util.concurrent.atomic.AtomicBoolean;
32 import java.util.function.Function;
33 import java.util.stream.Collectors;
35 import javax.measure.UnconvertibleException;
36 import javax.measure.Unit;
37 import javax.measure.quantity.Temperature;
39 import org.eclipse.jdt.annotation.NonNullByDefault;
40 import org.eclipse.jdt.annotation.Nullable;
41 import org.openhab.binding.homeconnect.internal.client.HomeConnectApiClient;
42 import org.openhab.binding.homeconnect.internal.client.HomeConnectEventSourceClient;
43 import org.openhab.binding.homeconnect.internal.client.exception.ApplianceOfflineException;
44 import org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException;
45 import org.openhab.binding.homeconnect.internal.client.exception.CommunicationException;
46 import org.openhab.binding.homeconnect.internal.client.listener.HomeConnectEventListener;
47 import org.openhab.binding.homeconnect.internal.client.model.AvailableProgramOption;
48 import org.openhab.binding.homeconnect.internal.client.model.Data;
49 import org.openhab.binding.homeconnect.internal.client.model.Event;
50 import org.openhab.binding.homeconnect.internal.client.model.HomeAppliance;
51 import org.openhab.binding.homeconnect.internal.client.model.Option;
52 import org.openhab.binding.homeconnect.internal.client.model.Program;
53 import org.openhab.binding.homeconnect.internal.handler.cache.ExpiringStateMap;
54 import org.openhab.binding.homeconnect.internal.type.HomeConnectDynamicStateDescriptionProvider;
55 import org.openhab.core.auth.client.oauth2.OAuthException;
56 import org.openhab.core.library.types.DecimalType;
57 import org.openhab.core.library.types.HSBType;
58 import org.openhab.core.library.types.IncreaseDecreaseType;
59 import org.openhab.core.library.types.OnOffType;
60 import org.openhab.core.library.types.OpenClosedType;
61 import org.openhab.core.library.types.PercentType;
62 import org.openhab.core.library.types.QuantityType;
63 import org.openhab.core.library.types.StringType;
64 import org.openhab.core.library.unit.ImperialUnits;
65 import org.openhab.core.library.unit.SIUnits;
66 import org.openhab.core.thing.Bridge;
67 import org.openhab.core.thing.Channel;
68 import org.openhab.core.thing.ChannelUID;
69 import org.openhab.core.thing.Thing;
70 import org.openhab.core.thing.ThingStatusDetail;
71 import org.openhab.core.thing.ThingStatusInfo;
72 import org.openhab.core.thing.binding.BaseThingHandler;
73 import org.openhab.core.thing.binding.BridgeHandler;
74 import org.openhab.core.types.Command;
75 import org.openhab.core.types.RefreshType;
76 import org.openhab.core.types.StateOption;
77 import org.openhab.core.types.UnDefType;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
82 * The {@link AbstractHomeConnectThingHandler} is responsible for handling commands, which are
83 * sent to one of the channels.
85 * @author Jonas Brüstel - Initial contribution
88 public abstract class AbstractHomeConnectThingHandler extends BaseThingHandler implements HomeConnectEventListener {
90 private static final int CACHE_TTL_SEC = 2;
91 private static final int OFFLINE_MONITOR_1_DELAY_MIN = 30;
92 private static final int OFFLINE_MONITOR_2_DELAY_MIN = 4;
93 private static final int EVENT_LISTENER_CONNECT_RETRY_DELAY_MIN = 10;
95 private @Nullable String operationState;
96 private @Nullable ScheduledFuture<?> reinitializationFuture1;
97 private @Nullable ScheduledFuture<?> reinitializationFuture2;
98 private @Nullable ScheduledFuture<?> reinitializationFuture3;
99 private boolean ignoreEventSourceClosedEvent;
100 private @Nullable String programOptionsDelayedUpdate;
102 private final ConcurrentHashMap<String, EventHandler> eventHandlers;
103 private final ConcurrentHashMap<String, ChannelUpdateHandler> channelUpdateHandlers;
104 private final HomeConnectDynamicStateDescriptionProvider dynamicStateDescriptionProvider;
105 private final ExpiringStateMap expiringStateMap;
106 private final AtomicBoolean accessible;
107 private final Logger logger = LoggerFactory.getLogger(AbstractHomeConnectThingHandler.class);
108 private final Map<String, List<AvailableProgramOption>> availableProgramOptionsCache;
110 public AbstractHomeConnectThingHandler(Thing thing,
111 HomeConnectDynamicStateDescriptionProvider dynamicStateDescriptionProvider) {
113 eventHandlers = new ConcurrentHashMap<>();
114 channelUpdateHandlers = new ConcurrentHashMap<>();
115 this.dynamicStateDescriptionProvider = dynamicStateDescriptionProvider;
116 expiringStateMap = new ExpiringStateMap(Duration.ofSeconds(CACHE_TTL_SEC));
117 accessible = new AtomicBoolean(false);
118 availableProgramOptionsCache = new ConcurrentHashMap<>();
120 configureEventHandlers(eventHandlers);
121 configureChannelUpdateHandlers(channelUpdateHandlers);
125 public void initialize() {
126 if (getBridgeHandler().isEmpty()) {
127 updateStatus(OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
128 accessible.set(false);
129 } else if (isBridgeOffline()) {
130 updateStatus(OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
131 accessible.set(false);
133 updateStatus(UNKNOWN);
134 scheduler.submit(() -> {
135 refreshThingStatus(); // set ONLINE / OFFLINE
136 updateSelectedProgramStateDescription();
138 registerEventListener();
139 scheduleOfflineMonitor1();
140 scheduleOfflineMonitor2();
146 public void dispose() {
147 stopRetryRegistering();
148 stopOfflineMonitor1();
149 stopOfflineMonitor2();
150 unregisterEventListener(true);
154 public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
155 logger.debug("Bridge status changed to {} ({}). haId={}", bridgeStatusInfo, getThingLabel(), getThingHaId());
159 private void reinitialize() {
160 logger.debug("Reinitialize thing handler ({}). haId={}", getThingLabel(), getThingHaId());
161 stopRetryRegistering();
162 stopOfflineMonitor1();
163 stopOfflineMonitor2();
164 unregisterEventListener();
169 * Handles a command for a given channel.
171 * This method is only called, if the thing has been initialized (status ONLINE/OFFLINE/UNKNOWN).
174 * @param channelUID the {@link ChannelUID} of the channel to which the command was sent
175 * @param command the {@link Command}
176 * @param apiClient the {@link HomeConnectApiClient}
177 * @throws CommunicationException communication problem
178 * @throws AuthorizationException authorization problem
179 * @throws ApplianceOfflineException appliance offline
181 protected void handleCommand(ChannelUID channelUID, Command command, HomeConnectApiClient apiClient)
182 throws CommunicationException, AuthorizationException, ApplianceOfflineException {
183 if (command instanceof RefreshType) {
184 updateChannel(channelUID);
185 } else if (command instanceof StringType && CHANNEL_BASIC_ACTIONS_STATE.equals(channelUID.getId())
186 && getBridgeHandler().isPresent()) {
187 updateState(channelUID, new StringType(""));
189 if (COMMAND_START.equalsIgnoreCase(command.toFullString())) {
190 HomeConnectBridgeHandler homeConnectBridgeHandler = getBridgeHandler().get();
191 // workaround for api bug
192 // if simulator, program options have to be passed along with the desired program
193 // if non simulator, some options throw a "SDK.Error.UnsupportedOption" error
194 if (homeConnectBridgeHandler.getConfiguration().isSimulator()) {
195 apiClient.startSelectedProgram(getThingHaId());
197 Program selectedProgram = apiClient.getSelectedProgram(getThingHaId());
198 if (selectedProgram != null) {
199 apiClient.startProgram(getThingHaId(), selectedProgram.getKey());
202 } else if (COMMAND_STOP.equalsIgnoreCase(command.toFullString())) {
203 apiClient.stopProgram(getThingHaId());
204 } else if (COMMAND_SELECTED.equalsIgnoreCase(command.toFullString())) {
205 apiClient.getSelectedProgram(getThingHaId());
207 logger.debug("Start custom program. command={} haId={}", command.toFullString(), getThingHaId());
208 apiClient.startCustomProgram(getThingHaId(), command.toFullString());
210 } else if (command instanceof StringType && CHANNEL_SELECTED_PROGRAM_STATE.equals(channelUID.getId())) {
211 apiClient.setSelectedProgram(getThingHaId(), command.toFullString());
216 public final void handleCommand(ChannelUID channelUID, Command command) {
217 var apiClient = getApiClient();
218 if ((isThingReadyToHandleCommand() || (this instanceof HomeConnectHoodHandler && isBridgeOnline()
219 && isThingAccessibleViaServerSentEvents())) && apiClient.isPresent()) {
220 logger.debug("Handle \"{}\" command ({}). haId={}", command, channelUID.getId(), getThingHaId());
222 handleCommand(channelUID, command, apiClient.get());
223 } catch (ApplianceOfflineException e) {
224 logger.debug("Could not handle command {}. Appliance offline. thing={}, haId={}, error={}",
225 command.toFullString(), getThingLabel(), getThingHaId(), e.getMessage());
226 updateStatus(OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
227 resetChannelsOnOfflineEvent();
228 resetProgramStateChannels(true);
229 } catch (CommunicationException e) {
230 logger.debug("Could not handle command {}. API communication problem! error={}, haId={}",
231 command.toFullString(), e.getMessage(), getThingHaId());
232 } catch (AuthorizationException e) {
233 logger.debug("Could not handle command {}. Authorization problem! error={}, haId={}",
234 command.toFullString(), e.getMessage(), getThingHaId());
236 handleAuthenticationError(e);
242 public void onEvent(Event event) {
243 if (DISCONNECTED.equals(event.getType())) {
244 logger.debug("Received DISCONNECTED event. Set {} to OFFLINE. haId={}", getThing().getLabel(),
246 updateStatus(OFFLINE);
247 resetChannelsOnOfflineEvent();
248 resetProgramStateChannels(true);
249 } else if (isThingOnline() && CONNECTED.equals(event.getType())) {
250 logger.debug("Received CONNECTED event. Update power state channel. haId={}", getThingHaId());
251 getThingChannel(CHANNEL_POWER_STATE).ifPresent(c -> updateChannel(c.getUID()));
252 } else if (isThingOffline() && !KEEP_ALIVE.equals(event.getType())) {
253 updateStatus(ONLINE);
254 logger.debug("Set {} to ONLINE and update channels. haId={}", getThing().getLabel(), getThingHaId());
255 updateSelectedProgramStateDescription();
259 String key = event.getKey();
260 if (EVENT_OPERATION_STATE.equals(key)) {
261 operationState = event.getValue() == null ? null : event.getValue();
264 if (key != null && eventHandlers.containsKey(key)) {
265 EventHandler eventHandler = eventHandlers.get(key);
266 if (eventHandler != null) {
267 eventHandler.handle(event);
271 accessible.set(true);
275 public void onClosed() {
276 if (ignoreEventSourceClosedEvent) {
277 logger.debug("Ignoring event source close event. thing={}, haId={}", getThing().getLabel(), getThingHaId());
279 unregisterEventListener();
280 refreshThingStatus();
281 registerEventListener();
286 public void onRateLimitReached() {
287 unregisterEventListener();
290 scheduleRetryRegistering();
294 * Register event listener.
296 protected void registerEventListener() {
297 if (isBridgeOnline() && isThingAccessibleViaServerSentEvents()) {
298 getEventSourceClient().ifPresent(client -> {
300 ignoreEventSourceClosedEvent = false;
301 client.registerEventListener(getThingHaId(), this);
302 } catch (CommunicationException | AuthorizationException e) {
303 logger.warn("Could not open event source connection. thing={}, haId={}, error={}", getThingLabel(),
304 getThingHaId(), e.getMessage());
311 * Unregister event listener.
313 protected void unregisterEventListener() {
314 unregisterEventListener(false);
317 private void unregisterEventListener(boolean immediate) {
318 getEventSourceClient().ifPresent(client -> {
319 ignoreEventSourceClosedEvent = true;
320 client.unregisterEventListener(this, immediate, false);
325 * Get {@link HomeConnectApiClient}.
327 * @return client instance
329 protected Optional<HomeConnectApiClient> getApiClient() {
330 return getBridgeHandler().map(HomeConnectBridgeHandler::getApiClient);
334 * Get {@link HomeConnectEventSourceClient}.
336 * @return client instance if present
338 protected Optional<HomeConnectEventSourceClient> getEventSourceClient() {
339 return getBridgeHandler().map(HomeConnectBridgeHandler::getEventSourceClient);
343 * Update state description of selected program (Fetch programs via API).
345 protected void updateSelectedProgramStateDescription() {
346 if (isBridgeOffline() || isThingOffline()) {
350 Optional<HomeConnectApiClient> apiClient = getApiClient();
351 if (apiClient.isPresent()) {
353 List<StateOption> stateOptions = apiClient.get().getPrograms(getThingHaId()).stream()
354 .map(p -> new StateOption(p.getKey(), mapStringType(p.getKey()))).collect(Collectors.toList());
356 getThingChannel(CHANNEL_SELECTED_PROGRAM_STATE).ifPresent(
357 channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(), stateOptions));
358 } catch (CommunicationException | ApplianceOfflineException | AuthorizationException e) {
359 logger.debug("Could not fetch available programs. thing={}, haId={}, error={}", getThingLabel(),
360 getThingHaId(), e.getMessage());
361 removeSelectedProgramStateDescription();
364 removeSelectedProgramStateDescription();
369 * Remove state description of selected program.
371 protected void removeSelectedProgramStateDescription() {
372 getThingChannel(CHANNEL_SELECTED_PROGRAM_STATE)
373 .ifPresent(channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(), emptyList()));
377 * Is thing ready to process commands. If bridge or thing itself is offline commands will be ignored.
379 * @return true if ready
381 protected boolean isThingReadyToHandleCommand() {
382 if (isBridgeOffline()) {
383 logger.debug("Bridge is OFFLINE. Ignore command. thing={}, haId={}", getThingLabel(), getThingHaId());
387 if (isThingOffline()) {
388 logger.debug("{} is OFFLINE. Ignore command. haId={}", getThing().getLabel(), getThingHaId());
396 * Checks if bridge is online and set.
398 * @return true if online
400 protected boolean isBridgeOnline() {
401 Bridge bridge = getBridge();
402 return bridge != null && ONLINE.equals(bridge.getStatus());
406 * Checks if bridge is offline or not set.
408 * @return true if offline
410 protected boolean isBridgeOffline() {
411 return !isBridgeOnline();
415 * Checks if thing is online.
417 * @return true if online
419 protected boolean isThingOnline() {
420 return ONLINE.equals(getThing().getStatus());
424 * Checks if thing is connected to the cloud and accessible via SSE.
426 * @return true if yes
428 public boolean isThingAccessibleViaServerSentEvents() {
429 return accessible.get();
433 * Checks if thing is offline.
435 * @return true if offline
437 protected boolean isThingOffline() {
438 return !isThingOnline();
442 * Get {@link HomeConnectBridgeHandler}.
444 * @return bridge handler
446 protected Optional<HomeConnectBridgeHandler> getBridgeHandler() {
447 Bridge bridge = getBridge();
448 if (bridge != null) {
449 BridgeHandler bridgeHandler = bridge.getHandler();
450 if (bridgeHandler instanceof HomeConnectBridgeHandler) {
451 return Optional.of((HomeConnectBridgeHandler) bridgeHandler);
454 return Optional.empty();
458 * Get thing channel by given channel id.
460 * @param channelId channel id
463 protected Optional<Channel> getThingChannel(String channelId) {
464 Channel channel = getThing().getChannel(channelId);
465 if (channel == null) {
466 return Optional.empty();
468 return Optional.of(channel);
473 * Configure channel update handlers. Classes which extend {@link AbstractHomeConnectThingHandler} must implement
474 * this class and add handlers.
476 * @param handlers channel update handlers
478 protected abstract void configureChannelUpdateHandlers(final Map<String, ChannelUpdateHandler> handlers);
481 * Configure event handlers. Classes which extend {@link AbstractHomeConnectThingHandler} must implement
482 * this class and add handlers.
484 * @param handlers Server-Sent-Event handlers
486 protected abstract void configureEventHandlers(final Map<String, EventHandler> handlers);
489 * Update all channels via API.
492 protected void updateChannels() {
493 if (isBridgeOffline()) {
494 logger.debug("Bridge handler not found or offline. Stopping update of channels. thing={}, haId={}",
495 getThingLabel(), getThingHaId());
496 } else if (isThingOffline()) {
497 logger.debug("{} offline. Stopping update of channels. haId={}", getThing().getLabel(), getThingHaId());
499 List<Channel> channels = getThing().getChannels();
500 for (Channel channel : channels) {
501 updateChannel(channel.getUID());
507 * Update Channel values via API.
509 * @param channelUID channel UID
511 protected void updateChannel(ChannelUID channelUID) {
512 if (!getApiClient().isPresent()) {
513 logger.error("Cannot update channel. No instance of api client found! thing={}, haId={}", getThingLabel(),
518 if (!isThingReadyToHandleCommand()) {
522 if ((isLinked(channelUID) || CHANNEL_OPERATION_STATE.equals(channelUID.getId())) // always update operation
524 && channelUpdateHandlers.containsKey(channelUID.getId())) {
526 ChannelUpdateHandler channelUpdateHandler = channelUpdateHandlers.get(channelUID.getId());
527 if (channelUpdateHandler != null) {
528 channelUpdateHandler.handle(channelUID, expiringStateMap);
530 } catch (ApplianceOfflineException e) {
532 "API communication problem while trying to update! Appliance offline. thing={}, haId={}, error={}",
533 getThingLabel(), getThingHaId(), e.getMessage());
534 updateStatus(OFFLINE);
535 resetChannelsOnOfflineEvent();
536 resetProgramStateChannels(true);
537 } catch (CommunicationException e) {
538 logger.debug("API communication problem while trying to update! thing={}, haId={}, error={}",
539 getThingLabel(), getThingHaId(), e.getMessage());
540 } catch (AuthorizationException e) {
541 logger.debug("Authentication problem while trying to update! thing={}, haId={}", getThingLabel(),
543 handleAuthenticationError(e);
549 * Reset program related channels.
551 * @param offline true if the device is considered as OFFLINE
553 protected void resetProgramStateChannels(boolean offline) {
554 logger.debug("Resetting active program channel states. thing={}, haId={}", getThingLabel(), getThingHaId());
558 * Reset all channels on OFFLINE event.
560 protected void resetChannelsOnOfflineEvent() {
561 logger.debug("Resetting channel states due to OFFLINE event. thing={}, haId={}", getThingLabel(),
563 getThingChannel(CHANNEL_POWER_STATE).ifPresent(channel -> updateState(channel.getUID(), OnOffType.OFF));
564 getThingChannel(CHANNEL_OPERATION_STATE).ifPresent(channel -> updateState(channel.getUID(), UnDefType.UNDEF));
565 getThingChannel(CHANNEL_DOOR_STATE).ifPresent(channel -> updateState(channel.getUID(), UnDefType.UNDEF));
566 getThingChannel(CHANNEL_LOCAL_CONTROL_ACTIVE_STATE)
567 .ifPresent(channel -> updateState(channel.getUID(), UnDefType.UNDEF));
568 getThingChannel(CHANNEL_REMOTE_CONTROL_ACTIVE_STATE)
569 .ifPresent(channel -> updateState(channel.getUID(), UnDefType.UNDEF));
570 getThingChannel(CHANNEL_REMOTE_START_ALLOWANCE_STATE)
571 .ifPresent(channel -> updateState(channel.getUID(), UnDefType.UNDEF));
572 getThingChannel(CHANNEL_SELECTED_PROGRAM_STATE)
573 .ifPresent(channel -> updateState(channel.getUID(), UnDefType.UNDEF));
577 * Map Home Connect key and value names to label.
578 * e.g. Dishcare.Dishwasher.Program.Eco50 --> Eco50 or BSH.Common.EnumType.OperationState.DelayedStart --> Delayed
582 * @return human readable label
584 protected String mapStringType(String type) {
585 int index = type.lastIndexOf(".");
586 if (index > 0 && type.length() > index) {
587 String sub = type.substring(index + 1);
588 StringBuilder sb = new StringBuilder();
589 for (String word : sub.split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])")) {
593 return sb.toString().trim();
599 * Map Home Connect stage value to label.
600 * e.g. Cooking.Hood.EnumType.IntensiveStage.IntensiveStage1 --> 1
603 * @return human readable label
605 protected String mapStageStringType(String stage) {
608 case STAGE_INTENSIVE_STAGE_OFF:
611 case STAGE_FAN_STAGE_01:
612 case STAGE_INTENSIVE_STAGE_1:
615 case STAGE_FAN_STAGE_02:
616 case STAGE_INTENSIVE_STAGE_2:
619 case STAGE_FAN_STAGE_03:
622 case STAGE_FAN_STAGE_04:
625 case STAGE_FAN_STAGE_05:
629 stage = mapStringType(stage);
636 * Map unit string (returned by home connect api) to Unit
638 * @param unit String eg. "°C"
641 protected Unit<Temperature> mapTemperature(@Nullable String unit) {
644 } else if (unit.endsWith("C")) {
652 * Map hex representation of color to HSB type.
654 * @param colorCode color code e.g. #001122
657 protected HSBType mapColor(String colorCode) {
658 HSBType color = HSBType.WHITE;
660 if (colorCode.length() == 7) {
661 int r = Integer.valueOf(colorCode.substring(1, 3), 16);
662 int g = Integer.valueOf(colorCode.substring(3, 5), 16);
663 int b = Integer.valueOf(colorCode.substring(5, 7), 16);
664 color = HSBType.fromRGB(r, g, b);
670 * Map HSB color type to hex representation.
672 * @param color HSB color
673 * @return color code e.g. #001122
675 protected String mapColor(HSBType color) {
676 String redValue = String.format("%02X", (int) (color.getRed().floatValue() * 2.55));
677 String greenValue = String.format("%02X", (int) (color.getGreen().floatValue() * 2.55));
678 String blueValue = String.format("%02X", (int) (color.getBlue().floatValue() * 2.55));
679 return "#" + redValue + greenValue + blueValue;
683 * Check bridge status and refresh connection status of thing accordingly.
685 protected void refreshThingStatus() {
686 Optional<HomeConnectApiClient> apiClient = getApiClient();
688 apiClient.ifPresent(client -> {
690 HomeAppliance homeAppliance = client.getHomeAppliance(getThingHaId());
691 if (!homeAppliance.isConnected()) {
692 updateStatus(OFFLINE);
694 updateStatus(ONLINE);
696 accessible.set(true);
697 } catch (CommunicationException e) {
699 "Update status to OFFLINE. Home Connect service is not reachable or a problem occurred! thing={}, haId={}, error={}.",
700 getThingLabel(), getThingHaId(), e.getMessage());
701 updateStatus(OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
702 "Home Connect service is not reachable or a problem occurred! (" + e.getMessage() + ").");
703 accessible.set(false);
704 } catch (AuthorizationException e) {
706 "Update status to OFFLINE. Home Connect service is not reachable or a problem occurred! thing={}, haId={}, error={}",
707 getThingLabel(), getThingHaId(), e.getMessage());
708 updateStatus(OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
709 "Home Connect service is not reachable or a problem occurred! (" + e.getMessage() + ").");
710 accessible.set(false);
711 handleAuthenticationError(e);
714 if (apiClient.isEmpty()) {
715 updateStatus(OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
716 accessible.set(false);
721 * Get home appliance id of Thing.
723 * @return home appliance id
725 public String getThingHaId() {
726 return getThing().getConfiguration().get(HA_ID).toString();
730 * Returns the human readable label for this thing.
732 * @return the human readable label
734 protected @Nullable String getThingLabel() {
735 return getThing().getLabel();
739 * Handle authentication exception.
741 protected void handleAuthenticationError(AuthorizationException exception) {
742 if (isBridgeOnline()) {
744 "Thing handler threw authentication exception --> clear credential storage thing={}, haId={} error={}",
745 getThingLabel(), getThingHaId(), exception.getMessage());
747 getBridgeHandler().ifPresent(homeConnectBridgeHandler -> {
749 homeConnectBridgeHandler.getOAuthClientService().remove();
750 homeConnectBridgeHandler.reinitialize();
751 } catch (OAuthException e) {
752 // client is already closed --> we can ignore it
759 * Get operation state of device.
761 * @return operation state string
763 protected @Nullable String getOperationState() {
764 return operationState;
767 protected EventHandler defaultElapsedProgramTimeEventHandler() {
768 return event -> getThingChannel(CHANNEL_ELAPSED_PROGRAM_TIME)
769 .ifPresent(channel -> updateState(channel.getUID(), new QuantityType<>(event.getValueAsInt(), SECOND)));
772 protected EventHandler defaultPowerStateEventHandler() {
774 getThingChannel(CHANNEL_POWER_STATE).ifPresent(
775 channel -> updateState(channel.getUID(), OnOffType.from(STATE_POWER_ON.equals(event.getValue()))));
777 if (STATE_POWER_ON.equals(event.getValue())) {
778 getThingChannel(CHANNEL_SELECTED_PROGRAM_STATE).ifPresent(c -> updateChannel(c.getUID()));
780 resetProgramStateChannels(true);
781 getThingChannel(CHANNEL_SELECTED_PROGRAM_STATE)
782 .ifPresent(c -> updateState(c.getUID(), UnDefType.UNDEF));
787 protected EventHandler defaultDoorStateEventHandler() {
788 return event -> getThingChannel(CHANNEL_DOOR_STATE).ifPresent(channel -> updateState(channel.getUID(),
789 STATE_DOOR_OPEN.equals(event.getValue()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED));
792 protected EventHandler defaultOperationStateEventHandler() {
794 String value = event.getValue();
795 getThingChannel(CHANNEL_OPERATION_STATE).ifPresent(channel -> updateState(channel.getUID(),
796 value == null ? UnDefType.UNDEF : new StringType(mapStringType(value))));
798 if (STATE_OPERATION_FINISHED.equals(event.getValue())) {
799 getThingChannel(CHANNEL_PROGRAM_PROGRESS_STATE)
800 .ifPresent(c -> updateState(c.getUID(), new QuantityType<>(100, PERCENT)));
801 getThingChannel(CHANNEL_REMAINING_PROGRAM_TIME_STATE)
802 .ifPresent(c -> updateState(c.getUID(), new QuantityType<>(0, SECOND)));
803 } else if (STATE_OPERATION_RUN.equals(event.getValue())) {
804 getThingChannel(CHANNEL_PROGRAM_PROGRESS_STATE)
805 .ifPresent(c -> updateState(c.getUID(), new QuantityType<>(0, PERCENT)));
806 getThingChannel(CHANNEL_ACTIVE_PROGRAM_STATE).ifPresent(c -> updateChannel(c.getUID()));
807 } else if (STATE_OPERATION_READY.equals(event.getValue())) {
808 resetProgramStateChannels(false);
813 protected EventHandler defaultActiveProgramEventHandler() {
815 String value = event.getValue();
816 getThingChannel(CHANNEL_ACTIVE_PROGRAM_STATE).ifPresent(channel -> updateState(channel.getUID(),
817 value == null ? UnDefType.UNDEF : new StringType(mapStringType(value))));
818 if (event.getValue() == null) {
819 resetProgramStateChannels(false);
824 protected EventHandler defaultEventPresentStateEventHandler(String channelId) {
825 return event -> getThingChannel(channelId).ifPresent(channel -> updateState(channel.getUID(),
826 OnOffType.from(!STATE_EVENT_PRESENT_STATE_OFF.equals(event.getValue()))));
829 protected EventHandler defaultBooleanEventHandler(String channelId) {
830 return event -> getThingChannel(channelId)
831 .ifPresent(channel -> updateState(channel.getUID(), OnOffType.from(event.getValueAsBoolean())));
834 protected EventHandler defaultRemainingProgramTimeEventHandler() {
835 return event -> getThingChannel(CHANNEL_REMAINING_PROGRAM_TIME_STATE)
836 .ifPresent(channel -> updateState(channel.getUID(), new QuantityType<>(event.getValueAsInt(), SECOND)));
839 protected EventHandler defaultSelectedProgramStateEventHandler() {
840 return event -> getThingChannel(CHANNEL_SELECTED_PROGRAM_STATE)
841 .ifPresent(channel -> updateState(channel.getUID(),
842 event.getValue() == null ? UnDefType.UNDEF : new StringType(event.getValue())));
845 protected EventHandler defaultAmbientLightColorStateEventHandler() {
846 return event -> getThingChannel(CHANNEL_AMBIENT_LIGHT_COLOR_STATE)
847 .ifPresent(channel -> updateState(channel.getUID(),
848 event.getValue() == null ? UnDefType.UNDEF : new StringType(event.getValue())));
851 protected EventHandler defaultAmbientLightCustomColorStateEventHandler() {
852 return event -> getThingChannel(CHANNEL_AMBIENT_LIGHT_CUSTOM_COLOR_STATE).ifPresent(channel -> {
853 String value = event.getValue();
855 updateState(channel.getUID(), mapColor(value));
857 updateState(channel.getUID(), UnDefType.UNDEF);
862 protected EventHandler updateRemoteControlActiveAndProgramOptionsStateEventHandler() {
864 defaultBooleanEventHandler(CHANNEL_REMOTE_CONTROL_ACTIVE_STATE).handle(event);
866 // update available program options if update was previously delayed and remote control is enabled
868 String programKey = programOptionsDelayedUpdate;
869 if (programKey != null && Boolean.parseBoolean(event.getValue())) {
870 logger.debug("Delayed update of options for program {}", programKey);
871 updateProgramOptionsStateDescriptions(programKey, null);
872 programOptionsDelayedUpdate = null;
874 } catch (CommunicationException | ApplianceOfflineException | AuthorizationException e) {
875 logger.debug("Could not update program options. {}", e.getMessage());
880 protected EventHandler updateProgramOptionsAndSelectedProgramStateEventHandler() {
882 defaultSelectedProgramStateEventHandler().handle(event);
884 // update available program options
886 Optional<HomeConnectApiClient> apiClient = getApiClient();
887 String programKey = event.getValue();
888 if (apiClient.isPresent() && programKey != null) {
889 // Delay the update if options are not yet cached and remote control is disabled
890 if (availableProgramOptionsCache.get(programKey) == null
891 && !apiClient.get().isRemoteControlActive(getThingHaId())) {
892 logger.debug("Delay update of options for program {}", programKey);
893 programOptionsDelayedUpdate = programKey;
895 updateProgramOptionsStateDescriptions(programKey, null);
898 } catch (CommunicationException | ApplianceOfflineException | AuthorizationException e) {
899 logger.debug("Could not update program options. {}", e.getMessage());
904 protected EventHandler defaultPercentQuantityTypeEventHandler(String channelId) {
905 return event -> getThingChannel(channelId).ifPresent(
906 channel -> updateState(channel.getUID(), new QuantityType<>(event.getValueAsInt(), PERCENT)));
909 protected EventHandler defaultPercentHandler(String channelId) {
910 return event -> getThingChannel(channelId)
911 .ifPresent(channel -> updateState(channel.getUID(), new PercentType(event.getValueAsInt())));
914 protected ChannelUpdateHandler defaultDoorStateChannelUpdateHandler() {
915 return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
916 Optional<HomeConnectApiClient> apiClient = getApiClient();
917 if (apiClient.isPresent()) {
918 Data data = apiClient.get().getDoorState(getThingHaId());
919 if (data.getValue() != null) {
920 return STATE_DOOR_OPEN.equals(data.getValue()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
922 return UnDefType.UNDEF;
925 return UnDefType.UNDEF;
930 protected ChannelUpdateHandler defaultPowerStateChannelUpdateHandler() {
931 return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
932 Optional<HomeConnectApiClient> apiClient = getApiClient();
933 if (apiClient.isPresent()) {
934 Data data = apiClient.get().getPowerState(getThingHaId());
935 if (data.getValue() != null) {
936 return OnOffType.from(STATE_POWER_ON.equals(data.getValue()));
938 return UnDefType.UNDEF;
941 return UnDefType.UNDEF;
946 protected ChannelUpdateHandler defaultAmbientLightChannelUpdateHandler() {
947 return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
948 Optional<HomeConnectApiClient> apiClient = getApiClient();
949 if (apiClient.isPresent()) {
950 Data data = apiClient.get().getAmbientLightState(getThingHaId());
951 if (data.getValue() != null) {
952 boolean enabled = data.getValueAsBoolean();
955 Data brightnessData = apiClient.get().getAmbientLightBrightnessState(getThingHaId());
956 getThingChannel(CHANNEL_AMBIENT_LIGHT_BRIGHTNESS_STATE)
957 .ifPresent(channel -> updateState(channel.getUID(),
958 new PercentType(brightnessData.getValueAsInt())));
961 Data colorData = apiClient.get().getAmbientLightColorState(getThingHaId());
962 getThingChannel(CHANNEL_AMBIENT_LIGHT_COLOR_STATE).ifPresent(
963 channel -> updateState(channel.getUID(), new StringType(colorData.getValue())));
966 Data customColorData = apiClient.get().getAmbientLightCustomColorState(getThingHaId());
967 getThingChannel(CHANNEL_AMBIENT_LIGHT_CUSTOM_COLOR_STATE).ifPresent(channel -> {
968 String value = customColorData.getValue();
970 updateState(channel.getUID(), mapColor(value));
972 updateState(channel.getUID(), UnDefType.UNDEF);
977 return OnOffType.from(enabled);
979 return UnDefType.UNDEF;
982 return UnDefType.UNDEF;
987 protected ChannelUpdateHandler defaultNoOpUpdateHandler() {
988 return (channelUID, cache) -> updateState(channelUID, UnDefType.UNDEF);
991 protected ChannelUpdateHandler defaultOperationStateChannelUpdateHandler() {
992 return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
993 Optional<HomeConnectApiClient> apiClient = getApiClient();
994 if (apiClient.isPresent()) {
995 Data data = apiClient.get().getOperationState(getThingHaId());
997 String value = data.getValue();
999 operationState = data.getValue();
1000 return new StringType(mapStringType(value));
1002 operationState = null;
1003 return UnDefType.UNDEF;
1006 return UnDefType.UNDEF;
1011 protected ChannelUpdateHandler defaultRemoteControlActiveStateChannelUpdateHandler() {
1012 return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
1013 Optional<HomeConnectApiClient> apiClient = getApiClient();
1014 if (apiClient.isPresent()) {
1015 return OnOffType.from(apiClient.get().isRemoteControlActive(getThingHaId()));
1017 return OnOffType.OFF;
1021 protected ChannelUpdateHandler defaultLocalControlActiveStateChannelUpdateHandler() {
1022 return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
1023 Optional<HomeConnectApiClient> apiClient = getApiClient();
1024 if (apiClient.isPresent()) {
1025 return OnOffType.from(apiClient.get().isLocalControlActive(getThingHaId()));
1027 return OnOffType.OFF;
1031 protected ChannelUpdateHandler defaultRemoteStartAllowanceChannelUpdateHandler() {
1032 return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
1033 Optional<HomeConnectApiClient> apiClient = getApiClient();
1034 if (apiClient.isPresent()) {
1035 return OnOffType.from(apiClient.get().isRemoteControlStartAllowed(getThingHaId()));
1037 return OnOffType.OFF;
1041 protected ChannelUpdateHandler defaultSelectedProgramStateUpdateHandler() {
1042 return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
1043 Optional<HomeConnectApiClient> apiClient = getApiClient();
1044 if (apiClient.isPresent()) {
1045 Program program = apiClient.get().getSelectedProgram(getThingHaId());
1046 if (program != null) {
1047 processProgramOptions(program.getOptions());
1048 return new StringType(program.getKey());
1050 return UnDefType.UNDEF;
1053 return UnDefType.UNDEF;
1057 protected ChannelUpdateHandler updateProgramOptionsStateDescriptionsAndSelectedProgramStateUpdateHandler() {
1058 return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
1059 Optional<HomeConnectApiClient> apiClient = getApiClient();
1060 if (apiClient.isPresent()) {
1061 Program program = apiClient.get().getSelectedProgram(getThingHaId());
1063 if (program != null) {
1064 updateProgramOptionsStateDescriptions(program.getKey(), program.getOptions());
1065 processProgramOptions(program.getOptions());
1067 return new StringType(program.getKey());
1069 return UnDefType.UNDEF;
1072 return UnDefType.UNDEF;
1076 protected ChannelUpdateHandler defaultActiveProgramStateUpdateHandler() {
1077 return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
1078 Optional<HomeConnectApiClient> apiClient = getApiClient();
1079 if (apiClient.isPresent()) {
1080 Program program = apiClient.get().getActiveProgram(getThingHaId());
1082 if (program != null) {
1083 processProgramOptions(program.getOptions());
1084 return new StringType(mapStringType(program.getKey()));
1086 resetProgramStateChannels(false);
1087 return UnDefType.UNDEF;
1090 return UnDefType.UNDEF;
1094 protected void handleTemperatureCommand(final ChannelUID channelUID, final Command command,
1095 final HomeConnectApiClient apiClient)
1096 throws CommunicationException, AuthorizationException, ApplianceOfflineException {
1097 if (command instanceof QuantityType) {
1098 QuantityType<?> quantity = (QuantityType<?>) command;
1104 if (quantity.getUnit().equals(SIUnits.CELSIUS) || quantity.getUnit().equals(ImperialUnits.FAHRENHEIT)) {
1105 unit = quantity.getUnit().toString();
1106 value = String.valueOf(quantity.intValue());
1108 logger.debug("Converting target temperature from {}{} to °C value. thing={}, haId={}",
1109 quantity.intValue(), quantity.getUnit().toString(), getThingLabel(), getThingHaId());
1111 var celsius = quantity.toUnit(SIUnits.CELSIUS);
1112 if (celsius == null) {
1113 logger.warn("Converting temperature to celsius failed! quantity={}", quantity);
1116 value = String.valueOf(celsius.intValue());
1118 logger.debug("Converted value {}{}", value, unit);
1121 if (value != null) {
1122 logger.debug("Set temperature to {} {}. thing={}, haId={}", value, unit, getThingLabel(),
1124 switch (channelUID.getId()) {
1125 case CHANNEL_REFRIGERATOR_SETPOINT_TEMPERATURE:
1126 apiClient.setFridgeSetpointTemperature(getThingHaId(), value, unit);
1127 case CHANNEL_FREEZER_SETPOINT_TEMPERATURE:
1128 apiClient.setFreezerSetpointTemperature(getThingHaId(), value, unit);
1130 case CHANNEL_SETPOINT_TEMPERATURE:
1131 apiClient.setProgramOptions(getThingHaId(), OPTION_SETPOINT_TEMPERATURE, value, unit, true,
1135 logger.debug("Unknown channel! Cannot set temperature. channelUID={}", channelUID);
1138 } catch (UnconvertibleException e) {
1139 logger.warn("Could not set temperature! haId={}, error={}", getThingHaId(), e.getMessage());
1144 protected void handleLightCommands(final ChannelUID channelUID, final Command command,
1145 final HomeConnectApiClient apiClient)
1146 throws CommunicationException, AuthorizationException, ApplianceOfflineException {
1147 switch (channelUID.getId()) {
1148 case CHANNEL_FUNCTIONAL_LIGHT_BRIGHTNESS_STATE:
1149 case CHANNEL_AMBIENT_LIGHT_BRIGHTNESS_STATE:
1150 // turn light on if turned off
1151 turnLightOn(channelUID, apiClient);
1153 int newBrightness = BRIGHTNESS_MIN;
1154 if (command instanceof OnOffType) {
1155 newBrightness = command == OnOffType.ON ? BRIGHTNESS_MAX : BRIGHTNESS_MIN;
1156 } else if (command instanceof IncreaseDecreaseType) {
1157 int currentBrightness = getCurrentBrightness(channelUID, apiClient);
1158 if (command.equals(IncreaseDecreaseType.INCREASE)) {
1159 newBrightness = currentBrightness + BRIGHTNESS_DIM_STEP;
1161 newBrightness = currentBrightness - BRIGHTNESS_DIM_STEP;
1163 } else if (command instanceof PercentType) {
1164 newBrightness = (int) Math.floor(((PercentType) command).doubleValue());
1165 } else if (command instanceof DecimalType) {
1166 newBrightness = ((DecimalType) command).intValue();
1169 // check in in range
1170 newBrightness = Math.min(Math.max(newBrightness, BRIGHTNESS_MIN), BRIGHTNESS_MAX);
1172 setLightBrightness(channelUID, apiClient, newBrightness);
1174 case CHANNEL_FUNCTIONAL_LIGHT_STATE:
1175 if (command instanceof OnOffType) {
1176 apiClient.setFunctionalLightState(getThingHaId(), OnOffType.ON.equals(command));
1179 case CHANNEL_AMBIENT_LIGHT_STATE:
1180 if (command instanceof OnOffType) {
1181 apiClient.setAmbientLightState(getThingHaId(), OnOffType.ON.equals(command));
1184 case CHANNEL_AMBIENT_LIGHT_COLOR_STATE:
1185 if (command instanceof StringType) {
1186 turnLightOn(channelUID, apiClient);
1187 apiClient.setAmbientLightColorState(getThingHaId(), command.toFullString());
1190 case CHANNEL_AMBIENT_LIGHT_CUSTOM_COLOR_STATE:
1191 turnLightOn(channelUID, apiClient);
1193 // make sure 'custom color' is set as color
1194 Data ambientLightColorState = apiClient.getAmbientLightColorState(getThingHaId());
1195 if (!STATE_AMBIENT_LIGHT_COLOR_CUSTOM_COLOR.equals(ambientLightColorState.getValue())) {
1196 apiClient.setAmbientLightColorState(getThingHaId(), STATE_AMBIENT_LIGHT_COLOR_CUSTOM_COLOR);
1199 if (command instanceof HSBType) {
1200 apiClient.setAmbientLightCustomColorState(getThingHaId(), mapColor((HSBType) command));
1201 } else if (command instanceof StringType) {
1202 apiClient.setAmbientLightCustomColorState(getThingHaId(), command.toFullString());
1208 protected void handlePowerCommand(final ChannelUID channelUID, final Command command,
1209 final HomeConnectApiClient apiClient, String stateNotOn)
1210 throws CommunicationException, AuthorizationException, ApplianceOfflineException {
1211 if (command instanceof OnOffType && CHANNEL_POWER_STATE.equals(channelUID.getId())) {
1212 apiClient.setPowerState(getThingHaId(), OnOffType.ON.equals(command) ? STATE_POWER_ON : stateNotOn);
1216 private int getCurrentBrightness(final ChannelUID channelUID, final HomeConnectApiClient apiClient)
1217 throws CommunicationException, AuthorizationException, ApplianceOfflineException {
1218 String id = channelUID.getId();
1219 if (CHANNEL_FUNCTIONAL_LIGHT_BRIGHTNESS_STATE.equals(id)) {
1220 return apiClient.getFunctionalLightBrightnessState(getThingHaId()).getValueAsInt();
1222 return apiClient.getAmbientLightBrightnessState(getThingHaId()).getValueAsInt();
1226 private void setLightBrightness(final ChannelUID channelUID, final HomeConnectApiClient apiClient, int value)
1227 throws CommunicationException, AuthorizationException, ApplianceOfflineException {
1228 switch (channelUID.getId()) {
1229 case CHANNEL_FUNCTIONAL_LIGHT_BRIGHTNESS_STATE:
1230 apiClient.setFunctionalLightBrightnessState(getThingHaId(), value);
1232 case CHANNEL_AMBIENT_LIGHT_BRIGHTNESS_STATE:
1233 apiClient.setAmbientLightBrightnessState(getThingHaId(), value);
1238 private void turnLightOn(final ChannelUID channelUID, final HomeConnectApiClient apiClient)
1239 throws CommunicationException, AuthorizationException, ApplianceOfflineException {
1240 switch (channelUID.getId()) {
1241 case CHANNEL_FUNCTIONAL_LIGHT_BRIGHTNESS_STATE:
1242 Data functionalLightState = apiClient.getFunctionalLightState(getThingHaId());
1243 if (!functionalLightState.getValueAsBoolean()) {
1244 apiClient.setFunctionalLightState(getThingHaId(), true);
1247 case CHANNEL_AMBIENT_LIGHT_CUSTOM_COLOR_STATE:
1248 case CHANNEL_AMBIENT_LIGHT_COLOR_STATE:
1249 case CHANNEL_AMBIENT_LIGHT_BRIGHTNESS_STATE:
1250 Data ambientLightState = apiClient.getAmbientLightState(getThingHaId());
1251 if (!ambientLightState.getValueAsBoolean()) {
1252 apiClient.setAmbientLightState(getThingHaId(), true);
1258 protected void processProgramOptions(List<Option> options) {
1259 options.forEach(option -> {
1260 String key = option.getKey();
1263 case OPTION_WASHER_TEMPERATURE:
1264 getThingChannel(CHANNEL_WASHER_TEMPERATURE)
1265 .ifPresent(channel -> updateState(channel.getUID(), new StringType(option.getValue())));
1267 case OPTION_WASHER_SPIN_SPEED:
1268 getThingChannel(CHANNEL_WASHER_SPIN_SPEED)
1269 .ifPresent(channel -> updateState(channel.getUID(), new StringType(option.getValue())));
1271 case OPTION_WASHER_IDOS_1_DOSING_LEVEL:
1272 getThingChannel(CHANNEL_WASHER_IDOS1)
1273 .ifPresent(channel -> updateState(channel.getUID(), new StringType(option.getValue())));
1275 case OPTION_WASHER_IDOS_2_DOSING_LEVEL:
1276 getThingChannel(CHANNEL_WASHER_IDOS2)
1277 .ifPresent(channel -> updateState(channel.getUID(), new StringType(option.getValue())));
1279 case OPTION_DRYER_DRYING_TARGET:
1280 getThingChannel(CHANNEL_DRYER_DRYING_TARGET)
1281 .ifPresent(channel -> updateState(channel.getUID(), new StringType(option.getValue())));
1283 case OPTION_HOOD_INTENSIVE_LEVEL:
1284 String hoodIntensiveLevelValue = option.getValue();
1285 if (hoodIntensiveLevelValue != null) {
1286 getThingChannel(CHANNEL_HOOD_INTENSIVE_LEVEL)
1287 .ifPresent(channel -> updateState(channel.getUID(),
1288 new StringType(mapStageStringType(hoodIntensiveLevelValue))));
1291 case OPTION_HOOD_VENTING_LEVEL:
1292 String hoodVentingLevel = option.getValue();
1293 if (hoodVentingLevel != null) {
1294 getThingChannel(CHANNEL_HOOD_VENTING_LEVEL)
1295 .ifPresent(channel -> updateState(channel.getUID(),
1296 new StringType(mapStageStringType(hoodVentingLevel))));
1299 case OPTION_SETPOINT_TEMPERATURE:
1300 getThingChannel(CHANNEL_SETPOINT_TEMPERATURE).ifPresent(channel -> updateState(channel.getUID(),
1301 new QuantityType<>(option.getValueAsInt(), mapTemperature(option.getUnit()))));
1303 case OPTION_DURATION:
1304 getThingChannel(CHANNEL_DURATION).ifPresent(channel -> updateState(channel.getUID(),
1305 new QuantityType<>(option.getValueAsInt(), SECOND)));
1307 case OPTION_FINISH_IN_RELATIVE:
1308 case OPTION_REMAINING_PROGRAM_TIME:
1309 getThingChannel(CHANNEL_REMAINING_PROGRAM_TIME_STATE)
1310 .ifPresent(channel -> updateState(channel.getUID(),
1311 new QuantityType<>(option.getValueAsInt(), SECOND)));
1313 case OPTION_ELAPSED_PROGRAM_TIME:
1314 getThingChannel(CHANNEL_ELAPSED_PROGRAM_TIME).ifPresent(channel -> updateState(channel.getUID(),
1315 new QuantityType<>(option.getValueAsInt(), SECOND)));
1317 case OPTION_PROGRAM_PROGRESS:
1318 getThingChannel(CHANNEL_PROGRAM_PROGRESS_STATE)
1319 .ifPresent(channel -> updateState(channel.getUID(),
1320 new QuantityType<>(option.getValueAsInt(), PERCENT)));
1327 protected String convertWasherTemperature(String value) {
1328 if (value.startsWith("LaundryCare.Washer.EnumType.Temperature.GC")) {
1329 return value.replace("LaundryCare.Washer.EnumType.Temperature.GC", "") + "°C";
1332 if (value.startsWith("LaundryCare.Washer.EnumType.Temperature.Ul")) {
1333 return mapStringType(value.replace("LaundryCare.Washer.EnumType.Temperature.Ul", ""));
1336 return mapStringType(value);
1339 protected String convertWasherSpinSpeed(String value) {
1340 if (value.startsWith("LaundryCare.Washer.EnumType.SpinSpeed.RPM")) {
1341 return value.replace("LaundryCare.Washer.EnumType.SpinSpeed.RPM", "") + " RPM";
1344 if (value.startsWith("LaundryCare.Washer.EnumType.SpinSpeed.Ul")) {
1345 return value.replace("LaundryCare.Washer.EnumType.SpinSpeed.Ul", "");
1348 return mapStringType(value);
1351 protected void updateProgramOptionsStateDescriptions(String programKey, @Nullable List<Option> optionsValues)
1352 throws CommunicationException, AuthorizationException, ApplianceOfflineException {
1353 Optional<HomeConnectApiClient> apiClient = getApiClient();
1354 if (apiClient.isPresent()) {
1355 List<AvailableProgramOption> availableProgramOptions;
1356 if (availableProgramOptionsCache.containsKey(programKey)) {
1357 logger.debug("Returning cached options for '{}'.", programKey);
1358 availableProgramOptions = availableProgramOptionsCache.get(programKey);
1359 availableProgramOptions = availableProgramOptions != null ? availableProgramOptions
1360 : Collections.emptyList();
1362 availableProgramOptions = apiClient.get().getProgramOptions(getThingHaId(), programKey);
1363 availableProgramOptionsCache.put(programKey, availableProgramOptions);
1366 Optional<Channel> channelSpinSpeed = getThingChannel(CHANNEL_WASHER_SPIN_SPEED);
1367 Optional<Channel> channelTemperature = getThingChannel(CHANNEL_WASHER_TEMPERATURE);
1368 Optional<Channel> channelDryingTarget = getThingChannel(CHANNEL_DRYER_DRYING_TARGET);
1370 if (availableProgramOptions.isEmpty()) {
1371 List<Option> options;
1372 if (optionsValues != null) {
1373 options = optionsValues;
1374 } else if (channelSpinSpeed.isPresent() || channelTemperature.isPresent()
1375 || channelDryingTarget.isPresent()) {
1376 Program program = apiClient.get().getSelectedProgram(getThingHaId());
1377 options = program != null ? program.getOptions() : emptyList();
1379 options = emptyList();
1382 channelSpinSpeed.ifPresent(channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(),
1384 .filter(option -> option.getKey() != null && option.getValue() != null
1385 && OPTION_WASHER_SPIN_SPEED.equals(option.getKey()))
1386 .map(option -> option.getValue())
1387 .map(value -> new StateOption(value == null ? "" : value,
1388 convertWasherSpinSpeed(value == null ? "" : value)))
1389 .collect(Collectors.toList())));
1391 .ifPresent(channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(),
1393 .filter(option -> option.getKey() != null && option.getValue() != null
1394 && OPTION_WASHER_TEMPERATURE.equals(option.getKey()))
1395 .map(option -> option.getValue())
1396 .map(value -> new StateOption(value == null ? "" : value,
1397 convertWasherTemperature(value == null ? "" : value)))
1398 .collect(Collectors.toList())));
1400 .ifPresent(channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(),
1402 .filter(option -> option.getKey() != null && option.getValue() != null
1403 && OPTION_DRYER_DRYING_TARGET.equals(option.getKey()))
1404 .map(option -> option.getValue())
1405 .map(value -> new StateOption(value == null ? "" : value,
1406 mapStringType(value == null ? "" : value)))
1407 .collect(Collectors.toList())));
1410 availableProgramOptions.forEach(option -> {
1411 switch (option.getKey()) {
1412 case OPTION_WASHER_SPIN_SPEED: {
1414 .ifPresent(channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(),
1415 createStateOptions(option, this::convertWasherSpinSpeed)));
1418 case OPTION_WASHER_TEMPERATURE: {
1420 .ifPresent(channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(),
1421 createStateOptions(option, this::convertWasherTemperature)));
1424 case OPTION_DRYER_DRYING_TARGET: {
1425 channelDryingTarget.ifPresent(channel -> dynamicStateDescriptionProvider
1426 .setStateOptions(channel.getUID(), createStateOptions(option, this::mapStringType)));
1434 protected HomeConnectDynamicStateDescriptionProvider getDynamicStateDescriptionProvider() {
1435 return dynamicStateDescriptionProvider;
1438 private List<StateOption> createStateOptions(AvailableProgramOption option,
1439 Function<String, String> stateConverter) {
1440 return option.getAllowedValues().stream().map(av -> new StateOption(av, stateConverter.apply(av)))
1441 .collect(Collectors.toList());
1444 private synchronized void scheduleOfflineMonitor1() {
1445 this.reinitializationFuture1 = scheduler.schedule(() -> {
1446 if (isBridgeOnline() && isThingOffline()) {
1447 logger.debug("Offline monitor 1: Check if thing is ONLINE. thing={}, haId={}", getThingLabel(),
1449 refreshThingStatus();
1450 if (isThingOnline()) {
1451 logger.debug("Offline monitor 1: Thing status changed to ONLINE. thing={}, haId={}",
1452 getThingLabel(), getThingHaId());
1455 scheduleOfflineMonitor1();
1458 scheduleOfflineMonitor1();
1460 }, AbstractHomeConnectThingHandler.OFFLINE_MONITOR_1_DELAY_MIN, TimeUnit.MINUTES);
1463 private synchronized void stopOfflineMonitor1() {
1464 ScheduledFuture<?> reinitializationFuture = this.reinitializationFuture1;
1465 if (reinitializationFuture != null) {
1466 reinitializationFuture.cancel(false);
1467 this.reinitializationFuture1 = null;
1471 private synchronized void scheduleOfflineMonitor2() {
1472 this.reinitializationFuture2 = scheduler.schedule(() -> {
1473 if (isBridgeOnline() && !accessible.get()) {
1474 logger.debug("Offline monitor 2: Check if thing is ONLINE. thing={}, haId={}", getThingLabel(),
1476 refreshThingStatus();
1477 if (isThingOnline()) {
1478 logger.debug("Offline monitor 2: Thing status changed to ONLINE. thing={}, haId={}",
1479 getThingLabel(), getThingHaId());
1482 scheduleOfflineMonitor2();
1485 scheduleOfflineMonitor2();
1487 }, AbstractHomeConnectThingHandler.OFFLINE_MONITOR_2_DELAY_MIN, TimeUnit.MINUTES);
1490 private synchronized void stopOfflineMonitor2() {
1491 ScheduledFuture<?> reinitializationFuture = this.reinitializationFuture2;
1492 if (reinitializationFuture != null) {
1493 reinitializationFuture.cancel(false);
1494 this.reinitializationFuture2 = null;
1498 private synchronized void scheduleRetryRegistering() {
1499 this.reinitializationFuture3 = scheduler.schedule(() -> {
1500 logger.debug("Try to register event listener again. haId={}", getThingHaId());
1501 unregisterEventListener();
1502 registerEventListener();
1503 }, AbstractHomeConnectThingHandler.EVENT_LISTENER_CONNECT_RETRY_DELAY_MIN, TimeUnit.MINUTES);
1506 private synchronized void stopRetryRegistering() {
1507 ScheduledFuture<?> reinitializationFuture = this.reinitializationFuture3;
1508 if (reinitializationFuture != null) {
1509 reinitializationFuture.cancel(true);
1510 this.reinitializationFuture3 = null;