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.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;
29 * A listener to set the binary sensor value to 'off' after a timeout.
31 * @author Jochen Klein - Initial contribution
34 public class OffDelayUpdateStateListener extends ChannelStateUpdateListenerProxy {
36 private final int offDelay;
37 private final Value value;
38 private final ScheduledExecutorService scheduler;
40 private final AtomicReference<@Nullable ScheduledFuture<?>> delay = new AtomicReference<>();
42 public OffDelayUpdateStateListener(ChannelStateUpdateListener original, int offDelay, Value value,
43 ScheduledExecutorService scheduler) {
45 this.offDelay = offDelay;
47 this.scheduler = scheduler;
51 public void updateChannelState(final ChannelUID channelUID, State state) {
52 super.updateChannelState(channelUID, state);
54 ScheduledFuture<?> newDelay = null;
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);
63 ScheduledFuture<?> oldDelay = delay.getAndSet(newDelay);
64 if (oldDelay != null) {
65 oldDelay.cancel(false);