2 * Copyright (c) 2010-2020 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.ChannelUID;
20 import org.openhab.core.thing.Thing;
21 import org.openhab.core.types.State;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
26 * The {@link XiaomiSensorBaseHandlerWithTimer} is an abstract class for sensor devices
27 * which use a timer to update a certain channel. The user can configure the timer via an item
30 * @author Dieter Schmidt - Initial contribution
33 public abstract class XiaomiSensorBaseHandlerWithTimer extends XiaomiSensorBaseHandler {
35 private int defaultTimer;
37 private Integer timerSetpoint;
38 private final String setpointChannel;
39 private boolean timerIsRunning;
40 private Timer trigger = new Timer();
42 private final Logger logger = LoggerFactory.getLogger(XiaomiSensorBaseHandlerWithTimer.class);
44 public XiaomiSensorBaseHandlerWithTimer(Thing thing, int defaultTimer, int minTimer, String setpointChannel) {
46 this.defaultTimer = defaultTimer;
47 this.minTimer = minTimer;
48 this.timerSetpoint = defaultTimer;
49 this.setpointChannel = setpointChannel;
52 class TimerAction extends TimerTask {
54 public synchronized void run() {
56 timerIsRunning = false;
60 synchronized void startTimer() {
62 logger.debug("Setting timer to {}s", timerSetpoint);
63 trigger.schedule(new TimerAction(), timerSetpoint * 1000);
64 timerIsRunning = true;
67 synchronized void cancelRunningTimer() {
70 logger.debug("Cancelled running timer");
71 trigger = new Timer();
72 timerIsRunning = false;
76 abstract void onTimer();
78 void setTimerFromDecimalType(DecimalType value) {
80 int newValue = value.intValue();
81 timerSetpoint = newValue < minTimer ? minTimer : newValue;
82 if (timerSetpoint == minTimer) {
83 updateState(setpointChannel, new DecimalType(timerSetpoint));
85 } catch (NumberFormatException e) {
86 logger.debug("Cannot parse the value {} to an Integer", value);
87 timerSetpoint = defaultTimer;
92 public void handleUpdate(ChannelUID channelUID, State newState) {
93 if (setpointChannel.equals(channelUID.getId())) {
94 if (newState instanceof DecimalType) {
95 logger.debug("Received update for timer setpoint channel: {}", newState);
96 timerSetpoint = ((DecimalType) newState).intValue();