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.jeelink.internal;
15 import java.util.concurrent.ScheduledExecutorService;
16 import java.util.concurrent.ScheduledFuture;
17 import java.util.concurrent.TimeUnit;
19 import org.openhab.binding.jeelink.internal.config.JeeLinkSensorConfig;
20 import org.openhab.core.thing.ChannelUID;
21 import org.openhab.core.thing.Thing;
22 import org.openhab.core.thing.ThingStatus;
23 import org.openhab.core.thing.binding.BaseThingHandler;
24 import org.openhab.core.types.Command;
27 * Abstract thing handler for sensors connected to a JeeLink.
29 * @author Volker Bier - Initial contribution
31 public abstract class JeeLinkSensorHandler<R extends Reading> extends BaseThingHandler implements ReadingHandler<R> {
33 protected final String sensorType;
35 private ReadingPublisher<R> publisher;
36 private long secsSinceLastReading;
37 private ScheduledFuture<?> statusUpdateJob;
39 public JeeLinkSensorHandler(Thing thing, String sensorType) {
41 this.sensorType = sensorType;
44 public abstract ReadingPublisher<R> createPublisher();
47 public String getSensorType() {
52 public void handleReading(R r) {
53 if (r != null && id.equals(r.getSensorId())) {
54 secsSinceLastReading = 0;
55 updateStatus(ThingStatus.ONLINE);
57 if (publisher != null) {
64 public synchronized void handleCommand(ChannelUID channelUid, Command command) {
68 public synchronized void initialize() {
69 JeeLinkHandler jlh = (JeeLinkHandler) getBridge().getHandler();
70 jlh.addReadingHandler(this);
72 JeeLinkSensorConfig cfg = getConfigAs(JeeLinkSensorConfig.class);
75 statusUpdateJob = createStatusUpdateJob(scheduler, cfg.sensorTimeout);
77 publisher = createPublisher();
79 updateStatus(ThingStatus.UNKNOWN);
83 public synchronized void dispose() {
86 JeeLinkHandler jlh = (JeeLinkHandler) getBridge().getHandler();
87 jlh.removeReadingHandler(this);
89 if (statusUpdateJob != null) {
90 statusUpdateJob.cancel(true);
91 statusUpdateJob = null;
94 if (publisher != null) {
102 private ScheduledFuture<?> createStatusUpdateJob(ScheduledExecutorService execService, final int sensorTimeout) {
103 return execService.scheduleWithFixedDelay(() -> {
104 if (secsSinceLastReading++ > sensorTimeout) {
105 updateStatus(ThingStatus.OFFLINE);
107 }, sensorTimeout, 1, TimeUnit.SECONDS);