]> git.basschouten.com Git - openhab-addons.git/blob
cc028eaed0c8aa3ac19b4c510e746b088f7dfbf0
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.mqtt.homeassistant.internal.listener;
14
15 import java.util.concurrent.ScheduledExecutorService;
16 import java.util.concurrent.ScheduledFuture;
17 import java.util.concurrent.TimeUnit;
18 import java.util.concurrent.atomic.AtomicReference;
19
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.openhab.binding.mqtt.generic.ChannelStateUpdateListener;
23 import org.openhab.binding.mqtt.generic.values.Value;
24 import org.openhab.core.library.types.OnOffType;
25 import org.openhab.core.thing.ChannelUID;
26 import org.openhab.core.types.State;
27
28 /**
29  * A listener to set the binary sensor value to 'off' after a timeout.
30  *
31  * @author Jochen Klein - Initial contribution
32  */
33 @NonNullByDefault
34 public class OffDelayUpdateStateListener extends ChannelStateUpdateListenerProxy {
35
36     private final int offDelay;
37     private final Value value;
38     private final ScheduledExecutorService scheduler;
39
40     private final AtomicReference<@Nullable ScheduledFuture<?>> delay = new AtomicReference<>();
41
42     public OffDelayUpdateStateListener(ChannelStateUpdateListener original, int offDelay, Value value,
43             ScheduledExecutorService scheduler) {
44         super(original);
45         this.offDelay = offDelay;
46         this.value = value;
47         this.scheduler = scheduler;
48     }
49
50     @Override
51     public void updateChannelState(final ChannelUID channelUID, State state) {
52         super.updateChannelState(channelUID, state);
53
54         ScheduledFuture<?> newDelay = null;
55
56         if (OnOffType.ON == state) {
57             newDelay = scheduler.schedule(() -> {
58                 value.update(OnOffType.OFF);
59                 OffDelayUpdateStateListener.super.updateChannelState(channelUID, value.getChannelState());
60             }, offDelay, TimeUnit.SECONDS);
61         }
62
63         ScheduledFuture<?> oldDelay = delay.getAndSet(newDelay);
64         if (oldDelay != null) {
65             oldDelay.cancel(false);
66         }
67     }
68 }