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.List;
26 import java.util.Optional;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.ScheduledFuture;
29 import java.util.concurrent.TimeUnit;
30 import java.util.concurrent.atomic.AtomicBoolean;
31 import java.util.function.Function;
32 import java.util.stream.Collectors;
34 import javax.measure.UnconvertibleException;
35 import javax.measure.Unit;
36 import javax.measure.quantity.Temperature;
38 import org.eclipse.jdt.annotation.NonNullByDefault;
39 import org.eclipse.jdt.annotation.Nullable;
40 import org.openhab.binding.homeconnect.internal.client.HomeConnectApiClient;
41 import org.openhab.binding.homeconnect.internal.client.HomeConnectEventSourceClient;
42 import org.openhab.binding.homeconnect.internal.client.exception.ApplianceOfflineException;
43 import org.openhab.binding.homeconnect.internal.client.exception.AuthorizationException;
44 import org.openhab.binding.homeconnect.internal.client.exception.CommunicationException;
45 import org.openhab.binding.homeconnect.internal.client.listener.HomeConnectEventListener;
46 import org.openhab.binding.homeconnect.internal.client.model.AvailableProgramOption;
47 import org.openhab.binding.homeconnect.internal.client.model.Data;
48 import org.openhab.binding.homeconnect.internal.client.model.Event;
49 import org.openhab.binding.homeconnect.internal.client.model.HomeAppliance;
50 import org.openhab.binding.homeconnect.internal.client.model.Option;
51 import org.openhab.binding.homeconnect.internal.client.model.Program;
52 import org.openhab.binding.homeconnect.internal.handler.cache.ExpiringStateMap;
53 import org.openhab.binding.homeconnect.internal.type.HomeConnectDynamicStateDescriptionProvider;
54 import org.openhab.core.auth.client.oauth2.OAuthException;
55 import org.openhab.core.library.types.DecimalType;
56 import org.openhab.core.library.types.HSBType;
57 import org.openhab.core.library.types.IncreaseDecreaseType;
58 import org.openhab.core.library.types.OnOffType;
59 import org.openhab.core.library.types.OpenClosedType;
60 import org.openhab.core.library.types.PercentType;
61 import org.openhab.core.library.types.QuantityType;
62 import org.openhab.core.library.types.StringType;
63 import org.openhab.core.library.unit.ImperialUnits;
64 import org.openhab.core.library.unit.SIUnits;
65 import org.openhab.core.thing.Bridge;
66 import org.openhab.core.thing.Channel;
67 import org.openhab.core.thing.ChannelUID;
68 import org.openhab.core.thing.Thing;
69 import org.openhab.core.thing.ThingStatusDetail;
70 import org.openhab.core.thing.ThingStatusInfo;
71 import org.openhab.core.thing.binding.BaseThingHandler;
72 import org.openhab.core.thing.binding.BridgeHandler;
73 import org.openhab.core.types.Command;
74 import org.openhab.core.types.RefreshType;
75 import org.openhab.core.types.StateOption;
76 import org.openhab.core.types.UnDefType;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
81 * The {@link AbstractHomeConnectThingHandler} is responsible for handling commands, which are
82 * sent to one of the channels.
84 * @author Jonas Brüstel - Initial contribution
87 public abstract class AbstractHomeConnectThingHandler extends BaseThingHandler implements HomeConnectEventListener {
89 private static final int CACHE_TTL_SEC = 2;
90 private static final int OFFLINE_MONITOR_1_DELAY_MIN = 30;
91 private static final int OFFLINE_MONITOR_2_DELAY_MIN = 4;
92 private static final int EVENT_LISTENER_CONNECT_RETRY_DELAY_MIN = 10;
94 private @Nullable String operationState;
95 private @Nullable ScheduledFuture<?> reinitializationFuture1;
96 private @Nullable ScheduledFuture<?> reinitializationFuture2;
97 private @Nullable ScheduledFuture<?> reinitializationFuture3;
98 private boolean ignoreEventSourceClosedEvent;
100 private final ConcurrentHashMap<String, EventHandler> eventHandlers;
101 private final ConcurrentHashMap<String, ChannelUpdateHandler> channelUpdateHandlers;
102 private final HomeConnectDynamicStateDescriptionProvider dynamicStateDescriptionProvider;
103 private final ExpiringStateMap expiringStateMap;
104 private final AtomicBoolean accessible;
105 private final Logger logger = LoggerFactory.getLogger(AbstractHomeConnectThingHandler.class);
107 public AbstractHomeConnectThingHandler(Thing thing,
108 HomeConnectDynamicStateDescriptionProvider dynamicStateDescriptionProvider) {
110 eventHandlers = new ConcurrentHashMap<>();
111 channelUpdateHandlers = new ConcurrentHashMap<>();
112 this.dynamicStateDescriptionProvider = dynamicStateDescriptionProvider;
113 expiringStateMap = new ExpiringStateMap(Duration.ofSeconds(CACHE_TTL_SEC));
114 accessible = new AtomicBoolean(false);
116 configureEventHandlers(eventHandlers);
117 configureChannelUpdateHandlers(channelUpdateHandlers);
121 public void initialize() {
122 if (getBridgeHandler().isEmpty()) {
123 updateStatus(OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
124 accessible.set(false);
125 } else if (isBridgeOffline()) {
126 updateStatus(OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
127 accessible.set(false);
129 updateStatus(UNKNOWN);
130 scheduler.submit(() -> {
131 refreshThingStatus(); // set ONLINE / OFFLINE
132 updateSelectedProgramStateDescription();
134 registerEventListener();
135 scheduleOfflineMonitor1();
136 scheduleOfflineMonitor2();
142 public void dispose() {
143 stopRetryRegistering();
144 stopOfflineMonitor1();
145 stopOfflineMonitor2();
146 unregisterEventListener(true);
150 public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) {
151 logger.debug("Bridge status changed to {} ({}). haId={}", bridgeStatusInfo, getThingLabel(), getThingHaId());
155 private void reinitialize() {
156 logger.debug("Reinitialize thing handler ({}). haId={}", getThingLabel(), getThingHaId());
157 stopRetryRegistering();
158 stopOfflineMonitor1();
159 stopOfflineMonitor2();
160 unregisterEventListener();
165 * Handles a command for a given channel.
167 * This method is only called, if the thing has been initialized (status ONLINE/OFFLINE/UNKNOWN).
170 * @param channelUID the {@link ChannelUID} of the channel to which the command was sent
171 * @param command the {@link Command}
172 * @param apiClient the {@link HomeConnectApiClient}
173 * @throws CommunicationException communication problem
174 * @throws AuthorizationException authorization problem
175 * @throws ApplianceOfflineException appliance offline
177 protected void handleCommand(ChannelUID channelUID, Command command, HomeConnectApiClient apiClient)
178 throws CommunicationException, AuthorizationException, ApplianceOfflineException {
179 if (command instanceof RefreshType) {
180 updateChannel(channelUID);
181 } else if (command instanceof StringType && CHANNEL_BASIC_ACTIONS_STATE.equals(channelUID.getId())
182 && getBridgeHandler().isPresent()) {
183 updateState(channelUID, new StringType(""));
185 if (COMMAND_START.equalsIgnoreCase(command.toFullString())) {
186 HomeConnectBridgeHandler homeConnectBridgeHandler = getBridgeHandler().get();
187 // workaround for api bug
188 // if simulator, program options have to be passed along with the desired program
189 // if non simulator, some options throw a "SDK.Error.UnsupportedOption" error
190 if (homeConnectBridgeHandler.getConfiguration().isSimulator()) {
191 apiClient.startSelectedProgram(getThingHaId());
193 Program selectedProgram = apiClient.getSelectedProgram(getThingHaId());
194 if (selectedProgram != null) {
195 apiClient.startProgram(getThingHaId(), selectedProgram.getKey());
198 } else if (COMMAND_STOP.equalsIgnoreCase(command.toFullString())) {
199 apiClient.stopProgram(getThingHaId());
200 } else if (COMMAND_SELECTED.equalsIgnoreCase(command.toFullString())) {
201 apiClient.getSelectedProgram(getThingHaId());
203 logger.debug("Start custom program. command={} haId={}", command.toFullString(), getThingHaId());
204 apiClient.startCustomProgram(getThingHaId(), command.toFullString());
206 } else if (command instanceof StringType && CHANNEL_SELECTED_PROGRAM_STATE.equals(channelUID.getId())) {
207 apiClient.setSelectedProgram(getThingHaId(), command.toFullString());
212 public final void handleCommand(ChannelUID channelUID, Command command) {
213 var apiClient = getApiClient();
214 if ((isThingReadyToHandleCommand() || (this instanceof HomeConnectHoodHandler && isBridgeOnline()
215 && isThingAccessibleViaServerSentEvents())) && apiClient.isPresent()) {
216 logger.debug("Handle \"{}\" command ({}). haId={}", command, channelUID.getId(), getThingHaId());
218 handleCommand(channelUID, command, apiClient.get());
219 } catch (ApplianceOfflineException e) {
220 logger.debug("Could not handle command {}. Appliance offline. thing={}, haId={}, error={}",
221 command.toFullString(), getThingLabel(), getThingHaId(), e.getMessage());
222 updateStatus(OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
223 resetChannelsOnOfflineEvent();
224 resetProgramStateChannels();
225 } catch (CommunicationException e) {
226 logger.debug("Could not handle command {}. API communication problem! error={}, haId={}",
227 command.toFullString(), e.getMessage(), getThingHaId());
228 } catch (AuthorizationException e) {
229 logger.debug("Could not handle command {}. Authorization problem! error={}, haId={}",
230 command.toFullString(), e.getMessage(), getThingHaId());
232 handleAuthenticationError(e);
238 public void onEvent(Event event) {
239 if (DISCONNECTED.equals(event.getType())) {
240 logger.debug("Received DISCONNECTED event. Set {} to OFFLINE. haId={}", getThing().getLabel(),
242 updateStatus(OFFLINE);
243 resetChannelsOnOfflineEvent();
244 resetProgramStateChannels();
245 } else if (isThingOnline() && CONNECTED.equals(event.getType())) {
246 logger.debug("Received CONNECTED event. Update power state channel. haId={}", getThingHaId());
247 getThingChannel(CHANNEL_POWER_STATE).ifPresent(c -> updateChannel(c.getUID()));
248 } else if (isThingOffline() && !KEEP_ALIVE.equals(event.getType())) {
249 updateStatus(ONLINE);
250 logger.debug("Set {} to ONLINE and update channels. haId={}", getThing().getLabel(), getThingHaId());
254 String key = event.getKey();
255 if (EVENT_OPERATION_STATE.equals(key)) {
256 operationState = event.getValue() == null ? null : event.getValue();
259 if (key != null && eventHandlers.containsKey(key)) {
260 EventHandler eventHandler = eventHandlers.get(key);
261 if (eventHandler != null) {
262 eventHandler.handle(event);
266 accessible.set(true);
270 public void onClosed() {
271 if (ignoreEventSourceClosedEvent) {
272 logger.debug("Ignoring event source close event. thing={}, haId={}", getThing().getLabel(), getThingHaId());
274 unregisterEventListener();
275 refreshThingStatus();
276 registerEventListener();
281 public void onRateLimitReached() {
282 unregisterEventListener();
285 scheduleRetryRegistering();
289 * Register event listener.
291 protected void registerEventListener() {
292 if (isBridgeOnline() && isThingAccessibleViaServerSentEvents()) {
293 getEventSourceClient().ifPresent(client -> {
295 ignoreEventSourceClosedEvent = false;
296 client.registerEventListener(getThingHaId(), this);
297 } catch (CommunicationException | AuthorizationException e) {
298 logger.warn("Could not open event source connection. thing={}, haId={}, error={}", getThingLabel(),
299 getThingHaId(), e.getMessage());
306 * Unregister event listener.
308 protected void unregisterEventListener() {
309 unregisterEventListener(false);
312 private void unregisterEventListener(boolean immediate) {
313 getEventSourceClient().ifPresent(client -> {
314 ignoreEventSourceClosedEvent = true;
315 client.unregisterEventListener(this, immediate, false);
320 * Get {@link HomeConnectApiClient}.
322 * @return client instance
324 protected Optional<HomeConnectApiClient> getApiClient() {
325 return getBridgeHandler().map(HomeConnectBridgeHandler::getApiClient);
329 * Get {@link HomeConnectEventSourceClient}.
331 * @return client instance if present
333 protected Optional<HomeConnectEventSourceClient> getEventSourceClient() {
334 return getBridgeHandler().map(HomeConnectBridgeHandler::getEventSourceClient);
338 * Update state description of selected program (Fetch programs via API).
340 protected void updateSelectedProgramStateDescription() {
341 if (isBridgeOffline() || isThingOffline()) {
345 Optional<HomeConnectApiClient> apiClient = getApiClient();
346 if (apiClient.isPresent()) {
348 List<StateOption> stateOptions = apiClient.get().getPrograms(getThingHaId()).stream()
349 .map(p -> new StateOption(p.getKey(), mapStringType(p.getKey()))).collect(Collectors.toList());
351 getThingChannel(CHANNEL_SELECTED_PROGRAM_STATE).ifPresent(
352 channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(), stateOptions));
353 } catch (CommunicationException | ApplianceOfflineException | AuthorizationException e) {
354 logger.debug("Could not fetch available programs. thing={}, haId={}, error={}", getThingLabel(),
355 getThingHaId(), e.getMessage());
356 removeSelectedProgramStateDescription();
359 removeSelectedProgramStateDescription();
364 * Remove state description of selected program.
366 protected void removeSelectedProgramStateDescription() {
367 getThingChannel(CHANNEL_SELECTED_PROGRAM_STATE)
368 .ifPresent(channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(), emptyList()));
372 * Is thing ready to process commands. If bridge or thing itself is offline commands will be ignored.
374 * @return true if ready
376 protected boolean isThingReadyToHandleCommand() {
377 if (isBridgeOffline()) {
378 logger.debug("Bridge is OFFLINE. Ignore command. thing={}, haId={}", getThingLabel(), getThingHaId());
382 if (isThingOffline()) {
383 logger.debug("{} is OFFLINE. Ignore command. haId={}", getThing().getLabel(), getThingHaId());
391 * Checks if bridge is online and set.
393 * @return true if online
395 protected boolean isBridgeOnline() {
396 Bridge bridge = getBridge();
397 return bridge != null && ONLINE.equals(bridge.getStatus());
401 * Checks if bridge is offline or not set.
403 * @return true if offline
405 protected boolean isBridgeOffline() {
406 return !isBridgeOnline();
410 * Checks if thing is online.
412 * @return true if online
414 protected boolean isThingOnline() {
415 return ONLINE.equals(getThing().getStatus());
419 * Checks if thing is connected to the cloud and accessible via SSE.
421 * @return true if yes
423 public boolean isThingAccessibleViaServerSentEvents() {
424 return accessible.get();
428 * Checks if thing is offline.
430 * @return true if offline
432 protected boolean isThingOffline() {
433 return !isThingOnline();
437 * Get {@link HomeConnectBridgeHandler}.
439 * @return bridge handler
441 protected Optional<HomeConnectBridgeHandler> getBridgeHandler() {
442 Bridge bridge = getBridge();
443 if (bridge != null) {
444 BridgeHandler bridgeHandler = bridge.getHandler();
445 if (bridgeHandler instanceof HomeConnectBridgeHandler) {
446 return Optional.of((HomeConnectBridgeHandler) bridgeHandler);
449 return Optional.empty();
453 * Get thing channel by given channel id.
455 * @param channelId channel id
458 protected Optional<Channel> getThingChannel(String channelId) {
459 Channel channel = getThing().getChannel(channelId);
460 if (channel == null) {
461 return Optional.empty();
463 return Optional.of(channel);
468 * Configure channel update handlers. Classes which extend {@link AbstractHomeConnectThingHandler} must implement
469 * this class and add handlers.
471 * @param handlers channel update handlers
473 protected abstract void configureChannelUpdateHandlers(final Map<String, ChannelUpdateHandler> handlers);
476 * Configure event handlers. Classes which extend {@link AbstractHomeConnectThingHandler} must implement
477 * this class and add handlers.
479 * @param handlers Server-Sent-Event handlers
481 protected abstract void configureEventHandlers(final Map<String, EventHandler> handlers);
484 * Update all channels via API.
487 protected void updateChannels() {
488 if (isBridgeOffline()) {
489 logger.debug("Bridge handler not found or offline. Stopping update of channels. thing={}, haId={}",
490 getThingLabel(), getThingHaId());
491 } else if (isThingOffline()) {
492 logger.debug("{} offline. Stopping update of channels. haId={}", getThing().getLabel(), getThingHaId());
494 List<Channel> channels = getThing().getChannels();
495 for (Channel channel : channels) {
496 updateChannel(channel.getUID());
502 * Update Channel values via API.
504 * @param channelUID channel UID
506 protected void updateChannel(ChannelUID channelUID) {
507 if (!getApiClient().isPresent()) {
508 logger.error("Cannot update channel. No instance of api client found! thing={}, haId={}", getThingLabel(),
513 if (!isThingReadyToHandleCommand()) {
517 if ((isLinked(channelUID) || CHANNEL_OPERATION_STATE.equals(channelUID.getId())) // always update operation
519 && channelUpdateHandlers.containsKey(channelUID.getId())) {
521 ChannelUpdateHandler channelUpdateHandler = channelUpdateHandlers.get(channelUID.getId());
522 if (channelUpdateHandler != null) {
523 channelUpdateHandler.handle(channelUID, expiringStateMap);
525 } catch (ApplianceOfflineException e) {
527 "API communication problem while trying to update! Appliance offline. thing={}, haId={}, error={}",
528 getThingLabel(), getThingHaId(), e.getMessage());
529 updateStatus(OFFLINE);
530 resetChannelsOnOfflineEvent();
531 resetProgramStateChannels();
532 } catch (CommunicationException e) {
533 logger.debug("API communication problem while trying to update! thing={}, haId={}, error={}",
534 getThingLabel(), getThingHaId(), e.getMessage());
535 } catch (AuthorizationException e) {
536 logger.debug("Authentication problem while trying to update! thing={}, haId={}", getThingLabel(),
538 handleAuthenticationError(e);
544 * Reset program related channels.
546 protected void resetProgramStateChannels() {
547 logger.debug("Resetting active program channel states. thing={}, haId={}", getThingLabel(), getThingHaId());
551 * Reset all channels on OFFLINE event.
553 protected void resetChannelsOnOfflineEvent() {
554 logger.debug("Resetting channel states due to OFFLINE event. thing={}, haId={}", getThingLabel(),
556 getThingChannel(CHANNEL_POWER_STATE).ifPresent(channel -> updateState(channel.getUID(), OnOffType.OFF));
557 getThingChannel(CHANNEL_OPERATION_STATE).ifPresent(channel -> updateState(channel.getUID(), UnDefType.UNDEF));
558 getThingChannel(CHANNEL_DOOR_STATE).ifPresent(channel -> updateState(channel.getUID(), UnDefType.UNDEF));
559 getThingChannel(CHANNEL_LOCAL_CONTROL_ACTIVE_STATE)
560 .ifPresent(channel -> updateState(channel.getUID(), UnDefType.UNDEF));
561 getThingChannel(CHANNEL_REMOTE_CONTROL_ACTIVE_STATE)
562 .ifPresent(channel -> updateState(channel.getUID(), UnDefType.UNDEF));
563 getThingChannel(CHANNEL_REMOTE_START_ALLOWANCE_STATE)
564 .ifPresent(channel -> updateState(channel.getUID(), UnDefType.UNDEF));
565 getThingChannel(CHANNEL_SELECTED_PROGRAM_STATE)
566 .ifPresent(channel -> updateState(channel.getUID(), UnDefType.UNDEF));
570 * Map Home Connect key and value names to label.
571 * e.g. Dishcare.Dishwasher.Program.Eco50 --> Eco50 or BSH.Common.EnumType.OperationState.DelayedStart --> Delayed
575 * @return human readable label
577 protected String mapStringType(String type) {
578 int index = type.lastIndexOf(".");
579 if (index > 0 && type.length() > index) {
580 String sub = type.substring(index + 1);
581 StringBuilder sb = new StringBuilder();
582 for (String word : sub.split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])")) {
586 return sb.toString().trim();
592 * Map Home Connect stage value to label.
593 * e.g. Cooking.Hood.EnumType.IntensiveStage.IntensiveStage1 --> 1
596 * @return human readable label
598 protected String mapStageStringType(String stage) {
601 case STAGE_INTENSIVE_STAGE_OFF:
604 case STAGE_FAN_STAGE_01:
605 case STAGE_INTENSIVE_STAGE_1:
608 case STAGE_FAN_STAGE_02:
609 case STAGE_INTENSIVE_STAGE_2:
612 case STAGE_FAN_STAGE_03:
615 case STAGE_FAN_STAGE_04:
618 case STAGE_FAN_STAGE_05:
622 stage = mapStringType(stage);
629 * Map unit string (returned by home connect api) to Unit
631 * @param unit String eg. "°C"
634 protected Unit<Temperature> mapTemperature(@Nullable String unit) {
637 } else if (unit.endsWith("C")) {
645 * Map hex representation of color to HSB type.
647 * @param colorCode color code e.g. #001122
650 protected HSBType mapColor(String colorCode) {
651 HSBType color = HSBType.WHITE;
653 if (colorCode.length() == 7) {
654 int r = Integer.valueOf(colorCode.substring(1, 3), 16);
655 int g = Integer.valueOf(colorCode.substring(3, 5), 16);
656 int b = Integer.valueOf(colorCode.substring(5, 7), 16);
657 color = HSBType.fromRGB(r, g, b);
663 * Map HSB color type to hex representation.
665 * @param color HSB color
666 * @return color code e.g. #001122
668 protected String mapColor(HSBType color) {
669 String redValue = String.format("%02X", (int) (color.getRed().floatValue() * 2.55));
670 String greenValue = String.format("%02X", (int) (color.getGreen().floatValue() * 2.55));
671 String blueValue = String.format("%02X", (int) (color.getBlue().floatValue() * 2.55));
672 return "#" + redValue + greenValue + blueValue;
676 * Check bridge status and refresh connection status of thing accordingly.
678 protected void refreshThingStatus() {
679 Optional<HomeConnectApiClient> apiClient = getApiClient();
681 apiClient.ifPresent(client -> {
683 HomeAppliance homeAppliance = client.getHomeAppliance(getThingHaId());
684 if (!homeAppliance.isConnected()) {
685 updateStatus(OFFLINE);
687 updateStatus(ONLINE);
689 accessible.set(true);
690 } catch (CommunicationException e) {
692 "Update status to OFFLINE. Home Connect service is not reachable or a problem occurred! thing={}, haId={}, error={}.",
693 getThingLabel(), getThingHaId(), e.getMessage());
694 updateStatus(OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
695 "Home Connect service is not reachable or a problem occurred! (" + e.getMessage() + ").");
696 accessible.set(false);
697 } catch (AuthorizationException 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 handleAuthenticationError(e);
707 if (apiClient.isEmpty()) {
708 updateStatus(OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
709 accessible.set(false);
714 * Get home appliance id of Thing.
716 * @return home appliance id
718 public String getThingHaId() {
719 return getThing().getConfiguration().get(HA_ID).toString();
723 * Returns the human readable label for this thing.
725 * @return the human readable label
727 protected @Nullable String getThingLabel() {
728 return getThing().getLabel();
732 * Handle authentication exception.
734 protected void handleAuthenticationError(AuthorizationException exception) {
735 if (isBridgeOnline()) {
737 "Thing handler threw authentication exception --> clear credential storage thing={}, haId={} error={}",
738 getThingLabel(), getThingHaId(), exception.getMessage());
740 getBridgeHandler().ifPresent(homeConnectBridgeHandler -> {
742 homeConnectBridgeHandler.getOAuthClientService().remove();
743 homeConnectBridgeHandler.reinitialize();
744 } catch (OAuthException e) {
745 // client is already closed --> we can ignore it
752 * Get operation state of device.
754 * @return operation state string
756 protected @Nullable String getOperationState() {
757 return operationState;
760 protected EventHandler defaultElapsedProgramTimeEventHandler() {
761 return event -> getThingChannel(CHANNEL_ELAPSED_PROGRAM_TIME)
762 .ifPresent(channel -> updateState(channel.getUID(), new QuantityType<>(event.getValueAsInt(), SECOND)));
765 protected EventHandler defaultPowerStateEventHandler() {
767 getThingChannel(CHANNEL_POWER_STATE).ifPresent(
768 channel -> updateState(channel.getUID(), OnOffType.from(STATE_POWER_ON.equals(event.getValue()))));
770 if (STATE_POWER_ON.equals(event.getValue())) {
771 getThingChannel(CHANNEL_SELECTED_PROGRAM_STATE).ifPresent(c -> updateChannel(c.getUID()));
773 resetProgramStateChannels();
774 getThingChannel(CHANNEL_SELECTED_PROGRAM_STATE)
775 .ifPresent(c -> updateState(c.getUID(), UnDefType.UNDEF));
780 protected EventHandler defaultDoorStateEventHandler() {
781 return event -> getThingChannel(CHANNEL_DOOR_STATE).ifPresent(channel -> updateState(channel.getUID(),
782 STATE_DOOR_OPEN.equals(event.getValue()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED));
785 protected EventHandler defaultOperationStateEventHandler() {
787 String value = event.getValue();
788 getThingChannel(CHANNEL_OPERATION_STATE).ifPresent(channel -> updateState(channel.getUID(),
789 value == null ? UnDefType.UNDEF : new StringType(mapStringType(value))));
791 if (STATE_OPERATION_FINISHED.equals(event.getValue())) {
792 getThingChannel(CHANNEL_PROGRAM_PROGRESS_STATE)
793 .ifPresent(c -> updateState(c.getUID(), new QuantityType<>(100, PERCENT)));
794 getThingChannel(CHANNEL_REMAINING_PROGRAM_TIME_STATE)
795 .ifPresent(c -> updateState(c.getUID(), new QuantityType<>(0, SECOND)));
796 } else if (STATE_OPERATION_RUN.equals(event.getValue())) {
797 getThingChannel(CHANNEL_PROGRAM_PROGRESS_STATE)
798 .ifPresent(c -> updateState(c.getUID(), new QuantityType<>(0, PERCENT)));
799 getThingChannel(CHANNEL_ACTIVE_PROGRAM_STATE).ifPresent(c -> updateChannel(c.getUID()));
800 } else if (STATE_OPERATION_READY.equals(event.getValue())) {
801 resetProgramStateChannels();
806 protected EventHandler defaultActiveProgramEventHandler() {
808 String value = event.getValue();
809 getThingChannel(CHANNEL_ACTIVE_PROGRAM_STATE).ifPresent(channel -> updateState(channel.getUID(),
810 value == null ? UnDefType.UNDEF : new StringType(mapStringType(value))));
811 if (event.getValue() == null) {
812 resetProgramStateChannels();
817 protected EventHandler defaultEventPresentStateEventHandler(String channelId) {
818 return event -> getThingChannel(channelId).ifPresent(channel -> updateState(channel.getUID(),
819 OnOffType.from(!STATE_EVENT_PRESENT_STATE_OFF.equals(event.getValue()))));
822 protected EventHandler defaultBooleanEventHandler(String channelId) {
823 return event -> getThingChannel(channelId)
824 .ifPresent(channel -> updateState(channel.getUID(), OnOffType.from(event.getValueAsBoolean())));
827 protected EventHandler defaultRemainingProgramTimeEventHandler() {
828 return event -> getThingChannel(CHANNEL_REMAINING_PROGRAM_TIME_STATE)
829 .ifPresent(channel -> updateState(channel.getUID(), new QuantityType<>(event.getValueAsInt(), SECOND)));
832 protected EventHandler defaultSelectedProgramStateEventHandler() {
833 return event -> getThingChannel(CHANNEL_SELECTED_PROGRAM_STATE)
834 .ifPresent(channel -> updateState(channel.getUID(),
835 event.getValue() == null ? UnDefType.UNDEF : new StringType(event.getValue())));
838 protected EventHandler defaultAmbientLightColorStateEventHandler() {
839 return event -> getThingChannel(CHANNEL_AMBIENT_LIGHT_COLOR_STATE)
840 .ifPresent(channel -> updateState(channel.getUID(),
841 event.getValue() == null ? UnDefType.UNDEF : new StringType(event.getValue())));
844 protected EventHandler defaultAmbientLightCustomColorStateEventHandler() {
845 return event -> getThingChannel(CHANNEL_AMBIENT_LIGHT_CUSTOM_COLOR_STATE).ifPresent(channel -> {
846 String value = event.getValue();
848 updateState(channel.getUID(), mapColor(value));
850 updateState(channel.getUID(), UnDefType.UNDEF);
855 protected EventHandler updateProgramOptionsAndSelectedProgramStateEventHandler() {
857 defaultSelectedProgramStateEventHandler().handle(event);
859 // update available program options
861 String programKey = event.getValue();
862 if (programKey != null) {
863 updateProgramOptionsStateDescriptions(programKey);
865 } catch (CommunicationException | ApplianceOfflineException | AuthorizationException e) {
866 logger.debug("Could not update program options. {}", e.getMessage());
871 protected EventHandler defaultPercentQuantityTypeEventHandler(String channelId) {
872 return event -> getThingChannel(channelId).ifPresent(
873 channel -> updateState(channel.getUID(), new QuantityType<>(event.getValueAsInt(), PERCENT)));
876 protected EventHandler defaultPercentHandler(String channelId) {
877 return event -> getThingChannel(channelId)
878 .ifPresent(channel -> updateState(channel.getUID(), new PercentType(event.getValueAsInt())));
881 protected ChannelUpdateHandler defaultDoorStateChannelUpdateHandler() {
882 return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
883 Optional<HomeConnectApiClient> apiClient = getApiClient();
884 if (apiClient.isPresent()) {
885 Data data = apiClient.get().getDoorState(getThingHaId());
886 if (data.getValue() != null) {
887 return STATE_DOOR_OPEN.equals(data.getValue()) ? OpenClosedType.OPEN : OpenClosedType.CLOSED;
889 return UnDefType.UNDEF;
892 return UnDefType.UNDEF;
897 protected ChannelUpdateHandler defaultPowerStateChannelUpdateHandler() {
898 return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
899 Optional<HomeConnectApiClient> apiClient = getApiClient();
900 if (apiClient.isPresent()) {
901 Data data = apiClient.get().getPowerState(getThingHaId());
902 if (data.getValue() != null) {
903 return OnOffType.from(STATE_POWER_ON.equals(data.getValue()));
905 return UnDefType.UNDEF;
908 return UnDefType.UNDEF;
913 protected ChannelUpdateHandler defaultAmbientLightChannelUpdateHandler() {
914 return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
915 Optional<HomeConnectApiClient> apiClient = getApiClient();
916 if (apiClient.isPresent()) {
917 Data data = apiClient.get().getAmbientLightState(getThingHaId());
918 if (data.getValue() != null) {
919 boolean enabled = data.getValueAsBoolean();
922 Data brightnessData = apiClient.get().getAmbientLightBrightnessState(getThingHaId());
923 getThingChannel(CHANNEL_AMBIENT_LIGHT_BRIGHTNESS_STATE)
924 .ifPresent(channel -> updateState(channel.getUID(),
925 new PercentType(brightnessData.getValueAsInt())));
928 Data colorData = apiClient.get().getAmbientLightColorState(getThingHaId());
929 getThingChannel(CHANNEL_AMBIENT_LIGHT_COLOR_STATE).ifPresent(
930 channel -> updateState(channel.getUID(), new StringType(colorData.getValue())));
933 Data customColorData = apiClient.get().getAmbientLightCustomColorState(getThingHaId());
934 getThingChannel(CHANNEL_AMBIENT_LIGHT_CUSTOM_COLOR_STATE).ifPresent(channel -> {
935 String value = customColorData.getValue();
937 updateState(channel.getUID(), mapColor(value));
939 updateState(channel.getUID(), UnDefType.UNDEF);
944 return OnOffType.from(enabled);
946 return UnDefType.UNDEF;
949 return UnDefType.UNDEF;
954 protected ChannelUpdateHandler defaultNoOpUpdateHandler() {
955 return (channelUID, cache) -> updateState(channelUID, UnDefType.UNDEF);
958 protected ChannelUpdateHandler defaultOperationStateChannelUpdateHandler() {
959 return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
960 Optional<HomeConnectApiClient> apiClient = getApiClient();
961 if (apiClient.isPresent()) {
962 Data data = apiClient.get().getOperationState(getThingHaId());
964 String value = data.getValue();
966 operationState = data.getValue();
967 return new StringType(mapStringType(value));
969 operationState = null;
970 return UnDefType.UNDEF;
973 return UnDefType.UNDEF;
978 protected ChannelUpdateHandler defaultRemoteControlActiveStateChannelUpdateHandler() {
979 return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
980 Optional<HomeConnectApiClient> apiClient = getApiClient();
981 if (apiClient.isPresent()) {
982 return OnOffType.from(apiClient.get().isRemoteControlActive(getThingHaId()));
984 return OnOffType.OFF;
988 protected ChannelUpdateHandler defaultLocalControlActiveStateChannelUpdateHandler() {
989 return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
990 Optional<HomeConnectApiClient> apiClient = getApiClient();
991 if (apiClient.isPresent()) {
992 return OnOffType.from(apiClient.get().isLocalControlActive(getThingHaId()));
994 return OnOffType.OFF;
998 protected ChannelUpdateHandler defaultRemoteStartAllowanceChannelUpdateHandler() {
999 return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
1000 Optional<HomeConnectApiClient> apiClient = getApiClient();
1001 if (apiClient.isPresent()) {
1002 return OnOffType.from(apiClient.get().isRemoteControlStartAllowed(getThingHaId()));
1004 return OnOffType.OFF;
1008 protected ChannelUpdateHandler defaultSelectedProgramStateUpdateHandler() {
1009 return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
1010 Optional<HomeConnectApiClient> apiClient = getApiClient();
1011 if (apiClient.isPresent()) {
1012 Program program = apiClient.get().getSelectedProgram(getThingHaId());
1013 if (program != null) {
1014 processProgramOptions(program.getOptions());
1015 return new StringType(program.getKey());
1017 return UnDefType.UNDEF;
1020 return UnDefType.UNDEF;
1024 protected ChannelUpdateHandler updateProgramOptionsStateDescriptionsAndSelectedProgramStateUpdateHandler() {
1025 return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
1026 Optional<HomeConnectApiClient> apiClient = getApiClient();
1027 if (apiClient.isPresent()) {
1028 Program program = apiClient.get().getSelectedProgram(getThingHaId());
1030 if (program != null) {
1031 updateProgramOptionsStateDescriptions(program.getKey());
1032 processProgramOptions(program.getOptions());
1034 return new StringType(program.getKey());
1036 return UnDefType.UNDEF;
1039 return UnDefType.UNDEF;
1043 protected ChannelUpdateHandler defaultActiveProgramStateUpdateHandler() {
1044 return (channelUID, cache) -> updateState(channelUID, cache.putIfAbsentAndGet(channelUID, () -> {
1045 Optional<HomeConnectApiClient> apiClient = getApiClient();
1046 if (apiClient.isPresent()) {
1047 Program program = apiClient.get().getActiveProgram(getThingHaId());
1049 if (program != null) {
1050 processProgramOptions(program.getOptions());
1051 return new StringType(mapStringType(program.getKey()));
1053 resetProgramStateChannels();
1054 return UnDefType.UNDEF;
1057 return UnDefType.UNDEF;
1061 protected void handleTemperatureCommand(final ChannelUID channelUID, final Command command,
1062 final HomeConnectApiClient apiClient)
1063 throws CommunicationException, AuthorizationException, ApplianceOfflineException {
1064 if (command instanceof QuantityType) {
1065 QuantityType<?> quantity = (QuantityType<?>) command;
1071 if (quantity.getUnit().equals(SIUnits.CELSIUS) || quantity.getUnit().equals(ImperialUnits.FAHRENHEIT)) {
1072 unit = quantity.getUnit().toString();
1073 value = String.valueOf(quantity.intValue());
1075 logger.debug("Converting target temperature from {}{} to °C value. thing={}, haId={}",
1076 quantity.intValue(), quantity.getUnit().toString(), getThingLabel(), getThingHaId());
1078 var celsius = quantity.toUnit(SIUnits.CELSIUS);
1079 if (celsius == null) {
1080 logger.warn("Converting temperature to celsius failed! quantity={}", quantity);
1083 value = String.valueOf(celsius.intValue());
1085 logger.debug("Converted value {}{}", value, unit);
1088 if (value != null) {
1089 logger.debug("Set temperature to {} {}. thing={}, haId={}", value, unit, getThingLabel(),
1091 switch (channelUID.getId()) {
1092 case CHANNEL_REFRIGERATOR_SETPOINT_TEMPERATURE:
1093 apiClient.setFridgeSetpointTemperature(getThingHaId(), value, unit);
1094 case CHANNEL_FREEZER_SETPOINT_TEMPERATURE:
1095 apiClient.setFreezerSetpointTemperature(getThingHaId(), value, unit);
1097 case CHANNEL_SETPOINT_TEMPERATURE:
1098 apiClient.setProgramOptions(getThingHaId(), OPTION_SETPOINT_TEMPERATURE, value, unit, true,
1102 logger.debug("Unknown channel! Cannot set temperature. channelUID={}", channelUID);
1105 } catch (UnconvertibleException e) {
1106 logger.warn("Could not set temperature! haId={}, error={}", getThingHaId(), e.getMessage());
1111 protected void handleLightCommands(final ChannelUID channelUID, final Command command,
1112 final HomeConnectApiClient apiClient)
1113 throws CommunicationException, AuthorizationException, ApplianceOfflineException {
1114 switch (channelUID.getId()) {
1115 case CHANNEL_FUNCTIONAL_LIGHT_BRIGHTNESS_STATE:
1116 case CHANNEL_AMBIENT_LIGHT_BRIGHTNESS_STATE:
1117 // turn light on if turned off
1118 turnLightOn(channelUID, apiClient);
1120 int newBrightness = BRIGHTNESS_MIN;
1121 if (command instanceof OnOffType) {
1122 newBrightness = command == OnOffType.ON ? BRIGHTNESS_MAX : BRIGHTNESS_MIN;
1123 } else if (command instanceof IncreaseDecreaseType) {
1124 int currentBrightness = getCurrentBrightness(channelUID, apiClient);
1125 if (command.equals(IncreaseDecreaseType.INCREASE)) {
1126 newBrightness = currentBrightness + BRIGHTNESS_DIM_STEP;
1128 newBrightness = currentBrightness - BRIGHTNESS_DIM_STEP;
1130 } else if (command instanceof PercentType) {
1131 newBrightness = (int) Math.floor(((PercentType) command).doubleValue());
1132 } else if (command instanceof DecimalType) {
1133 newBrightness = ((DecimalType) command).intValue();
1136 // check in in range
1137 newBrightness = Math.min(Math.max(newBrightness, BRIGHTNESS_MIN), BRIGHTNESS_MAX);
1139 setLightBrightness(channelUID, apiClient, newBrightness);
1141 case CHANNEL_FUNCTIONAL_LIGHT_STATE:
1142 if (command instanceof OnOffType) {
1143 apiClient.setFunctionalLightState(getThingHaId(), OnOffType.ON.equals(command));
1146 case CHANNEL_AMBIENT_LIGHT_STATE:
1147 if (command instanceof OnOffType) {
1148 apiClient.setAmbientLightState(getThingHaId(), OnOffType.ON.equals(command));
1151 case CHANNEL_AMBIENT_LIGHT_COLOR_STATE:
1152 if (command instanceof StringType) {
1153 turnLightOn(channelUID, apiClient);
1154 apiClient.setAmbientLightColorState(getThingHaId(), command.toFullString());
1157 case CHANNEL_AMBIENT_LIGHT_CUSTOM_COLOR_STATE:
1158 turnLightOn(channelUID, apiClient);
1160 // make sure 'custom color' is set as color
1161 Data ambientLightColorState = apiClient.getAmbientLightColorState(getThingHaId());
1162 if (!STATE_AMBIENT_LIGHT_COLOR_CUSTOM_COLOR.equals(ambientLightColorState.getValue())) {
1163 apiClient.setAmbientLightColorState(getThingHaId(), STATE_AMBIENT_LIGHT_COLOR_CUSTOM_COLOR);
1166 if (command instanceof HSBType) {
1167 apiClient.setAmbientLightCustomColorState(getThingHaId(), mapColor((HSBType) command));
1168 } else if (command instanceof StringType) {
1169 apiClient.setAmbientLightCustomColorState(getThingHaId(), command.toFullString());
1175 protected void handlePowerCommand(final ChannelUID channelUID, final Command command,
1176 final HomeConnectApiClient apiClient, String stateNotOn)
1177 throws CommunicationException, AuthorizationException, ApplianceOfflineException {
1178 if (command instanceof OnOffType && CHANNEL_POWER_STATE.equals(channelUID.getId())) {
1179 apiClient.setPowerState(getThingHaId(), OnOffType.ON.equals(command) ? STATE_POWER_ON : stateNotOn);
1183 private int getCurrentBrightness(final ChannelUID channelUID, final HomeConnectApiClient apiClient)
1184 throws CommunicationException, AuthorizationException, ApplianceOfflineException {
1185 String id = channelUID.getId();
1186 if (CHANNEL_FUNCTIONAL_LIGHT_BRIGHTNESS_STATE.equals(id)) {
1187 return apiClient.getFunctionalLightBrightnessState(getThingHaId()).getValueAsInt();
1189 return apiClient.getAmbientLightBrightnessState(getThingHaId()).getValueAsInt();
1193 private void setLightBrightness(final ChannelUID channelUID, final HomeConnectApiClient apiClient, int value)
1194 throws CommunicationException, AuthorizationException, ApplianceOfflineException {
1195 switch (channelUID.getId()) {
1196 case CHANNEL_FUNCTIONAL_LIGHT_BRIGHTNESS_STATE:
1197 apiClient.setFunctionalLightBrightnessState(getThingHaId(), value);
1199 case CHANNEL_AMBIENT_LIGHT_BRIGHTNESS_STATE:
1200 apiClient.setAmbientLightBrightnessState(getThingHaId(), value);
1205 private void turnLightOn(final ChannelUID channelUID, final HomeConnectApiClient apiClient)
1206 throws CommunicationException, AuthorizationException, ApplianceOfflineException {
1207 switch (channelUID.getId()) {
1208 case CHANNEL_FUNCTIONAL_LIGHT_BRIGHTNESS_STATE:
1209 Data functionalLightState = apiClient.getFunctionalLightState(getThingHaId());
1210 if (!functionalLightState.getValueAsBoolean()) {
1211 apiClient.setFunctionalLightState(getThingHaId(), true);
1214 case CHANNEL_AMBIENT_LIGHT_CUSTOM_COLOR_STATE:
1215 case CHANNEL_AMBIENT_LIGHT_COLOR_STATE:
1216 case CHANNEL_AMBIENT_LIGHT_BRIGHTNESS_STATE:
1217 Data ambientLightState = apiClient.getAmbientLightState(getThingHaId());
1218 if (!ambientLightState.getValueAsBoolean()) {
1219 apiClient.setAmbientLightState(getThingHaId(), true);
1225 protected void processProgramOptions(List<Option> options) {
1226 options.forEach(option -> {
1227 String key = option.getKey();
1230 case OPTION_WASHER_TEMPERATURE:
1231 getThingChannel(CHANNEL_WASHER_TEMPERATURE)
1232 .ifPresent(channel -> updateState(channel.getUID(), new StringType(option.getValue())));
1234 case OPTION_WASHER_SPIN_SPEED:
1235 getThingChannel(CHANNEL_WASHER_SPIN_SPEED)
1236 .ifPresent(channel -> updateState(channel.getUID(), new StringType(option.getValue())));
1238 case OPTION_WASHER_IDOS_1_DOSING_LEVEL:
1239 getThingChannel(CHANNEL_WASHER_IDOS1)
1240 .ifPresent(channel -> updateState(channel.getUID(), new StringType(option.getValue())));
1242 case OPTION_WASHER_IDOS_2_DOSING_LEVEL:
1243 getThingChannel(CHANNEL_WASHER_IDOS2)
1244 .ifPresent(channel -> updateState(channel.getUID(), new StringType(option.getValue())));
1246 case OPTION_DRYER_DRYING_TARGET:
1247 getThingChannel(CHANNEL_DRYER_DRYING_TARGET)
1248 .ifPresent(channel -> updateState(channel.getUID(), new StringType(option.getValue())));
1250 case OPTION_HOOD_INTENSIVE_LEVEL:
1251 String hoodIntensiveLevelValue = option.getValue();
1252 if (hoodIntensiveLevelValue != null) {
1253 getThingChannel(CHANNEL_HOOD_INTENSIVE_LEVEL)
1254 .ifPresent(channel -> updateState(channel.getUID(),
1255 new StringType(mapStageStringType(hoodIntensiveLevelValue))));
1258 case OPTION_HOOD_VENTING_LEVEL:
1259 String hoodVentingLevel = option.getValue();
1260 if (hoodVentingLevel != null) {
1261 getThingChannel(CHANNEL_HOOD_VENTING_LEVEL)
1262 .ifPresent(channel -> updateState(channel.getUID(),
1263 new StringType(mapStageStringType(hoodVentingLevel))));
1266 case OPTION_SETPOINT_TEMPERATURE:
1267 getThingChannel(CHANNEL_SETPOINT_TEMPERATURE).ifPresent(channel -> updateState(channel.getUID(),
1268 new QuantityType<>(option.getValueAsInt(), mapTemperature(option.getUnit()))));
1270 case OPTION_DURATION:
1271 getThingChannel(CHANNEL_DURATION).ifPresent(channel -> updateState(channel.getUID(),
1272 new QuantityType<>(option.getValueAsInt(), SECOND)));
1274 case OPTION_REMAINING_PROGRAM_TIME:
1275 getThingChannel(CHANNEL_REMAINING_PROGRAM_TIME_STATE)
1276 .ifPresent(channel -> updateState(channel.getUID(),
1277 new QuantityType<>(option.getValueAsInt(), SECOND)));
1279 case OPTION_ELAPSED_PROGRAM_TIME:
1280 getThingChannel(CHANNEL_ELAPSED_PROGRAM_TIME).ifPresent(channel -> updateState(channel.getUID(),
1281 new QuantityType<>(option.getValueAsInt(), SECOND)));
1283 case OPTION_PROGRAM_PROGRESS:
1284 getThingChannel(CHANNEL_PROGRAM_PROGRESS_STATE)
1285 .ifPresent(channel -> updateState(channel.getUID(),
1286 new QuantityType<>(option.getValueAsInt(), PERCENT)));
1293 protected String convertWasherTemperature(String value) {
1294 if (value.startsWith("LaundryCare.Washer.EnumType.Temperature.GC")) {
1295 return value.replace("LaundryCare.Washer.EnumType.Temperature.GC", "") + "°C";
1298 if (value.startsWith("LaundryCare.Washer.EnumType.Temperature.Ul")) {
1299 return mapStringType(value.replace("LaundryCare.Washer.EnumType.Temperature.Ul", ""));
1302 return mapStringType(value);
1305 protected String convertWasherSpinSpeed(String value) {
1306 if (value.startsWith("LaundryCare.Washer.EnumType.SpinSpeed.RPM")) {
1307 return value.replace("LaundryCare.Washer.EnumType.SpinSpeed.RPM", "") + " RPM";
1310 if (value.startsWith("LaundryCare.Washer.EnumType.SpinSpeed.Ul")) {
1311 return value.replace("LaundryCare.Washer.EnumType.SpinSpeed.Ul", "");
1314 return mapStringType(value);
1317 protected void updateProgramOptionsStateDescriptions(String programKey)
1318 throws CommunicationException, AuthorizationException, ApplianceOfflineException {
1319 Optional<HomeConnectApiClient> apiClient = getApiClient();
1320 if (apiClient.isPresent()) {
1321 List<AvailableProgramOption> availableProgramOptions = apiClient.get().getProgramOptions(getThingHaId(),
1324 Optional<Channel> channelSpinSpeed = getThingChannel(CHANNEL_WASHER_SPIN_SPEED);
1325 Optional<Channel> channelTemperature = getThingChannel(CHANNEL_WASHER_TEMPERATURE);
1326 Optional<Channel> channelDryingTarget = getThingChannel(CHANNEL_DRYER_DRYING_TARGET);
1328 if (availableProgramOptions.isEmpty()) {
1329 channelSpinSpeed.ifPresent(
1330 channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(), emptyList()));
1331 channelTemperature.ifPresent(
1332 channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(), emptyList()));
1333 channelDryingTarget.ifPresent(
1334 channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(), emptyList()));
1337 availableProgramOptions.forEach(option -> {
1338 switch (option.getKey()) {
1339 case OPTION_WASHER_SPIN_SPEED: {
1341 .ifPresent(channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(),
1342 createStateOptions(option, this::convertWasherSpinSpeed)));
1345 case OPTION_WASHER_TEMPERATURE: {
1347 .ifPresent(channel -> dynamicStateDescriptionProvider.setStateOptions(channel.getUID(),
1348 createStateOptions(option, this::convertWasherTemperature)));
1351 case OPTION_DRYER_DRYING_TARGET: {
1352 channelDryingTarget.ifPresent(channel -> dynamicStateDescriptionProvider
1353 .setStateOptions(channel.getUID(), createStateOptions(option, this::mapStringType)));
1361 protected HomeConnectDynamicStateDescriptionProvider getDynamicStateDescriptionProvider() {
1362 return dynamicStateDescriptionProvider;
1365 private List<StateOption> createStateOptions(AvailableProgramOption option,
1366 Function<String, String> stateConverter) {
1367 return option.getAllowedValues().stream().map(av -> new StateOption(av, stateConverter.apply(av)))
1368 .collect(Collectors.toList());
1371 private synchronized void scheduleOfflineMonitor1() {
1372 this.reinitializationFuture1 = scheduler.schedule(() -> {
1373 if (isBridgeOnline() && isThingOffline()) {
1374 logger.debug("Offline monitor 1: Check if thing is ONLINE. thing={}, haId={}", getThingLabel(),
1376 refreshThingStatus();
1377 if (isThingOnline()) {
1378 logger.debug("Offline monitor 1: Thing status changed to ONLINE. thing={}, haId={}",
1379 getThingLabel(), getThingHaId());
1382 scheduleOfflineMonitor1();
1385 scheduleOfflineMonitor1();
1387 }, AbstractHomeConnectThingHandler.OFFLINE_MONITOR_1_DELAY_MIN, TimeUnit.MINUTES);
1390 private synchronized void stopOfflineMonitor1() {
1391 ScheduledFuture<?> reinitializationFuture = this.reinitializationFuture1;
1392 if (reinitializationFuture != null) {
1393 reinitializationFuture.cancel(false);
1394 this.reinitializationFuture1 = null;
1398 private synchronized void scheduleOfflineMonitor2() {
1399 this.reinitializationFuture2 = scheduler.schedule(() -> {
1400 if (isBridgeOnline() && !accessible.get()) {
1401 logger.debug("Offline monitor 2: Check if thing is ONLINE. thing={}, haId={}", getThingLabel(),
1403 refreshThingStatus();
1404 if (isThingOnline()) {
1405 logger.debug("Offline monitor 2: Thing status changed to ONLINE. thing={}, haId={}",
1406 getThingLabel(), getThingHaId());
1409 scheduleOfflineMonitor2();
1412 scheduleOfflineMonitor2();
1414 }, AbstractHomeConnectThingHandler.OFFLINE_MONITOR_2_DELAY_MIN, TimeUnit.MINUTES);
1417 private synchronized void stopOfflineMonitor2() {
1418 ScheduledFuture<?> reinitializationFuture = this.reinitializationFuture2;
1419 if (reinitializationFuture != null) {
1420 reinitializationFuture.cancel(false);
1421 this.reinitializationFuture2 = null;
1425 private synchronized void scheduleRetryRegistering() {
1426 this.reinitializationFuture3 = scheduler.schedule(() -> {
1427 logger.debug("Try to register event listener again. haId={}", getThingHaId());
1428 unregisterEventListener();
1429 registerEventListener();
1430 }, AbstractHomeConnectThingHandler.EVENT_LISTENER_CONNECT_RETRY_DELAY_MIN, TimeUnit.MINUTES);
1433 private synchronized void stopRetryRegistering() {
1434 ScheduledFuture<?> reinitializationFuture = this.reinitializationFuture3;
1435 if (reinitializationFuture != null) {
1436 reinitializationFuture.cancel(true);
1437 this.reinitializationFuture3 = null;