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;
16 import java.util.Collections;
18 import java.util.concurrent.ConcurrentHashMap;
19 import java.util.concurrent.ExecutorService;
20 import java.util.concurrent.Executors;
21 import java.util.concurrent.ScheduledFuture;
22 import java.util.concurrent.TimeUnit;
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.openhab.binding.velux.internal.VeluxBinding;
27 import org.openhab.binding.velux.internal.VeluxBindingConstants;
28 import org.openhab.binding.velux.internal.VeluxItemType;
29 import org.openhab.binding.velux.internal.action.VeluxActions;
30 import org.openhab.binding.velux.internal.bridge.VeluxBridge;
31 import org.openhab.binding.velux.internal.bridge.VeluxBridgeActuators;
32 import org.openhab.binding.velux.internal.bridge.VeluxBridgeDeviceStatus;
33 import org.openhab.binding.velux.internal.bridge.VeluxBridgeGetFirmware;
34 import org.openhab.binding.velux.internal.bridge.VeluxBridgeGetHouseStatus;
35 import org.openhab.binding.velux.internal.bridge.VeluxBridgeInstance;
36 import org.openhab.binding.velux.internal.bridge.VeluxBridgeLANConfig;
37 import org.openhab.binding.velux.internal.bridge.VeluxBridgeProvider;
38 import org.openhab.binding.velux.internal.bridge.VeluxBridgeScenes;
39 import org.openhab.binding.velux.internal.bridge.VeluxBridgeSetHouseStatusMonitor;
40 import org.openhab.binding.velux.internal.bridge.VeluxBridgeWLANConfig;
41 import org.openhab.binding.velux.internal.bridge.common.BridgeAPI;
42 import org.openhab.binding.velux.internal.bridge.common.BridgeCommunicationProtocol;
43 import org.openhab.binding.velux.internal.bridge.common.RunProductCommand;
44 import org.openhab.binding.velux.internal.bridge.common.RunReboot;
45 import org.openhab.binding.velux.internal.bridge.json.JsonVeluxBridge;
46 import org.openhab.binding.velux.internal.bridge.slip.SlipVeluxBridge;
47 import org.openhab.binding.velux.internal.config.VeluxBridgeConfiguration;
48 import org.openhab.binding.velux.internal.development.Threads;
49 import org.openhab.binding.velux.internal.factory.VeluxHandlerFactory;
50 import org.openhab.binding.velux.internal.handler.utils.ExtendedBaseBridgeHandler;
51 import org.openhab.binding.velux.internal.handler.utils.Thing2VeluxActuator;
52 import org.openhab.binding.velux.internal.handler.utils.ThingProperty;
53 import org.openhab.binding.velux.internal.things.VeluxExistingProducts;
54 import org.openhab.binding.velux.internal.things.VeluxExistingScenes;
55 import org.openhab.binding.velux.internal.things.VeluxProduct;
56 import org.openhab.binding.velux.internal.things.VeluxProduct.ProductBridgeIndex;
57 import org.openhab.binding.velux.internal.things.VeluxProductPosition;
58 import org.openhab.binding.velux.internal.utils.Localization;
59 import org.openhab.core.common.AbstractUID;
60 import org.openhab.core.common.NamedThreadFactory;
61 import org.openhab.core.library.types.DecimalType;
62 import org.openhab.core.library.types.OnOffType;
63 import org.openhab.core.library.types.PercentType;
64 import org.openhab.core.thing.Bridge;
65 import org.openhab.core.thing.ChannelUID;
66 import org.openhab.core.thing.ThingStatus;
67 import org.openhab.core.thing.ThingStatusDetail;
68 import org.openhab.core.thing.ThingTypeUID;
69 import org.openhab.core.thing.binding.ThingHandlerService;
70 import org.openhab.core.types.Command;
71 import org.openhab.core.types.RefreshType;
72 import org.openhab.core.types.State;
73 import org.openhab.core.types.UnDefType;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
78 * <B>Common interaction with the </B><I>Velux</I><B> bridge.</B>
80 * It implements the communication between <B>OpenHAB</B> and the <I>Velux</I> Bridge:
82 * <LI><B>OpenHAB</B> Event Bus → <I>Velux</I> <B>bridge</B>
84 * Sending commands and value updates.</LI>
87 * <LI><I>Velux</I> <B>bridge</B> → <B>OpenHAB</B>:
89 * Retrieving information by sending a Refresh command.</LI>
92 * Entry point for this class is the method
93 * {@link VeluxBridgeHandler#handleCommand handleCommand}.
95 * @author Guenther Schreiner - Initial contribution.
98 public class VeluxBridgeHandler extends ExtendedBaseBridgeHandler implements VeluxBridgeInstance, VeluxBridgeProvider {
101 * timeout to ensure that the binding shutdown will not block and stall the shutdown of OH itself
103 private static final int COMMUNICATION_TASK_MAX_WAIT_SECS = 10;
106 * a modifier string to avoid the (small) risk of other tasks (outside this binding) locking on the same ip address
107 * Strings.intern() object
110 private static final String LOCK_MODIFIER = "velux.ipaddr.";
112 private final Logger logger = LoggerFactory.getLogger(VeluxBridgeHandler.class);
117 * Scheduler for continuous refresh by scheduleWithFixedDelay.
119 private @Nullable ScheduledFuture<?> refreshSchedulerJob = null;
122 * Counter of refresh invocations by {@link refreshSchedulerJob}.
124 private int refreshCounter = 0;
127 * Dedicated task executor for the long-running bridge communication tasks.
129 * Note: there is no point in using multi threaded thread-pool here, since all the submitted (Runnable) tasks are
130 * anyway forced to go through the same serial pipeline, because they all call the same class level "synchronized"
131 * method to actually communicate with the KLF bridge via its one single TCP socket connection
133 private @Nullable ExecutorService communicationsJobExecutor = null;
134 private @Nullable NamedThreadFactory threadFactory = null;
136 private VeluxBridge myJsonBridge = new JsonVeluxBridge(this);
137 private VeluxBridge mySlipBridge = new SlipVeluxBridge(this);
138 private boolean disposing = false;
141 * **************************************
142 * ***** Default visibility Objects *****
145 VeluxBridge thisBridge = myJsonBridge;
146 public BridgeParameters bridgeParameters = new BridgeParameters();
147 Localization localization;
150 * Mapping from ChannelUID to class Thing2VeluxActuator, which return Velux device information, probably cached.
152 Map<ChannelUID, Thing2VeluxActuator> channel2VeluxActuator = new ConcurrentHashMap<>();
155 * Information retrieved by {@link VeluxBinding#VeluxBinding}.
157 private VeluxBridgeConfiguration veluxBridgeConfiguration = new VeluxBridgeConfiguration();
160 * ************************
161 * ***** Constructors *****
164 public VeluxBridgeHandler(final Bridge bridge, Localization localization) {
166 logger.trace("VeluxBridgeHandler(constructor with bridge={}, localization={}) called.", bridge, localization);
167 this.localization = localization;
168 logger.debug("Creating a VeluxBridgeHandler for thing '{}'.", getThing().getUID());
175 * Set of information retrieved from the bridge/gateway:
178 * <LI>{@link #actuators} - Already known actuators,</LI>
179 * <LI>{@link #scenes} - Already on the gateway defined scenes,</LI>
180 * <LI>{@link #gateway} - Current status of the gateway status,</LI>
181 * <LI>{@link #firmware} - Information about the gateway firmware revision,</LI>
182 * <LI>{@link #lanConfig} - Information about the gateway configuration,</LI>
183 * <LI>{@link #wlanConfig} - Information about the gateway configuration.</LI>
186 public class BridgeParameters {
187 /** Information retrieved by {@link VeluxBridgeActuators#getProducts} */
188 public VeluxBridgeActuators actuators = new VeluxBridgeActuators();
190 /** Information retrieved by {@link org.openhab.binding.velux.internal.bridge.VeluxBridgeScenes#getScenes} */
191 VeluxBridgeScenes scenes = new VeluxBridgeScenes();
193 /** Information retrieved by {@link VeluxBridgeDeviceStatus#retrieve} */
194 VeluxBridgeDeviceStatus.Channel gateway = new VeluxBridgeDeviceStatus().getChannel();
196 /** Information retrieved by {@link VeluxBridgeGetFirmware#retrieve} */
197 VeluxBridgeGetFirmware.Channel firmware = new VeluxBridgeGetFirmware().getChannel();
199 /** Information retrieved by {@link VeluxBridgeLANConfig#retrieve} */
200 VeluxBridgeLANConfig.Channel lanConfig = new VeluxBridgeLANConfig().getChannel();
202 /** Information retrieved by {@link VeluxBridgeWLANConfig#retrieve} */
203 VeluxBridgeWLANConfig.Channel wlanConfig = new VeluxBridgeWLANConfig().getChannel();
209 * Provide the ThingType for a given Channel.
211 * Separated into this private method to deal with the deprecated method.
214 * @param channelUID for type {@link ChannelUID}.
215 * @return thingTypeUID of type {@link ThingTypeUID}.
217 public ThingTypeUID thingTypeUIDOf(ChannelUID channelUID) {
218 String[] segments = channelUID.getAsString().split(AbstractUID.SEPARATOR);
219 if (segments.length > 1) {
220 return new ThingTypeUID(segments[0], segments[1]);
222 logger.warn("thingTypeUIDOf({}) failed.", channelUID);
223 return new ThingTypeUID(VeluxBindingConstants.BINDING_ID, VeluxBindingConstants.UNKNOWN_THING_TYPE_ID);
226 // Objects and Methods for interface VeluxBridgeInstance
229 * Information retrieved by ...
232 public VeluxBridgeConfiguration veluxBridgeConfiguration() {
233 return veluxBridgeConfiguration;
237 * Information retrieved by {@link VeluxBridgeActuators#getProducts}
240 public VeluxExistingProducts existingProducts() {
241 return bridgeParameters.actuators.getChannel().existingProducts;
245 * Information retrieved by {@link VeluxBridgeScenes#getScenes}
248 public VeluxExistingScenes existingScenes() {
249 return bridgeParameters.scenes.getChannel().existingScenes;
252 // Objects and Methods for interface VeluxBridgeProvider *****
255 public boolean bridgeCommunicate(BridgeCommunicationProtocol communication) {
256 logger.warn("bridgeCommunicate() called. Should never be called (as implemented by protocol-specific layers).");
261 public @Nullable BridgeAPI bridgeAPI() {
262 logger.warn("bridgeAPI() called. Should never be called (as implemented by protocol-specific layers).");
266 // Provisioning/Deprovisioning methods *****
269 public void initialize() {
270 // set the thing status to UNKNOWN temporarily and let the background task decide the real status
271 updateStatus(ThingStatus.UNKNOWN);
273 // take care of unusual situations...
274 if (scheduler.isShutdown()) {
275 logger.warn("initialize(): scheduler is shutdown, aborting initialization.");
279 logger.trace("initialize(): initialize bridge configuration parameters.");
280 veluxBridgeConfiguration = new VeluxBinding(getConfigAs(VeluxBridgeConfiguration.class)).checked();
282 scheduler.execute(() -> {
284 initializeSchedulerJob();
289 * Various initialisation actions to be executed on a background thread
291 private void initializeSchedulerJob() {
293 * synchronize disposeSchedulerJob() and initializeSchedulerJob() based an IP address Strings.intern() object to
294 * prevent overlap of initialization and disposal communications towards the same physical bridge
296 synchronized (LOCK_MODIFIER.concat(veluxBridgeConfiguration.ipAddress).intern()) {
297 logger.trace("initializeSchedulerJob(): adopt new bridge configuration parameters.");
298 bridgeParamsUpdated();
300 long mSecs = veluxBridgeConfiguration.refreshMSecs;
301 logger.trace("initializeSchedulerJob(): scheduling refresh at {} milliseconds.", mSecs);
302 refreshSchedulerJob = scheduler.scheduleWithFixedDelay(() -> {
303 refreshSchedulerJob();
304 }, mSecs, mSecs, TimeUnit.MILLISECONDS);
306 VeluxHandlerFactory.refreshBindingInfo();
308 if (logger.isDebugEnabled()) {
309 logger.debug("Velux Bridge '{}' is initialized (with {} scenes and {} actuators).", getThing().getUID(),
310 bridgeParameters.scenes.getChannel().existingScenes.getNoMembers(),
311 bridgeParameters.actuators.getChannel().existingProducts.getNoMembers());
317 public void dispose() {
318 scheduler.submit(() -> {
320 disposeSchedulerJob();
325 * Various disposal actions to be executed on a background thread
327 private void disposeSchedulerJob() {
329 * synchronize disposeSchedulerJob() and initializeSchedulerJob() based an IP address Strings.intern() object to
330 * prevent overlap of initialization and disposal communications towards the same physical bridge
332 synchronized (LOCK_MODIFIER.concat(veluxBridgeConfiguration.ipAddress).intern()) {
334 * cancel the regular refresh polling job
336 ScheduledFuture<?> refreshSchedulerJob = this.refreshSchedulerJob;
337 if (refreshSchedulerJob != null) {
338 logger.trace("disposeSchedulerJob(): cancel the refresh polling job.");
339 refreshSchedulerJob.cancel(false);
342 ExecutorService commsJobExecutor = this.communicationsJobExecutor;
343 if (commsJobExecutor != null) {
344 this.communicationsJobExecutor = null;
345 logger.trace("disposeSchedulerJob(): cancel any other scheduled jobs.");
347 * remove un-started communication tasks from the execution queue; and stop accepting more tasks
349 commsJobExecutor.shutdownNow();
351 * if the last bridge communication was OK, wait for already started task(s) to complete (so the bridge
352 * won't lock up); but to prevent stalling the OH shutdown process, time out after
353 * MAX_COMMUNICATION_TASK_WAIT_TIME_SECS
355 if (thisBridge.lastCommunicationOk()) {
357 if (!commsJobExecutor.awaitTermination(COMMUNICATION_TASK_MAX_WAIT_SECS, TimeUnit.SECONDS)) {
358 logger.warn("disposeSchedulerJob(): unexpected awaitTermination() timeout.");
360 } catch (InterruptedException e) {
361 logger.warn("disposeSchedulerJob(): unexpected exception awaitTermination() '{}'.",
368 * if the last bridge communication was OK, deactivate HSM to prevent queueing more HSM events
370 if (thisBridge.lastCommunicationOk()
371 && (new VeluxBridgeSetHouseStatusMonitor().modifyHSM(thisBridge, false))) {
372 logger.trace("disposeSchedulerJob(): HSM deactivated.");
376 * finally clean up everything else
378 logger.trace("disposeSchedulerJob(): shut down JSON connection interface.");
379 myJsonBridge.shutdown();
380 logger.trace("disposeSchedulerJob(): shut down SLIP connection interface.");
381 mySlipBridge.shutdown();
382 VeluxHandlerFactory.refreshBindingInfo();
383 logger.debug("Velux Bridge '{}' is shut down.", getThing().getUID());
388 * NOTE: It takes care by calling {@link #handleCommand} with the REFRESH command, that every used channel is
392 public void channelLinked(ChannelUID channelUID) {
393 if (thing.getStatus() == ThingStatus.ONLINE) {
394 channel2VeluxActuator.put(channelUID, new Thing2VeluxActuator(this, channelUID));
395 logger.trace("channelLinked({}) refreshing channel value with help of handleCommand as Thing is online.",
396 channelUID.getAsString());
397 handleCommand(channelUID, RefreshType.REFRESH);
399 logger.trace("channelLinked({}) doing nothing as Thing is not online.", channelUID.getAsString());
404 public void channelUnlinked(ChannelUID channelUID) {
405 logger.trace("channelUnlinked({}) called.", channelUID.getAsString());
408 // Reconfiguration methods
410 private void bridgeParamsUpdated() {
411 logger.debug("bridgeParamsUpdated() called.");
413 // Determine the appropriate bridge communication channel
414 boolean validBridgeFound = false;
415 if (myJsonBridge.supportedProtocols.contains(veluxBridgeConfiguration.protocol)) {
416 logger.debug("bridgeParamsUpdated(): choosing JSON as communication method.");
417 thisBridge = myJsonBridge;
418 validBridgeFound = true;
420 if (mySlipBridge.supportedProtocols.contains(veluxBridgeConfiguration.protocol)) {
421 logger.debug("bridgeParamsUpdated(): choosing SLIP as communication method.");
422 thisBridge = mySlipBridge;
423 validBridgeFound = true;
425 if (!validBridgeFound) {
426 logger.debug("No valid protocol selected, aborting this {} binding.", VeluxBindingConstants.BINDING_ID);
427 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
428 "@text/runtime.bridge-offline-no-valid-bridgeProtocol-selected");
429 logger.trace("bridgeParamsUpdated() done.");
433 logger.trace("bridgeParamsUpdated(): Trying to authenticate towards bridge.");
435 if (!thisBridge.bridgeLogin()) {
436 logger.warn("{} bridge login sequence failed; expecting bridge is OFFLINE.",
437 VeluxBindingConstants.BINDING_ID);
438 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
439 "@text/runtime.bridge-offline-login-sequence-failed");
440 logger.trace("bridgeParamsUpdated() done.");
444 logger.trace("bridgeParamsUpdated(): Querying bridge state.");
445 bridgeParameters.gateway = new VeluxBridgeDeviceStatus().retrieve(thisBridge);
447 logger.trace("bridgeParamsUpdated(): Fetching existing scenes.");
448 bridgeParameters.scenes.getScenes(thisBridge);
449 logger.debug("Found Velux scenes:\n\t{}",
450 bridgeParameters.scenes.getChannel().existingScenes.toString(false, "\n\t"));
451 logger.trace("bridgeParamsUpdated(): Fetching existing actuators/products.");
452 bridgeParameters.actuators.getProducts(thisBridge);
453 logger.debug("Found Velux actuators:\n\t{}",
454 bridgeParameters.actuators.getChannel().existingProducts.toString(false, "\n\t"));
456 if (thisBridge.bridgeAPI().setHouseStatusMonitor() != null) {
457 logger.trace("bridgeParamsUpdated(): Activating HouseStatusMonitor.");
458 if (new VeluxBridgeSetHouseStatusMonitor().modifyHSM(thisBridge, true)) {
459 logger.trace("bridgeParamsUpdated(): HSM activated.");
461 logger.warn("Activation of House-Status-Monitoring failed (might lead to a lack of status updates).");
465 veluxBridgeConfiguration.hasChanged = false;
466 logger.debug("Velux veluxBridge is online, now.");
467 updateStatus(ThingStatus.ONLINE);
468 logger.trace("bridgeParamsUpdated() successfully finished.");
471 // Continuous synchronization methods
473 private synchronized void refreshSchedulerJob() {
474 logger.debug("refreshSchedulerJob() initiated by {} starting cycle {}.", Thread.currentThread(),
476 logger.trace("refreshSchedulerJob(): processing of possible HSM messages.");
478 // Background execution of bridge related I/O
479 submitCommunicationsJob(() -> {
480 getHouseStatusCommsJob();
484 "refreshSchedulerJob(): loop through all (child things and bridge) linked channels needing a refresh");
485 for (ChannelUID channelUID : BridgeChannels.getAllLinkedChannelUIDs(this)) {
486 if (VeluxItemType.isToBeRefreshedNow(refreshCounter, thingTypeUIDOf(channelUID), channelUID.getId())) {
487 logger.trace("refreshSchedulerJob(): refreshing channel {}.", channelUID);
488 handleCommand(channelUID, RefreshType.REFRESH);
492 logger.trace("refreshSchedulerJob(): loop through properties needing a refresh");
493 for (VeluxItemType veluxItem : VeluxItemType.getPropertyEntriesByThing(getThing().getThingTypeUID())) {
494 if (VeluxItemType.isToBeRefreshedNow(refreshCounter, getThing().getThingTypeUID(),
495 veluxItem.getIdentifier())) {
496 logger.trace("refreshSchedulerJob(): refreshing property {}.", veluxItem.getIdentifier());
497 handleCommand(new ChannelUID(getThing().getUID(), veluxItem.getIdentifier()), RefreshType.REFRESH);
500 logger.debug("refreshSchedulerJob() initiated by {} finished cycle {}.", Thread.currentThread(),
505 private void getHouseStatusCommsJob() {
506 logger.trace("getHouseStatusCommsJob() initiated by {} will process HouseStatus.", Thread.currentThread());
507 if (new VeluxBridgeGetHouseStatus().evaluateState(thisBridge)) {
508 logger.trace("getHouseStatusCommsJob(): => GetHouseStatus() => updates received => synchronizing");
509 syncChannelsWithProducts();
511 logger.trace("getHouseStatusCommsJob(): => GetHouseStatus() => no updates");
513 logger.trace("getHouseStatusCommsJob() initiated by {} has finished.", Thread.currentThread());
517 * In case of recognized changes in the real world, the method will
518 * update the corresponding states via openHAB event bus.
520 private void syncChannelsWithProducts() {
521 if (!bridgeParameters.actuators.getChannel().existingProducts.isDirty()) {
522 logger.trace("syncChannelsWithProducts(): no existing products with changed parameters.");
525 logger.trace("syncChannelsWithProducts(): there are some existing products with changed parameters.");
526 for (VeluxProduct product : bridgeParameters.actuators.getChannel().existingProducts.valuesOfModified()) {
527 logger.trace("syncChannelsWithProducts(): actuator {} has changed values.", product.getProductName());
528 ProductBridgeIndex productPbi = product.getBridgeProductIndex();
529 logger.trace("syncChannelsWithProducts(): bridge index is {}.", productPbi);
530 for (ChannelUID channelUID : BridgeChannels.getAllLinkedChannelUIDs(this)) {
531 if (!channel2VeluxActuator.containsKey(channelUID)) {
532 logger.trace("syncChannelsWithProducts(): channel {} not found.", channelUID);
535 Thing2VeluxActuator actuator = channel2VeluxActuator.get(channelUID);
536 if (actuator == null || !actuator.isKnown()) {
537 logger.trace("syncChannelsWithProducts(): channel {} not registered on bridge.", channelUID);
540 ProductBridgeIndex channelPbi = actuator.getProductBridgeIndex();
541 if (!channelPbi.equals(productPbi)) {
544 // Handle value inversion
545 boolean isInverted = actuator.isInverted();
546 logger.trace("syncChannelsWithProducts(): isInverted is {}.", isInverted);
547 VeluxProductPosition position = new VeluxProductPosition(product.getDisplayPosition());
548 if (position.isValid()) {
549 PercentType positionAsPercent = position.getPositionAsPercentType(isInverted);
550 logger.debug("syncChannelsWithProducts(): updating channel {} to position {}%.", channelUID,
552 updateState(channelUID, positionAsPercent);
555 logger.trace("syncChannelsWithProducts(): update channel {} to 'UNDEFINED'.", channelUID);
556 updateState(channelUID, UnDefType.UNDEF);
560 logger.trace("syncChannelsWithProducts(): resetting dirty flag.");
561 bridgeParameters.actuators.getChannel().existingProducts.resetDirtyFlag();
562 logger.trace("syncChannelsWithProducts() done.");
565 // Processing of openHAB events
568 public void handleCommand(ChannelUID channelUID, Command command) {
569 logger.trace("handleCommand({}): command {} on channel {} will be scheduled.", Thread.currentThread(), command,
570 channelUID.getAsString());
571 logger.debug("handleCommand({},{}) called.", channelUID.getAsString(), command);
573 // Background execution of bridge related I/O
574 submitCommunicationsJob(() -> {
575 handleCommandCommsJob(channelUID, command);
577 logger.trace("handleCommand({}) done.", Thread.currentThread());
581 * Normally called by {@link #handleCommand} to handle a command for a given channel with possibly long execution
584 * <B>NOTE:</B> This method is to be called as separated thread to ensure proper openHAB framework in parallel.
587 * @param channelUID the {@link ChannelUID} of the channel to which the command was sent,
588 * @param command the {@link Command}.
590 private synchronized void handleCommandCommsJob(ChannelUID channelUID, Command command) {
591 logger.trace("handleCommandCommsJob({}): command {} on channel {}.", Thread.currentThread(), command,
592 channelUID.getAsString());
593 logger.debug("handleCommandCommsJob({},{}) called.", channelUID.getAsString(), command);
596 * ===========================================================
600 if (veluxBridgeConfiguration.isProtocolTraceEnabled) {
601 Threads.findDeadlocked();
604 String channelId = channelUID.getId();
605 State newState = null;
606 String itemName = channelUID.getAsString();
607 VeluxItemType itemType = VeluxItemType.getByThingAndChannel(thingTypeUIDOf(channelUID), channelUID.getId());
609 if (itemType == VeluxItemType.UNKNOWN) {
610 logger.warn("{} Cannot determine type of Channel {}, ignoring command {}.",
611 VeluxBindingConstants.LOGGING_CONTACT, channelUID, command);
612 logger.trace("handleCommandCommsJob() aborting.");
617 if (!channel2VeluxActuator.containsKey(channelUID)) {
618 channel2VeluxActuator.put(channelUID, new Thing2VeluxActuator(this, channelUID));
621 if (veluxBridgeConfiguration.hasChanged) {
622 logger.trace("handleCommandCommsJob(): work on updated bridge configuration parameters.");
623 bridgeParamsUpdated();
626 syncChannelsWithProducts();
628 if (command instanceof RefreshType) {
630 * ===========================================================
633 logger.trace("handleCommandCommsJob(): work on refresh.");
634 if (!itemType.isReadable()) {
635 logger.debug("handleCommandCommsJob(): received a Refresh command for a non-readable item.");
637 logger.trace("handleCommandCommsJob(): refreshing item {} (type {}).", itemName, itemType);
638 try { // expecting an IllegalArgumentException for unknown Velux device
642 newState = ChannelBridgeStatus.handleRefresh(channelUID, channelId, this);
644 case BRIDGE_DOWNTIME:
645 newState = new DecimalType(
646 thisBridge.lastCommunication() - thisBridge.lastSuccessfulCommunication());
648 case BRIDGE_FIRMWARE:
649 newState = ChannelBridgeFirmware.handleRefresh(channelUID, channelId, this);
652 // delete legacy property name entry (if any) and fall through
653 ThingProperty.setValue(this, VeluxBridgeConfiguration.BRIDGE_IPADDRESS, null);
654 case BRIDGE_SUBNETMASK:
655 case BRIDGE_DEFAULTGW:
657 newState = ChannelBridgeLANconfig.handleRefresh(channelUID, channelId, this);
659 case BRIDGE_WLANSSID:
660 case BRIDGE_WLANPASSWORD:
661 newState = ChannelBridgeWLANconfig.handleRefresh(channelUID, channelId, this);
664 newState = ChannelBridgeScenes.handleRefresh(channelUID, channelId, this);
666 case BRIDGE_PRODUCTS:
667 newState = ChannelBridgeProducts.handleRefresh(channelUID, channelId, this);
670 newState = ChannelBridgeCheck.handleRefresh(channelUID, channelId, this);
673 case ACTUATOR_POSITION:
675 case ROLLERSHUTTER_POSITION:
676 case WINDOW_POSITION:
677 newState = ChannelActuatorPosition.handleRefresh(channelUID, channelId, this);
679 case ACTUATOR_LIMIT_MINIMUM:
680 case ROLLERSHUTTER_LIMIT_MINIMUM:
681 case WINDOW_LIMIT_MINIMUM:
682 // note: the empty string ("") below is intentional
683 newState = ChannelActuatorLimitation.handleRefresh(channelUID, "", this);
685 case ACTUATOR_LIMIT_MAXIMUM:
686 case ROLLERSHUTTER_LIMIT_MAXIMUM:
687 case WINDOW_LIMIT_MAXIMUM:
688 newState = ChannelActuatorLimitation.handleRefresh(channelUID, channelId, this);
691 // VirtualShutter channels
692 case VSHUTTER_POSITION:
693 newState = ChannelVShutterPosition.handleRefresh(channelUID, channelId, this);
698 "handleCommandCommsJob(): cannot handle REFRESH on channel {} as it is of type {}.",
699 itemName, channelId);
701 } catch (IllegalArgumentException e) {
702 logger.warn("Cannot handle REFRESH on channel {} as it isn't (yet) known to the bridge.", itemName);
704 if (newState != null) {
705 if (itemType.isChannel()) {
706 logger.debug("handleCommandCommsJob(): updating channel {} to {}.", channelUID, newState);
707 updateState(channelUID, newState);
708 } else if (itemType.isProperty()) {
709 // if property value is 'unknown', null it completely
710 String val = newState.toString();
711 if (VeluxBindingConstants.UNKNOWN.equals(val)) {
714 logger.debug("handleCommandCommsJob(): updating property {} to {}.", channelUID, val);
715 ThingProperty.setValue(this, itemType.getIdentifier(), val);
718 logger.warn("handleCommandCommsJob({},{}): updating of item {} (type {}) failed.",
719 channelUID.getAsString(), command, itemName, itemType);
724 * ===========================================================
727 logger.trace("handleCommandCommsJob(): working on item {} (type {}) with COMMAND {}.", itemName, itemType,
729 Command newValue = null;
730 try { // expecting an IllegalArgumentException for unknown Velux device
734 if (command == OnOffType.ON) {
735 logger.trace("handleCommandCommsJob(): about to reload informations from veluxBridge.");
736 bridgeParamsUpdated();
738 logger.trace("handleCommandCommsJob(): ignoring OFF command.");
741 case BRIDGE_DO_DETECTION:
742 ChannelBridgeDoDetection.handleCommand(channelUID, channelId, command, this);
747 ChannelSceneAction.handleCommand(channelUID, channelId, command, this);
751 * NOTA BENE: Setting of a scene silent mode is no longer supported via the KLF API (i.e. the
752 * GW_SET_NODE_VELOCITY_REQ/CFM command set is no longer supported in the API), so the binding can
753 * no longer explicitly support a Channel with such a function. Therefore the silent mode Channel
754 * type was removed from the binding implementation.
756 * By contrast scene actions can still be called with a silent mode argument, so a silent mode
757 * Configuration Parameter has been introduced as a means for the user to set this argument.
759 * Strictly speaking the following case statement will now never be called, so in theory it,
760 * AND ALL THE CLASSES BEHIND, could be deleted from the binding CODE BASE. But out of prudence
761 * it is retained anyway 'just in case'.
763 case SCENE_SILENTMODE:
764 ChannelSceneSilentmode.handleCommand(channelUID, channelId, command, this);
768 case ACTUATOR_POSITION:
770 case ROLLERSHUTTER_POSITION:
771 case WINDOW_POSITION:
772 newValue = ChannelActuatorPosition.handleCommand(channelUID, channelId, command, this);
774 case ACTUATOR_LIMIT_MINIMUM:
775 case ROLLERSHUTTER_LIMIT_MINIMUM:
776 case WINDOW_LIMIT_MINIMUM:
777 ChannelActuatorLimitation.handleCommand(channelUID, channelId, command, this);
779 case ACTUATOR_LIMIT_MAXIMUM:
780 case ROLLERSHUTTER_LIMIT_MAXIMUM:
781 case WINDOW_LIMIT_MAXIMUM:
782 ChannelActuatorLimitation.handleCommand(channelUID, channelId, command, this);
785 // VirtualShutter channels
786 case VSHUTTER_POSITION:
787 newValue = ChannelVShutterPosition.handleCommand(channelUID, channelId, command, this);
791 logger.warn("{} Cannot handle command {} on channel {} (type {}).",
792 VeluxBindingConstants.LOGGING_CONTACT, command, itemName, itemType);
794 } catch (IllegalArgumentException e) {
795 logger.warn("Cannot handle command on channel {} as it isn't (yet) known to the bridge.", itemName);
797 if (newValue != null) {
798 postCommand(channelUID, newValue);
801 ThingProperty.setValue(this, VeluxBindingConstants.PROPERTY_BRIDGE_TIMESTAMP_ATTEMPT,
802 new java.util.Date(thisBridge.lastCommunication()).toString());
803 ThingProperty.setValue(this, VeluxBindingConstants.PROPERTY_BRIDGE_TIMESTAMP_SUCCESS,
804 new java.util.Date(thisBridge.lastSuccessfulCommunication()).toString());
805 logger.trace("handleCommandCommsJob({}) done.", Thread.currentThread());
809 * Register the exported actions
812 public Collection<Class<? extends ThingHandlerService>> getServices() {
813 return Collections.singletonList(VeluxActions.class);
817 * Exported method (called by an OpenHAB Rules Action) to issue a reboot command to the hub.
819 * @return true if the command could be issued
821 public boolean runReboot() {
822 logger.trace("runReboot() called on {}", getThing().getUID());
823 RunReboot bcp = thisBridge.bridgeAPI().runReboot();
825 // background execution of reboot process
826 submitCommunicationsJob(() -> {
827 if (thisBridge.bridgeCommunicate(bcp)) {
828 logger.info("Reboot command {}sucessfully sent to {}", bcp.isCommunicationSuccessful() ? "" : "un",
829 getThing().getUID());
838 * Exported method (called by an OpenHAB Rules Action) to move an actuator relative to its current position
840 * @param nodeId the node to be moved
841 * @param relativePercent relative position change to the current position (-100% <= relativePercent <= +100%)
842 * @return true if the command could be issued
844 public boolean moveRelative(int nodeId, int relativePercent) {
845 logger.trace("moveRelative() called on {}", getThing().getUID());
846 RunProductCommand bcp = thisBridge.bridgeAPI().runProductCommand();
848 bcp.setNodeAndMainParameter(nodeId, new VeluxProductPosition(new PercentType(Math.abs(relativePercent)))
849 .getAsRelativePosition((relativePercent >= 0)));
850 // background execution of moveRelative
851 submitCommunicationsJob(() -> {
852 if (thisBridge.bridgeCommunicate(bcp)) {
853 logger.trace("moveRelative() command {}sucessfully sent to {}",
854 bcp.isCommunicationSuccessful() ? "" : "un", getThing().getUID());
863 * If necessary initialise the communications job executor. Then check if the executor is shut down. And if it is
864 * not shut down, then submit the given communications job for execution.
866 private void submitCommunicationsJob(Runnable communicationsJob) {
867 ExecutorService commsJobExecutor = this.communicationsJobExecutor;
868 if (commsJobExecutor == null) {
869 commsJobExecutor = this.communicationsJobExecutor = Executors.newSingleThreadExecutor(getThreadFactory());
871 if (!commsJobExecutor.isShutdown()) {
872 commsJobExecutor.execute(communicationsJob);
877 * If necessary initialise the thread factory and return it
879 * @return the thread factory
881 public NamedThreadFactory getThreadFactory() {
882 NamedThreadFactory threadFactory = this.threadFactory;
883 if (threadFactory == null) {
884 threadFactory = new NamedThreadFactory(getThing().getUID().getAsString());
886 return threadFactory;
890 * Indicates if the bridge thing is being disposed.
892 * @return true if the bridge thing is being disposed.
894 public boolean isDisposing() {