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.velux.internal.handler;
15 import java.util.Collection;
17 import java.util.Map.Entry;
19 import java.util.concurrent.ConcurrentHashMap;
20 import java.util.concurrent.ExecutorService;
21 import java.util.concurrent.Executors;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.binding.velux.internal.VeluxBinding;
28 import org.openhab.binding.velux.internal.VeluxBindingConstants;
29 import org.openhab.binding.velux.internal.VeluxItemType;
30 import org.openhab.binding.velux.internal.action.VeluxActions;
31 import org.openhab.binding.velux.internal.bridge.VeluxBridge;
32 import org.openhab.binding.velux.internal.bridge.VeluxBridgeActuators;
33 import org.openhab.binding.velux.internal.bridge.VeluxBridgeDeviceStatus;
34 import org.openhab.binding.velux.internal.bridge.VeluxBridgeGetFirmware;
35 import org.openhab.binding.velux.internal.bridge.VeluxBridgeGetHouseStatus;
36 import org.openhab.binding.velux.internal.bridge.VeluxBridgeInstance;
37 import org.openhab.binding.velux.internal.bridge.VeluxBridgeLANConfig;
38 import org.openhab.binding.velux.internal.bridge.VeluxBridgeProvider;
39 import org.openhab.binding.velux.internal.bridge.VeluxBridgeScenes;
40 import org.openhab.binding.velux.internal.bridge.VeluxBridgeSetHouseStatusMonitor;
41 import org.openhab.binding.velux.internal.bridge.VeluxBridgeWLANConfig;
42 import org.openhab.binding.velux.internal.bridge.common.BridgeAPI;
43 import org.openhab.binding.velux.internal.bridge.common.BridgeCommunicationProtocol;
44 import org.openhab.binding.velux.internal.bridge.common.RunProductCommand;
45 import org.openhab.binding.velux.internal.bridge.common.RunReboot;
46 import org.openhab.binding.velux.internal.bridge.json.JsonVeluxBridge;
47 import org.openhab.binding.velux.internal.bridge.slip.FunctionalParameters;
48 import org.openhab.binding.velux.internal.bridge.slip.SlipVeluxBridge;
49 import org.openhab.binding.velux.internal.config.VeluxBridgeConfiguration;
50 import org.openhab.binding.velux.internal.development.Threads;
51 import org.openhab.binding.velux.internal.factory.VeluxHandlerFactory;
52 import org.openhab.binding.velux.internal.handler.utils.ExtendedBaseBridgeHandler;
53 import org.openhab.binding.velux.internal.handler.utils.Thing2VeluxActuator;
54 import org.openhab.binding.velux.internal.handler.utils.ThingProperty;
55 import org.openhab.binding.velux.internal.things.VeluxExistingProducts;
56 import org.openhab.binding.velux.internal.things.VeluxExistingScenes;
57 import org.openhab.binding.velux.internal.things.VeluxProduct;
58 import org.openhab.binding.velux.internal.things.VeluxProduct.ProductBridgeIndex;
59 import org.openhab.binding.velux.internal.things.VeluxProductPosition;
60 import org.openhab.binding.velux.internal.things.VeluxProductPosition.PositionType;
61 import org.openhab.binding.velux.internal.utils.Localization;
62 import org.openhab.core.common.AbstractUID;
63 import org.openhab.core.common.NamedThreadFactory;
64 import org.openhab.core.library.types.DecimalType;
65 import org.openhab.core.library.types.OnOffType;
66 import org.openhab.core.library.types.PercentType;
67 import org.openhab.core.thing.Bridge;
68 import org.openhab.core.thing.ChannelUID;
69 import org.openhab.core.thing.ThingStatus;
70 import org.openhab.core.thing.ThingStatusDetail;
71 import org.openhab.core.thing.ThingTypeUID;
72 import org.openhab.core.thing.binding.ThingHandler;
73 import org.openhab.core.thing.binding.ThingHandlerService;
74 import org.openhab.core.types.Command;
75 import org.openhab.core.types.RefreshType;
76 import org.openhab.core.types.State;
77 import org.openhab.core.types.UnDefType;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
82 * <B>Common interaction with the </B><I>Velux</I><B> bridge.</B>
84 * It implements the communication between <B>OpenHAB</B> and the <I>Velux</I> Bridge:
86 * <LI><B>OpenHAB</B> Event Bus → <I>Velux</I> <B>bridge</B>
88 * Sending commands and value updates.</LI>
91 * <LI><I>Velux</I> <B>bridge</B> → <B>OpenHAB</B>:
93 * Retrieving information by sending a Refresh command.</LI>
96 * Entry point for this class is the method
97 * {@link VeluxBridgeHandler#handleCommand handleCommand}.
99 * @author Guenther Schreiner - Initial contribution.
102 public class VeluxBridgeHandler extends ExtendedBaseBridgeHandler implements VeluxBridgeInstance, VeluxBridgeProvider {
105 * timeout to ensure that the binding shutdown will not block and stall the shutdown of OH itself
107 private static final int COMMUNICATION_TASK_MAX_WAIT_SECS = 10;
110 * a modifier string to avoid the (small) risk of other tasks (outside this binding) locking on the same ip address
111 * Strings.intern() object
114 private static final String LOCK_MODIFIER = "velux.ipaddr.";
116 private final Logger logger = LoggerFactory.getLogger(VeluxBridgeHandler.class);
121 * Scheduler for continuous refresh by scheduleWithFixedDelay.
123 private @Nullable ScheduledFuture<?> refreshSchedulerJob = null;
126 * Counter of refresh invocations by {@link refreshSchedulerJob}.
128 private int refreshCounter = 0;
131 * Dedicated task executor for the long-running bridge communication tasks.
133 * Note: there is no point in using multi threaded thread-pool here, since all the submitted (Runnable) tasks are
134 * anyway forced to go through the same serial pipeline, because they all call the same class level "synchronized"
135 * method to actually communicate with the KLF bridge via its one single TCP socket connection
137 private @Nullable ExecutorService communicationsJobExecutor = null;
138 private @Nullable NamedThreadFactory threadFactory = null;
140 private VeluxBridge myJsonBridge = new JsonVeluxBridge(this);
141 private VeluxBridge mySlipBridge = new SlipVeluxBridge(this);
142 private boolean disposing = false;
145 * **************************************
146 * ***** Default visibility Objects *****
149 public VeluxBridge thisBridge = myJsonBridge;
150 public BridgeParameters bridgeParameters = new BridgeParameters();
151 public Localization localization;
154 * Mapping from ChannelUID to class Thing2VeluxActuator, which return Velux device information, probably cached.
156 public final Map<ChannelUID, Thing2VeluxActuator> channel2VeluxActuator = new ConcurrentHashMap<>();
159 * Information retrieved by {@link VeluxBinding#VeluxBinding}.
161 private VeluxBridgeConfiguration veluxBridgeConfiguration = new VeluxBridgeConfiguration();
164 * ************************
165 * ***** Constructors *****
168 public VeluxBridgeHandler(final Bridge bridge, Localization localization) {
170 logger.trace("VeluxBridgeHandler(constructor with bridge={}, localization={}) called.", bridge, localization);
171 this.localization = localization;
172 logger.debug("Creating a VeluxBridgeHandler for thing '{}'.", getThing().getUID());
179 * Set of information retrieved from the bridge/gateway:
182 * <LI>{@link #actuators} - Already known actuators,</LI>
183 * <LI>{@link #scenes} - Already on the gateway defined scenes,</LI>
184 * <LI>{@link #gateway} - Current status of the gateway status,</LI>
185 * <LI>{@link #firmware} - Information about the gateway firmware revision,</LI>
186 * <LI>{@link #lanConfig} - Information about the gateway configuration,</LI>
187 * <LI>{@link #wlanConfig} - Information about the gateway configuration.</LI>
190 public class BridgeParameters {
191 /** Information retrieved by {@link VeluxBridgeActuators#getProducts} */
192 public VeluxBridgeActuators actuators = new VeluxBridgeActuators();
194 /** Information retrieved by {@link org.openhab.binding.velux.internal.bridge.VeluxBridgeScenes#getScenes} */
195 VeluxBridgeScenes scenes = new VeluxBridgeScenes();
197 /** Information retrieved by {@link VeluxBridgeDeviceStatus#retrieve} */
198 VeluxBridgeDeviceStatus.Channel gateway = new VeluxBridgeDeviceStatus().getChannel();
200 /** Information retrieved by {@link VeluxBridgeGetFirmware#retrieve} */
201 VeluxBridgeGetFirmware.Channel firmware = new VeluxBridgeGetFirmware().getChannel();
203 /** Information retrieved by {@link VeluxBridgeLANConfig#retrieve} */
204 VeluxBridgeLANConfig.Channel lanConfig = new VeluxBridgeLANConfig().getChannel();
206 /** Information retrieved by {@link VeluxBridgeWLANConfig#retrieve} */
207 VeluxBridgeWLANConfig.Channel wlanConfig = new VeluxBridgeWLANConfig().getChannel();
213 * Provide the ThingType for a given Channel.
215 * Separated into this private method to deal with the deprecated method.
218 * @param channelUID for type {@link ChannelUID}.
219 * @return thingTypeUID of type {@link ThingTypeUID}.
221 public ThingTypeUID thingTypeUIDOf(ChannelUID channelUID) {
222 String[] segments = channelUID.getAsString().split(AbstractUID.SEPARATOR);
223 if (segments.length > 1) {
224 return new ThingTypeUID(segments[0], segments[1]);
226 logger.warn("thingTypeUIDOf({}) failed.", channelUID);
227 return new ThingTypeUID(VeluxBindingConstants.BINDING_ID, VeluxBindingConstants.UNKNOWN_THING_TYPE_ID);
230 // Objects and Methods for interface VeluxBridgeInstance
233 * Information retrieved by ...
236 public VeluxBridgeConfiguration veluxBridgeConfiguration() {
237 return veluxBridgeConfiguration;
241 * Information retrieved by {@link VeluxBridgeActuators#getProducts}
244 public VeluxExistingProducts existingProducts() {
245 return bridgeParameters.actuators.getChannel().existingProducts;
249 * Information retrieved by {@link VeluxBridgeScenes#getScenes}
252 public VeluxExistingScenes existingScenes() {
253 return bridgeParameters.scenes.getChannel().existingScenes;
256 // Objects and Methods for interface VeluxBridgeProvider *****
259 public boolean bridgeCommunicate(BridgeCommunicationProtocol communication) {
260 logger.warn("bridgeCommunicate() called. Should never be called (as implemented by protocol-specific layers).");
265 public @Nullable BridgeAPI bridgeAPI() {
266 logger.warn("bridgeAPI() called. Should never be called (as implemented by protocol-specific layers).");
270 // Provisioning/Deprovisioning methods *****
273 public void initialize() {
274 // set the thing status to UNKNOWN temporarily and let the background task decide the real status
275 updateStatus(ThingStatus.UNKNOWN);
277 // take care of unusual situations...
278 if (scheduler.isShutdown()) {
279 logger.warn("initialize(): scheduler is shutdown, aborting initialization.");
283 logger.trace("initialize(): initialize bridge configuration parameters.");
284 veluxBridgeConfiguration = new VeluxBinding(getConfigAs(VeluxBridgeConfiguration.class)).checked();
286 scheduler.execute(() -> {
288 initializeSchedulerJob();
293 * Various initialisation actions to be executed on a background thread
295 private void initializeSchedulerJob() {
297 * synchronize disposeSchedulerJob() and initializeSchedulerJob() based an IP address Strings.intern() object to
298 * prevent overlap of initialization and disposal communications towards the same physical bridge
300 synchronized (LOCK_MODIFIER.concat(veluxBridgeConfiguration.ipAddress).intern()) {
301 logger.trace("initializeSchedulerJob(): adopt new bridge configuration parameters.");
302 bridgeParamsUpdated();
304 long mSecs = veluxBridgeConfiguration.refreshMSecs;
305 logger.trace("initializeSchedulerJob(): scheduling refresh at {} milliseconds.", mSecs);
306 refreshSchedulerJob = scheduler.scheduleWithFixedDelay(() -> {
307 refreshSchedulerJob();
308 }, mSecs, mSecs, TimeUnit.MILLISECONDS);
310 VeluxHandlerFactory.refreshBindingInfo();
312 if (logger.isDebugEnabled()) {
313 logger.debug("Velux Bridge '{}' is initialized (with {} scenes and {} actuators).", getThing().getUID(),
314 bridgeParameters.scenes.getChannel().existingScenes.getNoMembers(),
315 bridgeParameters.actuators.getChannel().existingProducts.getNoMembers());
321 public void dispose() {
322 scheduler.submit(() -> {
324 disposeSchedulerJob();
329 * Various disposal actions to be executed on a background thread
331 private void disposeSchedulerJob() {
333 * synchronize disposeSchedulerJob() and initializeSchedulerJob() based an IP address Strings.intern() object to
334 * prevent overlap of initialization and disposal communications towards the same physical bridge
336 synchronized (LOCK_MODIFIER.concat(veluxBridgeConfiguration.ipAddress).intern()) {
338 * cancel the regular refresh polling job
340 ScheduledFuture<?> refreshSchedulerJob = this.refreshSchedulerJob;
341 if (refreshSchedulerJob != null) {
342 logger.trace("disposeSchedulerJob(): cancel the refresh polling job.");
343 refreshSchedulerJob.cancel(false);
346 ExecutorService commsJobExecutor = this.communicationsJobExecutor;
347 if (commsJobExecutor != null) {
348 this.communicationsJobExecutor = null;
349 logger.trace("disposeSchedulerJob(): cancel any other scheduled jobs.");
351 * remove un-started communication tasks from the execution queue; and stop accepting more tasks
353 commsJobExecutor.shutdownNow();
355 * if the last bridge communication was OK, wait for already started task(s) to complete (so the bridge
356 * won't lock up); but to prevent stalling the OH shutdown process, time out after
357 * MAX_COMMUNICATION_TASK_WAIT_TIME_SECS
359 if (thisBridge.lastCommunicationOk()) {
361 if (!commsJobExecutor.awaitTermination(COMMUNICATION_TASK_MAX_WAIT_SECS, TimeUnit.SECONDS)) {
362 logger.warn("disposeSchedulerJob(): unexpected awaitTermination() timeout.");
364 } catch (InterruptedException e) {
365 logger.warn("disposeSchedulerJob(): unexpected exception awaitTermination() '{}'.",
372 * if the last bridge communication was OK, deactivate HSM to prevent queueing more HSM events
374 if (thisBridge.lastCommunicationOk()
375 && (new VeluxBridgeSetHouseStatusMonitor().modifyHSM(thisBridge, false))) {
376 logger.trace("disposeSchedulerJob(): HSM deactivated.");
380 * finally clean up everything else
382 logger.trace("disposeSchedulerJob(): shut down JSON connection interface.");
383 myJsonBridge.shutdown();
384 logger.trace("disposeSchedulerJob(): shut down SLIP connection interface.");
385 mySlipBridge.shutdown();
386 VeluxHandlerFactory.refreshBindingInfo();
387 logger.debug("Velux Bridge '{}' is shut down.", getThing().getUID());
392 * NOTE: It takes care by calling {@link #handleCommand} with the REFRESH command, that every used channel is
396 public void channelLinked(ChannelUID channelUID) {
397 if (thing.getStatus() == ThingStatus.ONLINE) {
398 channel2VeluxActuator.put(channelUID, new Thing2VeluxActuator(this, channelUID));
399 logger.trace("channelLinked({}) refreshing channel value with help of handleCommand as Thing is online.",
400 channelUID.getAsString());
401 handleCommand(channelUID, RefreshType.REFRESH);
403 logger.trace("channelLinked({}) doing nothing as Thing is not online.", channelUID.getAsString());
408 public void channelUnlinked(ChannelUID channelUID) {
409 logger.trace("channelUnlinked({}) called.", channelUID.getAsString());
412 // Reconfiguration methods
414 private void bridgeParamsUpdated() {
415 logger.debug("bridgeParamsUpdated() called.");
417 // Determine the appropriate bridge communication channel
418 boolean validBridgeFound = false;
419 if (myJsonBridge.supportedProtocols.contains(veluxBridgeConfiguration.protocol)) {
420 logger.debug("bridgeParamsUpdated(): choosing JSON as communication method.");
421 thisBridge = myJsonBridge;
422 validBridgeFound = true;
424 if (mySlipBridge.supportedProtocols.contains(veluxBridgeConfiguration.protocol)) {
425 logger.debug("bridgeParamsUpdated(): choosing SLIP as communication method.");
426 thisBridge = mySlipBridge;
427 validBridgeFound = true;
429 if (!validBridgeFound) {
430 logger.debug("No valid protocol selected, aborting this {} binding.", VeluxBindingConstants.BINDING_ID);
431 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
432 "@text/runtime.bridge-offline-no-valid-bridgeProtocol-selected");
433 logger.trace("bridgeParamsUpdated() done.");
437 logger.trace("bridgeParamsUpdated(): Trying to authenticate towards bridge.");
439 if (!thisBridge.bridgeLogin()) {
440 logger.warn("{} bridge login sequence failed; expecting bridge is OFFLINE.",
441 VeluxBindingConstants.BINDING_ID);
442 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
443 "@text/runtime.bridge-offline-login-sequence-failed");
444 logger.trace("bridgeParamsUpdated() done.");
448 logger.trace("bridgeParamsUpdated(): Querying bridge state.");
449 bridgeParameters.gateway = new VeluxBridgeDeviceStatus().retrieve(thisBridge);
451 logger.trace("bridgeParamsUpdated(): Fetching existing scenes.");
452 bridgeParameters.scenes.getScenes(thisBridge);
453 logger.debug("Found Velux scenes:\n\t{}",
454 bridgeParameters.scenes.getChannel().existingScenes.toString(false, "\n\t"));
455 logger.trace("bridgeParamsUpdated(): Fetching existing actuators/products.");
456 bridgeParameters.actuators.getProducts(thisBridge);
457 logger.debug("Found Velux actuators:\n\t{}",
458 bridgeParameters.actuators.getChannel().existingProducts.toString(false, "\n\t"));
460 if (thisBridge.bridgeAPI().setHouseStatusMonitor() != null) {
461 logger.trace("bridgeParamsUpdated(): Activating HouseStatusMonitor.");
462 if (new VeluxBridgeSetHouseStatusMonitor().modifyHSM(thisBridge, true)) {
463 logger.trace("bridgeParamsUpdated(): HSM activated.");
465 logger.warn("Activation of House-Status-Monitoring failed (might lead to a lack of status updates).");
469 updateDynamicChannels();
471 veluxBridgeConfiguration.hasChanged = false;
472 logger.debug("Velux veluxBridge is online, now.");
473 updateStatus(ThingStatus.ONLINE);
474 logger.trace("bridgeParamsUpdated() successfully finished.");
477 // Continuous synchronization methods
479 private synchronized void refreshSchedulerJob() {
480 logger.debug("refreshSchedulerJob() initiated by {} starting cycle {}.", Thread.currentThread(),
482 logger.trace("refreshSchedulerJob(): processing of possible HSM messages.");
484 // Background execution of bridge related I/O
485 submitCommunicationsJob(() -> {
486 getHouseStatusCommsJob();
490 "refreshSchedulerJob(): loop through all (child things and bridge) linked channels needing a refresh");
491 for (ChannelUID channelUID : BridgeChannels.getAllLinkedChannelUIDs(this)) {
492 if (VeluxItemType.isToBeRefreshedNow(refreshCounter, thingTypeUIDOf(channelUID), channelUID.getId())) {
493 logger.trace("refreshSchedulerJob(): refreshing channel {}.", channelUID);
494 handleCommand(channelUID, RefreshType.REFRESH);
498 logger.trace("refreshSchedulerJob(): loop through properties needing a refresh");
499 for (VeluxItemType veluxItem : VeluxItemType.getPropertyEntriesByThing(getThing().getThingTypeUID())) {
500 if (VeluxItemType.isToBeRefreshedNow(refreshCounter, getThing().getThingTypeUID(),
501 veluxItem.getIdentifier())) {
502 logger.trace("refreshSchedulerJob(): refreshing property {}.", veluxItem.getIdentifier());
503 handleCommand(new ChannelUID(getThing().getUID(), veluxItem.getIdentifier()), RefreshType.REFRESH);
506 logger.debug("refreshSchedulerJob() initiated by {} finished cycle {}.", Thread.currentThread(),
511 private void getHouseStatusCommsJob() {
512 logger.trace("getHouseStatusCommsJob() initiated by {} will process HouseStatus.", Thread.currentThread());
513 if (new VeluxBridgeGetHouseStatus().evaluateState(thisBridge)) {
514 logger.trace("getHouseStatusCommsJob(): => GetHouseStatus() => updates received => synchronizing");
515 syncChannelsWithProducts();
517 logger.trace("getHouseStatusCommsJob(): => GetHouseStatus() => no updates");
519 logger.trace("getHouseStatusCommsJob() initiated by {} has finished.", Thread.currentThread());
523 * In case of recognized changes in the real world, the method will
524 * update the corresponding states via openHAB event bus.
526 private void syncChannelsWithProducts() {
527 if (!bridgeParameters.actuators.getChannel().existingProducts.isDirty()) {
528 logger.trace("syncChannelsWithProducts(): no existing products with changed parameters.");
531 logger.trace("syncChannelsWithProducts(): there are some existing products with changed parameters.");
532 for (VeluxProduct product : bridgeParameters.actuators.getChannel().existingProducts.valuesOfModified()) {
533 logger.trace("syncChannelsWithProducts(): actuator {} has changed values.", product.getProductName());
534 ProductBridgeIndex productPbi = product.getBridgeProductIndex();
535 logger.trace("syncChannelsWithProducts(): bridge index is {}.", productPbi);
536 for (ChannelUID channelUID : BridgeChannels.getAllLinkedChannelUIDs(this)) {
537 if (!channel2VeluxActuator.containsKey(channelUID)) {
538 logger.trace("syncChannelsWithProducts(): channel {} not found.", channelUID);
541 Thing2VeluxActuator actuator = channel2VeluxActuator.get(channelUID);
542 if (actuator == null || !actuator.isKnown()) {
543 logger.trace("syncChannelsWithProducts(): channel {} not registered on bridge.", channelUID);
546 ProductBridgeIndex channelPbi = actuator.getProductBridgeIndex();
547 if (!channelPbi.equals(productPbi)) {
551 VeluxProductPosition position;
552 if (channelUID.getId().equals(VeluxBindingConstants.CHANNEL_VANE_POSITION)) {
554 position = new VeluxProductPosition(product.getVanePosition());
556 // Handle value inversion
557 isInverted = actuator.isInverted();
558 logger.trace("syncChannelsWithProducts(): isInverted is {}.", isInverted);
559 position = new VeluxProductPosition(product.getDisplayPosition());
561 if (position.isValid()) {
562 PercentType positionAsPercent = position.getPositionAsPercentType(isInverted);
563 logger.debug("syncChannelsWithProducts(): updating channel {} to position {}%.", channelUID,
565 updateState(channelUID, positionAsPercent);
568 logger.trace("syncChannelsWithProducts(): updating channel {} to 'UNDEFINED'.", channelUID);
569 updateState(channelUID, UnDefType.UNDEF);
573 logger.trace("syncChannelsWithProducts(): resetting dirty flag.");
574 bridgeParameters.actuators.getChannel().existingProducts.resetDirtyFlag();
575 logger.trace("syncChannelsWithProducts() done.");
578 // Processing of openHAB events
581 public void handleCommand(ChannelUID channelUID, Command command) {
582 logger.trace("handleCommand({}): command {} on channel {} will be scheduled.", Thread.currentThread(), command,
583 channelUID.getAsString());
584 logger.debug("handleCommand({},{}) called.", channelUID.getAsString(), command);
586 // Background execution of bridge related I/O
587 submitCommunicationsJob(() -> {
588 handleCommandCommsJob(channelUID, command);
590 logger.trace("handleCommand({}) done.", Thread.currentThread());
594 * Normally called by {@link #handleCommand} to handle a command for a given channel with possibly long execution
597 * <B>NOTE:</B> This method is to be called as separated thread to ensure proper openHAB framework in parallel.
600 * @param channelUID the {@link ChannelUID} of the channel to which the command was sent,
601 * @param command the {@link Command}.
603 private synchronized void handleCommandCommsJob(ChannelUID channelUID, Command command) {
604 logger.trace("handleCommandCommsJob({}): command {} on channel {}.", Thread.currentThread(), command,
605 channelUID.getAsString());
606 logger.debug("handleCommandCommsJob({},{}) called.", channelUID.getAsString(), command);
609 * ===========================================================
613 if (veluxBridgeConfiguration.isProtocolTraceEnabled) {
614 Threads.findDeadlocked();
617 String channelId = channelUID.getId();
618 State newState = null;
619 String itemName = channelUID.getAsString();
620 VeluxItemType itemType = VeluxItemType.getByThingAndChannel(thingTypeUIDOf(channelUID), channelUID.getId());
622 if (itemType == VeluxItemType.UNKNOWN) {
623 logger.warn("{} Cannot determine type of Channel {}, ignoring command {}.",
624 VeluxBindingConstants.LOGGING_CONTACT, channelUID, command);
625 logger.trace("handleCommandCommsJob() aborting.");
630 if (!channel2VeluxActuator.containsKey(channelUID)) {
631 channel2VeluxActuator.put(channelUID, new Thing2VeluxActuator(this, channelUID));
634 if (veluxBridgeConfiguration.hasChanged) {
635 logger.trace("handleCommandCommsJob(): work on updated bridge configuration parameters.");
636 bridgeParamsUpdated();
639 syncChannelsWithProducts();
641 if (command instanceof RefreshType) {
643 * ===========================================================
646 logger.trace("handleCommandCommsJob(): work on refresh.");
647 if (!itemType.isReadable()) {
648 logger.debug("handleCommandCommsJob(): received a Refresh command for a non-readable item.");
650 logger.trace("handleCommandCommsJob(): refreshing item {} (type {}).", itemName, itemType);
651 try { // expecting an IllegalArgumentException for unknown Velux device
655 newState = ChannelBridgeStatus.handleRefresh(channelUID, channelId, this);
657 case BRIDGE_DOWNTIME:
658 newState = new DecimalType(
659 thisBridge.lastCommunication() - thisBridge.lastSuccessfulCommunication());
661 case BRIDGE_FIRMWARE:
662 newState = ChannelBridgeFirmware.handleRefresh(channelUID, channelId, this);
665 // delete legacy property name entry (if any) and fall through
666 ThingProperty.setValue(this, VeluxBridgeConfiguration.BRIDGE_IPADDRESS, null);
667 case BRIDGE_SUBNETMASK:
668 case BRIDGE_DEFAULTGW:
670 newState = ChannelBridgeLANconfig.handleRefresh(channelUID, channelId, this);
672 case BRIDGE_WLANSSID:
673 case BRIDGE_WLANPASSWORD:
674 newState = ChannelBridgeWLANconfig.handleRefresh(channelUID, channelId, this);
677 newState = ChannelBridgeScenes.handleRefresh(channelUID, channelId, this);
679 case BRIDGE_PRODUCTS:
680 newState = ChannelBridgeProducts.handleRefresh(channelUID, channelId, this);
683 newState = ChannelBridgeCheck.handleRefresh(channelUID, channelId, this);
686 case ACTUATOR_POSITION:
688 case ROLLERSHUTTER_POSITION:
689 case WINDOW_POSITION:
690 case ROLLERSHUTTER_VANE_POSITION:
691 newState = ChannelActuatorPosition.handleRefresh(channelUID, channelId, this);
693 case ACTUATOR_LIMIT_MINIMUM:
694 case ROLLERSHUTTER_LIMIT_MINIMUM:
695 case WINDOW_LIMIT_MINIMUM:
696 // note: the empty string ("") below is intentional
697 newState = ChannelActuatorLimitation.handleRefresh(channelUID, "", this);
699 case ACTUATOR_LIMIT_MAXIMUM:
700 case ROLLERSHUTTER_LIMIT_MAXIMUM:
701 case WINDOW_LIMIT_MAXIMUM:
702 newState = ChannelActuatorLimitation.handleRefresh(channelUID, channelId, this);
705 // VirtualShutter channels
706 case VSHUTTER_POSITION:
707 newState = ChannelVShutterPosition.handleRefresh(channelUID, channelId, this);
711 logger.warn("{} Cannot handle REFRESH on channel {} as it is of type {}.",
712 VeluxBindingConstants.LOGGING_CONTACT, itemName, channelId);
714 } catch (IllegalArgumentException e) {
715 logger.warn("Cannot handle REFRESH on channel {} as it isn't (yet) known to the bridge.", itemName);
717 if (newState != null) {
718 if (itemType.isChannel()) {
719 logger.debug("handleCommandCommsJob(): updating channel {} to {}.", channelUID, newState);
720 updateState(channelUID, newState);
721 } else if (itemType.isProperty()) {
722 // if property value is 'unknown', null it completely
723 String val = newState.toString();
724 if (VeluxBindingConstants.UNKNOWN.equals(val)) {
727 logger.debug("handleCommandCommsJob(): updating property {} to {}.", channelUID, val);
728 ThingProperty.setValue(this, itemType.getIdentifier(), val);
731 logger.warn("handleCommandCommsJob({},{}): updating of item {} (type {}) failed.",
732 channelUID.getAsString(), command, itemName, itemType);
737 * ===========================================================
740 logger.trace("handleCommandCommsJob(): working on item {} (type {}) with COMMAND {}.", itemName, itemType,
742 Command newValue = null;
743 try { // expecting an IllegalArgumentException for unknown Velux device
747 if (command == OnOffType.ON) {
748 logger.trace("handleCommandCommsJob(): about to reload informations from veluxBridge.");
749 bridgeParamsUpdated();
751 logger.trace("handleCommandCommsJob(): ignoring OFF command.");
754 case BRIDGE_DO_DETECTION:
755 ChannelBridgeDoDetection.handleCommand(channelUID, channelId, command, this);
760 ChannelSceneAction.handleCommand(channelUID, channelId, command, this);
764 * NOTA BENE: Setting of a scene silent mode is no longer supported via the KLF API (i.e. the
765 * GW_SET_NODE_VELOCITY_REQ/CFM command set is no longer supported in the API), so the binding can
766 * no longer explicitly support a Channel with such a function. Therefore the silent mode Channel
767 * type was removed from the binding implementation.
769 * By contrast scene actions can still be called with a silent mode argument, so a silent mode
770 * Configuration Parameter has been introduced as a means for the user to set this argument.
772 * Strictly speaking the following case statement will now never be called, so in theory it,
773 * AND ALL THE CLASSES BEHIND, could be deleted from the binding CODE BASE. But out of prudence
774 * it is retained anyway 'just in case'.
776 case SCENE_SILENTMODE:
777 ChannelSceneSilentmode.handleCommand(channelUID, channelId, command, this);
781 case ACTUATOR_POSITION:
783 case ROLLERSHUTTER_POSITION:
784 case WINDOW_POSITION:
785 case ROLLERSHUTTER_VANE_POSITION:
786 newValue = ChannelActuatorPosition.handleCommand(channelUID, channelId, command, this);
788 case ACTUATOR_LIMIT_MINIMUM:
789 case ROLLERSHUTTER_LIMIT_MINIMUM:
790 case WINDOW_LIMIT_MINIMUM:
791 ChannelActuatorLimitation.handleCommand(channelUID, channelId, command, this);
793 case ACTUATOR_LIMIT_MAXIMUM:
794 case ROLLERSHUTTER_LIMIT_MAXIMUM:
795 case WINDOW_LIMIT_MAXIMUM:
796 ChannelActuatorLimitation.handleCommand(channelUID, channelId, command, this);
799 // VirtualShutter channels
800 case VSHUTTER_POSITION:
801 newValue = ChannelVShutterPosition.handleCommand(channelUID, channelId, command, this);
805 logger.warn("{} Cannot handle command {} on channel {} (type {}).",
806 VeluxBindingConstants.LOGGING_CONTACT, command, itemName, itemType);
808 } catch (IllegalArgumentException e) {
809 logger.warn("Cannot handle command on channel {} as it isn't (yet) known to the bridge.", itemName);
811 if (newValue != null) {
812 postCommand(channelUID, newValue);
815 ThingProperty.setValue(this, VeluxBindingConstants.PROPERTY_BRIDGE_TIMESTAMP_ATTEMPT,
816 new java.util.Date(thisBridge.lastCommunication()).toString());
817 ThingProperty.setValue(this, VeluxBindingConstants.PROPERTY_BRIDGE_TIMESTAMP_SUCCESS,
818 new java.util.Date(thisBridge.lastSuccessfulCommunication()).toString());
819 logger.trace("handleCommandCommsJob({}) done.", Thread.currentThread());
823 * Register the exported actions
826 public Collection<Class<? extends ThingHandlerService>> getServices() {
827 return Set.of(VeluxActions.class);
831 * Exported method (called by an OpenHAB Rules Action) to issue a reboot command to the hub.
833 * @return true if the command could be issued
835 public boolean rebootBridge() {
836 logger.trace("runReboot() called on {}", getThing().getUID());
837 RunReboot bcp = thisBridge.bridgeAPI().runReboot();
839 // background execution of reboot process
840 submitCommunicationsJob(() -> {
841 if (thisBridge.bridgeCommunicate(bcp)) {
842 logger.info("Reboot command {}sucessfully sent to {}", bcp.isCommunicationSuccessful() ? "" : "un",
843 getThing().getUID());
852 * Exported method (called by an OpenHAB Rules Action) to move an actuator relative to its current position
854 * @param nodeId the node to be moved
855 * @param relativePercent relative position change to the current position (-100% <= relativePercent <= +100%)
856 * @return true if the command could be issued
858 public boolean moveRelative(int nodeId, int relativePercent) {
859 logger.trace("moveRelative() called on {}", getThing().getUID());
860 RunProductCommand bcp = thisBridge.bridgeAPI().runProductCommand();
862 // background execution of moveRelative
863 submitCommunicationsJob(() -> {
865 bcp.setNodeIdAndParameters(nodeId,
866 new VeluxProductPosition(new PercentType(Math.abs(relativePercent))).overridePositionType(
867 relativePercent > 0 ? PositionType.OFFSET_POSITIVE : PositionType.OFFSET_NEGATIVE),
869 if (thisBridge.bridgeCommunicate(bcp)) {
870 logger.trace("moveRelative() command {}sucessfully sent to {}",
871 bcp.isCommunicationSuccessful() ? "" : "un", getThing().getUID());
881 * If necessary initialise the communications job executor. Then check if the executor is shut down. And if it is
882 * not shut down, then submit the given communications job for execution.
884 private void submitCommunicationsJob(Runnable communicationsJob) {
885 ExecutorService commsJobExecutor = this.communicationsJobExecutor;
886 if (commsJobExecutor == null) {
887 commsJobExecutor = this.communicationsJobExecutor = Executors.newSingleThreadExecutor(getThreadFactory());
889 if (!commsJobExecutor.isShutdown()) {
890 commsJobExecutor.execute(communicationsJob);
895 * If necessary initialise the thread factory and return it
897 * @return the thread factory
899 public NamedThreadFactory getThreadFactory() {
900 NamedThreadFactory threadFactory = this.threadFactory;
901 if (threadFactory == null) {
902 threadFactory = new NamedThreadFactory(getThing().getUID().getAsString());
904 return threadFactory;
908 * Indicates if the bridge thing is being disposed.
910 * @return true if the bridge thing is being disposed.
912 public boolean isDisposing() {
917 * Exported method (called by an OpenHAB Rules Action) to simultaneously move the shade main position and the vane
920 * @param node the node index in the bridge.
921 * @param mainPosition the desired main position.
922 * @param vanePosition the desired vane position.
923 * @return true if the command could be issued.
925 public Boolean moveMainAndVane(ProductBridgeIndex node, PercentType mainPosition, PercentType vanePosition) {
926 logger.trace("moveMainAndVane() called on {}", getThing().getUID());
927 RunProductCommand bcp = thisBridge.bridgeAPI().runProductCommand();
929 VeluxProduct product = existingProducts().get(node).clone();
930 FunctionalParameters functionalParameters = null;
931 if (product.supportsVanePosition()) {
932 int vanePos = new VeluxProductPosition(vanePosition).getPositionAsVeluxType();
933 product.setVanePosition(vanePos);
934 functionalParameters = product.getFunctionalParameters();
936 VeluxProductPosition mainPos = new VeluxProductPosition(mainPosition);
937 bcp.setNodeIdAndParameters(node.toInt(), mainPos, functionalParameters);
938 submitCommunicationsJob(() -> {
939 if (thisBridge.bridgeCommunicate(bcp)) {
940 logger.trace("moveMainAndVane() command {}sucessfully sent to {}",
941 bcp.isCommunicationSuccessful() ? "" : "un", getThing().getUID());
950 * Get the bridge product index for a given thing name.
952 * @param thingName the thing name
953 * @return the bridge product index or ProductBridgeIndex.UNKNOWN if not found.
955 public ProductBridgeIndex getProductBridgeIndex(String thingName) {
956 for (Entry<ChannelUID, Thing2VeluxActuator> entry : channel2VeluxActuator.entrySet()) {
957 if (thingName.equals(entry.getKey().getThingUID().getAsString())) {
958 return entry.getValue().getProductBridgeIndex();
961 return ProductBridgeIndex.UNKNOWN;
965 * Ask all things in the hub to initialise their dynamic vane position channel if they support it.
967 private void updateDynamicChannels() {
968 getThing().getThings().stream().forEach(thing -> {
969 ThingHandler thingHandler = thing.getHandler();
970 if (thingHandler instanceof VeluxHandler) {
971 ((VeluxHandler) thingHandler).updateDynamicChannels(this);