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.*;
19 import java.util.concurrent.ScheduledFuture;
20 import java.util.concurrent.TimeUnit;
22 import javax.ws.rs.NotSupportedException;
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.openhab.binding.hdpowerview.internal.HDPowerViewBindingConstants;
27 import org.openhab.binding.hdpowerview.internal.HDPowerViewWebTargets;
28 import org.openhab.binding.hdpowerview.internal.api.CoordinateSystem;
29 import org.openhab.binding.hdpowerview.internal.api.Firmware;
30 import org.openhab.binding.hdpowerview.internal.api.ShadePosition;
31 import org.openhab.binding.hdpowerview.internal.api.responses.Shades.ShadeData;
32 import org.openhab.binding.hdpowerview.internal.api.responses.Survey;
33 import org.openhab.binding.hdpowerview.internal.config.HDPowerViewShadeConfiguration;
34 import org.openhab.binding.hdpowerview.internal.database.ShadeCapabilitiesDatabase;
35 import org.openhab.binding.hdpowerview.internal.database.ShadeCapabilitiesDatabase.Capabilities;
36 import org.openhab.binding.hdpowerview.internal.exceptions.HubException;
37 import org.openhab.binding.hdpowerview.internal.exceptions.HubInvalidResponseException;
38 import org.openhab.binding.hdpowerview.internal.exceptions.HubMaintenanceException;
39 import org.openhab.binding.hdpowerview.internal.exceptions.HubProcessingException;
40 import org.openhab.core.library.types.DecimalType;
41 import org.openhab.core.library.types.OnOffType;
42 import org.openhab.core.library.types.PercentType;
43 import org.openhab.core.library.types.QuantityType;
44 import org.openhab.core.library.types.StopMoveType;
45 import org.openhab.core.library.types.UpDownType;
46 import org.openhab.core.library.unit.Units;
47 import org.openhab.core.thing.Bridge;
48 import org.openhab.core.thing.ChannelUID;
49 import org.openhab.core.thing.Thing;
50 import org.openhab.core.thing.ThingStatus;
51 import org.openhab.core.thing.ThingStatusDetail;
52 import org.openhab.core.types.Command;
53 import org.openhab.core.types.RefreshType;
54 import org.openhab.core.types.UnDefType;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
59 * Handles commands for an HD PowerView Shade
61 * @author Andy Lintner - Initial contribution
62 * @author Andrew Fiddian-Green - Added support for secondary rail positions
65 public class HDPowerViewShadeHandler extends AbstractHubbedThingHandler {
67 private enum RefreshKind {
73 private final Logger logger = LoggerFactory.getLogger(HDPowerViewShadeHandler.class);
74 private final ShadeCapabilitiesDatabase db = new ShadeCapabilitiesDatabase();
76 private @Nullable ScheduledFuture<?> refreshPositionFuture = null;
77 private @Nullable ScheduledFuture<?> refreshSignalFuture = null;
78 private @Nullable ScheduledFuture<?> refreshBatteryLevelFuture = null;
79 private @Nullable Capabilities capabilities;
81 private boolean isDisposing;
83 public HDPowerViewShadeHandler(Thing thing) {
88 public void initialize() {
90 shadeId = getConfigAs(HDPowerViewShadeConfiguration.class).id;
91 logger.debug("Initializing shade handler for shade {}", shadeId);
93 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
94 "@text/offline.conf-error.invalid-id");
97 Bridge bridge = getBridge();
99 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED);
102 if (!(bridge.getHandler() instanceof HDPowerViewHubHandler)) {
103 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED,
104 "@text/offline.conf-error.invalid-bridge-handler");
107 ThingStatus bridgeStatus = bridge.getStatus();
108 if (bridgeStatus == ThingStatus.ONLINE) {
109 updateStatus(ThingStatus.UNKNOWN);
111 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
116 public void dispose() {
117 logger.debug("Disposing shade handler for shade {}", shadeId);
119 ScheduledFuture<?> future = refreshPositionFuture;
120 if (future != null) {
123 refreshPositionFuture = null;
124 future = refreshSignalFuture;
125 if (future != null) {
128 refreshSignalFuture = null;
129 future = refreshBatteryLevelFuture;
130 if (future != null) {
133 refreshBatteryLevelFuture = null;
138 public void handleCommand(ChannelUID channelUID, Command command) {
139 String channelId = channelUID.getId();
141 if (RefreshType.REFRESH == command) {
143 case CHANNEL_SHADE_POSITION:
144 case CHANNEL_SHADE_SECONDARY_POSITION:
145 case CHANNEL_SHADE_VANE:
146 requestRefreshShadePosition();
148 case CHANNEL_SHADE_LOW_BATTERY:
149 case CHANNEL_SHADE_BATTERY_LEVEL:
150 case CHANNEL_SHADE_BATTERY_VOLTAGE:
151 requestRefreshShadeBatteryLevel();
153 case CHANNEL_SHADE_SIGNAL_STRENGTH:
154 requestRefreshShadeSurvey();
160 HDPowerViewHubHandler bridge = getBridgeHandler();
161 if (bridge == null) {
162 logger.warn("Missing bridge handler");
165 HDPowerViewWebTargets webTargets = bridge.getWebTargets();
166 if (webTargets == null) {
167 logger.warn("Web targets not initialized");
171 handleShadeCommand(channelId, command, webTargets, shadeId);
172 } catch (HubInvalidResponseException e) {
173 Throwable cause = e.getCause();
175 logger.warn("Bridge returned a bad JSON response: {}", e.getMessage());
177 logger.warn("Bridge returned a bad JSON response: {} -> {}", e.getMessage(), cause.getMessage());
179 } catch (HubMaintenanceException e) {
180 // exceptions are logged in HDPowerViewWebTargets
181 } catch (HubException e) {
182 // ScheduledFutures will be cancelled by dispose(), naturally causing InterruptedException in invoke()
183 // for any ongoing requests. Logging this would only cause confusion.
185 logger.warn("Unexpected error: {}", e.getMessage());
190 private void handleShadeCommand(String channelId, Command command, HDPowerViewWebTargets webTargets, int shadeId)
191 throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException {
193 case CHANNEL_SHADE_POSITION:
194 if (command instanceof PercentType) {
195 moveShade(PRIMARY_ZERO_IS_CLOSED, ((PercentType) command).intValue(), webTargets, shadeId);
196 } else if (command instanceof UpDownType) {
197 moveShade(PRIMARY_ZERO_IS_CLOSED, 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_COORDS, ((PercentType) command).intValue(), webTargets, shadeId);
210 } else if (command instanceof OnOffType) {
211 moveShade(VANE_TILT_COORDS, OnOffType.ON == command ? 100 : 0, webTargets, shadeId);
215 case CHANNEL_SHADE_SECONDARY_POSITION:
216 if (command instanceof PercentType) {
217 moveShade(SECONDARY_ZERO_IS_OPEN, ((PercentType) command).intValue(), webTargets, shadeId);
218 } else if (command instanceof UpDownType) {
219 moveShade(SECONDARY_ZERO_IS_OPEN, 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_CALIBRATE:
230 if (OnOffType.ON == command) {
231 calibrateShade(webTargets, shadeId);
238 * Update the state of the channels based on the ShadeData provided.
240 * @param shadeData the ShadeData to be used; may be null.
242 protected void onReceiveUpdate(@Nullable ShadeData shadeData) {
243 if (shadeData != null) {
244 updateStatus(ThingStatus.ONLINE);
245 updateCapabilities(shadeData);
246 updateSoftProperties(shadeData);
247 updateFirmwareProperties(shadeData);
248 ShadePosition shadePosition = shadeData.positions;
249 if (shadePosition != null) {
250 updatePositionStates(shadePosition);
252 updateBatteryLevelStates(shadeData.batteryStatus);
253 updateState(CHANNEL_SHADE_BATTERY_VOLTAGE,
254 shadeData.batteryStrength > 0 ? new QuantityType<>(shadeData.batteryStrength / 10, Units.VOLT)
256 updateState(CHANNEL_SHADE_SIGNAL_STRENGTH, new DecimalType(shadeData.signalStrength));
258 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
262 private void updateCapabilities(ShadeData shade) {
263 if (capabilities != null) {
267 Integer value = shade.capabilities;
269 int valueAsInt = value.intValue();
270 logger.debug("Caching capabilities {} for shade {}", valueAsInt, shade.id);
271 capabilities = db.getCapabilities(valueAsInt);
273 logger.debug("Capabilities not included in shade response");
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 final Integer temp = shadeData.capabilities;
312 final int capabilitiesVal = temp != null ? temp.intValue() : -1;
313 Capabilities capabilities = db.getCapabilities(capabilitiesVal);
314 propKey = HDPowerViewBindingConstants.PROPERTY_SHADE_CAPABILITIES;
315 propOldVal = properties.getOrDefault(propKey, "");
316 propNewVal = capabilities.toString();
317 if (!propNewVal.equals(propOldVal)) {
319 getThing().setProperty(propKey, propNewVal);
320 if ((capabilitiesVal >= 0) && !db.isCapabilitiesInDatabase(capabilitiesVal)) {
321 db.logCapabilitiesNotInDatabase(type, capabilitiesVal);
325 if (propChanged && db.isCapabilitiesInDatabase(capabilitiesVal) && db.isTypeInDatabase(type)
326 && (capabilitiesVal != db.getType(type).getCapabilities())) {
327 db.logCapabilitiesMismatch(type, capabilitiesVal);
331 private void updateFirmwareProperties(ShadeData shadeData) {
332 Map<String, String> properties = editProperties();
333 Firmware shadeFirmware = shadeData.firmware;
334 Firmware motorFirmware = shadeData.motor;
335 if (shadeFirmware != null) {
336 properties.put(Thing.PROPERTY_FIRMWARE_VERSION, shadeFirmware.toString());
338 if (motorFirmware != null) {
339 properties.put(PROPERTY_MOTOR_FIRMWARE_VERSION, motorFirmware.toString());
341 updateProperties(properties);
345 * After a hard refresh, update the Thing's properties based on the contents of the provided ShadeData.
347 * Checks if the secondary support capabilities in the database of known Shade 'types' and 'capabilities' matches
348 * that implied by the ShadeData and logs any incompatible values, so that developers can be kept updated about the
349 * potential need to add support for that type resp. capabilities.
353 private void updateHardProperties(ShadeData shadeData) {
354 final ShadePosition positions = shadeData.positions;
355 if (positions == null) {
358 Capabilities capabilities = getCapabilitiesOrDefault();
359 final Map<String, String> properties = getThing().getProperties();
361 // update 'secondary rail detected' property
362 String propKey = HDPowerViewBindingConstants.PROPERTY_SECONDARY_RAIL_DETECTED;
363 String propOldVal = properties.getOrDefault(propKey, "");
364 boolean propNewBool = positions.secondaryRailDetected();
365 String propNewVal = String.valueOf(propNewBool);
366 if (!propNewVal.equals(propOldVal)) {
367 getThing().setProperty(propKey, propNewVal);
368 if (propNewBool != capabilities.supportsSecondary()) {
369 db.logPropertyMismatch(propKey, shadeData.type, capabilities.getValue(), propNewBool);
373 // update 'tilt anywhere detected' property
374 propKey = HDPowerViewBindingConstants.PROPERTY_TILT_ANYWHERE_DETECTED;
375 propOldVal = properties.getOrDefault(propKey, "");
376 propNewBool = positions.tiltAnywhereDetected();
377 propNewVal = String.valueOf(propNewBool);
378 if (!propNewVal.equals(propOldVal)) {
379 getThing().setProperty(propKey, propNewVal);
380 if (propNewBool != capabilities.supportsTiltAnywhere()) {
381 db.logPropertyMismatch(propKey, shadeData.type, capabilities.getValue(), propNewBool);
386 private void updatePositionStates(ShadePosition shadePos) {
387 Capabilities capabilities = this.capabilities;
388 if (capabilities == null) {
389 logger.debug("The 'shadeCapabilities' field has not yet been initialized");
390 updateState(CHANNEL_SHADE_POSITION, UnDefType.UNDEF);
391 updateState(CHANNEL_SHADE_VANE, UnDefType.UNDEF);
392 updateState(CHANNEL_SHADE_SECONDARY_POSITION, UnDefType.UNDEF);
395 updateState(CHANNEL_SHADE_POSITION, shadePos.getState(capabilities, PRIMARY_ZERO_IS_CLOSED));
396 updateState(CHANNEL_SHADE_VANE, shadePos.getState(capabilities, VANE_TILT_COORDS));
397 updateState(CHANNEL_SHADE_SECONDARY_POSITION, shadePos.getState(capabilities, SECONDARY_ZERO_IS_OPEN));
400 private void updateBatteryLevelStates(int batteryStatus) {
402 switch (batteryStatus) {
410 case 4: // Plugged in
413 default: // No status available (0) or invalid
414 updateState(CHANNEL_SHADE_LOW_BATTERY, UnDefType.UNDEF);
415 updateState(CHANNEL_SHADE_BATTERY_LEVEL, UnDefType.UNDEF);
418 updateState(CHANNEL_SHADE_LOW_BATTERY, batteryStatus == 1 ? OnOffType.ON : OnOffType.OFF);
419 updateState(CHANNEL_SHADE_BATTERY_LEVEL, new DecimalType(mappedValue));
422 private void moveShade(CoordinateSystem coordSys, int newPercent, HDPowerViewWebTargets webTargets, int shadeId)
423 throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException {
424 ShadePosition newPosition = null;
425 // (try to) read the positions from the hub
426 ShadeData shadeData = webTargets.getShade(shadeId);
427 updateCapabilities(shadeData);
428 newPosition = shadeData.positions;
429 // if no positions returned, then create a new position
430 if (newPosition == null) {
431 newPosition = new ShadePosition();
433 Capabilities capabilities = getCapabilitiesOrDefault();
434 // set the new position value, and write the positions to the hub
435 shadeData = webTargets.moveShade(shadeId, newPosition.setPosition(capabilities, coordSys, newPercent));
436 updateShadePositions(shadeData);
439 private void stopShade(HDPowerViewWebTargets webTargets, int shadeId)
440 throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException {
441 updateShadePositions(webTargets.stopShade(shadeId));
442 // Positions in response from stop motion is not updated to to actual positions yet,
443 // so we need to request hard refresh.
444 requestRefreshShadePosition();
447 private void calibrateShade(HDPowerViewWebTargets webTargets, int shadeId)
448 throws HubInvalidResponseException, HubProcessingException, HubMaintenanceException {
449 updateShadePositions(webTargets.calibrateShade(shadeId));
452 private void updateShadePositions(ShadeData shadeData) {
453 ShadePosition shadePosition = shadeData.positions;
454 if (shadePosition == null) {
457 updateCapabilities(shadeData);
458 updatePositionStates(shadePosition);
462 * Request that the shade shall undergo a 'hard' refresh for querying its current position
464 protected synchronized void requestRefreshShadePosition() {
465 if (refreshPositionFuture == null) {
466 refreshPositionFuture = scheduler.schedule(this::doRefreshShadePosition, 0, TimeUnit.SECONDS);
471 * Request that the shade shall undergo a 'hard' refresh for querying its survey data
473 protected synchronized void requestRefreshShadeSurvey() {
474 if (refreshSignalFuture == null) {
475 refreshSignalFuture = scheduler.schedule(this::doRefreshShadeSignal, 0, TimeUnit.SECONDS);
480 * Request that the shade shall undergo a 'hard' refresh for querying its battery level state
482 protected synchronized void requestRefreshShadeBatteryLevel() {
483 if (refreshBatteryLevelFuture == null) {
484 refreshBatteryLevelFuture = scheduler.schedule(this::doRefreshShadeBatteryLevel, 0, TimeUnit.SECONDS);
488 private void doRefreshShadePosition() {
489 this.doRefreshShade(RefreshKind.POSITION);
490 refreshPositionFuture = null;
493 private void doRefreshShadeSignal() {
494 this.doRefreshShade(RefreshKind.SURVEY);
495 refreshSignalFuture = null;
498 private void doRefreshShadeBatteryLevel() {
499 this.doRefreshShade(RefreshKind.BATTERY_LEVEL);
500 refreshBatteryLevelFuture = null;
503 private void doRefreshShade(RefreshKind kind) {
505 HDPowerViewHubHandler bridge;
506 if ((bridge = getBridgeHandler()) == null) {
507 throw new HubProcessingException("Missing bridge handler");
509 HDPowerViewWebTargets webTargets = bridge.getWebTargets();
510 if (webTargets == null) {
511 throw new HubProcessingException("Web targets not initialized");
516 shadeData = webTargets.refreshShadePosition(shadeId);
519 Survey survey = webTargets.getShadeSurvey(shadeId);
520 if (survey.surveyData != null) {
521 logger.debug("Survey response for shade {}: {}", survey.shadeId, survey.toString());
523 logger.warn("No response from shade {} survey", shadeId);
527 shadeData = webTargets.refreshShadeBatteryLevel(shadeId);
530 throw new NotSupportedException("Unsupported refresh kind " + kind.toString());
532 if (Boolean.TRUE.equals(shadeData.timedOut)) {
533 logger.warn("Shade {} wireless refresh time out", shadeId);
534 } else if (kind == RefreshKind.POSITION) {
535 updateShadePositions(shadeData);
536 updateHardProperties(shadeData);
538 } catch (HubInvalidResponseException e) {
539 Throwable cause = e.getCause();
541 logger.warn("Bridge returned a bad JSON response: {}", e.getMessage());
543 logger.warn("Bridge returned a bad JSON response: {} -> {}", e.getMessage(), cause.getMessage());
545 } catch (HubMaintenanceException e) {
546 // exceptions are logged in HDPowerViewWebTargets
547 } catch (HubException e) {
548 // ScheduledFutures will be cancelled by dispose(), naturally causing InterruptedException in invoke()
549 // for any ongoing requests. Logging this would only cause confusion.
551 logger.warn("Unexpected error: {}", e.getMessage());