]> git.basschouten.com Git - openhab-addons.git/blob
4ea7a1b212153f524ea7551b839096eb83d4589d
[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.AvailabilityTracker;
23 import org.openhab.binding.mqtt.generic.ChannelStateUpdateListener;
24 import org.openhab.binding.mqtt.generic.values.Value;
25 import org.openhab.core.thing.ChannelUID;
26 import org.openhab.core.types.State;
27
28 /**
29  * A listener to reset the channel value after a timeout.
30  *
31  * @author Jochen Klein - Initial contribution
32  */
33 @NonNullByDefault
34 public class ExpireUpdateStateListener extends ChannelStateUpdateListenerProxy {
35
36     private final int expireAfter;
37     private final Value value;
38     private final AvailabilityTracker tracker;
39     private final ScheduledExecutorService scheduler;
40
41     private final AtomicReference<@Nullable ScheduledFuture<?>> expire = new AtomicReference<>();
42
43     public ExpireUpdateStateListener(ChannelStateUpdateListener original, int expireAfter, Value value,
44             AvailabilityTracker tracker, ScheduledExecutorService scheduler) {
45         super(original);
46         this.expireAfter = expireAfter;
47         this.value = value;
48         this.tracker = tracker;
49         this.scheduler = scheduler;
50     }
51
52     @Override
53     public void updateChannelState(final ChannelUID channelUID, State state) {
54         super.updateChannelState(channelUID, state);
55
56         ScheduledFuture<?> oldExpire = expire.getAndSet(scheduler.schedule(() -> {
57             value.resetState();
58             tracker.resetMessageReceived();
59             ExpireUpdateStateListener.super.updateChannelState(channelUID, value.getChannelState());
60         }, expireAfter, TimeUnit.SECONDS));
61
62         if (oldExpire != null) {
63             oldExpire.cancel(false);
64         }
65     }
66 }