2 * Copyright (c) 2010-2023 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.mqtt.homeassistant.internal.listener;
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;
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;
29 * A listener to reset the channel value after a timeout.
31 * @author Jochen Klein - Initial contribution
34 public class ExpireUpdateStateListener extends ChannelStateUpdateListenerProxy {
36 private final int expireAfter;
37 private final Value value;
38 private final AvailabilityTracker tracker;
39 private final ScheduledExecutorService scheduler;
41 private final AtomicReference<@Nullable ScheduledFuture<?>> expire = new AtomicReference<>();
43 public ExpireUpdateStateListener(ChannelStateUpdateListener original, int expireAfter, Value value,
44 AvailabilityTracker tracker, ScheduledExecutorService scheduler) {
46 this.expireAfter = expireAfter;
48 this.tracker = tracker;
49 this.scheduler = scheduler;
53 public void updateChannelState(final ChannelUID channelUID, State state) {
54 super.updateChannelState(channelUID, state);
56 ScheduledFuture<?> oldExpire = expire.getAndSet(scheduler.schedule(() -> {
58 tracker.resetMessageReceived();
59 ExpireUpdateStateListener.super.updateChannelState(channelUID, value.getChannelState());
60 }, expireAfter, TimeUnit.SECONDS));
62 if (oldExpire != null) {
63 oldExpire.cancel(false);