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.plugwise.internal;
15 import java.time.Duration;
16 import java.util.concurrent.ScheduledExecutorService;
17 import java.util.concurrent.ScheduledFuture;
18 import java.util.concurrent.TimeUnit;
19 import java.util.concurrent.locks.ReentrantLock;
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.openhab.binding.plugwise.internal.protocol.field.DeviceType;
24 import org.openhab.binding.plugwise.internal.protocol.field.MACAddress;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
29 * A recurring Plugwise device task that can for instance be extended for updating a channel or setting the clock.
31 * @author Wouter Born - Initial contribution
34 public abstract class PlugwiseDeviceTask {
36 private final Logger logger = LoggerFactory.getLogger(PlugwiseDeviceTask.class);
38 private final ReentrantLock lock = new ReentrantLock();
39 private final String name;
40 private final ScheduledExecutorService scheduler;
42 private @Nullable DeviceType deviceType;
43 private @Nullable Duration interval;
44 private @Nullable MACAddress macAddress;
46 private @Nullable ScheduledFuture<?> future;
48 private final Runnable scheduledRunnable = () -> {
51 logger.debug("Running '{}' Plugwise task for {} ({})", getName(), deviceType, macAddress);
53 } catch (Exception e) {
54 logger.warn("Error while running '{}' Plugwise task for {} ({})", getName(), deviceType, macAddress, e);
60 protected PlugwiseDeviceTask(String name, ScheduledExecutorService scheduler) {
62 this.scheduler = scheduler;
65 public abstract Duration getConfiguredInterval();
67 public @Nullable Duration getInterval() {
71 public String getName() {
75 public boolean isScheduled() {
76 return future != null && !future.isCancelled();
79 public abstract void runTask();
81 public abstract boolean shouldBeScheduled();
87 Duration configuredInterval = getConfiguredInterval();
88 future = scheduler.scheduleWithFixedDelay(scheduledRunnable, 0, configuredInterval.getSeconds(),
90 interval = configuredInterval;
91 logger.debug("Scheduled '{}' Plugwise task for {} ({}) with {} seconds interval", name, deviceType,
92 macAddress, configuredInterval.getSeconds());
103 ScheduledFuture<?> localFuture = future;
104 if (localFuture != null) {
105 localFuture.cancel(true);
108 logger.debug("Stopped '{}' Plugwise task for {} ({})", name, deviceType, macAddress);
115 public void update(DeviceType deviceType, @Nullable MACAddress macAddress) {
116 this.deviceType = deviceType;
117 this.macAddress = macAddress;