2 * Copyright (c) 2010-2021 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.mqtt.discovery;
15 import java.util.Date;
17 import java.util.concurrent.ScheduledFuture;
18 import java.util.concurrent.TimeUnit;
20 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.openhab.core.config.discovery.AbstractDiscoveryService;
23 import org.openhab.core.thing.ThingTypeUID;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
28 * Base MQTT discovery class. Responsible for connecting to the {@link MQTTTopicDiscoveryService}.
30 * Implement MQTT discovery services on top of this. You still need to reference
31 * the MQTTTopicDiscoveryService like in:
34 * @NonNullByDefault({})
36 * protected MQTTTopicDiscoveryService mqttTopicDiscovery;
39 * @author David Graeff - Initial contribution
42 public abstract class AbstractMQTTDiscovery extends AbstractDiscoveryService implements MQTTTopicDiscoveryParticipant {
43 private final Logger logger = LoggerFactory.getLogger(AbstractMQTTDiscovery.class);
45 protected final String subscribeTopic;
49 private @Nullable ScheduledFuture<?> scheduledStop;
51 public AbstractMQTTDiscovery(@Nullable Set<ThingTypeUID> supportedThingTypes, int timeout,
52 boolean backgroundDiscoveryEnabledByDefault, String baseTopic) {
53 super(supportedThingTypes, 0, backgroundDiscoveryEnabledByDefault);
54 this.subscribeTopic = baseTopic;
55 this.timeout = timeout;
59 * Return the topic discovery service.
61 protected abstract MQTTTopicDiscoveryService getDiscoveryService();
63 private synchronized void stopTimeout() {
64 if (scheduledStop != null) {
65 scheduledStop.cancel(false);
70 protected synchronized void resetTimeout() {
73 // schedule an automatic call of stopScan when timeout is reached
75 Runnable runnable = new Runnable() {
80 } catch (Exception e) {
81 logger.debug("Exception occurred during execution: {}", e.getMessage(), e);
86 scheduledStop = scheduler.schedule(runnable, timeout, TimeUnit.SECONDS);
91 protected void startScan() {
92 if (isBackgroundDiscoveryEnabled()) {
97 getDiscoveryService().subscribe(this, subscribeTopic);
101 protected synchronized void stopScan() {
102 if (isBackgroundDiscoveryEnabled()) {
107 getDiscoveryService().unsubscribe(this);
112 public synchronized void abortScan() {
118 protected void startBackgroundDiscovery() {
119 // Remove results that are restored after a restart
120 removeOlderResults(new Date().getTime());
121 getDiscoveryService().subscribe(this, subscribeTopic);
125 protected void stopBackgroundDiscovery() {
126 getDiscoveryService().unsubscribe(this);