2 * Copyright (c) 2010-2022 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 Runnable scheduledRunnable = new Runnable() {
53 logger.debug("Running '{}' Plugwise task for {} ({})", name, deviceType, macAddress);
55 } catch (Exception e) {
56 logger.warn("Error while running '{}' Plugwise task for {} ({})", name, deviceType, macAddress, e);
63 public PlugwiseDeviceTask(String name, ScheduledExecutorService scheduler) {
65 this.scheduler = scheduler;
68 public abstract Duration getConfiguredInterval();
70 public @Nullable Duration getInterval() {
74 public String getName() {
78 public boolean isScheduled() {
79 return future != null && !future.isCancelled();
82 public abstract void runTask();
84 public abstract boolean shouldBeScheduled();
90 Duration configuredInterval = getConfiguredInterval();
91 future = scheduler.scheduleWithFixedDelay(scheduledRunnable, 0, configuredInterval.getSeconds(),
93 interval = configuredInterval;
94 logger.debug("Scheduled '{}' Plugwise task for {} ({}) with {} seconds interval", name, deviceType,
95 macAddress, configuredInterval.getSeconds());
106 ScheduledFuture<?> localFuture = future;
107 if (localFuture != null) {
108 localFuture.cancel(true);
111 logger.debug("Stopped '{}' Plugwise task for {} ({})", name, deviceType, macAddress);
118 public void update(DeviceType deviceType, @Nullable MACAddress macAddress) {
119 this.deviceType = deviceType;
120 this.macAddress = macAddress;