2 * Copyright (c) 2010-2022 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.hdpowerview.internal.handler;
15 import static org.openhab.binding.hdpowerview.internal.HDPowerViewBindingConstants.*;
16 import static org.openhab.binding.hdpowerview.internal.api.CoordinateSystem.*;
18 import java.util.HashMap;
19 import java.util.List;
21 import java.util.StringJoiner;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
25 import javax.ws.rs.NotSupportedException;
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.openhab.binding.hdpowerview.internal.HDPowerViewBindingConstants;
30 import org.openhab.binding.hdpowerview.internal.HDPowerViewWebTargets;
31 import org.openhab.binding.hdpowerview.internal.api.CoordinateSystem;
32 import org.openhab.binding.hdpowerview.internal.api.Firmware;
33 import org.openhab.binding.hdpowerview.internal.api.ShadePosition;
34 import org.openhab.binding.hdpowerview.internal.api.SurveyData;
35 import org.openhab.binding.hdpowerview.internal.api.responses.Shades.ShadeData;
36 import org.openhab.binding.hdpowerview.internal.config.HDPowerViewShadeConfiguration;
37 import org.openhab.binding.hdpowerview.internal.database.ShadeCapabilitiesDatabase;
38 import org.openhab.binding.hdpowerview.internal.database.ShadeCapabilitiesDatabase.Capabilities;
39 import org.openhab.binding.hdpowerview.internal.exceptions.HubException;
40 import org.openhab.binding.hdpowerview.internal.exceptions.HubInvalidResponseException;
41 import org.openhab.binding.hdpowerview.internal.exceptions.HubMaintenanceException;
42 import org.openhab.binding.hdpowerview.internal.exceptions.HubProcessingException;
43 import org.openhab.binding.hdpowerview.internal.exceptions.HubShadeTimeoutException;
44 import org.openhab.core.library.types.DecimalType;
45 import org.openhab.core.library.types.OnOffType;
46 import org.openhab.core.library.types.PercentType;
47 import org.openhab.core.library.types.QuantityType;
48 import org.openhab.core.library.types.StopMoveType;
49 import org.openhab.core.library.types.StringType;
50 import org.openhab.core.library.types.UpDownType;
51 import org.openhab.core.library.unit.Units;
52 import org.openhab.core.thing.Bridge;
53 import org.openhab.core.thing.ChannelUID;
54 import org.openhab.core.thing.Thing;
55 import org.openhab.core.thing.ThingStatus;
56 import org.openhab.core.thing.ThingStatusDetail;
57 import org.openhab.core.types.Command;
58 import org.openhab.core.types.RefreshType;
59 import org.openhab.core.types.UnDefType;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
64 * Handles commands for an HD PowerView Shade
66 * @author Andy Lintner - Initial contribution
67 * @author Andrew Fiddian-Green - Added support for secondary rail positions
70 public class HDPowerViewShadeHandler extends AbstractHubbedThingHandler {
72 private enum RefreshKind {
78 private static final String COMMAND_CALIBRATE = "CALIBRATE";
79 private static final String COMMAND_IDENTIFY = "IDENTIFY";
81 private static final String DETECTED_SECONDARY_RAIL = "secondaryRailDetected";
82 private static final String DETECTED_TILT_ANYWHERE = "tiltAnywhereDetected";
83 private final Map<String, String> detectedCapabilities = new HashMap<>();
85 private final Logger logger = LoggerFactory.getLogger(HDPowerViewShadeHandler.class);
86 private final ShadeCapabilitiesDatabase db = new ShadeCapabilitiesDatabase();
88 private @Nullable ScheduledFuture<?> refreshPositionFuture = null;
89 private @Nullable ScheduledFuture<?> refreshSignalFuture = null;
90 private @Nullable ScheduledFuture<?> refreshBatteryLevelFuture = null;
91 private @Nullable Capabilities capabilities;
93 private boolean isDisposing;
95 public HDPowerViewShadeHandler(Thing thing) {
100 public void initialize() {
102 shadeId = getConfigAs(HDPowerViewShadeConfiguration.class).id;
103 logger.debug("Initializing shade handler for shade {}", shadeId);
104 Bridge bridge = getBridge();
105 if (bridge == null) {
106 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
107 "@text/offline.conf-error.invalid-bridge-handler");
111 updateStatus(ThingStatus.UNKNOWN);
115 public void dispose() {
116 logger.debug("Disposing shade handler for shade {}", shadeId);
118 ScheduledFuture<?> future = refreshPositionFuture;
119 if (future != null) {
122 refreshPositionFuture = null;
123 future = refreshSignalFuture;
124 if (future != null) {
127 refreshSignalFuture = null;
128 future = refreshBatteryLevelFuture;
129 if (future != null) {
132 refreshBatteryLevelFuture = null;
137 public void handleCommand(ChannelUID channelUID, Command command) {
138 String channelId = channelUID.getId();
140 if (RefreshType.REFRESH == command) {
142 case CHANNEL_SHADE_POSITION:
143 case CHANNEL_SHADE_SECONDARY_POSITION:
144 case CHANNEL_SHADE_VANE:
145 requestRefreshShadePosition();
147 case CHANNEL_SHADE_LOW_BATTERY:
148 case CHANNEL_SHADE_BATTERY_LEVEL:
149 case CHANNEL_SHADE_BATTERY_VOLTAGE:
150 requestRefreshShadeBatteryLevel();
152 case CHANNEL_SHADE_SIGNAL_STRENGTH:
153 case CHANNEL_SHADE_HUB_RSSI:
154 case CHANNEL_SHADE_REPEATER_RSSI:
155 requestRefreshShadeSurvey();
161 HDPowerViewHubHandler bridge = getBridgeHandler();
162 if (bridge == null) {
163 logger.warn("Missing bridge handler");
166 HDPowerViewWebTargets webTargets = bridge.getWebTargets();
168 handleShadeCommand(channelId, command, webTargets, shadeId);
169 } catch (HubInvalidResponseException e) {
170 Throwable cause = e.getCause();
172 logger.warn("Bridge returned a bad JSON response: {}", e.getMessage());
174 logger.warn("Bridge returned a bad JSON response: {} -> {}", e.getMessage(), cause.getMessage());
176 } catch (HubMaintenanceException e) {
177 // exceptions are logged in HDPowerViewWebTargets
178 } catch (HubShadeTimeoutException e) {
179 logger.warn("Shade {} timeout when sending command {}", shadeId, command);
180 } catch (HubException e) {
181 // ScheduledFutures will be cancelled by dispose(), naturally causing InterruptedException in invoke()
182 // for any ongoing requests. Logging this would only cause confusion.
184 logger.warn("Unexpected error: {}", e.getMessage());
189 private void handleShadeCommand(String channelId, Command command, HDPowerViewWebTargets webTargets, int shadeId)
190 throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException,
191 HubShadeTimeoutException {
193 case CHANNEL_SHADE_POSITION:
194 if (command instanceof PercentType) {
195 moveShade(PRIMARY_POSITION, ((PercentType) command).intValue(), webTargets, shadeId);
196 } else if (command instanceof UpDownType) {
197 moveShade(PRIMARY_POSITION, UpDownType.UP == command ? 0 : 100, webTargets, shadeId);
198 } else if (command instanceof StopMoveType) {
199 if (StopMoveType.STOP == command) {
200 stopShade(webTargets, shadeId);
202 logger.warn("Unexpected StopMoveType command");
207 case CHANNEL_SHADE_VANE:
208 if (command instanceof PercentType) {
209 moveShade(VANE_TILT_POSITION, ((PercentType) command).intValue(), webTargets, shadeId);
210 } else if (command instanceof OnOffType) {
211 moveShade(VANE_TILT_POSITION, OnOffType.ON == command ? 100 : 0, webTargets, shadeId);
215 case CHANNEL_SHADE_SECONDARY_POSITION:
216 if (command instanceof PercentType) {
217 moveShade(SECONDARY_POSITION, ((PercentType) command).intValue(), webTargets, shadeId);
218 } else if (command instanceof UpDownType) {
219 moveShade(SECONDARY_POSITION, UpDownType.UP == command ? 0 : 100, webTargets, shadeId);
220 } else if (command instanceof StopMoveType) {
221 if (StopMoveType.STOP == command) {
222 stopShade(webTargets, shadeId);
224 logger.warn("Unexpected StopMoveType command");
229 case CHANNEL_SHADE_COMMAND:
230 if (command instanceof StringType) {
231 if (COMMAND_IDENTIFY.equals(((StringType) command).toString())) {
232 logger.debug("Identify shade {}", shadeId);
233 identifyShade(webTargets, shadeId);
234 } else if (COMMAND_CALIBRATE.equals(((StringType) command).toString())) {
235 logger.debug("Calibrate shade {}", shadeId);
236 calibrateShade(webTargets, shadeId);
239 logger.warn("Unsupported command: {}. Supported commands are: " + COMMAND_CALIBRATE, command);
246 * Update the state of the channels based on the ShadeData provided.
248 * @param shadeData the ShadeData to be used.
250 protected void onReceiveUpdate(ShadeData shadeData) {
251 updateStatus(ThingStatus.ONLINE);
252 updateCapabilities(shadeData);
253 updateSoftProperties(shadeData);
254 updateFirmwareProperties(shadeData);
255 ShadePosition shadePosition = shadeData.positions;
256 if (shadePosition != null) {
257 updatePositionStates(shadePosition);
259 updateBatteryStates(shadeData.batteryStatus, shadeData.batteryStrength);
260 updateSignalStrengthState(shadeData.signalStrength);
263 private void updateCapabilities(ShadeData shade) {
264 if (capabilities != null) {
268 Capabilities capabilities = db.getCapabilities(shade.type, shade.capabilities);
269 if (capabilities.getValue() < 0) {
270 logger.debug("Unable to set capabilities for shade {}", shade.id);
273 logger.debug("Caching capabilities {} for shade {}", capabilities.getValue(), shade.id);
274 this.capabilities = capabilities;
277 private Capabilities getCapabilitiesOrDefault() {
278 Capabilities capabilities = this.capabilities;
279 if (capabilities == null) {
280 return new Capabilities();
286 * Update the Thing's properties based on the contents of the provided ShadeData.
288 * Checks the database of known Shade 'types' and 'capabilities' and logs any unknown or incompatible values, so
289 * that developers can be kept updated about the potential need to add support for that type resp. capabilities.
293 private void updateSoftProperties(ShadeData shadeData) {
294 final Map<String, String> properties = getThing().getProperties();
295 boolean propChanged = false;
297 // update 'type' property
298 final int type = shadeData.type;
299 String propKey = HDPowerViewBindingConstants.PROPERTY_SHADE_TYPE;
300 String propOldVal = properties.getOrDefault(propKey, "");
301 String propNewVal = db.getType(type).toString();
302 if (!propNewVal.equals(propOldVal)) {
304 getThing().setProperty(propKey, propNewVal);
305 if ((type > 0) && !db.isTypeInDatabase(type)) {
306 db.logTypeNotInDatabase(type);
310 // update 'capabilities' property
311 Capabilities capabilities = db.getCapabilities(shadeData.capabilities);
312 final int capabilitiesVal = capabilities.getValue();
313 propKey = HDPowerViewBindingConstants.PROPERTY_SHADE_CAPABILITIES;
314 propOldVal = properties.getOrDefault(propKey, "");
315 propNewVal = capabilities.toString();
316 if (!propNewVal.equals(propOldVal)) {
318 getThing().setProperty(propKey, propNewVal);
319 if ((capabilitiesVal >= 0) && !db.isCapabilitiesInDatabase(capabilitiesVal)) {
320 db.logCapabilitiesNotInDatabase(type, capabilitiesVal);
324 if (propChanged && db.isCapabilitiesInDatabase(capabilitiesVal) && db.isTypeInDatabase(type)
325 && (capabilitiesVal != db.getType(type).getCapabilities()) && (shadeData.capabilities != null)) {
326 db.logCapabilitiesMismatch(type, capabilitiesVal);
330 private void updateFirmwareProperties(ShadeData shadeData) {
331 Map<String, String> properties = editProperties();
332 Firmware shadeFirmware = shadeData.firmware;
333 Firmware motorFirmware = shadeData.motor;
334 if (shadeFirmware != null) {
335 properties.put(Thing.PROPERTY_FIRMWARE_VERSION, shadeFirmware.toString());
337 if (motorFirmware != null) {
338 properties.put(PROPERTY_MOTOR_FIRMWARE_VERSION, motorFirmware.toString());
340 updateProperties(properties);
344 * After a hard refresh, update the Thing's detected capabilities based on the contents of the provided ShadeData.
346 * Checks if the secondary support capabilities in the database of known Shade 'types' and 'capabilities' matches
347 * that implied by the ShadeData and logs any incompatible values, so that developers can be kept updated about the
348 * potential need to add support for that type resp. capabilities.
352 private void updateDetectedCapabilities(ShadeData shadeData) {
353 final ShadePosition positions = shadeData.positions;
354 if (positions == null) {
357 Capabilities capabilities = getCapabilitiesOrDefault();
359 // update 'secondary rail' detected capability
360 String capsKey = DETECTED_SECONDARY_RAIL;
361 String capsOldVal = detectedCapabilities.getOrDefault(capsKey, "");
362 boolean capsNewBool = positions.secondaryRailDetected();
363 String capsNewVal = String.valueOf(capsNewBool);
364 if (!capsNewVal.equals(capsOldVal)) {
365 detectedCapabilities.put(capsKey, capsNewVal);
366 if (capsNewBool != capabilities.supportsSecondary()) {
367 db.logPropertyMismatch(capsKey, shadeData.type, capabilities.getValue(), capsNewBool);
371 // update 'tilt anywhere' detected capability
372 capsKey = DETECTED_TILT_ANYWHERE;
373 capsOldVal = detectedCapabilities.getOrDefault(capsKey, "");
374 capsNewBool = positions.tiltAnywhereDetected();
375 capsNewVal = String.valueOf(capsNewBool);
376 if (!capsNewVal.equals(capsOldVal)) {
377 detectedCapabilities.put(capsKey, capsNewVal);
378 if (capsNewBool != capabilities.supportsTiltAnywhere()) {
379 db.logPropertyMismatch(capsKey, shadeData.type, capabilities.getValue(), capsNewBool);
384 private void updatePositionStates(ShadePosition shadePos) {
385 Capabilities capabilities = this.capabilities;
386 if (capabilities == null) {
387 logger.debug("The 'shadeCapabilities' field has not yet been initialized");
388 updateState(CHANNEL_SHADE_POSITION, UnDefType.UNDEF);
389 updateState(CHANNEL_SHADE_VANE, UnDefType.UNDEF);
390 updateState(CHANNEL_SHADE_SECONDARY_POSITION, UnDefType.UNDEF);
393 updateState(CHANNEL_SHADE_POSITION, shadePos.getState(capabilities, PRIMARY_POSITION));
394 updateState(CHANNEL_SHADE_VANE, shadePos.getState(capabilities, VANE_TILT_POSITION));
395 updateState(CHANNEL_SHADE_SECONDARY_POSITION, shadePos.getState(capabilities, SECONDARY_POSITION));
398 private void updateBatteryStates(int batteryStatus, double batteryStrength) {
399 updateBatteryLevelStates(batteryStatus);
400 updateState(CHANNEL_SHADE_BATTERY_VOLTAGE,
401 batteryStrength > 0 ? new QuantityType<>(batteryStrength / 10, Units.VOLT) : UnDefType.UNDEF);
404 private void updateBatteryLevelStates(int batteryStatus) {
406 switch (batteryStatus) {
414 case 4: // Plugged in
417 default: // No status available (0) or invalid
418 updateState(CHANNEL_SHADE_LOW_BATTERY, UnDefType.UNDEF);
419 updateState(CHANNEL_SHADE_BATTERY_LEVEL, UnDefType.UNDEF);
422 updateState(CHANNEL_SHADE_LOW_BATTERY, batteryStatus == 1 ? OnOffType.ON : OnOffType.OFF);
423 updateState(CHANNEL_SHADE_BATTERY_LEVEL, new DecimalType(mappedValue));
426 private void updateSignalStrengthState(int signalStrength) {
427 updateState(CHANNEL_SHADE_SIGNAL_STRENGTH, new DecimalType(signalStrength));
430 private void moveShade(CoordinateSystem coordSys, int newPercent, HDPowerViewWebTargets webTargets, int shadeId)
431 throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException,
432 HubShadeTimeoutException {
433 ShadePosition newPosition = null;
434 // (try to) read the positions from the hub
435 ShadeData shadeData = webTargets.getShade(shadeId);
436 updateCapabilities(shadeData);
437 newPosition = shadeData.positions;
438 // if no positions returned, then create a new position
439 if (newPosition == null) {
440 newPosition = new ShadePosition();
442 Capabilities capabilities = getCapabilitiesOrDefault();
443 // set the new position value, and write the positions to the hub
444 shadeData = webTargets.moveShade(shadeId, newPosition.setPosition(capabilities, coordSys, newPercent));
445 updateShadePositions(shadeData);
448 private void stopShade(HDPowerViewWebTargets webTargets, int shadeId) throws HubInvalidResponseException,
449 HubProcessingException, HubMaintenanceException, HubShadeTimeoutException {
450 updateShadePositions(webTargets.stopShade(shadeId));
451 // Positions in response from stop motion is not updated to to actual positions yet,
452 // so we need to request hard refresh.
453 requestRefreshShadePosition();
456 private void identifyShade(HDPowerViewWebTargets webTargets, int shadeId) throws HubInvalidResponseException,
457 HubProcessingException, HubMaintenanceException, HubShadeTimeoutException {
458 updateShadePositions(webTargets.jogShade(shadeId));
461 private void calibrateShade(HDPowerViewWebTargets webTargets, int shadeId) throws HubInvalidResponseException,
462 HubProcessingException, HubMaintenanceException, HubShadeTimeoutException {
463 updateShadePositions(webTargets.calibrateShade(shadeId));
466 private void updateShadePositions(ShadeData shadeData) {
467 ShadePosition shadePosition = shadeData.positions;
468 if (shadePosition == null) {
471 updateCapabilities(shadeData);
472 updatePositionStates(shadePosition);
476 * Request that the shade shall undergo a 'hard' refresh for querying its current position
478 protected synchronized void requestRefreshShadePosition() {
479 if (refreshPositionFuture == null) {
480 refreshPositionFuture = scheduler.schedule(this::doRefreshShadePosition, 0, TimeUnit.SECONDS);
485 * Request that the shade shall undergo a 'hard' refresh for querying its survey data
487 protected synchronized void requestRefreshShadeSurvey() {
488 if (refreshSignalFuture == null) {
489 refreshSignalFuture = scheduler.schedule(this::doRefreshShadeSignal, 0, TimeUnit.SECONDS);
494 * Request that the shade shall undergo a 'hard' refresh for querying its battery level state
496 protected synchronized void requestRefreshShadeBatteryLevel() {
497 if (refreshBatteryLevelFuture == null) {
498 refreshBatteryLevelFuture = scheduler.schedule(this::doRefreshShadeBatteryLevel, 0, TimeUnit.SECONDS);
502 private void doRefreshShadePosition() {
503 this.doRefreshShade(RefreshKind.POSITION);
504 refreshPositionFuture = null;
507 private void doRefreshShadeSignal() {
508 this.doRefreshShade(RefreshKind.SURVEY);
509 refreshSignalFuture = null;
512 private void doRefreshShadeBatteryLevel() {
513 this.doRefreshShade(RefreshKind.BATTERY_LEVEL);
514 refreshBatteryLevelFuture = null;
517 private void doRefreshShade(RefreshKind kind) {
519 HDPowerViewHubHandler bridge;
520 if ((bridge = getBridgeHandler()) == null) {
521 throw new HubProcessingException("Missing bridge handler");
523 HDPowerViewWebTargets webTargets = bridge.getWebTargets();
527 shadeData = webTargets.refreshShadePosition(shadeId);
528 updateShadePositions(shadeData);
529 updateDetectedCapabilities(shadeData);
532 List<SurveyData> surveyData = webTargets.getShadeSurvey(shadeId);
533 if (!surveyData.isEmpty()) {
534 if (logger.isDebugEnabled()) {
535 StringJoiner joiner = new StringJoiner(", ");
536 surveyData.forEach(data -> joiner.add(data.toString()));
537 logger.debug("Survey response for shade {}: {}", shadeId, joiner.toString());
540 int hubRssi = Integer.MAX_VALUE;
541 int repeaterRssi = Integer.MAX_VALUE;
542 for (SurveyData survey : surveyData) {
543 if (survey.neighborId == 0) {
544 hubRssi = survey.rssi;
546 repeaterRssi = survey.rssi;
549 updateState(CHANNEL_SHADE_HUB_RSSI, hubRssi == Integer.MAX_VALUE ? UnDefType.UNDEF
550 : new QuantityType<>(hubRssi, Units.DECIBEL_MILLIWATTS));
551 updateState(CHANNEL_SHADE_REPEATER_RSSI, repeaterRssi == Integer.MAX_VALUE ? UnDefType.UNDEF
552 : new QuantityType<>(repeaterRssi, Units.DECIBEL_MILLIWATTS));
554 shadeData = webTargets.getShade(shadeId);
555 updateSignalStrengthState(shadeData.signalStrength);
557 logger.info("No data from shade {} survey", shadeId);
559 * Setting signal strength channel to UNDEF here would be reverted on next poll,
560 * since signal strength is part of shade response. So leaving current value,
561 * even though refreshing the value failed.
563 updateState(CHANNEL_SHADE_HUB_RSSI, UnDefType.UNDEF);
564 updateState(CHANNEL_SHADE_REPEATER_RSSI, UnDefType.UNDEF);
568 shadeData = webTargets.refreshShadeBatteryLevel(shadeId);
569 updateBatteryStates(shadeData.batteryStatus, shadeData.batteryStrength);
572 throw new NotSupportedException("Unsupported refresh kind " + kind.toString());
574 } catch (HubInvalidResponseException e) {
575 Throwable cause = e.getCause();
577 logger.warn("Bridge returned a bad JSON response: {}", e.getMessage());
579 logger.warn("Bridge returned a bad JSON response: {} -> {}", e.getMessage(), cause.getMessage());
581 // Survey calls are unreliable and often returns "{}" as payload. For repeater RSSI tracking to be useful,
582 // we need to reset channels also in this case.
583 if (kind == RefreshKind.SURVEY) {
584 updateState(CHANNEL_SHADE_HUB_RSSI, UnDefType.UNDEF);
585 updateState(CHANNEL_SHADE_REPEATER_RSSI, UnDefType.UNDEF);
587 } catch (HubMaintenanceException e) {
588 // exceptions are logged in HDPowerViewWebTargets
589 } catch (HubShadeTimeoutException e) {
590 logger.info("Shade {} wireless refresh time out", shadeId);
591 } catch (HubException e) {
592 // ScheduledFutures will be cancelled by dispose(), naturally causing InterruptedException in invoke()
593 // for any ongoing requests. Logging this would only cause confusion.
595 logger.warn("Unexpected error: {}", e.getMessage());