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.mihome.internal.handler;
15 import java.util.Timer;
16 import java.util.TimerTask;
18 import org.openhab.core.library.types.DecimalType;
19 import org.openhab.core.thing.Thing;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
24 * The {@link XiaomiSensorBaseHandlerWithTimer} is an abstract class for sensor devices
25 * which use a timer to update a certain channel. The user can configure the timer via an item
28 * @author Dieter Schmidt - Initial contribution
31 public abstract class XiaomiSensorBaseHandlerWithTimer extends XiaomiSensorBaseHandler {
33 private int defaultTimer;
35 private Integer timerSetpoint;
36 private final String setpointChannel;
37 private boolean timerIsRunning;
38 private Timer trigger = new Timer();
40 private final Logger logger = LoggerFactory.getLogger(XiaomiSensorBaseHandlerWithTimer.class);
42 public XiaomiSensorBaseHandlerWithTimer(Thing thing, int defaultTimer, int minTimer, String setpointChannel) {
44 this.defaultTimer = defaultTimer;
45 this.minTimer = minTimer;
46 this.timerSetpoint = defaultTimer;
47 this.setpointChannel = setpointChannel;
50 class TimerAction extends TimerTask {
52 public synchronized void run() {
54 timerIsRunning = false;
58 synchronized void startTimer() {
60 logger.debug("Setting timer to {}s", timerSetpoint);
61 trigger.schedule(new TimerAction(), timerSetpoint * 1000);
62 timerIsRunning = true;
65 synchronized void cancelRunningTimer() {
68 logger.debug("Cancelled running timer");
69 trigger = new Timer();
70 timerIsRunning = false;
74 abstract void onTimer();
76 void setTimerFromDecimalType(DecimalType value) {
78 int newValue = value.intValue();
79 timerSetpoint = newValue < minTimer ? minTimer : newValue;
80 if (timerSetpoint == minTimer) {
81 updateState(setpointChannel, new DecimalType(timerSetpoint));
83 } catch (NumberFormatException e) {
84 logger.debug("Cannot parse the value {} to an Integer", value);
85 timerSetpoint = defaultTimer;