diff --git a/bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/AirQualityHandlerFactory.java b/bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/AirQualityHandlerFactory.java index 518a29c2bc138..b6417fff7788c 100644 --- a/bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/AirQualityHandlerFactory.java +++ b/bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/AirQualityHandlerFactory.java @@ -64,7 +64,6 @@ public boolean supportsThingType(ThingTypeUID thingTypeUID) { return THING_TYPE_STATION.equals(thingTypeUID) ? new AirQualityStationHandler(thing, timeZoneProvider, locationProvider) - : BRIDGE_TYPE_API.equals(thingTypeUID) ? new AirQualityBridgeHandler((Bridge) thing, locationProvider) - : null; + : BRIDGE_TYPE_API.equals(thingTypeUID) ? new AirQualityBridgeHandler((Bridge) thing) : null; } } diff --git a/bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/discovery/AirQualityDiscoveryService.java b/bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/discovery/AirQualityDiscoveryService.java index 88ace830cced9..8d971bf55b3f6 100644 --- a/bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/discovery/AirQualityDiscoveryService.java +++ b/bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/discovery/AirQualityDiscoveryService.java @@ -18,18 +18,18 @@ import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.airquality.internal.handler.AirQualityBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.i18n.LocationProvider; import org.openhab.core.library.types.PointType; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -38,40 +38,28 @@ * * @author Gaël L'hopital - Initial Contribution */ -@Component(service = DiscoveryService.class, configurationPid = "discovery.airquality") +@Component(scope = ServiceScope.PROTOTYPE, service = AirQualityDiscoveryService.class, configurationPid = "discovery.airquality") @NonNullByDefault -public class AirQualityDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class AirQualityDiscoveryService extends AbstractThingHandlerDiscoveryService + implements ThingHandlerService { private static final int DISCOVER_TIMEOUT_SECONDS = 2; private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_STATION); private final Logger logger = LoggerFactory.getLogger(AirQualityDiscoveryService.class); - private @Nullable LocationProvider locationProvider; - private @Nullable AirQualityBridgeHandler bridgeHandler; + private @NonNullByDefault({}) LocationProvider locationProvider; /** * Creates an AirQualityDiscoveryService with enabled autostart. */ + @Activate public AirQualityDiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, DISCOVER_TIMEOUT_SECONDS, false); + super(AirQualityBridgeHandler.class, SUPPORTED_THING_TYPES_UIDS, DISCOVER_TIMEOUT_SECONDS, false); } - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof AirQualityBridgeHandler bridgeHandlerInstance) { - this.bridgeHandler = bridgeHandlerInstance; - this.locationProvider = bridgeHandler.getLocationProvider(); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - - @Override - public void deactivate() { - super.deactivate(); + @Reference(unbind = "-") + public void bindLocationProvider(LocationProvider locationProvider) { + this.locationProvider = locationProvider; } @Override @@ -80,7 +68,7 @@ protected void startScan() { LocationProvider provider = locationProvider; if (provider != null) { PointType location = provider.getLocation(); - AirQualityBridgeHandler bridge = this.bridgeHandler; + AirQualityBridgeHandler bridge = this.thingHandler; if (location == null || bridge == null) { logger.info("openHAB server location is not defined, will not provide any discovery results"); return; diff --git a/bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/handler/AirQualityBridgeHandler.java b/bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/handler/AirQualityBridgeHandler.java index ce8d07d77e08c..7fb4697cb8171 100644 --- a/bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/handler/AirQualityBridgeHandler.java +++ b/bundles/org.openhab.binding.airquality/src/main/java/org/openhab/binding/airquality/internal/handler/AirQualityBridgeHandler.java @@ -19,7 +19,6 @@ import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.airquality.internal.api.ApiBridge; import org.openhab.binding.airquality.internal.discovery.AirQualityDiscoveryService; -import org.openhab.core.i18n.LocationProvider; import org.openhab.core.thing.Bridge; import org.openhab.core.thing.ChannelUID; import org.openhab.core.thing.ThingStatus; @@ -36,12 +35,10 @@ */ @NonNullByDefault public class AirQualityBridgeHandler extends BaseBridgeHandler { - private final LocationProvider locationProvider; private @Nullable ApiBridge apiBridge; - public AirQualityBridgeHandler(Bridge bridge, LocationProvider locationProvider) { + public AirQualityBridgeHandler(Bridge bridge) { super(bridge); - this.locationProvider = locationProvider; } @Override @@ -69,8 +66,4 @@ public void handleCommand(ChannelUID channelUID, Command command) { public Collection> getServices() { return Set.of(AirQualityDiscoveryService.class); } - - public LocationProvider getLocationProvider() { - return locationProvider; - } } diff --git a/bundles/org.openhab.binding.alarmdecoder/src/main/java/org/openhab/binding/alarmdecoder/internal/actions/BridgeActions.java b/bundles/org.openhab.binding.alarmdecoder/src/main/java/org/openhab/binding/alarmdecoder/internal/actions/BridgeActions.java index c77f6abc8d448..1a0f03b344a89 100644 --- a/bundles/org.openhab.binding.alarmdecoder/src/main/java/org/openhab/binding/alarmdecoder/internal/actions/BridgeActions.java +++ b/bundles/org.openhab.binding.alarmdecoder/src/main/java/org/openhab/binding/alarmdecoder/internal/actions/BridgeActions.java @@ -20,6 +20,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,6 +30,7 @@ * * @author Bob Adair - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = BridgeActions.class) @ThingActionsScope(name = "alarmdecoder") @NonNullByDefault public class BridgeActions implements ThingActions { diff --git a/bundles/org.openhab.binding.amplipi/src/main/java/org/openhab/binding/amplipi/internal/InputStateOptionProvider.java b/bundles/org.openhab.binding.amplipi/src/main/java/org/openhab/binding/amplipi/internal/InputStateOptionProvider.java index e656f63003fcd..d8861b89b8f6d 100644 --- a/bundles/org.openhab.binding.amplipi/src/main/java/org/openhab/binding/amplipi/internal/InputStateOptionProvider.java +++ b/bundles/org.openhab.binding.amplipi/src/main/java/org/openhab/binding/amplipi/internal/InputStateOptionProvider.java @@ -24,8 +24,11 @@ import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandlerService; import org.openhab.core.thing.type.ChannelTypeUID; +import org.openhab.core.thing.type.DynamicStateDescriptionProvider; import org.openhab.core.types.StateDescription; import org.openhab.core.types.StateOption; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * This class provides the list of valid inputs for the input channel of a source. @@ -33,6 +36,8 @@ * @author Kai Kreuzer - Initial contribution * */ +@Component(scope = ServiceScope.PROTOTYPE, service = { DynamicStateDescriptionProvider.class, + InputStateOptionProvider.class }) @NonNullByDefault public class InputStateOptionProvider extends BaseDynamicStateDescriptionProvider implements ThingHandlerService { diff --git a/bundles/org.openhab.binding.amplipi/src/main/java/org/openhab/binding/amplipi/internal/PresetCommandOptionProvider.java b/bundles/org.openhab.binding.amplipi/src/main/java/org/openhab/binding/amplipi/internal/PresetCommandOptionProvider.java index 70ebdaf9d77ee..40c04fa9a78d5 100644 --- a/bundles/org.openhab.binding.amplipi/src/main/java/org/openhab/binding/amplipi/internal/PresetCommandOptionProvider.java +++ b/bundles/org.openhab.binding.amplipi/src/main/java/org/openhab/binding/amplipi/internal/PresetCommandOptionProvider.java @@ -24,8 +24,11 @@ import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandlerService; import org.openhab.core.thing.type.ChannelTypeUID; +import org.openhab.core.thing.type.DynamicCommandDescriptionProvider; import org.openhab.core.types.CommandDescription; import org.openhab.core.types.CommandOption; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * This class provides the list of valid commands for the preset channel. @@ -33,6 +36,8 @@ * @author Kai Kreuzer - Initial contribution * */ +@Component(scope = ServiceScope.PROTOTYPE, service = { PresetCommandOptionProvider.class, + DynamicCommandDescriptionProvider.class }) @NonNullByDefault public class PresetCommandOptionProvider extends BaseDynamicCommandDescriptionProvider implements ThingHandlerService { diff --git a/bundles/org.openhab.binding.amplipi/src/main/java/org/openhab/binding/amplipi/internal/audio/PAAudioSink.java b/bundles/org.openhab.binding.amplipi/src/main/java/org/openhab/binding/amplipi/internal/audio/PAAudioSink.java index d8aa303d76cfa..80b9ef10f6de1 100644 --- a/bundles/org.openhab.binding.amplipi/src/main/java/org/openhab/binding/amplipi/internal/audio/PAAudioSink.java +++ b/bundles/org.openhab.binding.amplipi/src/main/java/org/openhab/binding/amplipi/internal/audio/PAAudioSink.java @@ -30,6 +30,8 @@ import org.openhab.core.library.types.PercentType; import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,6 +41,7 @@ * @author Kai Kreuzer - Initial contribution * */ +@Component(scope = ServiceScope.PROTOTYPE, service = PAAudioSink.class) @NonNullByDefault public class PAAudioSink extends AudioSinkSync implements ThingHandlerService { diff --git a/bundles/org.openhab.binding.amplipi/src/main/java/org/openhab/binding/amplipi/internal/discovery/AmpliPiZoneAndGroupDiscoveryService.java b/bundles/org.openhab.binding.amplipi/src/main/java/org/openhab/binding/amplipi/internal/discovery/AmpliPiZoneAndGroupDiscoveryService.java index d46f40c0f4dde..112ff917cd6b5 100644 --- a/bundles/org.openhab.binding.amplipi/src/main/java/org/openhab/binding/amplipi/internal/discovery/AmpliPiZoneAndGroupDiscoveryService.java +++ b/bundles/org.openhab.binding.amplipi/src/main/java/org/openhab/binding/amplipi/internal/discovery/AmpliPiZoneAndGroupDiscoveryService.java @@ -16,19 +16,18 @@ import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.amplipi.internal.AmpliPiBindingConstants; import org.openhab.binding.amplipi.internal.AmpliPiHandler; import org.openhab.binding.amplipi.internal.AmpliPiStatusChangeListener; import org.openhab.binding.amplipi.internal.model.Group; import org.openhab.binding.amplipi.internal.model.Status; import org.openhab.binding.amplipi.internal.model.Zone; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * This class discoveres the available zones and groups of the AmpliPi system. @@ -36,30 +35,26 @@ * @author Kai Kreuzer - Initial contribution * */ +@Component(scope = ServiceScope.PROTOTYPE, service = AmpliPiZoneAndGroupDiscoveryService.class) @NonNullByDefault -public class AmpliPiZoneAndGroupDiscoveryService extends AbstractDiscoveryService - implements ThingHandlerService, AmpliPiStatusChangeListener { +public class AmpliPiZoneAndGroupDiscoveryService extends AbstractThingHandlerDiscoveryService + implements AmpliPiStatusChangeListener { private static final int TIMEOUT = 10; - private @Nullable AmpliPiHandler handler; private List zones = List.of(); private List groups = List.of(); public AmpliPiZoneAndGroupDiscoveryService() throws IllegalArgumentException { - super(Set.of(AmpliPiBindingConstants.THING_TYPE_GROUP, AmpliPiBindingConstants.THING_TYPE_ZONE), TIMEOUT, true); + super(AmpliPiHandler.class, + Set.of(AmpliPiBindingConstants.THING_TYPE_GROUP, AmpliPiBindingConstants.THING_TYPE_ZONE), TIMEOUT, + true); } @Override - public void setThingHandler(ThingHandler handler) { - AmpliPiHandler ampliPiHander = (AmpliPiHandler) handler; - ampliPiHander.addStatusChangeListener(this); - this.handler = ampliPiHander; - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return handler; + public void initialize() { + thingHandler.addStatusChangeListener(this); + super.initialize(); } @Override @@ -75,33 +70,27 @@ protected void startScan() { } private void createZone(Zone z) { - if (handler != null) { - ThingUID bridgeUID = handler.getThing().getUID(); - ThingUID uid = new ThingUID(AmpliPiBindingConstants.THING_TYPE_ZONE, bridgeUID, z.getId().toString()); - DiscoveryResult result = DiscoveryResultBuilder.create(uid).withLabel("AmpliPi Zone '" + z.getName() + "'") - .withProperty(AmpliPiBindingConstants.CFG_PARAM_ID, z.getId()).withBridge(bridgeUID) - .withRepresentationProperty(AmpliPiBindingConstants.CFG_PARAM_ID).build(); - thingDiscovered(result); - } + ThingUID bridgeUID = thingHandler.getThing().getUID(); + ThingUID uid = new ThingUID(AmpliPiBindingConstants.THING_TYPE_ZONE, bridgeUID, z.getId().toString()); + DiscoveryResult result = DiscoveryResultBuilder.create(uid).withLabel("AmpliPi Zone '" + z.getName() + "'") + .withProperty(AmpliPiBindingConstants.CFG_PARAM_ID, z.getId()).withBridge(bridgeUID) + .withRepresentationProperty(AmpliPiBindingConstants.CFG_PARAM_ID).build(); + thingDiscovered(result); } private void createGroup(Group g) { - if (handler != null) { - ThingUID bridgeUID = handler.getThing().getUID(); - ThingUID uid = new ThingUID(AmpliPiBindingConstants.THING_TYPE_GROUP, bridgeUID, g.getId().toString()); - DiscoveryResult result = DiscoveryResultBuilder.create(uid).withLabel("AmpliPi Group '" + g.getName() + "'") - .withProperty(AmpliPiBindingConstants.CFG_PARAM_ID, g.getId()).withBridge(bridgeUID) - .withRepresentationProperty(AmpliPiBindingConstants.CFG_PARAM_ID).build(); - thingDiscovered(result); - } + ThingUID bridgeUID = thingHandler.getThing().getUID(); + ThingUID uid = new ThingUID(AmpliPiBindingConstants.THING_TYPE_GROUP, bridgeUID, g.getId().toString()); + DiscoveryResult result = DiscoveryResultBuilder.create(uid).withLabel("AmpliPi Group '" + g.getName() + "'") + .withProperty(AmpliPiBindingConstants.CFG_PARAM_ID, g.getId()).withBridge(bridgeUID) + .withRepresentationProperty(AmpliPiBindingConstants.CFG_PARAM_ID).build(); + thingDiscovered(result); } @Override - public void deactivate() { - if (handler != null) { - handler.removeStatusChangeListener(this); - } - super.deactivate(); + public void dispose() { + super.dispose(); + thingHandler.removeStatusChangeListener(this); } @Override diff --git a/bundles/org.openhab.binding.astro/src/main/java/org/openhab/binding/astro/internal/action/AstroActions.java b/bundles/org.openhab.binding.astro/src/main/java/org/openhab/binding/astro/internal/action/AstroActions.java index 2a897b4764be6..687668763ca0f 100644 --- a/bundles/org.openhab.binding.astro/src/main/java/org/openhab/binding/astro/internal/action/AstroActions.java +++ b/bundles/org.openhab.binding.astro/src/main/java/org/openhab/binding/astro/internal/action/AstroActions.java @@ -31,6 +31,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,6 +41,7 @@ * * @author Gaël L'hopital - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = AstroActions.class) @ThingActionsScope(name = "astro") @NonNullByDefault public class AstroActions implements ThingActions { diff --git a/bundles/org.openhab.binding.asuswrt/src/main/java/org/openhab/binding/asuswrt/internal/AsuswrtDiscoveryService.java b/bundles/org.openhab.binding.asuswrt/src/main/java/org/openhab/binding/asuswrt/internal/AsuswrtDiscoveryService.java index 10d88657ed4e4..e56fd652b8245 100644 --- a/bundles/org.openhab.binding.asuswrt/src/main/java/org/openhab/binding/asuswrt/internal/AsuswrtDiscoveryService.java +++ b/bundles/org.openhab.binding.asuswrt/src/main/java/org/openhab/binding/asuswrt/internal/AsuswrtDiscoveryService.java @@ -21,19 +21,19 @@ import java.util.Map; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.asuswrt.internal.structures.AsuswrtClientInfo; import org.openhab.binding.asuswrt.internal.structures.AsuswrtClientList; import org.openhab.binding.asuswrt.internal.structures.AsuswrtInterfaceList; import org.openhab.binding.asuswrt.internal.structures.AsuswrtIpInfo; import org.openhab.binding.asuswrt.internal.things.AsuswrtRouter; import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,38 +42,27 @@ * * @author Christian Wild - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = AbstractDiscoveryService.class) @NonNullByDefault -public class AsuswrtDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class AsuswrtDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(AsuswrtDiscoveryService.class); private String uid = ""; - protected @NonNullByDefault({}) AsuswrtRouter router; public AsuswrtDiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIMEOUT_S, false); + super(AsuswrtRouter.class, SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIMEOUT_S, false); } @Override - public void activate() { - } - - @Override - public void deactivate() { - super.deactivate(); + public void dispose() { + super.dispose(); removeAllResults(); } @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof AsuswrtRouter router) { - router.setDiscoveryService(this); - this.router = router; - this.uid = router.getUID().getAsString(); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return this.router; + public void initialize() { + thingHandler.setDiscoveryService(this); + uid = thingHandler.getThing().getUID().getAsString(); + super.initialize(); } /* @@ -86,16 +75,14 @@ public void setThingHandler(@Nullable ThingHandler handler) { @Override public void startScan() { logger.trace("{} starting scan", uid); - if (router != null) { - /* query Data */ - router.queryDeviceData(false); - /* discover interfaces */ - AsuswrtInterfaceList ifList = router.getInterfaces(); - handleInterfaceScan(ifList); - /* discover clients */ - AsuswrtClientList clientList = router.getClients(); - handleClientScan(clientList); - } + /* query Data */ + thingHandler.queryDeviceData(false); + /* discover interfaces */ + AsuswrtInterfaceList ifList = thingHandler.getInterfaces(); + handleInterfaceScan(ifList); + /* discover clients */ + AsuswrtClientList clientList = thingHandler.getClients(); + handleClientScan(clientList); } @Override @@ -156,17 +143,12 @@ private DiscoveryResult createInterfaceResult(AsuswrtIpInfo interfaceInfo) { properties.put(Thing.PROPERTY_MAC_ADDRESS, macAddress); logger.debug("{} thing discovered: '{}", uid, label); - if (this.router != null) { - ThingUID bridgeUID = router.getUID(); - ThingUID thingUID = new ThingUID(THING_TYPE_INTERFACE, bridgeUID, ifName); - return DiscoveryResultBuilder.create(thingUID).withProperties(properties) - .withRepresentationProperty(NETWORK_REPRESENTATION_PROPERTY).withBridge(bridgeUID).withLabel(label) - .build(); - } else { - ThingUID thingUID = new ThingUID(BINDING_ID, ifName); - return DiscoveryResultBuilder.create(thingUID).withProperties(properties) - .withRepresentationProperty(NETWORK_REPRESENTATION_PROPERTY).withLabel(label).build(); - } + + ThingUID bridgeUID = thingHandler.getUID(); + ThingUID thingUID = new ThingUID(THING_TYPE_INTERFACE, bridgeUID, ifName); + return DiscoveryResultBuilder.create(thingUID).withProperties(properties) + .withRepresentationProperty(NETWORK_REPRESENTATION_PROPERTY).withBridge(bridgeUID).withLabel(label) + .build(); } /** @@ -196,17 +178,10 @@ private DiscoveryResult createClientResult(AsuswrtClientInfo clientInfo) { properties.put(CHANNEL_CLIENT_NICKNAME, nickName); logger.debug("{} thing discovered: '{}", uid, label); - if (this.router != null) { - ThingUID bridgeUID = router.getUID(); - ThingUID thingUID = new ThingUID(THING_TYPE_CLIENT, bridgeUID, unformatedMac); - return DiscoveryResultBuilder.create(thingUID).withProperties(properties) - .withRepresentationProperty(CLIENT_REPRESENTATION_PROPERTY).withTTL(DISCOVERY_AUTOREMOVE_S) - .withBridge(bridgeUID).withLabel(label).build(); - } else { - ThingUID thingUID = new ThingUID(BINDING_ID, unformatedMac); - return DiscoveryResultBuilder.create(thingUID).withProperties(properties) - .withRepresentationProperty(CLIENT_REPRESENTATION_PROPERTY).withTTL(DISCOVERY_AUTOREMOVE_S) - .withLabel(label).build(); - } + ThingUID bridgeUID = thingHandler.getUID(); + ThingUID thingUID = new ThingUID(THING_TYPE_CLIENT, bridgeUID, unformatedMac); + return DiscoveryResultBuilder.create(thingUID).withProperties(properties) + .withRepresentationProperty(CLIENT_REPRESENTATION_PROPERTY).withTTL(DISCOVERY_AUTOREMOVE_S) + .withBridge(bridgeUID).withLabel(label).build(); } } diff --git a/bundles/org.openhab.binding.automower/src/main/java/org/openhab/binding/automower/internal/actions/AutomowerActions.java b/bundles/org.openhab.binding.automower/src/main/java/org/openhab/binding/automower/internal/actions/AutomowerActions.java index 185ebadce6bc2..b8626e878131c 100644 --- a/bundles/org.openhab.binding.automower/src/main/java/org/openhab/binding/automower/internal/actions/AutomowerActions.java +++ b/bundles/org.openhab.binding.automower/src/main/java/org/openhab/binding/automower/internal/actions/AutomowerActions.java @@ -21,12 +21,15 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Markus Pfleger - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = AutomowerActions.class) @ThingActionsScope(name = "automower") @NonNullByDefault public class AutomowerActions implements ThingActions { diff --git a/bundles/org.openhab.binding.avmfritz/src/main/java/org/openhab/binding/avmfritz/internal/discovery/AVMFritzDiscoveryService.java b/bundles/org.openhab.binding.avmfritz/src/main/java/org/openhab/binding/avmfritz/internal/discovery/AVMFritzDiscoveryService.java index 0bb02caf5fe4f..de4c541b5863e 100644 --- a/bundles/org.openhab.binding.avmfritz/src/main/java/org/openhab/binding/avmfritz/internal/discovery/AVMFritzDiscoveryService.java +++ b/bundles/org.openhab.binding.avmfritz/src/main/java/org/openhab/binding/avmfritz/internal/discovery/AVMFritzDiscoveryService.java @@ -22,19 +22,18 @@ import java.util.stream.Stream; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.avmfritz.internal.dto.AVMFritzBaseModel; import org.openhab.binding.avmfritz.internal.dto.GroupModel; import org.openhab.binding.avmfritz.internal.handler.AVMFritzBaseBridgeHandler; import org.openhab.binding.avmfritz.internal.hardware.FritzAhaStatusListener; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,66 +43,50 @@ * @author Robert Bausdorf - Initial contribution * @author Christoph Weitkamp - Added support for groups */ +@Component(scope = ServiceScope.PROTOTYPE, service = AVMFritzDiscoveryService.class) @NonNullByDefault -public class AVMFritzDiscoveryService extends AbstractDiscoveryService - implements FritzAhaStatusListener, DiscoveryService, ThingHandlerService { - +public class AVMFritzDiscoveryService extends AbstractThingHandlerDiscoveryService + implements FritzAhaStatusListener, DiscoveryService { private final Logger logger = LoggerFactory.getLogger(AVMFritzDiscoveryService.class); - /** - * Handler of the bridge of which devices have to be discovered. - */ - private @NonNullByDefault({}) AVMFritzBaseBridgeHandler bridgeHandler; public AVMFritzDiscoveryService() { - super(Stream + super(AVMFritzBaseBridgeHandler.class, Stream .of(SUPPORTED_LIGHTING_THING_TYPES, SUPPORTED_BUTTON_THING_TYPES_UIDS, SUPPORTED_HEATING_THING_TYPES, SUPPORTED_DEVICE_THING_TYPES_UIDS, SUPPORTED_GROUP_THING_TYPES_UIDS) .flatMap(Set::stream).collect(Collectors.toUnmodifiableSet()), 30); } @Override - public void activate() { - super.activate(null); - bridgeHandler.registerStatusListener(this); + public void initialize() { + thingHandler.registerStatusListener(this); + super.initialize(); } @Override - public void deactivate() { - bridgeHandler.unregisterStatusListener(this); - super.deactivate(); + public void dispose() { + super.dispose(); + thingHandler.unregisterStatusListener(this); } @Override public void startScan() { - logger.debug("Start manual scan on bridge {}", bridgeHandler.getThing().getUID()); - bridgeHandler.handleRefreshCommand(); + logger.debug("Start manual scan on bridge {}", thingHandler.getThing().getUID()); + thingHandler.handleRefreshCommand(); } @Override protected synchronized void stopScan() { - logger.debug("Stop manual scan on bridge {}", bridgeHandler.getThing().getUID()); + logger.debug("Stop manual scan on bridge {}", thingHandler.getThing().getUID()); super.stopScan(); } - @Override - public void setThingHandler(@NonNullByDefault({}) ThingHandler handler) { - if (handler instanceof AVMFritzBaseBridgeHandler baseBridgeHandler) { - bridgeHandler = baseBridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - @Override public void onDeviceAdded(AVMFritzBaseModel device) { - String id = bridgeHandler.getThingTypeId(device); + String id = thingHandler.getThingTypeId(device); ThingTypeUID thingTypeUID = id.isEmpty() ? null : new ThingTypeUID(BINDING_ID, id); if (thingTypeUID != null && getSupportedThingTypes().contains(thingTypeUID)) { - ThingUID thingUID = new ThingUID(thingTypeUID, bridgeHandler.getThing().getUID(), - bridgeHandler.getThingName(device)); + ThingUID thingUID = new ThingUID(thingTypeUID, thingHandler.getThing().getUID(), + thingHandler.getThingName(device)); onDeviceAddedInternal(thingUID, device); } else { logger.debug("Discovered unsupported device: {}", device); @@ -134,7 +117,7 @@ private void onDeviceAddedInternal(ThingUID thingUID, AVMFritzBaseModel device) } DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withProperties(properties) - .withRepresentationProperty(CONFIG_AIN).withBridge(bridgeHandler.getThing().getUID()) + .withRepresentationProperty(CONFIG_AIN).withBridge(thingHandler.getThing().getUID()) .withLabel(device.getName()).build(); thingDiscovered(discoveryResult); diff --git a/bundles/org.openhab.binding.bondhome/src/main/java/org/openhab/binding/bondhome/internal/discovery/BondDiscoveryService.java b/bundles/org.openhab.binding.bondhome/src/main/java/org/openhab/binding/bondhome/internal/discovery/BondDiscoveryService.java index 9e1c4b4c9497c..65c01f941b1ff 100644 --- a/bundles/org.openhab.binding.bondhome/src/main/java/org/openhab/binding/bondhome/internal/discovery/BondDiscoveryService.java +++ b/bundles/org.openhab.binding.bondhome/src/main/java/org/openhab/binding/bondhome/internal/discovery/BondDiscoveryService.java @@ -24,12 +24,12 @@ import org.openhab.binding.bondhome.internal.api.BondDevice; import org.openhab.binding.bondhome.internal.api.BondHttpApi; import org.openhab.binding.bondhome.internal.handler.BondBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -38,36 +38,24 @@ * * @author Sara Geleskie Damiano - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = BondDiscoveryService.class) @NonNullByDefault -public class BondDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class BondDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final long REFRESH_INTERVAL_MINUTES = 60; private final Logger logger = LoggerFactory.getLogger(BondDiscoveryService.class); private @Nullable ScheduledFuture discoveryJob; - private @Nullable BondBridgeHandler bridgeHandler; private @Nullable BondHttpApi api; public BondDiscoveryService() { - super(SUPPORTED_THING_TYPES, 10); + super(BondBridgeHandler.class, SUPPORTED_THING_TYPES, 10); this.discoveryJob = null; } @Override - public void deactivate() { - super.deactivate(); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof BondBridgeHandler localHandler) { - bridgeHandler = localHandler; - localHandler.setDiscoveryService(this); - api = localHandler.getBridgeAPI(); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; + public void initialize() { + thingHandler.setDiscoveryService(this); + api = thingHandler.getBridgeAPI(); + super.initialize(); } @Override @@ -87,6 +75,7 @@ public synchronized void discoverNow() { protected synchronized void startScan() { logger.debug("Start scan for Bond devices."); try { + BondBridgeHandler bridgeHandler = thingHandler; final ThingUID bridgeUid = bridgeHandler.getThing().getUID(); api = bridgeHandler.getBridgeAPI(); List deviceList = api.getDevices(); diff --git a/bundles/org.openhab.binding.boschindego/src/main/java/org/openhab/binding/boschindego/internal/discovery/IndegoDiscoveryService.java b/bundles/org.openhab.binding.boschindego/src/main/java/org/openhab/binding/boschindego/internal/discovery/IndegoDiscoveryService.java index eb5b4305ebc3a..ecdbcd6b9d093 100644 --- a/bundles/org.openhab.binding.boschindego/src/main/java/org/openhab/binding/boschindego/internal/discovery/IndegoDiscoveryService.java +++ b/bundles/org.openhab.binding.boschindego/src/main/java/org/openhab/binding/boschindego/internal/discovery/IndegoDiscoveryService.java @@ -19,19 +19,18 @@ import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.boschindego.internal.IndegoTypeDatabase; import org.openhab.binding.boschindego.internal.dto.response.DevicePropertiesResponse; import org.openhab.binding.boschindego.internal.exceptions.IndegoException; import org.openhab.binding.boschindego.internal.handler.BoschAccountHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,29 +39,15 @@ * * @author Jacob Laursen - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = IndegoDiscoveryService.class) @NonNullByDefault -public class IndegoDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { - +public class IndegoDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int TIMEOUT_SECONDS = 60; private final Logger logger = LoggerFactory.getLogger(IndegoDiscoveryService.class); - private @NonNullByDefault({}) BoschAccountHandler accountHandler; - public IndegoDiscoveryService() { - super(Set.of(THING_TYPE_ACCOUNT), TIMEOUT_SECONDS, false); - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return accountHandler; - } - - @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof BoschAccountHandler accountHandler) { - this.accountHandler = accountHandler; - } + super(BoschAccountHandler.class, Set.of(THING_TYPE_ACCOUNT), TIMEOUT_SECONDS, false); } @Override @@ -73,9 +58,9 @@ public Set getSupportedThingTypes() { @Override public void startScan() { try { - Collection devices = accountHandler.getDevices(); + Collection devices = thingHandler.getDevices(); - ThingUID bridgeUID = accountHandler.getThing().getUID(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); for (DevicePropertiesResponse device : devices) { ThingUID thingUID = new ThingUID(THING_TYPE_INDEGO, bridgeUID, device.serialNumber); DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID) @@ -97,7 +82,8 @@ protected synchronized void stopScan() { } @Override - public void deactivate() { + public void dispose() { + super.dispose(); removeOlderResults(Instant.now().getEpochSecond()); } } diff --git a/bundles/org.openhab.binding.boschshc/src/main/java/org/openhab/binding/boschshc/internal/discovery/ThingDiscoveryService.java b/bundles/org.openhab.binding.boschshc/src/main/java/org/openhab/binding/boschshc/internal/discovery/ThingDiscoveryService.java index 4ab52ba6802ae..aab73ed725d24 100644 --- a/bundles/org.openhab.binding.boschshc/src/main/java/org/openhab/binding/boschshc/internal/discovery/ThingDiscoveryService.java +++ b/bundles/org.openhab.binding.boschshc/src/main/java/org/openhab/binding/boschshc/internal/discovery/ThingDiscoveryService.java @@ -25,12 +25,13 @@ import org.openhab.binding.boschshc.internal.devices.bridge.dto.Device; import org.openhab.binding.boschshc.internal.devices.bridge.dto.Room; import org.openhab.binding.boschshc.internal.devices.bridge.dto.UserDefinedState; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -48,12 +49,12 @@ * * @author Gerd Zanker - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = ThingHandlerService.class) @NonNullByDefault -public class ThingDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class ThingDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int SEARCH_TIME = 1; private final Logger logger = LoggerFactory.getLogger(ThingDiscoveryService.class); - private @Nullable BridgeHandler shcBridgeHandler; protected static final Set SUPPORTED_THING_TYPES = Set.of( BoschSHCBindingConstants.THING_TYPE_INWALL_SWITCH, BoschSHCBindingConstants.THING_TYPE_TWINGUARD, @@ -97,37 +98,28 @@ public class ThingDiscoveryService extends AbstractDiscoveryService implements T // @formatter:on public ThingDiscoveryService() { - super(SUPPORTED_THING_TYPES, SEARCH_TIME); + super(BridgeHandler.class, SUPPORTED_THING_TYPES, SEARCH_TIME); } @Override - public void activate() { - logger.trace("activate"); - final BridgeHandler handler = shcBridgeHandler; - if (handler != null) { - handler.registerDiscoveryListener(this); - } + public void initialize() { + logger.trace("initialize"); + thingHandler.registerDiscoveryListener(this); + super.initialize(); } @Override - public void deactivate() { - logger.trace("deactivate"); - final BridgeHandler handler = shcBridgeHandler; - if (handler != null) { - removeOlderResults(new Date().getTime(), handler.getThing().getUID()); - handler.unregisterDiscoveryListener(); - } + public void dispose() { + super.dispose(); + logger.trace("dispose"); + removeOlderResults(new Date().getTime(), thingHandler.getThing().getUID()); + thingHandler.unregisterDiscoveryListener(); super.deactivate(); } @Override protected void startScan() { - if (shcBridgeHandler == null) { - logger.debug("The shcBridgeHandler is empty, no manual scan is currently possible"); - return; - } - try { doScan(); } catch (InterruptedException e) { @@ -138,36 +130,19 @@ protected void startScan() { @Override protected synchronized void stopScan() { - logger.debug("Stop manual scan on bridge {}", - shcBridgeHandler != null ? shcBridgeHandler.getThing().getUID() : "?"); + logger.debug("Stop manual scan on bridge {}", thingHandler.getThing().getUID()); super.stopScan(); - final BridgeHandler handler = shcBridgeHandler; - if (handler != null) { - removeOlderResults(getTimestampOfLastScan(), handler.getThing().getUID()); - } - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof BridgeHandler bridgeHandler) { - logger.trace("Set bridge handler {}", handler); - shcBridgeHandler = bridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return shcBridgeHandler; + removeOlderResults(getTimestampOfLastScan(), thingHandler.getThing().getUID()); } public void doScan() throws InterruptedException { - logger.debug("Start manual scan on bridge {}", shcBridgeHandler.getThing().getUID()); + logger.debug("Start manual scan on bridge {}", thingHandler.getThing().getUID()); // use shcBridgeHandler to getDevices() - List rooms = shcBridgeHandler.getRooms(); + List rooms = thingHandler.getRooms(); logger.debug("SHC has {} rooms", rooms.size()); - List devices = shcBridgeHandler.getDevices(); + List devices = thingHandler.getDevices(); logger.debug("SHC has {} devices", devices.size()); - List userStates = shcBridgeHandler.getUserStates(); + List userStates = thingHandler.getUserStates(); logger.debug("SHC has {} user-defined states", userStates.size()); // Write found devices into openhab.log to support manual configuration @@ -195,9 +170,6 @@ protected void addUserStates(List userStates) { } private void addUserState(UserDefinedState userState) { - // see startScan for the runtime null check of shcBridgeHandler - assert shcBridgeHandler != null; - logger.trace("Discovering user-defined state {}", userState.getName()); logger.trace("- details: id {}, state {}", userState.getId(), userState.isState()); @@ -206,7 +178,7 @@ private void addUserState(UserDefinedState userState) { logger.trace("- got thingTypeID '{}' for user-defined state '{}'", thingTypeUID.getId(), userState.getName()); - ThingUID thingUID = new ThingUID(thingTypeUID, shcBridgeHandler.getThing().getUID(), + ThingUID thingUID = new ThingUID(thingTypeUID, thingHandler.getThing().getUID(), userState.getId().replace(':', '_')); logger.trace("- got thingUID '{}' for user-defined state: '{}'", thingUID, userState); @@ -214,7 +186,7 @@ private void addUserState(UserDefinedState userState) { DiscoveryResultBuilder discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID) .withProperty("id", userState.getId()).withLabel(userState.getName()); - discoveryResult.withBridge(shcBridgeHandler.getThing().getUID()); + discoveryResult.withBridge(thingHandler.getThing().getUID()); thingDiscovered(discoveryResult.build()); @@ -234,8 +206,6 @@ protected String getRoomNameForDevice(Device device, List rooms) { protected void addDevice(Device device, String roomName) { // see startScan for the runtime null check of shcBridgeHandler - assert shcBridgeHandler != null; - logger.trace("Discovering device {}", device.name); logger.trace("- details: id {}, roomId {}, deviceModel {}", device.id, device.roomId, device.deviceModel); @@ -246,16 +216,13 @@ protected void addDevice(Device device, String roomName) { logger.trace("- got thingTypeID '{}' for deviceModel '{}'", thingTypeUID.getId(), device.deviceModel); - ThingUID thingUID = new ThingUID(thingTypeUID, shcBridgeHandler.getThing().getUID(), - device.id.replace(':', '_')); + ThingUID thingUID = new ThingUID(thingTypeUID, thingHandler.getThing().getUID(), device.id.replace(':', '_')); logger.trace("- got thingUID '{}' for device: '{}'", thingUID, device); DiscoveryResultBuilder discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID) .withProperty("id", device.id).withLabel(getNiceName(device.name, roomName)); - if (null != shcBridgeHandler) { - discoveryResult.withBridge(shcBridgeHandler.getThing().getUID()); - } + discoveryResult.withBridge(thingHandler.getThing().getUID()); if (!roomName.isEmpty()) { discoveryResult.withProperty("Location", roomName); } diff --git a/bundles/org.openhab.binding.bticinosmarther/src/main/java/org/openhab/binding/bticinosmarther/internal/discovery/SmartherModuleDiscoveryService.java b/bundles/org.openhab.binding.bticinosmarther/src/main/java/org/openhab/binding/bticinosmarther/internal/discovery/SmartherModuleDiscoveryService.java index bb58bc316eb3b..6cff33630d98d 100644 --- a/bundles/org.openhab.binding.bticinosmarther/src/main/java/org/openhab/binding/bticinosmarther/internal/discovery/SmartherModuleDiscoveryService.java +++ b/bundles/org.openhab.binding.bticinosmarther/src/main/java/org/openhab/binding/bticinosmarther/internal/discovery/SmartherModuleDiscoveryService.java @@ -24,14 +24,14 @@ import org.openhab.binding.bticinosmarther.internal.account.SmartherAccountHandler; import org.openhab.binding.bticinosmarther.internal.api.dto.Location; import org.openhab.binding.bticinosmarther.internal.api.dto.Module; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,9 +41,9 @@ * * @author Fabio Possieri - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = SmartherModuleDiscoveryService.class) @NonNullByDefault -public class SmartherModuleDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { +public class SmartherModuleDiscoveryService extends AbstractThingHandlerDiscoveryService { // Only modules can be discovered. A bridge must be manually added. private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_MODULE); @@ -54,14 +54,13 @@ public class SmartherModuleDiscoveryService extends AbstractDiscoveryService private final Logger logger = LoggerFactory.getLogger(SmartherModuleDiscoveryService.class); - private @Nullable SmartherAccountHandler bridgeHandler; private @Nullable ThingUID bridgeUID; /** * Constructs a {@code SmartherModuleDiscoveryService}. */ public SmartherModuleDiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIME_SECONDS); + super(SmartherAccountHandler.class, SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIME_SECONDS); } @Override @@ -71,29 +70,23 @@ public Set getSupportedThingTypes() { @Override public void activate() { - logger.debug("Bridge[{}] Activating chronothermostat discovery service", this.bridgeUID); Map properties = new HashMap<>(); properties.put(DiscoveryService.CONFIG_PROPERTY_BACKGROUND_DISCOVERY, Boolean.TRUE); super.activate(properties); } @Override - public void deactivate() { - logger.debug("Bridge[{}] Deactivating chronothermostat discovery service", this.bridgeUID); - removeOlderResults(new Date().getTime()); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof SmartherAccountHandler localBridgeHandler) { - this.bridgeHandler = localBridgeHandler; - this.bridgeUID = localBridgeHandler.getUID(); - } + public void initialize() { + logger.debug("Bridge[{}] Activating chronothermostat discovery service", this.bridgeUID); + this.bridgeUID = thingHandler.getThing().getUID(); + super.initialize(); } @Override - public @Nullable ThingHandler getThingHandler() { - return this.bridgeHandler; + public void dispose() { + super.dispose(); + logger.debug("Bridge[{}] Deactivating chronothermostat discovery service", this.bridgeUID); + removeOlderResults(new Date().getTime()); } @Override @@ -123,13 +116,10 @@ protected synchronized void stopScan() { * Discovers Chronothermostat devices for the given bridge handler. */ private synchronized void discoverChronothermostats() { - final SmartherAccountHandler localBridgeHandler = this.bridgeHandler; - if (localBridgeHandler != null) { - // If the bridge is not online no other thing devices can be found, so no reason to scan at this moment - if (localBridgeHandler.isOnline()) { - localBridgeHandler.getLocations() - .forEach(l -> localBridgeHandler.getLocationModules(l).forEach(m -> addDiscoveredDevice(l, m))); - } + // If the bridge is not online no other thing devices can be found, so no reason to scan at this moment + if (thingHandler.isOnline()) { + thingHandler.getLocations() + .forEach(l -> thingHandler.getLocationModules(l).forEach(m -> addDiscoveredDevice(l, m))); } } diff --git a/bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/action/CaddxBridgeActions.java b/bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/action/CaddxBridgeActions.java index ee0b115587f9d..de7e751d32f4e 100644 --- a/bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/action/CaddxBridgeActions.java +++ b/bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/action/CaddxBridgeActions.java @@ -19,6 +19,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,6 +30,7 @@ * * @author Georgios Moutsos - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = CaddxBridgeActions.class) @ThingActionsScope(name = "caddx") @NonNullByDefault public class CaddxBridgeActions implements ThingActions { diff --git a/bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/action/CaddxKeypadActions.java b/bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/action/CaddxKeypadActions.java index e080663fefa08..bebc0e66de791 100644 --- a/bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/action/CaddxKeypadActions.java +++ b/bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/action/CaddxKeypadActions.java @@ -20,6 +20,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -29,6 +31,7 @@ * * @author Georgios Moutsos - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = CaddxKeypadActions.class) @ThingActionsScope(name = "caddx") @NonNullByDefault public class CaddxKeypadActions implements ThingActions { diff --git a/bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/action/CaddxPanelActions.java b/bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/action/CaddxPanelActions.java index b428cee4c4d6c..969728df37c96 100644 --- a/bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/action/CaddxPanelActions.java +++ b/bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/action/CaddxPanelActions.java @@ -20,6 +20,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -29,6 +31,7 @@ * * @author Georgios Moutsos - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = CaddxPanelActions.class) @ThingActionsScope(name = "caddx") @NonNullByDefault public class CaddxPanelActions implements ThingActions { diff --git a/bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/discovery/CaddxDiscoveryService.java b/bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/discovery/CaddxDiscoveryService.java index 0ef08974aadf4..b136f054430b0 100644 --- a/bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/discovery/CaddxDiscoveryService.java +++ b/bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/discovery/CaddxDiscoveryService.java @@ -15,7 +15,6 @@ import java.util.Map; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.caddx.internal.CaddxBindingConstants; import org.openhab.binding.caddx.internal.CaddxEvent; import org.openhab.binding.caddx.internal.config.CaddxKeypadConfiguration; @@ -23,14 +22,13 @@ import org.openhab.binding.caddx.internal.config.CaddxZoneConfiguration; import org.openhab.binding.caddx.internal.handler.CaddxBridgeHandler; import org.openhab.binding.caddx.internal.handler.CaddxThingType; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.Bridge; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,14 +37,13 @@ * * @author Georgios Moutsos - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = CaddxDiscoveryService.class) @NonNullByDefault -public class CaddxDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService, DiscoveryService { +public class CaddxDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(CaddxDiscoveryService.class); - private @Nullable CaddxBridgeHandler caddxBridgeHandler = null; - public CaddxDiscoveryService() { - super(CaddxBindingConstants.SUPPORTED_THING_TYPES_UIDS, 15, false); + super(CaddxBridgeHandler.class, CaddxBindingConstants.SUPPORTED_THING_TYPES_UIDS, 15, false); } @Override @@ -133,33 +130,17 @@ public void addThing(Bridge bridge, CaddxThingType caddxThingType, CaddxEvent ev * Activates the Discovery Service. */ @Override - public void activate() { - CaddxBridgeHandler handler = caddxBridgeHandler; - if (handler != null) { - handler.registerDiscoveryService(this); - } + public void initialize() { + thingHandler.registerDiscoveryService(this); + super.initialize(); } /** * Deactivates the Discovery Service. */ @Override - public void deactivate() { - CaddxBridgeHandler handler = caddxBridgeHandler; - if (handler != null) { - handler.unregisterDiscoveryService(); - } - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof CaddxBridgeHandler bridgeHandler) { - caddxBridgeHandler = bridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return caddxBridgeHandler; + public void dispose() { + super.dispose(); + thingHandler.unregisterDiscoveryService(); } } diff --git a/bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/handler/CaddxBridgeHandler.java b/bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/handler/CaddxBridgeHandler.java index 696742d702f15..b94082b6cf536 100644 --- a/bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/handler/CaddxBridgeHandler.java +++ b/bundles/org.openhab.binding.caddx/src/main/java/org/openhab/binding/caddx/internal/handler/CaddxBridgeHandler.java @@ -17,7 +17,6 @@ import java.io.IOException; import java.math.BigDecimal; import java.util.Collection; -import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TooManyListenersException; @@ -451,10 +450,7 @@ public void childHandlerDisposed(ThingHandler childHandler, Thing childThing) { @Override public Collection> getServices() { - Set> set = new HashSet>(2); - set.add(CaddxDiscoveryService.class); - set.add(CaddxBridgeActions.class); - return set; + return Set.of(CaddxBridgeActions.class, CaddxDiscoveryService.class); } public void restart() { diff --git a/bundles/org.openhab.binding.chatgpt/src/main/java/org/openhab/binding/chatgpt/internal/ChatGPTModelOptionProvider.java b/bundles/org.openhab.binding.chatgpt/src/main/java/org/openhab/binding/chatgpt/internal/ChatGPTModelOptionProvider.java index e09ac285be359..fd6c1ec2d6fb9 100644 --- a/bundles/org.openhab.binding.chatgpt/src/main/java/org/openhab/binding/chatgpt/internal/ChatGPTModelOptionProvider.java +++ b/bundles/org.openhab.binding.chatgpt/src/main/java/org/openhab/binding/chatgpt/internal/ChatGPTModelOptionProvider.java @@ -26,6 +26,8 @@ import org.openhab.core.config.core.ParameterOption; import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * The {@link ChatGPTModelOptionProvider} provides the available models from OpenAI as options for the channel @@ -33,6 +35,7 @@ * * @author Kai Kreuzer - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = { ChatGPTModelOptionProvider.class, ConfigOptionProvider.class }) @NonNullByDefault public class ChatGPTModelOptionProvider implements ThingHandlerService, ConfigOptionProvider { diff --git a/bundles/org.openhab.binding.chromecast/src/main/java/org/openhab/binding/chromecast/internal/action/ChromecastActions.java b/bundles/org.openhab.binding.chromecast/src/main/java/org/openhab/binding/chromecast/internal/action/ChromecastActions.java index 20a20d9a5a3d1..a585dcecdafd8 100644 --- a/bundles/org.openhab.binding.chromecast/src/main/java/org/openhab/binding/chromecast/internal/action/ChromecastActions.java +++ b/bundles/org.openhab.binding.chromecast/src/main/java/org/openhab/binding/chromecast/internal/action/ChromecastActions.java @@ -21,6 +21,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -29,6 +31,7 @@ * * @author Scott Hanson - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = ChromecastActions.class) @ThingActionsScope(name = "chromecast") @NonNullByDefault public class ChromecastActions implements ThingActions { diff --git a/bundles/org.openhab.binding.dbquery/src/main/java/org/openhab/binding/dbquery/action/DBQueryActions.java b/bundles/org.openhab.binding.dbquery/src/main/java/org/openhab/binding/dbquery/action/DBQueryActions.java index 586adc38ce3ef..04c650cf35e93 100644 --- a/bundles/org.openhab.binding.dbquery/src/main/java/org/openhab/binding/dbquery/action/DBQueryActions.java +++ b/bundles/org.openhab.binding.dbquery/src/main/java/org/openhab/binding/dbquery/action/DBQueryActions.java @@ -30,12 +30,15 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Joan Pujol - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = DBQueryActions.class) @ThingActionsScope(name = "dbquery") @NonNullByDefault public class DBQueryActions implements IDBQueryActions, ThingActions { diff --git a/bundles/org.openhab.binding.deconz/src/main/java/org/openhab/binding/deconz/internal/action/BridgeActions.java b/bundles/org.openhab.binding.deconz/src/main/java/org/openhab/binding/deconz/internal/action/BridgeActions.java index 44dd176b0a69a..4542b2a33b24a 100644 --- a/bundles/org.openhab.binding.deconz/src/main/java/org/openhab/binding/deconz/internal/action/BridgeActions.java +++ b/bundles/org.openhab.binding.deconz/src/main/java/org/openhab/binding/deconz/internal/action/BridgeActions.java @@ -25,6 +25,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,6 +35,7 @@ * * @author Jan N. Klug - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = BridgeActions.class) @ThingActionsScope(name = "deconz") @NonNullByDefault public class BridgeActions implements ThingActions { diff --git a/bundles/org.openhab.binding.deconz/src/main/java/org/openhab/binding/deconz/internal/action/GroupActions.java b/bundles/org.openhab.binding.deconz/src/main/java/org/openhab/binding/deconz/internal/action/GroupActions.java index 4b83ddb1f9240..386a0703a52b7 100644 --- a/bundles/org.openhab.binding.deconz/src/main/java/org/openhab/binding/deconz/internal/action/GroupActions.java +++ b/bundles/org.openhab.binding.deconz/src/main/java/org/openhab/binding/deconz/internal/action/GroupActions.java @@ -31,6 +31,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,6 +45,7 @@ * * @author Jan N. Klug - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = GroupActions.class) @ThingActionsScope(name = "deconz") @NonNullByDefault public class GroupActions implements ThingActions { diff --git a/bundles/org.openhab.binding.deconz/src/main/java/org/openhab/binding/deconz/internal/discovery/ThingDiscoveryService.java b/bundles/org.openhab.binding.deconz/src/main/java/org/openhab/binding/deconz/internal/discovery/ThingDiscoveryService.java index 0b910f50334bd..a255f699df024 100644 --- a/bundles/org.openhab.binding.deconz/src/main/java/org/openhab/binding/deconz/internal/discovery/ThingDiscoveryService.java +++ b/bundles/org.openhab.binding.deconz/src/main/java/org/openhab/binding/deconz/internal/discovery/ThingDiscoveryService.java @@ -35,15 +35,16 @@ import org.openhab.binding.deconz.internal.handler.SensorThingHandler; import org.openhab.binding.deconz.internal.types.GroupType; import org.openhab.binding.deconz.internal.types.LightType; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -53,36 +54,35 @@ * * @author David Graeff - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = ThingDiscoveryService.class) @NonNullByDefault -public class ThingDiscoveryService extends AbstractDiscoveryService implements DiscoveryService, ThingHandlerService { +public class ThingDiscoveryService extends AbstractThingHandlerDiscoveryService + implements DiscoveryService { private static final Set SUPPORTED_THING_TYPES_UIDS = Stream .of(LightThingHandler.SUPPORTED_THING_TYPE_UIDS, SensorThingHandler.SUPPORTED_THING_TYPES, SensorThermostatThingHandler.SUPPORTED_THING_TYPES) .flatMap(Set::stream).collect(Collectors.toSet()); private final Logger logger = LoggerFactory.getLogger(ThingDiscoveryService.class); - private @Nullable DeconzBridgeHandler handler; private @Nullable ScheduledFuture scanningJob; private @Nullable ThingUID bridgeUID; + @Activate public ThingDiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, 30); + super(DeconzBridgeHandler.class, SUPPORTED_THING_TYPES_UIDS, 30); } @Override public void startScan() { - final DeconzBridgeHandler handler = this.handler; - if (handler != null) { - handler.getBridgeFullState().thenAccept(fullState -> { - stopScan(); - fullState.ifPresent(state -> { - state.sensors.forEach(this::addSensor); - state.lights.forEach(this::addLight); - state.groups.forEach(this::addGroup); - }); - + thingHandler.getBridgeFullState().thenAccept(fullState -> { + stopScan(); + fullState.ifPresent(state -> { + state.sensors.forEach(this::addSensor); + state.lights.forEach(this::addLight); + state.groups.forEach(this::addGroup); }); - } + + }); } @Override @@ -290,26 +290,14 @@ private void addSensor(String sensorID, SensorMessage sensor) { } @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof DeconzBridgeHandler bridgeHandler) { - this.handler = bridgeHandler; - this.bridgeUID = handler.getThing().getUID(); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return handler; - } - - @Override - public void activate() { - super.activate(null); + public void initialize() { + bridgeUID = thingHandler.getThing().getUID(); + super.initialize(); } @Override - public void deactivate() { + public void dispose() { + super.dispose(); removeOlderResults(new Date().getTime()); - super.deactivate(); } } diff --git a/bundles/org.openhab.binding.deconz/src/test/java/org/openhab/binding/deconz/DeconzTest.java b/bundles/org.openhab.binding.deconz/src/test/java/org/openhab/binding/deconz/DeconzTest.java index 0086d9fea7950..dcc5a2db2ade6 100644 --- a/bundles/org.openhab.binding.deconz/src/test/java/org/openhab/binding/deconz/DeconzTest.java +++ b/bundles/org.openhab.binding.deconz/src/test/java/org/openhab/binding/deconz/DeconzTest.java @@ -93,6 +93,7 @@ public void discoveryTest() throws IOException { .getBridgeFullState(); ThingDiscoveryService discoveryService = new ThingDiscoveryService(); discoveryService.setThingHandler(bridgeHandler); + discoveryService.initialize(); discoveryService.addDiscoveryListener(discoveryListener); discoveryService.startScan(); Mockito.verify(discoveryListener, times(20)).thingDiscovered(any(), any()); diff --git a/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/discovery/DigiplexDiscoveryService.java b/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/discovery/DigiplexDiscoveryService.java index d93000d0204e0..d504df82e0302 100644 --- a/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/discovery/DigiplexDiscoveryService.java +++ b/bundles/org.openhab.binding.digiplex/src/main/java/org/openhab/binding/digiplex/internal/discovery/DigiplexDiscoveryService.java @@ -19,7 +19,6 @@ import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.digiplex.internal.communication.AreaLabelRequest; import org.openhab.binding.digiplex.internal.communication.AreaLabelResponse; import org.openhab.binding.digiplex.internal.communication.DigiplexMessageHandler; @@ -27,13 +26,12 @@ import org.openhab.binding.digiplex.internal.communication.ZoneLabelRequest; import org.openhab.binding.digiplex.internal.communication.ZoneLabelResponse; import org.openhab.binding.digiplex.internal.handler.DigiplexBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * Service for discovering things on Digiplex alarm systems @@ -41,41 +39,40 @@ * @author Robert Michalak - Initial contribution * */ +@Component(scope = ServiceScope.PROTOTYPE, service = DigiplexDiscoveryService.class) @NonNullByDefault -public class DigiplexDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService, DigiplexMessageHandler { +public class DigiplexDiscoveryService extends AbstractThingHandlerDiscoveryService + implements DigiplexMessageHandler { private static final int MAX_ZONE = 96; private static final int MAX_AREA = 8; private static final int DISCOVERY_TIMEOUT = 30; - private @Nullable DigiplexBridgeHandler bridgeHandler; - public DigiplexDiscoveryService() { - super(Set.of(THING_TYPE_ZONE), DISCOVERY_TIMEOUT, false); + super(DigiplexBridgeHandler.class, Set.of(THING_TYPE_ZONE), DISCOVERY_TIMEOUT, false); } @Override @SuppressWarnings("null") protected void startScan() { - bridgeHandler.registerMessageHandler(this); + thingHandler.registerMessageHandler(this); // find zones for (int i = 1; i <= MAX_ZONE; i++) { DigiplexRequest command = new ZoneLabelRequest(i); - bridgeHandler.sendRequest(command); + thingHandler.sendRequest(command); } // find areas for (int i = 1; i <= MAX_AREA; i++) { DigiplexRequest command = new AreaLabelRequest(i); - bridgeHandler.sendRequest(command); + thingHandler.sendRequest(command); } } @Override @SuppressWarnings("null") protected synchronized void stopScan() { - bridgeHandler.unregisterMessageHandler(this); + thingHandler.unregisterMessageHandler(this); super.stopScan(); } @@ -86,8 +83,7 @@ public void handleZoneLabelResponse(ZoneLabelResponse response) { if (isDefaultName(response)) { return; } - - ThingUID bridgeUID = bridgeHandler.getThing().getUID(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); ThingUID thingUID = new ThingUID(THING_TYPE_ZONE, bridgeUID, String.format("zone%d", response.zoneNo)); Map properties = new HashMap<>(1); @@ -112,7 +108,7 @@ public void handleAreaLabelResponse(AreaLabelResponse response) { return; } - ThingUID bridgeUID = bridgeHandler.getThing().getUID(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); ThingUID thingUID = new ThingUID(THING_TYPE_AREA, bridgeUID, String.format("area%d", response.areaNo)); Map properties = new HashMap<>(1); @@ -125,25 +121,8 @@ public void handleAreaLabelResponse(AreaLabelResponse response) { } @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof DigiplexBridgeHandler digiplexBridgeHandler) { - bridgeHandler = digiplexBridgeHandler; - bridgeHandler.registerMessageHandler(this); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - - @Override - public void activate() { - super.activate(null); - } - - @Override - public void deactivate() { - super.deactivate(); + public void initialize() { + thingHandler.registerMessageHandler(this); + super.initialize(); } } diff --git a/bundles/org.openhab.binding.dmx/src/main/java/org/openhab/binding/dmx/internal/action/DmxActions.java b/bundles/org.openhab.binding.dmx/src/main/java/org/openhab/binding/dmx/internal/action/DmxActions.java index b610dc2f960d4..ca2c334ec0614 100644 --- a/bundles/org.openhab.binding.dmx/src/main/java/org/openhab/binding/dmx/internal/action/DmxActions.java +++ b/bundles/org.openhab.binding.dmx/src/main/java/org/openhab/binding/dmx/internal/action/DmxActions.java @@ -20,6 +20,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,6 +30,7 @@ * * @author Jan N. Klug - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = DmxActions.class) @ThingActionsScope(name = "dmx") @NonNullByDefault public class DmxActions implements ThingActions { diff --git a/bundles/org.openhab.binding.doorbird/src/main/java/org/openhab/binding/doorbird/internal/action/DoorbirdActions.java b/bundles/org.openhab.binding.doorbird/src/main/java/org/openhab/binding/doorbird/internal/action/DoorbirdActions.java index a47a7bf6f730c..e4121e8a94a39 100644 --- a/bundles/org.openhab.binding.doorbird/src/main/java/org/openhab/binding/doorbird/internal/action/DoorbirdActions.java +++ b/bundles/org.openhab.binding.doorbird/src/main/java/org/openhab/binding/doorbird/internal/action/DoorbirdActions.java @@ -20,6 +20,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,6 +30,7 @@ * * @author Mark Hilbush - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = DoorbirdActions.class) @ThingActionsScope(name = "doorbird") @NonNullByDefault public class DoorbirdActions implements ThingActions { diff --git a/bundles/org.openhab.binding.draytonwiser/src/main/java/org/openhab/binding/draytonwiser/internal/discovery/DraytonWiserDiscoveryService.java b/bundles/org.openhab.binding.draytonwiser/src/main/java/org/openhab/binding/draytonwiser/internal/discovery/DraytonWiserDiscoveryService.java index 500d0a4d970ac..832be2a6d1886 100644 --- a/bundles/org.openhab.binding.draytonwiser/src/main/java/org/openhab/binding/draytonwiser/internal/discovery/DraytonWiserDiscoveryService.java +++ b/bundles/org.openhab.binding.draytonwiser/src/main/java/org/openhab/binding/draytonwiser/internal/discovery/DraytonWiserDiscoveryService.java @@ -29,14 +29,13 @@ import org.openhab.binding.draytonwiser.internal.model.RoomStatDTO; import org.openhab.binding.draytonwiser.internal.model.SmartPlugDTO; import org.openhab.binding.draytonwiser.internal.model.SmartValveDTO; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,36 +44,23 @@ * * @author Andrew Schofield - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = DraytonWiserDiscoveryService.class) @NonNullByDefault -public class DraytonWiserDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService, DraytonWiserRefreshListener { +public class DraytonWiserDiscoveryService extends AbstractThingHandlerDiscoveryService + implements DraytonWiserRefreshListener { private final Logger logger = LoggerFactory.getLogger(DraytonWiserDiscoveryService.class); - private @Nullable HeatHubHandler bridgeHandler; private @Nullable ThingUID bridgeUID; public DraytonWiserDiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, 30, false); - } - - @Override - public void activate() { - super.activate(null); - } - - @Override - public void deactivate() { - super.deactivate(); + super(HeatHubHandler.class, SUPPORTED_THING_TYPES_UIDS, 30, false); } @Override protected void startScan() { - final HeatHubHandler handler = bridgeHandler; - if (handler != null) { - removeOlderResults(getTimestampOfLastScan()); - handler.setDiscoveryService(this); - } + removeOlderResults(getTimestampOfLastScan()); + thingHandler.setDiscoveryService(this); } @Override @@ -192,27 +178,13 @@ private void onThingWithSerialNumber(final ThingTypeUID deviceType, final String @Override public synchronized void stopScan() { - final HeatHubHandler handler = bridgeHandler; - - if (handler != null) { - handler.unsetDiscoveryService(); - } + thingHandler.unsetDiscoveryService(); super.stopScan(); } @Override - public void setThingHandler(@Nullable final ThingHandler handler) { - if (handler instanceof HeatHubHandler hubHandler) { - bridgeHandler = hubHandler; - bridgeUID = handler.getThing().getUID(); - } else { - bridgeHandler = null; - bridgeUID = null; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; + public void initialize() { + bridgeUID = thingHandler.getThing().getUID(); + super.initialize(); } } diff --git a/bundles/org.openhab.binding.draytonwiser/src/test/java/org/openhab/binding/draytonwiser/internal/discovery/DraytonWiserDiscoveryServiceTest.java b/bundles/org.openhab.binding.draytonwiser/src/test/java/org/openhab/binding/draytonwiser/internal/discovery/DraytonWiserDiscoveryServiceTest.java index ff1605560283e..2828b52fb71b3 100644 --- a/bundles/org.openhab.binding.draytonwiser/src/test/java/org/openhab/binding/draytonwiser/internal/discovery/DraytonWiserDiscoveryServiceTest.java +++ b/bundles/org.openhab.binding.draytonwiser/src/test/java/org/openhab/binding/draytonwiser/internal/discovery/DraytonWiserDiscoveryServiceTest.java @@ -100,6 +100,7 @@ protected void thingDiscovered(final DiscoveryResult discoveryResult) { } }; service.setThingHandler(bridgeHandler); + service.initialize(); final DomainDTO domain = api.getDomain(); if (domain == null) { diff --git a/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/discovery/DSMRI18nProviderTracker.java b/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/discovery/DSMRI18nProviderTracker.java deleted file mode 100644 index 92828cd59cfdb..0000000000000 --- a/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/discovery/DSMRI18nProviderTracker.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (c) 2010-2024 Contributors to the openHAB project - * - * See the NOTICE file(s) distributed with this work for additional - * information. - * - * This program and the accompanying materials are made available under the - * terms of the Eclipse Public License 2.0 which is available at - * http://www.eclipse.org/legal/epl-2.0 - * - * SPDX-License-Identifier: EPL-2.0 - */ -package org.openhab.binding.dsmr.internal.discovery; - -import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; -import org.openhab.core.i18n.LocaleProvider; -import org.openhab.core.i18n.TranslationProvider; -import org.openhab.core.thing.binding.ThingHandlerService; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Component; -import org.osgi.service.component.annotations.Deactivate; -import org.osgi.service.component.annotations.Reference; - -/** - * Tracks the i18n provider dependencies of the {@link DSMRMeterDiscoveryService}. The {@link DSMRMeterDiscoveryService} - * is a {@link ThingHandlerService} so its i18n dependencies cannot be injected using service component annotations. - * - * @author Wouter Born - Initial contribution - */ -@Component -@NonNullByDefault -public class DSMRI18nProviderTracker { - - static @Nullable TranslationProvider i18nProvider; - static @Nullable LocaleProvider localeProvider; - - @Activate - public DSMRI18nProviderTracker(final @Reference TranslationProvider i18nProvider, - final @Reference LocaleProvider localeProvider) { - DSMRI18nProviderTracker.i18nProvider = i18nProvider; - DSMRI18nProviderTracker.localeProvider = localeProvider; - } - - @Deactivate - public void deactivate() { - i18nProvider = null; - localeProvider = null; - } -} diff --git a/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/discovery/DSMRMeterDiscoveryService.java b/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/discovery/DSMRMeterDiscoveryService.java index 969c9210b5dfc..cd49283e65078 100644 --- a/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/discovery/DSMRMeterDiscoveryService.java +++ b/bundles/org.openhab.binding.dsmr/src/main/java/org/openhab/binding/dsmr/internal/discovery/DSMRMeterDiscoveryService.java @@ -30,10 +30,15 @@ import org.openhab.binding.dsmr.internal.handler.DSMRMeterHandler; import org.openhab.binding.dsmr.internal.meter.DSMRMeterDescriptor; import org.openhab.binding.dsmr.internal.meter.DSMRMeterType; +import org.openhab.core.i18n.LocaleProvider; +import org.openhab.core.i18n.TranslationProvider; import org.openhab.core.library.types.StringType; import org.openhab.core.thing.Thing; import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,6 +48,7 @@ * @author M. Volaart - Initial contribution * @author Hilbrand Bouwkamp - Refactored code to detect meters during actual discovery phase. */ +@Component(scope = ServiceScope.PROTOTYPE, service = DSMRMeterDiscoveryService.class) @NonNullByDefault public class DSMRMeterDiscoveryService extends DSMRDiscoveryService implements P1TelegramListener, ThingHandlerService { @@ -53,13 +59,14 @@ public class DSMRMeterDiscoveryService extends DSMRDiscoveryService implements P */ private @NonNullByDefault({}) DSMRBridgeHandler dsmrBridgeHandler; - /** - * Constructs a new {@link DSMRMeterDiscoveryService} attached to the give bridge handler. - */ - public DSMRMeterDiscoveryService() { - super(); - this.i18nProvider = DSMRI18nProviderTracker.i18nProvider; - this.localeProvider = DSMRI18nProviderTracker.localeProvider; + @Reference(unbind = "-") + public void bindTranslationProvider(TranslationProvider translationProvider) { + this.i18nProvider = translationProvider; + } + + @Reference(unbind = "-") + public void bindLocaleProvider(LocaleProvider localeProvider) { + this.localeProvider = localeProvider; } @Override diff --git a/bundles/org.openhab.binding.easee/src/main/java/org/openhab/binding/easee/internal/discovery/EaseeSiteDiscoveryService.java b/bundles/org.openhab.binding.easee/src/main/java/org/openhab/binding/easee/internal/discovery/EaseeSiteDiscoveryService.java index 2450fc65b8c21..ae51595b71769 100644 --- a/bundles/org.openhab.binding.easee/src/main/java/org/openhab/binding/easee/internal/discovery/EaseeSiteDiscoveryService.java +++ b/bundles/org.openhab.binding.easee/src/main/java/org/openhab/binding/easee/internal/discovery/EaseeSiteDiscoveryService.java @@ -21,12 +21,12 @@ import org.openhab.binding.easee.internal.command.site.GetSite; import org.openhab.binding.easee.internal.connector.CommunicationStatus; import org.openhab.binding.easee.internal.handler.EaseeSiteHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,38 +40,25 @@ * @author Alexander Friese - initial contribution * */ +@Component(scope = ServiceScope.PROTOTYPE, service = EaseeSiteDiscoveryService.class) @NonNullByDefault -public class EaseeSiteDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class EaseeSiteDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(EaseeSiteDiscoveryService.class); - private @NonNullByDefault({}) EaseeSiteHandler bridgeHandler; public EaseeSiteDiscoveryService() throws IllegalArgumentException { - super(EaseeBindingConstants.SUPPORTED_THING_TYPES_UIDS, 300, false); + super(EaseeSiteHandler.class, EaseeBindingConstants.SUPPORTED_THING_TYPES_UIDS, 300, false); } @Override protected void startScan() { - bridgeHandler.enqueueCommand(new GetSite(bridgeHandler, this::processSiteDiscoveryResult)); + thingHandler.enqueueCommand(new GetSite(thingHandler, this::processSiteDiscoveryResult)); } @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof EaseeSiteHandler siteHandler) { - this.bridgeHandler = siteHandler; - this.bridgeHandler.setDiscoveryService(this); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - - // method is defined in both implemented interface and inherited class, thus we must define a behaviour here. - @Override - public void deactivate() { - super.deactivate(); + public void initialize() { + thingHandler.setDiscoveryService(this); + super.initialize(); } /** @@ -157,7 +144,7 @@ private void handleChargerDiscovery(JsonElement json, String circuitId, String c */ private DiscoveryResultBuilder initDiscoveryResultBuilder(String deviceType, String deviceId, @Nullable String deviceName) { - ThingUID bridgeUID = bridgeHandler.getThing().getUID(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); ThingTypeUID typeUid = new ThingTypeUID(BINDING_ID, deviceType); ThingUID thingUID = new ThingUID(typeUid, bridgeUID, deviceId); diff --git a/bundles/org.openhab.binding.echonetlite/src/main/java/org/openhab/binding/echonetlite/internal/EchonetDiscoveryService.java b/bundles/org.openhab.binding.echonetlite/src/main/java/org/openhab/binding/echonetlite/internal/EchonetDiscoveryService.java index 6da7137c9bff2..2d0add5d193de 100644 --- a/bundles/org.openhab.binding.echonetlite/src/main/java/org/openhab/binding/echonetlite/internal/EchonetDiscoveryService.java +++ b/bundles/org.openhab.binding.echonetlite/src/main/java/org/openhab/binding/echonetlite/internal/EchonetDiscoveryService.java @@ -23,90 +23,52 @@ import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Michael Barker - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = EchonetDiscoveryService.class) @NonNullByDefault -public class EchonetDiscoveryService extends AbstractDiscoveryService - implements EchonetDiscoveryListener, ThingHandlerService { +public class EchonetDiscoveryService extends AbstractThingHandlerDiscoveryService + implements EchonetDiscoveryListener { private final Logger logger = LoggerFactory.getLogger(EchonetDiscoveryService.class); - @Nullable - private EchonetLiteBridgeHandler bridgeHandler; - public EchonetDiscoveryService() { - super(Set.of(THING_TYPE_ECHONET_DEVICE), 10); + super(EchonetLiteBridgeHandler.class, Set.of(THING_TYPE_ECHONET_DEVICE), 10); } @Override protected void startScan() { - final EchonetLiteBridgeHandler bridgeHandler = this.bridgeHandler; - logger.debug("startScan: {}", bridgeHandler); - if (null != bridgeHandler) { - bridgeHandler.startDiscovery(this); - } + logger.debug("startScan: {}", thingHandler); + thingHandler.startDiscovery(this); } @Override protected synchronized void stopScan() { - final EchonetLiteBridgeHandler bridgeHandler = this.bridgeHandler; - logger.debug("stopScan: {}", bridgeHandler); - if (null != bridgeHandler) { - bridgeHandler.stopDiscovery(); - } + logger.debug("stopScan: {}", thingHandler); + thingHandler.stopDiscovery(); } @Override public void onDeviceFound(String identifier, InstanceKey instanceKey) { - final EchonetLiteBridgeHandler bridgeHandler = this.bridgeHandler; - - if (null == bridgeHandler) { - return; - } - final DiscoveryResult discoveryResult = DiscoveryResultBuilder - .create(new ThingUID(THING_TYPE_ECHONET_DEVICE, bridgeHandler.getThing().getUID(), identifier)) + .create(new ThingUID(THING_TYPE_ECHONET_DEVICE, thingHandler.getThing().getUID(), identifier)) .withProperty(PROPERTY_NAME_INSTANCE_KEY, instanceKey.representationProperty()) .withProperty(PROPERTY_NAME_HOSTNAME, instanceKey.address.getAddress().getHostAddress()) .withProperty(PROPERTY_NAME_PORT, instanceKey.address.getPort()) .withProperty(PROPERTY_NAME_GROUP_CODE, instanceKey.klass.groupCode()) .withProperty(PROPERTY_NAME_CLASS_CODE, instanceKey.klass.classCode()) - .withProperty(PROPERTY_NAME_INSTANCE, instanceKey.instance) - .withBridge(bridgeHandler.getThing().getUID()).withRepresentationProperty(PROPERTY_NAME_INSTANCE_KEY) - .build(); + .withProperty(PROPERTY_NAME_INSTANCE, instanceKey.instance).withBridge(thingHandler.getThing().getUID()) + .withRepresentationProperty(PROPERTY_NAME_INSTANCE_KEY).build(); thingDiscovered(discoveryResult); } - - @Override - public void deactivate() { - ThingHandlerService.super.deactivate(); - } - - @Override - public void activate() { - ThingHandlerService.super.activate(); - } - - @Override - public void setThingHandler(ThingHandler thingHandler) { - if (thingHandler instanceof EchonetLiteBridgeHandler bridgeHandler) { - this.bridgeHandler = bridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } } diff --git a/bundles/org.openhab.binding.ecobee/src/main/java/org/openhab/binding/ecobee/internal/action/EcobeeActions.java b/bundles/org.openhab.binding.ecobee/src/main/java/org/openhab/binding/ecobee/internal/action/EcobeeActions.java index 7fd019dcb2cd6..95dd6e24d1801 100644 --- a/bundles/org.openhab.binding.ecobee/src/main/java/org/openhab/binding/ecobee/internal/action/EcobeeActions.java +++ b/bundles/org.openhab.binding.ecobee/src/main/java/org/openhab/binding/ecobee/internal/action/EcobeeActions.java @@ -45,6 +45,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -55,6 +57,7 @@ * @author Mark Hilbush - Adapted for OH2/3 * @author Connor Petty - Proxy method for invoking actions */ +@Component(scope = ServiceScope.PROTOTYPE, service = EcobeeActions.class) @ThingActionsScope(name = "ecobee") @NonNullByDefault public class EcobeeActions implements ThingActions { diff --git a/bundles/org.openhab.binding.ecobee/src/main/java/org/openhab/binding/ecobee/internal/discovery/EcobeeDiscoveryService.java b/bundles/org.openhab.binding.ecobee/src/main/java/org/openhab/binding/ecobee/internal/discovery/EcobeeDiscoveryService.java index 2da42a1f970da..3925c00f7657e 100644 --- a/bundles/org.openhab.binding.ecobee/src/main/java/org/openhab/binding/ecobee/internal/discovery/EcobeeDiscoveryService.java +++ b/bundles/org.openhab.binding.ecobee/src/main/java/org/openhab/binding/ecobee/internal/discovery/EcobeeDiscoveryService.java @@ -27,15 +27,15 @@ import org.openhab.binding.ecobee.internal.dto.thermostat.ThermostatDTO; import org.openhab.binding.ecobee.internal.handler.EcobeeAccountBridgeHandler; import org.openhab.binding.ecobee.internal.handler.EcobeeThermostatBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -46,39 +46,16 @@ * * @author Mark Hilbush - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = EcobeeDiscoveryService.class) @NonNullByDefault -public class EcobeeDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class EcobeeDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(EcobeeDiscoveryService.class); - private @NonNullByDefault({}) EcobeeAccountBridgeHandler bridgeHandler; - private @Nullable Future discoveryJob; public EcobeeDiscoveryService() { - super(SUPPORTED_THERMOSTAT_AND_SENSOR_THING_TYPES_UIDS, 8, true); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof EcobeeAccountBridgeHandler accountBridgeHandler) { - this.bridgeHandler = accountBridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - - @Override - public void activate() { - super.activate(null); - } - - @Override - public void deactivate() { - super.deactivate(); + super(EcobeeAccountBridgeHandler.class, SUPPORTED_THERMOSTAT_AND_SENSOR_THING_TYPES_UIDS, 8, true); } @Override @@ -113,14 +90,14 @@ public void startScan() { } private void backgroundDiscover() { - if (!bridgeHandler.isBackgroundDiscoveryEnabled()) { + if (!thingHandler.isBackgroundDiscoveryEnabled()) { return; } discover(); } private void discover() { - if (bridgeHandler.getThing().getStatus() != ThingStatus.ONLINE) { + if (thingHandler.getThing().getStatus() != ThingStatus.ONLINE) { logger.debug("EcobeeDiscovery: Skipping discovery because Account Bridge thing is not ONLINE"); return; } @@ -131,11 +108,11 @@ private void discover() { private synchronized void discoverThermostats() { logger.debug("EcobeeDiscovery: Discovering thermostats"); - for (ThermostatDTO thermostat : bridgeHandler.getRegisteredThermostats()) { + for (ThermostatDTO thermostat : thingHandler.getRegisteredThermostats()) { String name = thermostat.name; String identifier = thermostat.identifier; if (identifier != null && name != null) { - ThingUID thingUID = new ThingUID(UID_THERMOSTAT_BRIDGE, bridgeHandler.getThing().getUID(), identifier); + ThingUID thingUID = new ThingUID(UID_THERMOSTAT_BRIDGE, thingHandler.getThing().getUID(), identifier); thingDiscovered(createThermostatDiscoveryResult(thingUID, identifier, name)); logger.debug("EcobeeDiscovery: Thermostat '{}' and name '{}' added with UID '{}'", identifier, name, thingUID); @@ -144,6 +121,10 @@ private synchronized void discoverThermostats() { } private DiscoveryResult createThermostatDiscoveryResult(ThingUID thermostatUID, String identifier, String name) { + EcobeeAccountBridgeHandler bridgeHandler = thingHandler; + if (bridgeHandler == null) { + throw new IllegalStateException("thingHandler must not be null"); + } Map properties = new HashMap<>(); properties.put(CONFIG_THERMOSTAT_ID, identifier); return DiscoveryResultBuilder.create(thermostatUID).withProperties(properties) @@ -152,7 +133,7 @@ private DiscoveryResult createThermostatDiscoveryResult(ThingUID thermostatUID, } private synchronized void discoverSensors() { - List thermostatThings = bridgeHandler.getThing().getThings(); + List thermostatThings = thingHandler.getThing().getThings(); if (thermostatThings.isEmpty()) { logger.debug("EcobeeDiscovery: Skipping sensor discovery because there are no thermostat things"); return; diff --git a/bundles/org.openhab.binding.ecovacs/src/main/java/org/openhab/binding/ecovacs/internal/action/EcovacsVacuumActions.java b/bundles/org.openhab.binding.ecovacs/src/main/java/org/openhab/binding/ecovacs/internal/action/EcovacsVacuumActions.java index c07138eb864e7..9b2908c152b75 100644 --- a/bundles/org.openhab.binding.ecovacs/src/main/java/org/openhab/binding/ecovacs/internal/action/EcovacsVacuumActions.java +++ b/bundles/org.openhab.binding.ecovacs/src/main/java/org/openhab/binding/ecovacs/internal/action/EcovacsVacuumActions.java @@ -25,12 +25,15 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Danny Baumann - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = EcovacsVacuumActions.class) @ThingActionsScope(name = "ecovacs") @NonNullByDefault public class EcovacsVacuumActions implements ThingActions { diff --git a/bundles/org.openhab.binding.ecovacs/src/main/java/org/openhab/binding/ecovacs/internal/discovery/EcovacsDeviceDiscoveryService.java b/bundles/org.openhab.binding.ecovacs/src/main/java/org/openhab/binding/ecovacs/internal/discovery/EcovacsDeviceDiscoveryService.java index b8a2027bf331a..7fb8caa164a09 100644 --- a/bundles/org.openhab.binding.ecovacs/src/main/java/org/openhab/binding/ecovacs/internal/discovery/EcovacsDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.ecovacs/src/main/java/org/openhab/binding/ecovacs/internal/discovery/EcovacsDeviceDiscoveryService.java @@ -19,21 +19,19 @@ import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.ecovacs.internal.api.EcovacsApi; import org.openhab.binding.ecovacs.internal.api.EcovacsApiException; import org.openhab.binding.ecovacs.internal.api.EcovacsDevice; import org.openhab.binding.ecovacs.internal.api.util.SchedulerTask; import org.openhab.binding.ecovacs.internal.handler.EcovacsApiHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,13 +41,11 @@ * @author Danny Baumann - Initial contribution */ @NonNullByDefault -@Component(service = DiscoveryService.class, configurationPid = "discovery.ecovacs") -public class EcovacsDeviceDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +@Component(scope = ServiceScope.PROTOTYPE, service = DiscoveryService.class, configurationPid = "discovery.ecovacs") +public class EcovacsDeviceDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(EcovacsDeviceDiscoveryService.class); private static final int DISCOVER_TIMEOUT_SECONDS = 10; - - private @NonNullByDefault({}) EcovacsApiHandler apiHandler; private Optional api = Optional.empty(); private final SchedulerTask onDemandScanTask = new SchedulerTask(scheduler, logger, "OnDemandScan", this::scanForDevices); @@ -57,30 +53,13 @@ public class EcovacsDeviceDiscoveryService extends AbstractDiscoveryService impl this::scanForDevices); public EcovacsDeviceDiscoveryService() { - super(Set.of(THING_TYPE_VACUUM), DISCOVER_TIMEOUT_SECONDS, true); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof EcovacsApiHandler ecovacsApiHandler) { - this.apiHandler = ecovacsApiHandler; - this.apiHandler.setDiscoveryService(this); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return apiHandler; - } - - @Override - public void activate() { - super.activate(null); + super(EcovacsApiHandler.class, Set.of(THING_TYPE_VACUUM), DISCOVER_TIMEOUT_SECONDS, true); } @Override - public void deactivate() { - super.deactivate(); + public void initialize() { + thingHandler.setDiscoveryService(this); + super.initialize(); } @Override @@ -123,7 +102,7 @@ private void scanForDevices() { for (EcovacsDevice device : devices) { deviceDiscovered(device); } - for (Thing thing : apiHandler.getThing().getThings()) { + for (Thing thing : thingHandler.getThing().getThings()) { String serial = thing.getUID().getId(); if (!devices.stream().anyMatch(d -> serial.equals(d.getSerialNumber()))) { thingRemoved(thing.getUID()); @@ -140,9 +119,9 @@ private void scanForDevices() { } private void deviceDiscovered(EcovacsDevice device) { - ThingUID thingUID = new ThingUID(THING_TYPE_VACUUM, apiHandler.getThing().getUID(), device.getSerialNumber()); + ThingUID thingUID = new ThingUID(THING_TYPE_VACUUM, thingHandler.getThing().getUID(), device.getSerialNumber()); DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID) - .withBridge(apiHandler.getThing().getUID()).withLabel(device.getModelName()) + .withBridge(thingHandler.getThing().getUID()).withLabel(device.getModelName()) .withProperty(Thing.PROPERTY_SERIAL_NUMBER, device.getSerialNumber()) .withProperty(Thing.PROPERTY_MODEL_ID, device.getModelName()) .withRepresentationProperty(Thing.PROPERTY_SERIAL_NUMBER).build(); diff --git a/bundles/org.openhab.binding.electroluxair/src/main/java/org/openhab/binding/electroluxair/internal/discovery/ElectroluxAirDiscoveryService.java b/bundles/org.openhab.binding.electroluxair/src/main/java/org/openhab/binding/electroluxair/internal/discovery/ElectroluxAirDiscoveryService.java index 2b09a7dcda428..c875c066d0853 100644 --- a/bundles/org.openhab.binding.electroluxair/src/main/java/org/openhab/binding/electroluxair/internal/discovery/ElectroluxAirDiscoveryService.java +++ b/bundles/org.openhab.binding.electroluxair/src/main/java/org/openhab/binding/electroluxair/internal/discovery/ElectroluxAirDiscoveryService.java @@ -14,18 +14,14 @@ import static org.openhab.binding.electroluxair.internal.ElectroluxAirBindingConstants.*; -import java.util.Map; - import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.electroluxair.internal.ElectroluxAirConfiguration; import org.openhab.binding.electroluxair.internal.handler.ElectroluxAirBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * The {@link ElectroluxAirDiscoveryService} searches for available @@ -33,51 +29,26 @@ * * @author Jan Gustafsson - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = ElectroluxAirDiscoveryService.class) @NonNullByDefault -public class ElectroluxAirDiscoveryService extends AbstractDiscoveryService - implements ThingHandlerService, DiscoveryService { +public class ElectroluxAirDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int SEARCH_TIME = 2; - private @Nullable ElectroluxAirBridgeHandler handler; public ElectroluxAirDiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof ElectroluxAirBridgeHandler bridgeHandler) { - this.handler = bridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return handler; - } - - @Override - public void activate(@Nullable Map configProperties) { - super.activate(configProperties); - } - - @Override - public void deactivate() { - super.deactivate(); + super(ElectroluxAirBridgeHandler.class, SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME); } @Override protected void startScan() { - ElectroluxAirBridgeHandler bridgeHandler = this.handler; - if (bridgeHandler != null) { - ThingUID bridgeUID = bridgeHandler.getThing().getUID(); - bridgeHandler.getElectroluxAirThings().entrySet().stream().forEach(thing -> { - thingDiscovered(DiscoveryResultBuilder - .create(new ThingUID(THING_TYPE_ELECTROLUX_PURE_A9, bridgeUID, thing.getKey())) - .withLabel("Electrolux Pure A9").withBridge(bridgeUID) - .withProperty(ElectroluxAirConfiguration.DEVICE_ID_LABEL, thing.getKey()) - .withRepresentationProperty(ElectroluxAirConfiguration.DEVICE_ID_LABEL).build()); - }); - } + ThingUID bridgeUID = thingHandler.getThing().getUID(); + thingHandler.getElectroluxAirThings().entrySet().stream().forEach(thing -> { + thingDiscovered(DiscoveryResultBuilder + .create(new ThingUID(THING_TYPE_ELECTROLUX_PURE_A9, bridgeUID, thing.getKey())) + .withLabel("Electrolux Pure A9").withBridge(bridgeUID) + .withProperty(ElectroluxAirConfiguration.DEVICE_ID_LABEL, thing.getKey()) + .withRepresentationProperty(ElectroluxAirConfiguration.DEVICE_ID_LABEL).build()); + }); + stopScan(); } } diff --git a/bundles/org.openhab.binding.elroconnects/src/main/java/org/openhab/binding/elroconnects/internal/discovery/ElroConnectsBridgeDiscoveryService.java b/bundles/org.openhab.binding.elroconnects/src/main/java/org/openhab/binding/elroconnects/internal/discovery/ElroConnectsBridgeDiscoveryService.java index a04ecd75392d5..7a022de7c3e5f 100644 --- a/bundles/org.openhab.binding.elroconnects/src/main/java/org/openhab/binding/elroconnects/internal/discovery/ElroConnectsBridgeDiscoveryService.java +++ b/bundles/org.openhab.binding.elroconnects/src/main/java/org/openhab/binding/elroconnects/internal/discovery/ElroConnectsBridgeDiscoveryService.java @@ -25,12 +25,12 @@ import org.openhab.binding.elroconnects.internal.ElroConnectsBindingConstants; import org.openhab.binding.elroconnects.internal.devices.ElroConnectsConnector; import org.openhab.binding.elroconnects.internal.handler.ElroConnectsAccountHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,13 +39,13 @@ * * @author Mark Herwege - Initial Contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = ElroConnectsBridgeDiscoveryService.class) @NonNullByDefault -public class ElroConnectsBridgeDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class ElroConnectsBridgeDiscoveryService + extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(ElroConnectsBridgeDiscoveryService.class); - private @Nullable ElroConnectsAccountHandler accountHandler; - private volatile @Nullable ScheduledFuture discoveryJob; private static final int TIMEOUT_S = 5; @@ -54,7 +54,7 @@ public class ElroConnectsBridgeDiscoveryService extends AbstractDiscoveryService private static final int REFRESH_INTERVAL_S = 60; public ElroConnectsBridgeDiscoveryService() { - super(ElroConnectsBindingConstants.SUPPORTED_CONNECTOR_TYPES_UIDS, TIMEOUT_S); + super(ElroConnectsAccountHandler.class, ElroConnectsBindingConstants.SUPPORTED_CONNECTOR_TYPES_UIDS, TIMEOUT_S); logger.debug("Bridge discovery service started"); } @@ -67,14 +67,10 @@ protected void startScan() { private void discoverConnectors() { logger.debug("Starting hub discovery scan"); - ElroConnectsAccountHandler account = accountHandler; - if (account == null) { - return; - } - ThingUID bridgeUID = account.getThing().getUID(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); - Map connectors = account.getDevices(); + Map connectors = thingHandler.getDevices(); if (connectors == null) { return; } @@ -134,21 +130,14 @@ public void stopBackgroundDiscovery() { } @Override - public void deactivate() { + public void dispose() { + super.dispose(); removeOlderResults(Instant.now().toEpochMilli()); - super.deactivate(); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof ElroConnectsAccountHandler accountHandler) { - this.accountHandler = accountHandler; - accountHandler.setDiscoveryService(this); - } } @Override - public @Nullable ThingHandler getThingHandler() { - return accountHandler; + public void initialize() { + thingHandler.setDiscoveryService(this); + super.initialize(); } } diff --git a/bundles/org.openhab.binding.elroconnects/src/main/java/org/openhab/binding/elroconnects/internal/discovery/ElroConnectsDiscoveryService.java b/bundles/org.openhab.binding.elroconnects/src/main/java/org/openhab/binding/elroconnects/internal/discovery/ElroConnectsDiscoveryService.java index f654e024fc82d..a716a4ef80a80 100644 --- a/bundles/org.openhab.binding.elroconnects/src/main/java/org/openhab/binding/elroconnects/internal/discovery/ElroConnectsDiscoveryService.java +++ b/bundles/org.openhab.binding.elroconnects/src/main/java/org/openhab/binding/elroconnects/internal/discovery/ElroConnectsDiscoveryService.java @@ -25,12 +25,12 @@ import org.openhab.binding.elroconnects.internal.ElroConnectsBindingConstants.ElroDeviceType; import org.openhab.binding.elroconnects.internal.devices.ElroConnectsDevice; import org.openhab.binding.elroconnects.internal.handler.ElroConnectsBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,20 +39,19 @@ * * @author Mark Herwege - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = ElroConnectsDiscoveryService.class) @NonNullByDefault -public class ElroConnectsDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class ElroConnectsDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(ElroConnectsDiscoveryService.class); - private @Nullable ElroConnectsBridgeHandler bridgeHandler; - private static final int TIMEOUT_S = 5; private static final int REFRESH_INTERVAL_S = 60; private @Nullable ScheduledFuture discoveryJob; public ElroConnectsDiscoveryService() { - super(ElroConnectsBindingConstants.SUPPORTED_DEVICE_TYPES_UIDS, TIMEOUT_S); + super(ElroConnectsBridgeHandler.class, ElroConnectsBindingConstants.SUPPORTED_DEVICE_TYPES_UIDS, TIMEOUT_S); logger.debug("Discovery service started"); } @@ -63,28 +62,24 @@ protected void startScan() { private void discoverDevices() { logger.debug("Starting device discovery scan"); - ElroConnectsBridgeHandler bridge = bridgeHandler; - if (bridge != null) { - Map devices = bridge.getDevices(); - ThingUID bridgeUID = bridge.getThing().getUID(); - devices.entrySet().forEach(e -> { - String deviceId = e.getKey().toString(); - String deviceName = e.getValue().getDeviceName(); - String deviceType = e.getValue().getDeviceType(); - if (!deviceType.isEmpty()) { - ElroDeviceType type = TYPE_MAP.get(deviceType); - if (type != null) { - ThingTypeUID thingTypeUID = THING_TYPE_MAP.get(type); - if (thingTypeUID != null) { - thingDiscovered(DiscoveryResultBuilder - .create(new ThingUID(thingTypeUID, bridgeUID, deviceId)).withLabel(deviceName) - .withBridge(bridgeUID).withProperty(CONFIG_DEVICE_ID, deviceId) - .withRepresentationProperty(CONFIG_DEVICE_ID).build()); - } + Map devices = thingHandler.getDevices(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); + devices.entrySet().forEach(e -> { + String deviceId = e.getKey().toString(); + String deviceName = e.getValue().getDeviceName(); + String deviceType = e.getValue().getDeviceType(); + if (!deviceType.isEmpty()) { + ElroDeviceType type = TYPE_MAP.get(deviceType); + if (type != null) { + ThingTypeUID thingTypeUID = THING_TYPE_MAP.get(type); + if (thingTypeUID != null) { + thingDiscovered(DiscoveryResultBuilder.create(new ThingUID(thingTypeUID, bridgeUID, deviceId)) + .withLabel(deviceName).withBridge(bridgeUID).withProperty(CONFIG_DEVICE_ID, deviceId) + .withRepresentationProperty(CONFIG_DEVICE_ID).build()); } } - }); - } + } + }); } @Override @@ -114,21 +109,14 @@ protected void stopBackgroundDiscovery() { } @Override - public void deactivate() { + public void dispose() { + super.dispose(); removeOlderResults(Instant.now().toEpochMilli()); - super.deactivate(); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof ElroConnectsBridgeHandler bridgeHandler) { - this.bridgeHandler = bridgeHandler; - bridgeHandler.setDiscoveryService(this); - } } @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; + public void initialize() { + thingHandler.setDiscoveryService(this); + super.initialize(); } } diff --git a/bundles/org.openhab.binding.energidataservice/src/main/java/org/openhab/binding/energidataservice/internal/action/EnergiDataServiceActions.java b/bundles/org.openhab.binding.energidataservice/src/main/java/org/openhab/binding/energidataservice/internal/action/EnergiDataServiceActions.java index b63303763b80d..5232fd6fb4215 100644 --- a/bundles/org.openhab.binding.energidataservice/src/main/java/org/openhab/binding/energidataservice/internal/action/EnergiDataServiceActions.java +++ b/bundles/org.openhab.binding.energidataservice/src/main/java/org/openhab/binding/energidataservice/internal/action/EnergiDataServiceActions.java @@ -45,6 +45,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -53,6 +55,7 @@ * * @author Jacob Laursen - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = EnergiDataServiceActions.class) @ThingActionsScope(name = "energidataservice") @NonNullByDefault public class EnergiDataServiceActions implements ThingActions { diff --git a/bundles/org.openhab.binding.enigma2/src/main/java/org/openhab/binding/enigma2/internal/actions/Enigma2Actions.java b/bundles/org.openhab.binding.enigma2/src/main/java/org/openhab/binding/enigma2/internal/actions/Enigma2Actions.java index 16d1e3b9916ae..82e4393138a9e 100644 --- a/bundles/org.openhab.binding.enigma2/src/main/java/org/openhab/binding/enigma2/internal/actions/Enigma2Actions.java +++ b/bundles/org.openhab.binding.enigma2/src/main/java/org/openhab/binding/enigma2/internal/actions/Enigma2Actions.java @@ -21,6 +21,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * This is the automation engine actions handler service for the @@ -28,6 +30,7 @@ * * @author Guido Dolfen - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = Enigma2Actions.class) @ThingActionsScope(name = "enigma2") @NonNullByDefault public class Enigma2Actions implements ThingActions { diff --git a/bundles/org.openhab.binding.enphase/src/main/java/org/openhab/binding/enphase/internal/discovery/EnphaseDevicesDiscoveryService.java b/bundles/org.openhab.binding.enphase/src/main/java/org/openhab/binding/enphase/internal/discovery/EnphaseDevicesDiscoveryService.java index 0fcfb278625f9..596d0c6625783 100644 --- a/bundles/org.openhab.binding.enphase/src/main/java/org/openhab/binding/enphase/internal/discovery/EnphaseDevicesDiscoveryService.java +++ b/bundles/org.openhab.binding.enphase/src/main/java/org/openhab/binding/enphase/internal/discovery/EnphaseDevicesDiscoveryService.java @@ -28,14 +28,13 @@ import org.openhab.binding.enphase.internal.dto.InventoryJsonDTO.DeviceDTO; import org.openhab.binding.enphase.internal.dto.InverterDTO; import org.openhab.binding.enphase.internal.handler.EnvoyBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,49 +44,28 @@ * @author Thomas Hentschel - Initial contribution * @author Hilbrand Bouwkamp - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = EnphaseDevicesDiscoveryService.class) @NonNullByDefault -public class EnphaseDevicesDiscoveryService extends AbstractDiscoveryService - implements ThingHandlerService, DiscoveryService { - +public class EnphaseDevicesDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int TIMEOUT_SECONDS = 20; private final Logger logger = LoggerFactory.getLogger(EnphaseDevicesDiscoveryService.class); - private @Nullable EnvoyBridgeHandler envoyHandler; public EnphaseDevicesDiscoveryService() { - super(Set.of(THING_TYPE_ENPHASE_INVERTER), TIMEOUT_SECONDS, false); - } - - @Override - public void setThingHandler(final @Nullable ThingHandler handler) { - if (handler instanceof EnvoyBridgeHandler bridgeHandler) { - envoyHandler = bridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return envoyHandler; - } - - @Override - public void deactivate() { - super.deactivate(); + super(EnvoyBridgeHandler.class, Set.of(THING_TYPE_ENPHASE_INVERTER), TIMEOUT_SECONDS, false); } @Override protected void startScan() { removeOlderResults(getTimestampOfLastScan()); - final EnvoyBridgeHandler envoyHandler = this.envoyHandler; - - if (envoyHandler == null || !envoyHandler.isOnline()) { - logger.debug("Envoy handler not available or online: {}", envoyHandler); + if (!thingHandler.isOnline()) { + logger.debug("Envoy handler not available or online: {}", thingHandler); return; } - final ThingUID uid = envoyHandler.getThing().getUID(); + final ThingUID uid = thingHandler.getThing().getUID(); - scanForInverterThings(envoyHandler, uid); - scanForDeviceThings(envoyHandler, uid); + scanForInverterThings(thingHandler, uid); + scanForDeviceThings(thingHandler, uid); } private void scanForInverterThings(final EnvoyBridgeHandler envoyHandler, final ThingUID bridgeID) { diff --git a/bundles/org.openhab.binding.foobot/src/main/java/org/openhab/binding/foobot/internal/discovery/FoobotAccountDiscoveryService.java b/bundles/org.openhab.binding.foobot/src/main/java/org/openhab/binding/foobot/internal/discovery/FoobotAccountDiscoveryService.java index 67b70280569a3..fcf557f1a399d 100644 --- a/bundles/org.openhab.binding.foobot/src/main/java/org/openhab/binding/foobot/internal/discovery/FoobotAccountDiscoveryService.java +++ b/bundles/org.openhab.binding.foobot/src/main/java/org/openhab/binding/foobot/internal/discovery/FoobotAccountDiscoveryService.java @@ -17,20 +17,18 @@ import java.util.Map; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.foobot.internal.FoobotApiException; import org.openhab.binding.foobot.internal.FoobotBindingConstants; import org.openhab.binding.foobot.internal.FoobotHandlerFactory; import org.openhab.binding.foobot.internal.handler.FoobotAccountHandler; import org.openhab.binding.foobot.internal.handler.FoobotDeviceHandler; import org.openhab.binding.foobot.internal.json.FoobotDevice; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,19 +39,18 @@ * @author George Katsis - Initial contribution * @author Hilbrand Bouwkamp - Completed implementation */ +@Component(scope = ServiceScope.PROTOTYPE, service = FoobotAccountDiscoveryService.class) @NonNullByDefault -public class FoobotAccountDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { +public class FoobotAccountDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int TIMEOUT_SECONDS = 5; private final Logger logger = LoggerFactory.getLogger(FoobotAccountDiscoveryService.class); - private @Nullable FoobotAccountHandler handler; private @NonNullByDefault({}) ThingUID bridgeUID; public FoobotAccountDiscoveryService() { - super(FoobotHandlerFactory.DISCOVERABLE_THING_TYPE_UIDS, TIMEOUT_SECONDS, false); + super(FoobotAccountHandler.class, FoobotHandlerFactory.DISCOVERABLE_THING_TYPE_UIDS, TIMEOUT_SECONDS, false); } @Override @@ -62,13 +59,10 @@ protected void startScan() { } private void retrieveFoobots() { - if (handler == null) { - return; - } try { - final List footbotHandlers = handler.getFootbotHandlers(); + final List footbotHandlers = thingHandler.getFootbotHandlers(); - handler.getDeviceList().stream() + thingHandler.getDeviceList().stream() .filter(d -> !footbotHandlers.stream().anyMatch(h -> h.getUuid().equals(d.getUuid()))) .forEach(this::addThing); } catch (final FoobotApiException e) { @@ -77,11 +71,6 @@ private void retrieveFoobots() { } } - @Override - public void deactivate() { - super.deactivate(); - } - private void addThing(final FoobotDevice foobot) { logger.debug("Adding new Foobot '{}' with uuid: {}", foobot.getName(), foobot.getUuid()); @@ -95,16 +84,4 @@ private void addThing(final FoobotDevice foobot) { thingDiscovered(DiscoveryResultBuilder.create(thingUID).withBridge(bridgeUID).withProperties(properties) .withLabel(foobot.getName()).withRepresentationProperty(foobot.getUuid()).build()); } - - @Override - public void setThingHandler(@Nullable final ThingHandler handler) { - if (handler instanceof FoobotAccountHandler accountHandler) { - this.handler = accountHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return handler; - } } diff --git a/bundles/org.openhab.binding.freebox/src/main/java/org/openhab/binding/freebox/internal/discovery/FreeboxDiscoveryService.java b/bundles/org.openhab.binding.freebox/src/main/java/org/openhab/binding/freebox/internal/discovery/FreeboxDiscoveryService.java index 21f4ec130b8dc..c9ffa48355478 100644 --- a/bundles/org.openhab.binding.freebox/src/main/java/org/openhab/binding/freebox/internal/discovery/FreeboxDiscoveryService.java +++ b/bundles/org.openhab.binding.freebox/src/main/java/org/openhab/binding/freebox/internal/discovery/FreeboxDiscoveryService.java @@ -30,14 +30,14 @@ import org.openhab.binding.freebox.internal.config.FreeboxServerConfiguration; import org.openhab.binding.freebox.internal.handler.FreeboxHandler; import org.openhab.core.config.core.Configuration; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -50,17 +50,16 @@ * @author Laurent Garnier - use new internal API manager * @author Laurent Garnier - use ThingHandlerService */ +@Component(scope = ServiceScope.PROTOTYPE, service = FreeboxDiscoveryService.class) @NonNullByDefault -public class FreeboxDiscoveryService extends AbstractDiscoveryService - implements FreeboxDataListener, ThingHandlerService { +public class FreeboxDiscoveryService extends AbstractThingHandlerDiscoveryService + implements FreeboxDataListener { private final Logger logger = LoggerFactory.getLogger(FreeboxDiscoveryService.class); private static final int SEARCH_TIME = 10; private static final String PHONE_ID = "wired"; - - private @Nullable FreeboxHandler bridgeHandler; private boolean discoverPhone; private boolean discoverNetDevice; private boolean discoverNetInterface; @@ -70,7 +69,7 @@ public class FreeboxDiscoveryService extends AbstractDiscoveryService * Creates a FreeboxDiscoveryService with background discovery disabled. */ public FreeboxDiscoveryService() { - super(FreeboxBindingConstants.SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME, false); + super(FreeboxHandler.class, FreeboxBindingConstants.SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME, false); this.discoverPhone = true; this.discoverNetDevice = true; this.discoverNetInterface = true; @@ -78,58 +77,39 @@ public FreeboxDiscoveryService() { } @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof FreeboxHandler freeboxHandler) { - bridgeHandler = freeboxHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; + public void initialize() { + Configuration config = thingHandler.getThing().getConfiguration(); + Object property = config.get(FreeboxServerConfiguration.DISCOVER_PHONE); + discoverPhone = property != null ? ((Boolean) property).booleanValue() : true; + property = config.get(FreeboxServerConfiguration.DISCOVER_NET_DEVICE); + discoverNetDevice = property != null ? ((Boolean) property).booleanValue() : true; + property = config.get(FreeboxServerConfiguration.DISCOVER_NET_INTERFACE); + discoverNetInterface = property != null ? ((Boolean) property).booleanValue() : true; + property = config.get(FreeboxServerConfiguration.DISCOVER_AIRPLAY_RECEIVER); + discoverAirPlayReceiver = property != null ? ((Boolean) property).booleanValue() : true; + logger.debug("Freebox discovery - discoverPhone : {}", discoverPhone); + logger.debug("Freebox discovery - discoverNetDevice : {}", discoverNetDevice); + logger.debug("Freebox discovery - discoverNetInterface : {}", discoverNetInterface); + logger.debug("Freebox discovery - discoverAirPlayReceiver : {}", discoverAirPlayReceiver); + + thingHandler.registerDataListener(this); + super.initialize(); } @Override - public void activate() { - super.activate(null); - FreeboxHandler handler = bridgeHandler; - if (handler != null) { - Configuration config = handler.getThing().getConfiguration(); - Object property = config.get(FreeboxServerConfiguration.DISCOVER_PHONE); - discoverPhone = property != null ? ((Boolean) property).booleanValue() : true; - property = config.get(FreeboxServerConfiguration.DISCOVER_NET_DEVICE); - discoverNetDevice = property != null ? ((Boolean) property).booleanValue() : true; - property = config.get(FreeboxServerConfiguration.DISCOVER_NET_INTERFACE); - discoverNetInterface = property != null ? ((Boolean) property).booleanValue() : true; - property = config.get(FreeboxServerConfiguration.DISCOVER_AIRPLAY_RECEIVER); - discoverAirPlayReceiver = property != null ? ((Boolean) property).booleanValue() : true; - logger.debug("Freebox discovery - discoverPhone : {}", discoverPhone); - logger.debug("Freebox discovery - discoverNetDevice : {}", discoverNetDevice); - logger.debug("Freebox discovery - discoverNetInterface : {}", discoverNetInterface); - logger.debug("Freebox discovery - discoverAirPlayReceiver : {}", discoverAirPlayReceiver); - - handler.registerDataListener(this); - } - } - - @Override - public void deactivate() { - FreeboxHandler handler = bridgeHandler; - if (handler != null) { - handler.unregisterDataListener(this); - } - super.deactivate(); + public void dispose() { + super.dispose(); + thingHandler.unregisterDataListener(this); } @Override protected void startScan() { logger.debug("Starting Freebox discovery scan"); - FreeboxHandler handler = bridgeHandler; - if (handler != null && handler.getThing().getStatus() == ThingStatus.ONLINE) { + if (thingHandler.getThing().getStatus() == ThingStatus.ONLINE) { try { - List lanHosts = handler.getApiManager().getLanHosts(); - List airPlayDevices = handler.getApiManager().getAirMediaReceivers(); - onDataFetched(handler.getThing().getUID(), lanHosts, airPlayDevices); + List lanHosts = thingHandler.getApiManager().getLanHosts(); + List airPlayDevices = thingHandler.getApiManager().getAirMediaReceivers(); + onDataFetched(thingHandler.getThing().getUID(), lanHosts, airPlayDevices); } catch (FreeboxException e) { logger.warn("Error while requesting data for things discovery", e); } diff --git a/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/ActivePlayerActions.java b/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/ActivePlayerActions.java index 713d1483b73ba..f9639ab824aa8 100644 --- a/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/ActivePlayerActions.java +++ b/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/ActivePlayerActions.java @@ -18,6 +18,8 @@ import org.openhab.core.automation.annotation.RuleAction; import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -26,6 +28,7 @@ * * @author Gaël L'hopital - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = ActivePlayerActions.class) @ThingActionsScope(name = "freeboxos") @NonNullByDefault public class ActivePlayerActions extends PlayerActions { diff --git a/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/CallActions.java b/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/CallActions.java index 9a016e180184d..6d529d2d57d86 100644 --- a/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/CallActions.java +++ b/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/CallActions.java @@ -19,6 +19,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,6 +29,7 @@ * * @author Gaël L'hopital - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = CallActions.class) @ThingActionsScope(name = "freeboxos") @NonNullByDefault public class CallActions implements ThingActions { diff --git a/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/FreeplugActions.java b/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/FreeplugActions.java index 4956f243403aa..495add037852f 100644 --- a/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/FreeplugActions.java +++ b/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/FreeplugActions.java @@ -19,6 +19,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,6 +29,7 @@ * * @author Gaël L'hopital - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = FreeplugActions.class) @ThingActionsScope(name = "freeboxos") @NonNullByDefault public class FreeplugActions implements ThingActions { diff --git a/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/HostActions.java b/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/HostActions.java index 71d5c8926502d..04b2b2c2a55ac 100644 --- a/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/HostActions.java +++ b/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/HostActions.java @@ -19,6 +19,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,6 +29,7 @@ * * @author Gaël L'hopital - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = HostActions.class) @ThingActionsScope(name = "freeboxos") @NonNullByDefault public class HostActions implements ThingActions { diff --git a/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/PlayerActions.java b/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/PlayerActions.java index 40cf8d22a0342..26ef622e7f7f5 100644 --- a/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/PlayerActions.java +++ b/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/PlayerActions.java @@ -20,6 +20,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,6 +30,7 @@ * * @author Gaël L'hopital - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = PlayerActions.class) @ThingActionsScope(name = "freeboxos") @NonNullByDefault public class PlayerActions implements ThingActions { diff --git a/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/RepeaterActions.java b/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/RepeaterActions.java index 1921a1a170592..bbfd7e802acd5 100644 --- a/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/RepeaterActions.java +++ b/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/RepeaterActions.java @@ -19,6 +19,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,6 +29,7 @@ * * @author Gaël L'hopital - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = RepeaterActions.class) @ThingActionsScope(name = "freeboxos") @NonNullByDefault public class RepeaterActions implements ThingActions { diff --git a/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/ServerActions.java b/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/ServerActions.java index 651ac83244feb..d111c807a0300 100644 --- a/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/ServerActions.java +++ b/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/action/ServerActions.java @@ -19,6 +19,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,6 +29,7 @@ * * @author Gaël L'hopital - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = ServerActions.class) @ThingActionsScope(name = "freeboxos") @NonNullByDefault public class ServerActions implements ThingActions { diff --git a/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/discovery/FreeboxOsDiscoveryService.java b/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/discovery/FreeboxOsDiscoveryService.java index 931224c3aa3cc..9fc5b15fb6401 100644 --- a/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/discovery/FreeboxOsDiscoveryService.java +++ b/bundles/org.openhab.binding.freeboxos/src/main/java/org/openhab/binding/freeboxos/internal/discovery/FreeboxOsDiscoveryService.java @@ -24,7 +24,6 @@ import java.util.stream.Stream; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.freeboxos.internal.api.FreeboxException; import org.openhab.binding.freeboxos.internal.api.PermissionException; import org.openhab.binding.freeboxos.internal.api.rest.APManager; @@ -47,15 +46,15 @@ import org.openhab.binding.freeboxos.internal.config.NodeConfigurationBuilder; import org.openhab.binding.freeboxos.internal.config.PhoneConfigurationBuilder; import org.openhab.binding.freeboxos.internal.handler.FreeboxOsHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -67,48 +66,28 @@ * * @author Gaël L'hopital - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = FreeboxOsDiscoveryService.class) @NonNullByDefault -public class FreeboxOsDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class FreeboxOsDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int DISCOVERY_TIME_SECONDS = 10; private final Logger logger = LoggerFactory.getLogger(FreeboxOsDiscoveryService.class); private Optional> backgroundFuture = Optional.empty(); - private @Nullable FreeboxOsHandler bridgeHandler; public FreeboxOsDiscoveryService() { - super(Stream.of(THINGS_TYPES_UIDS, HOME_TYPES_UIDS).flatMap(Set::stream).collect(Collectors.toSet()), + super(FreeboxOsHandler.class, + Stream.of(THINGS_TYPES_UIDS, HOME_TYPES_UIDS).flatMap(Set::stream).collect(Collectors.toSet()), DISCOVERY_TIME_SECONDS); } - @Override - public void deactivate() { - super.deactivate(); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof FreeboxOsHandler freeboxosHandler) { - bridgeHandler = freeboxosHandler; - activate(null); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - @Override protected void startBackgroundDiscovery() { stopBackgroundDiscovery(); - FreeboxOsHandler handler = bridgeHandler; - if (handler != null) { - int interval = handler.getConfiguration().discoveryInterval; - if (interval > 0) { - backgroundFuture = Optional - .of(scheduler.scheduleWithFixedDelay(this::startScan, 1, interval, TimeUnit.MINUTES)); - } + int interval = thingHandler.getConfiguration().discoveryInterval; + if (interval > 0) { + backgroundFuture = Optional + .of(scheduler.scheduleWithFixedDelay(this::startScan, 1, interval, TimeUnit.MINUTES)); } } @@ -121,23 +100,22 @@ protected void stopBackgroundDiscovery() { @Override protected void startScan() { logger.debug("Starting Freebox discovery scan"); - FreeboxOsHandler handler = bridgeHandler; - if (handler != null && handler.getThing().getStatus() == ThingStatus.ONLINE) { + if (thingHandler.getThing().getStatus() == ThingStatus.ONLINE) { try { - ThingUID bridgeUID = handler.getThing().getUID(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); - List lanHosts = new ArrayList<>(handler.getManager(LanBrowserManager.class).getHosts().stream() - .filter(LanHost::reachable).toList()); + List lanHosts = new ArrayList<>(thingHandler.getManager(LanBrowserManager.class).getHosts() + .stream().filter(LanHost::reachable).toList()); - discoverServer(handler.getManager(SystemManager.class), bridgeUID); - discoverPhone(handler.getManager(PhoneManager.class), bridgeUID); - discoverPlugs(handler.getManager(FreeplugManager.class), bridgeUID); - discoverRepeater(handler.getManager(RepeaterManager.class), bridgeUID, lanHosts); - discoverPlayer(handler.getManager(PlayerManager.class), bridgeUID, lanHosts); - discoverVM(handler.getManager(VmManager.class), bridgeUID, lanHosts); - discoverHome(handler.getManager(HomeManager.class), bridgeUID); - if (handler.getConfiguration().discoverNetDevice) { - discoverHosts(handler, bridgeUID, lanHosts); + discoverServer(thingHandler.getManager(SystemManager.class), bridgeUID); + discoverPhone(thingHandler.getManager(PhoneManager.class), bridgeUID); + discoverPlugs(thingHandler.getManager(FreeplugManager.class), bridgeUID); + discoverRepeater(thingHandler.getManager(RepeaterManager.class), bridgeUID, lanHosts); + discoverPlayer(thingHandler.getManager(PlayerManager.class), bridgeUID, lanHosts); + discoverVM(thingHandler.getManager(VmManager.class), bridgeUID, lanHosts); + discoverHome(thingHandler.getManager(HomeManager.class), bridgeUID); + if (thingHandler.getConfiguration().discoverNetDevice) { + discoverHosts(thingHandler, bridgeUID, lanHosts); } } catch (FreeboxException e) { logger.warn("Error while requesting data for things discovery: {}", e.getMessage()); diff --git a/bundles/org.openhab.binding.gardena/src/main/java/org/openhab/binding/gardena/internal/discovery/GardenaDeviceDiscoveryService.java b/bundles/org.openhab.binding.gardena/src/main/java/org/openhab/binding/gardena/internal/discovery/GardenaDeviceDiscoveryService.java index 0ca0c7bc098cc..e6557de8be994 100644 --- a/bundles/org.openhab.binding.gardena/src/main/java/org/openhab/binding/gardena/internal/discovery/GardenaDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.gardena/src/main/java/org/openhab/binding/gardena/internal/discovery/GardenaDeviceDiscoveryService.java @@ -28,15 +28,14 @@ import org.openhab.binding.gardena.internal.model.dto.Device; import org.openhab.binding.gardena.internal.util.PropertyUtils; import org.openhab.binding.gardena.internal.util.UidUtils; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,45 +44,24 @@ * * @author Gerhard Riegler - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = GardenaDeviceDiscoveryService.class) @NonNullByDefault -public class GardenaDeviceDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { +public class GardenaDeviceDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(GardenaDeviceDiscoveryService.class); private static final int DISCOVER_TIMEOUT_SECONDS = 5; - - private @NonNullByDefault({}) GardenaAccountHandler accountHandler; private @Nullable Future scanFuture; public GardenaDeviceDiscoveryService() { - super(Collections.unmodifiableSet(Stream.of(new ThingTypeUID(BINDING_ID, "-")).collect(Collectors.toSet())), + super(GardenaAccountHandler.class, + Collections.unmodifiableSet(Stream.of(new ThingTypeUID(BINDING_ID, "-")).collect(Collectors.toSet())), DISCOVER_TIMEOUT_SECONDS, false); } @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof GardenaAccountHandler gardenaAccountHandler) { - this.accountHandler = gardenaAccountHandler; - this.accountHandler.setDiscoveryService(this); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return accountHandler; - } - - /** - * Called on component activation. - */ - @Override - public void activate() { - super.activate(null); - } - - @Override - public void deactivate() { - super.deactivate(); + public void initialize() { + thingHandler.setDiscoveryService(this); + super.initialize(); } @Override @@ -108,13 +86,13 @@ public void stopScan() { private void loadDevices() { if (scanFuture == null) { scanFuture = scheduler.submit(() -> { - GardenaSmart gardena = accountHandler.getGardenaSmart(); + GardenaSmart gardena = thingHandler.getGardenaSmart(); if (gardena != null) { for (Device device : gardena.getAllDevices()) { deviceDiscovered(device); } - for (Thing thing : accountHandler.getThing().getThings()) { + for (Thing thing : thingHandler.getThing().getThings()) { try { gardena.getDevice(UidUtils.getGardenaDeviceId(thing)); } catch (GardenaException ex) { @@ -155,8 +133,8 @@ public void waitForScanFinishing() { */ public void deviceDiscovered(Device device) { if (device.active) { - ThingUID accountUID = accountHandler.getThing().getUID(); - ThingUID thingUID = UidUtils.generateThingUID(device, accountHandler.getThing()); + ThingUID accountUID = thingHandler.getThing().getUID(); + ThingUID thingUID = UidUtils.generateThingUID(device, thingHandler.getThing()); try { DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withBridge(accountUID) diff --git a/bundles/org.openhab.binding.gce/src/main/java/org/openhab/binding/gce/internal/action/Ipx800Actions.java b/bundles/org.openhab.binding.gce/src/main/java/org/openhab/binding/gce/internal/action/Ipx800Actions.java index a126b325890c7..4a7c95019eca2 100644 --- a/bundles/org.openhab.binding.gce/src/main/java/org/openhab/binding/gce/internal/action/Ipx800Actions.java +++ b/bundles/org.openhab.binding.gce/src/main/java/org/openhab/binding/gce/internal/action/Ipx800Actions.java @@ -20,6 +20,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,6 +30,7 @@ * * @author Gaël L'hopital - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = Ipx800Actions.class) @ThingActionsScope(name = "gce") @NonNullByDefault public class Ipx800Actions implements ThingActions { diff --git a/bundles/org.openhab.binding.groupepsa/src/main/java/org/openhab/binding/groupepsa/internal/discovery/GroupePSADiscoveryService.java b/bundles/org.openhab.binding.groupepsa/src/main/java/org/openhab/binding/groupepsa/internal/discovery/GroupePSADiscoveryService.java index c67025e95d4b3..2c80b6c779a50 100644 --- a/bundles/org.openhab.binding.groupepsa/src/main/java/org/openhab/binding/groupepsa/internal/discovery/GroupePSADiscoveryService.java +++ b/bundles/org.openhab.binding.groupepsa/src/main/java/org/openhab/binding/groupepsa/internal/discovery/GroupePSADiscoveryService.java @@ -25,14 +25,13 @@ import org.openhab.binding.groupepsa.internal.bridge.GroupePSABridgeHandler; import org.openhab.binding.groupepsa.internal.rest.api.dto.Vehicle; import org.openhab.binding.groupepsa.internal.rest.exceptions.GroupePSACommunicationException; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,48 +41,25 @@ * * @author Arjan Mels - Initial contribution */ -@Component(service = ThingHandlerService.class) +@Component(scope = ServiceScope.PROTOTYPE, service = GroupePSADiscoveryService.class) @NonNullByDefault -public class GroupePSADiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class GroupePSADiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(GroupePSADiscoveryService.class); - private @Nullable GroupePSABridgeHandler bridgeHandler; - public GroupePSADiscoveryService() { - super(Set.of(THING_TYPE_VEHICLE), 10, false); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof GroupePSABridgeHandler bridgeHandler) { - this.bridgeHandler = bridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - - @Override - public void deactivate() { - super.deactivate(); + super(GroupePSABridgeHandler.class, Set.of(THING_TYPE_VEHICLE), 10, false); } @Override protected void startScan() { try { - GroupePSABridgeHandler localBridgeHandler = bridgeHandler; - if (localBridgeHandler == null) { - return; - } - List vehicles = localBridgeHandler.getVehicles(); + List vehicles = thingHandler.getVehicles(); if (vehicles == null || vehicles.isEmpty()) { logger.warn("No vehicles found"); return; } for (Vehicle vehicle : vehicles) { - ThingUID bridgeUID = localBridgeHandler.getThing().getUID(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); ThingTypeUID thingTypeUID = THING_TYPE_VEHICLE; String id = vehicle.getId(); if (id != null) { diff --git a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/discovery/HaywardDiscoveryService.java b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/discovery/HaywardDiscoveryService.java index 3a2eb778ad092..0cd34f2e290ee 100644 --- a/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/discovery/HaywardDiscoveryService.java +++ b/bundles/org.openhab.binding.haywardomnilogic/src/main/java/org/openhab/binding/haywardomnilogic/internal/discovery/HaywardDiscoveryService.java @@ -27,14 +27,13 @@ import org.openhab.binding.haywardomnilogic.internal.HaywardException; import org.openhab.binding.haywardomnilogic.internal.HaywardTypeToRequest; import org.openhab.binding.haywardomnilogic.internal.handler.HaywardBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,34 +42,20 @@ * * @author Matt Myers - Initial contribution */ - +@Component(scope = ServiceScope.PROTOTYPE, service = HaywardDiscoveryService.class) @NonNullByDefault -public class HaywardDiscoveryService extends AbstractDiscoveryService implements DiscoveryService, ThingHandlerService { +public class HaywardDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(HaywardDiscoveryService.class); - private @Nullable HaywardBridgeHandler discoveryBridgehandler; public HaywardDiscoveryService() { - super(THING_TYPES_UIDS, 0, false); - } - - @Override - public void activate() { - super.activate(null); - } - - @Override - public void deactivate() { - super.deactivate(); + super(HaywardBridgeHandler.class, THING_TYPES_UIDS, 0, false); } @Override protected void startScan() { - HaywardBridgeHandler bridgehandler = discoveryBridgehandler; try { - if (bridgehandler != null) { - String xmlResults = bridgehandler.getMspConfig(); - mspConfigDiscovery(xmlResults); - } + String xmlResults = thingHandler.getMspConfig(); + mspConfigDiscovery(xmlResults); } catch (HaywardException e) { logger.warn("Exception during discovery scan: {}", e.getMessage()); } catch (InterruptedException e) { @@ -83,36 +68,30 @@ public synchronized void mspConfigDiscovery(String xmlResponse) { List names = new ArrayList<>(); Map backyardProperties = new HashMap<>(); Map bowProperties = new HashMap<>(); - HaywardBridgeHandler bridgehandler = discoveryBridgehandler; - - if (bridgehandler == null) { - return; - } // Find Backyard - names = bridgehandler.evaluateXPath("//Backyard/Name/text()", xmlResponse); + names = thingHandler.evaluateXPath("//Backyard/Name/text()", xmlResponse); for (int i = 0; i < names.size(); i++) { backyardProperties.put(HaywardBindingConstants.PROPERTY_TYPE, HaywardTypeToRequest.BACKYARD); - backyardProperties.put(HaywardBindingConstants.PROPERTY_SYSTEM_ID, bridgehandler.account.mspSystemID); + backyardProperties.put(HaywardBindingConstants.PROPERTY_SYSTEM_ID, thingHandler.account.mspSystemID); onDeviceDiscovered(HaywardBindingConstants.THING_TYPE_BACKYARD, names.get(i), backyardProperties); } // Find Bodies of Water - systemIDs = bridgehandler.evaluateXPath("//Body-of-water/System-Id/text()", xmlResponse); - names = bridgehandler.evaluateXPath("//Body-of-water/Name/text()", xmlResponse); + systemIDs = thingHandler.evaluateXPath("//Body-of-water/System-Id/text()", xmlResponse); + names = thingHandler.evaluateXPath("//Body-of-water/Name/text()", xmlResponse); - final List bowProperty1 = bridgehandler.evaluateXPath("//Body-of-water/Type/text()", xmlResponse); - final List bowProperty2 = bridgehandler.evaluateXPath("//Body-of-water/Shared-Type/text()", - xmlResponse); - final List bowProperty3 = bridgehandler.evaluateXPath("//Body-of-water/Shared-Priority/text()", + final List bowProperty1 = thingHandler.evaluateXPath("//Body-of-water/Type/text()", xmlResponse); + final List bowProperty2 = thingHandler.evaluateXPath("//Body-of-water/Shared-Type/text()", xmlResponse); + final List bowProperty3 = thingHandler.evaluateXPath("//Body-of-water/Shared-Priority/text()", xmlResponse); - final List bowProperty4 = bridgehandler + final List bowProperty4 = thingHandler .evaluateXPath("//Body-of-water/Shared-Equipment-System-ID/text()", xmlResponse); - final List bowProperty5 = bridgehandler.evaluateXPath("//Body-of-water/Supports-Spillover/text()", + final List bowProperty5 = thingHandler.evaluateXPath("//Body-of-water/Supports-Spillover/text()", xmlResponse); - final List bowProperty6 = bridgehandler.evaluateXPath("//Body-of-water/Size-In-Gallons/text()", + final List bowProperty6 = thingHandler.evaluateXPath("//Body-of-water/Size-In-Gallons/text()", xmlResponse); for (int i = 0; i < systemIDs.size(); i++) { @@ -129,16 +108,16 @@ public synchronized void mspConfigDiscovery(String xmlResponse) { } // Find Chlorinators - final List chlorinatorProperty1 = bridgehandler + final List chlorinatorProperty1 = thingHandler .evaluateXPath("//Body-of-water/Chlorinator/Shared-Type/text()", xmlResponse); - final List chlorinatorProperty2 = bridgehandler.evaluateXPath("//Body-of-water/Chlorinator/Mode/text()", + final List chlorinatorProperty2 = thingHandler.evaluateXPath("//Body-of-water/Chlorinator/Mode/text()", xmlResponse); - final List chlorinatorProperty3 = bridgehandler + final List chlorinatorProperty3 = thingHandler .evaluateXPath("//Body-of-water/Chlorinator/Cell-Type/text()", xmlResponse); - final List chlorinatorProperty4 = bridgehandler + final List chlorinatorProperty4 = thingHandler .evaluateXPath("//Body-of-water/Chlorinator/Dispenser-Type/text()", xmlResponse); - discoverDevices(bridgehandler, xmlResponse, "Chlorinator", HaywardTypeToRequest.CHLORINATOR, + discoverDevices(thingHandler, xmlResponse, "Chlorinator", HaywardTypeToRequest.CHLORINATOR, HaywardBindingConstants.THING_TYPE_CHLORINATOR, (props, i) -> { props.put(HaywardBindingConstants.PROPERTY_CHLORINATOR_SHAREDTYPE, chlorinatorProperty1.get(i)); props.put(HaywardBindingConstants.PROPERTY_CHLORINATOR_MODE, chlorinatorProperty2.get(i)); @@ -147,41 +126,41 @@ public synchronized void mspConfigDiscovery(String xmlResponse) { }); // Find ColorLogic Lights - final List colorLogicProperty1 = bridgehandler.evaluateXPath("//Backyard//ColorLogic-Light/Type/text()", + final List colorLogicProperty1 = thingHandler.evaluateXPath("//Backyard//ColorLogic-Light/Type/text()", xmlResponse); - discoverDevices(bridgehandler, xmlResponse, "ColorLogic-Light", HaywardTypeToRequest.COLORLOGIC, + discoverDevices(thingHandler, xmlResponse, "ColorLogic-Light", HaywardTypeToRequest.COLORLOGIC, HaywardBindingConstants.THING_TYPE_COLORLOGIC, (props, i) -> { props.put(HaywardBindingConstants.PROPERTY_COLORLOGIC_TYPE, colorLogicProperty1.get(i)); }); // Find Filters - final List filterProperty1 = bridgehandler.evaluateXPath("//Body-of-water/Filter/Shared-Type/text()", + final List filterProperty1 = thingHandler.evaluateXPath("//Body-of-water/Filter/Shared-Type/text()", + xmlResponse); + final List filterProperty2 = thingHandler.evaluateXPath("//Body-of-water/Filter/Filter-Type/text()", xmlResponse); - final List filterProperty2 = bridgehandler.evaluateXPath("//Body-of-water/Filter/Filter-Type/text()", + final List filterProperty3 = thingHandler.evaluateXPath("//Body-of-water/Filter/Priming-Enabled/text()", xmlResponse); - final List filterProperty3 = bridgehandler - .evaluateXPath("//Body-of-water/Filter/Priming-Enabled/text()", xmlResponse); - final List filterProperty4 = bridgehandler.evaluateXPath("//Body-of-water/Filter/Min-Pump-Speed/text()", + final List filterProperty4 = thingHandler.evaluateXPath("//Body-of-water/Filter/Min-Pump-Speed/text()", xmlResponse); - final List filterProperty5 = bridgehandler.evaluateXPath("//Body-of-water/Filter/Max-Pump-Speed/text()", + final List filterProperty5 = thingHandler.evaluateXPath("//Body-of-water/Filter/Max-Pump-Speed/text()", xmlResponse); - final List filterProperty6 = bridgehandler.evaluateXPath("//Body-of-water/Filter/Min-Pump-RPM/text()", + final List filterProperty6 = thingHandler.evaluateXPath("//Body-of-water/Filter/Min-Pump-RPM/text()", xmlResponse); - final List filterProperty7 = bridgehandler.evaluateXPath("//Body-of-water/Filter/Max-Pump-RPM/text()", + final List filterProperty7 = thingHandler.evaluateXPath("//Body-of-water/Filter/Max-Pump-RPM/text()", xmlResponse); - final List filterProperty8 = bridgehandler + final List filterProperty8 = thingHandler .evaluateXPath("//Body-of-water/Filter/Vsp-Low-Pump-Speed/text()", xmlResponse); - final List filterProperty9 = bridgehandler + final List filterProperty9 = thingHandler .evaluateXPath("//Body-of-water/Filter/Vsp-Medium-Pump-Speed/text()", xmlResponse); - final List filterProperty10 = bridgehandler + final List filterProperty10 = thingHandler .evaluateXPath("//Body-of-water/Filter/Vsp-High-Pump-Speed/text()", xmlResponse); - final List filterProperty11 = bridgehandler + final List filterProperty11 = thingHandler .evaluateXPath("//Body-of-water/Filter/Vsp-Custom-Pump-Speed/text()", xmlResponse); - final List filterProperty12 = bridgehandler + final List filterProperty12 = thingHandler .evaluateXPath("//Body-of-water/Filter/Freeze-Protect-Override-Interval/text()", xmlResponse); - discoverDevices(bridgehandler, xmlResponse, "Filter", HaywardTypeToRequest.FILTER, + discoverDevices(thingHandler, xmlResponse, "Filter", HaywardTypeToRequest.FILTER, HaywardBindingConstants.THING_TYPE_FILTER, (props, i) -> { props.put(HaywardBindingConstants.PROPERTY_FILTER_SHAREDTYPE, filterProperty1.get(i)); props.put(HaywardBindingConstants.PROPERTY_FILTER_FILTERTYPE, filterProperty2.get(i)); @@ -199,14 +178,14 @@ public synchronized void mspConfigDiscovery(String xmlResponse) { }); // Find Heaters - final List heaterProperty1 = bridgehandler + final List heaterProperty1 = thingHandler .evaluateXPath("//Body-of-water/Heater/Operation/Heater-Equipment/Type/text()", xmlResponse); - final List heaterProperty2 = bridgehandler + final List heaterProperty2 = thingHandler .evaluateXPath("//Body-of-water/Heater/Operation/Heater-Equipment/Heater-Type/text()", xmlResponse); - final List heaterProperty3 = bridgehandler.evaluateXPath( + final List heaterProperty3 = thingHandler.evaluateXPath( "//Body-of-water/Heater/Operation/Heater-Equipment/Shared-Equipment-System-ID/text()", xmlResponse); - discoverDevices(bridgehandler, xmlResponse, "Heater-Equipment", HaywardTypeToRequest.HEATER, + discoverDevices(thingHandler, xmlResponse, "Heater-Equipment", HaywardTypeToRequest.HEATER, HaywardBindingConstants.THING_TYPE_HEATER, (props, i) -> { props.put(HaywardBindingConstants.PROPERTY_HEATER_TYPE, heaterProperty1.get(i)); props.put(HaywardBindingConstants.PROPERTY_HEATER_HEATERTYPE, heaterProperty2.get(i)); @@ -214,29 +193,29 @@ public synchronized void mspConfigDiscovery(String xmlResponse) { }); // Find Pumps - final List pumpProperty1 = bridgehandler.evaluateXPath("//Body-of-water/Pump/Type/text()", xmlResponse); - final List pumpProperty2 = bridgehandler.evaluateXPath("//Body-of-water/Pump/Function/text()", + final List pumpProperty1 = thingHandler.evaluateXPath("//Body-of-water/Pump/Type/text()", xmlResponse); + final List pumpProperty2 = thingHandler.evaluateXPath("//Body-of-water/Pump/Function/text()", xmlResponse); - final List pumpProperty3 = bridgehandler.evaluateXPath("//Body-of-water/Pump/Priming-Enabled/text()", + final List pumpProperty3 = thingHandler.evaluateXPath("//Body-of-water/Pump/Priming-Enabled/text()", xmlResponse); - final List pumpProperty4 = bridgehandler.evaluateXPath("//Body-of-water/Pump/Min-Pump-Speed/text()", + final List pumpProperty4 = thingHandler.evaluateXPath("//Body-of-water/Pump/Min-Pump-Speed/text()", xmlResponse); - final List pumpProperty5 = bridgehandler.evaluateXPath("//Body-of-water/Pump/Max-Pump-Speed/text()", + final List pumpProperty5 = thingHandler.evaluateXPath("//Body-of-water/Pump/Max-Pump-Speed/text()", xmlResponse); - final List pumpProperty6 = bridgehandler.evaluateXPath("//Body-of-water/Pump/Min-Pump-RPM/text()", + final List pumpProperty6 = thingHandler.evaluateXPath("//Body-of-water/Pump/Min-Pump-RPM/text()", xmlResponse); - final List pumpProperty7 = bridgehandler.evaluateXPath("//Body-of-water/Pump/Max-Pump-RPM/text()", + final List pumpProperty7 = thingHandler.evaluateXPath("//Body-of-water/Pump/Max-Pump-RPM/text()", xmlResponse); - final List pumpProperty8 = bridgehandler.evaluateXPath("//Body-of-water/Pump/Vsp-Low-Pump-Speed/text()", + final List pumpProperty8 = thingHandler.evaluateXPath("//Body-of-water/Pump/Vsp-Low-Pump-Speed/text()", xmlResponse); - final List pumpProperty9 = bridgehandler + final List pumpProperty9 = thingHandler .evaluateXPath("//Body-of-water/Pump/Vsp-Medium-Pump-Speed/text()", xmlResponse); - final List pumpProperty10 = bridgehandler + final List pumpProperty10 = thingHandler .evaluateXPath("//Body-of-water/Pump/Vsp-High-Pump-Speed/text()", xmlResponse); - final List pumpProperty11 = bridgehandler + final List pumpProperty11 = thingHandler .evaluateXPath("//Body-of-water/Pump/Vsp-Custom-Pump-Speed/text()", xmlResponse); - discoverDevices(bridgehandler, xmlResponse, "Pump", HaywardTypeToRequest.PUMP, + discoverDevices(thingHandler, xmlResponse, "Pump", HaywardTypeToRequest.PUMP, HaywardBindingConstants.THING_TYPE_PUMP, (props, i) -> { props.put(HaywardBindingConstants.PROPERTY_PUMP_TYPE, pumpProperty1.get(i)); props.put(HaywardBindingConstants.PROPERTY_PUMP_FUNCTION, pumpProperty2.get(i)); @@ -252,27 +231,27 @@ public synchronized void mspConfigDiscovery(String xmlResponse) { }); // Find Relays - final List relayProperty1 = bridgehandler.evaluateXPath("//Backyard//Relay/Type/text()", xmlResponse); - final List relayProperty2 = bridgehandler.evaluateXPath("//Backyard//Relay/Function/text()", + final List relayProperty1 = thingHandler.evaluateXPath("//Backyard//Relay/Type/text()", xmlResponse); + final List relayProperty2 = thingHandler.evaluateXPath("//Backyard//Relay/Function/text()", xmlResponse); - discoverDevices(bridgehandler, xmlResponse, "Relay", HaywardTypeToRequest.RELAY, + discoverDevices(thingHandler, xmlResponse, "Relay", HaywardTypeToRequest.RELAY, HaywardBindingConstants.THING_TYPE_RELAY, (props, i) -> { props.put(HaywardBindingConstants.PROPERTY_RELAY_TYPE, relayProperty1.get(i)); props.put(HaywardBindingConstants.PROPERTY_RELAY_FUNCTION, relayProperty2.get(i)); }); // Find Virtual Heaters - final List virtualHeaterProperty1 = bridgehandler + final List virtualHeaterProperty1 = thingHandler .evaluateXPath("//Body-of-water/Heater/Shared-Type/text()", xmlResponse); - final List virtualHeaterProperty2 = bridgehandler + final List virtualHeaterProperty2 = thingHandler .evaluateXPath("//Body-of-water/Heater/Min-Settable-Water-Temp/text()", xmlResponse); - final List virtualHeaterProperty3 = bridgehandler + final List virtualHeaterProperty3 = thingHandler .evaluateXPath("//Body-of-water/Heater/Max-Settable-Water-Temp/text()", xmlResponse); - final List virtualHeaterProperty4 = bridgehandler + final List virtualHeaterProperty4 = thingHandler .evaluateXPath("//Body-of-water/Heater/Max-Water-Temp/text()", xmlResponse); - discoverDevices(bridgehandler, xmlResponse, "Heater", HaywardTypeToRequest.VIRTUALHEATER, + discoverDevices(thingHandler, xmlResponse, "Heater", HaywardTypeToRequest.VIRTUALHEATER, HaywardBindingConstants.THING_TYPE_VIRTUALHEATER, (props, i) -> { props.put(HaywardBindingConstants.PROPERTY_VIRTUALHEATER_SHAREDTYPE, virtualHeaterProperty1.get(i)); props.put(HaywardBindingConstants.PROPERTY_VIRTUALHEATER_MINSETTABLEWATERTEMP, @@ -333,7 +312,7 @@ private void discoverDevices(HaywardBridgeHandler bridgehandler, String xmlRespo } public void onDeviceDiscovered(ThingTypeUID thingType, String label, Map properties) { - HaywardBridgeHandler bridgehandler = discoveryBridgehandler; + HaywardBridgeHandler bridgehandler = thingHandler; String systemID = (String) properties.get(HaywardBindingConstants.PROPERTY_SYSTEM_ID); if (bridgehandler != null) { if (systemID != null) { @@ -346,16 +325,4 @@ public void onDeviceDiscovered(ThingTypeUID thingType, String label, Map { private static final int SEARCH_TIME_SEC = 20; private final Logger logger = LoggerFactory.getLogger(HomeConnectDiscoveryService.class); - private @Nullable HomeConnectBridgeHandler bridgeHandler; - /** * Construct a {@link HomeConnectDiscoveryService}. * */ public HomeConnectDiscoveryService() { - super(DISCOVERABLE_DEVICE_THING_TYPES_UIDS, SEARCH_TIME_SEC, true); - } - - @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof HomeConnectBridgeHandler homeConnectBridgeHandler) { - this.bridgeHandler = homeConnectBridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; + super(HomeConnectBridgeHandler.class, DISCOVERABLE_DEVICE_THING_TYPES_UIDS, SEARCH_TIME_SEC, true); } @Override protected void startScan() { logger.debug("Starting device scan."); - var bridgeHandler = this.bridgeHandler; - if (bridgeHandler != null) { - HomeConnectApiClient apiClient = bridgeHandler.getApiClient(); - - try { - List appliances = apiClient.getHomeAppliances(); - logger.debug("Scan found {} devices.", appliances.size()); - - // add found devices - for (HomeAppliance appliance : appliances) { - @Nullable - ThingTypeUID thingTypeUID = getThingTypeUID(appliance); - - if (thingTypeUID != null) { - logger.debug("Found {} ({}).", appliance.getHaId(), appliance.getType().toUpperCase()); - - Map properties = Map.of(HA_ID, appliance.getHaId()); - String name = appliance.getBrand() + " " + appliance.getName() + " (" + appliance.getHaId() - + ")"; - - DiscoveryResult discoveryResult = DiscoveryResultBuilder - .create(new ThingUID(BINDING_ID, appliance.getType(), - bridgeHandler.getThing().getUID().getId(), appliance.getHaId())) - .withThingType(thingTypeUID).withProperties(properties) - .withRepresentationProperty(HA_ID).withBridge(bridgeHandler.getThing().getUID()) - .withLabel(name).build(); - thingDiscovered(discoveryResult); - } else { - logger.debug("Ignoring unsupported device {} of type {}.", appliance.getHaId(), - appliance.getType()); - } + HomeConnectApiClient apiClient = thingHandler.getApiClient(); + + try { + List appliances = apiClient.getHomeAppliances(); + logger.debug("Scan found {} devices.", appliances.size()); + + // add found devices + for (HomeAppliance appliance : appliances) { + @Nullable + ThingTypeUID thingTypeUID = getThingTypeUID(appliance); + + if (thingTypeUID != null) { + logger.debug("Found {} ({}).", appliance.getHaId(), appliance.getType().toUpperCase()); + + Map properties = Map.of(HA_ID, appliance.getHaId()); + String name = appliance.getBrand() + " " + appliance.getName() + " (" + appliance.getHaId() + ")"; + + DiscoveryResult discoveryResult = DiscoveryResultBuilder + .create(new ThingUID(BINDING_ID, appliance.getType(), + thingHandler.getThing().getUID().getId(), appliance.getHaId())) + .withThingType(thingTypeUID).withProperties(properties).withRepresentationProperty(HA_ID) + .withBridge(thingHandler.getThing().getUID()).withLabel(name).build(); + thingDiscovered(discoveryResult); + } else { + logger.debug("Ignoring unsupported device {} of type {}.", appliance.getHaId(), + appliance.getType()); } - } catch (CommunicationException | AuthorizationException e) { - logger.debug("Exception during scan.", e); } + } catch (CommunicationException | AuthorizationException e) { + logger.debug("Exception during scan.", e); } + logger.debug("Finished device scan."); } @Override - public void deactivate() { - super.deactivate(); - var bridgeHandler = this.bridgeHandler; - if (bridgeHandler != null) { - removeOlderResults(System.currentTimeMillis(), bridgeHandler.getThing().getUID()); - } + public void dispose() { + super.dispose(); + removeOlderResults(System.currentTimeMillis(), thingHandler.getThing().getUID()); } @Override protected synchronized void stopScan() { super.stopScan(); - var bridgeHandler = this.bridgeHandler; - if (bridgeHandler != null) { - removeOlderResults(getTimestampOfLastScan(), bridgeHandler.getThing().getUID()); - } + removeOlderResults(getTimestampOfLastScan(), thingHandler.getThing().getUID()); } private @Nullable ThingTypeUID getThingTypeUID(HomeAppliance appliance) { diff --git a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/discovery/HomematicDeviceDiscoveryService.java b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/discovery/HomematicDeviceDiscoveryService.java index 8028445c7bef1..acc172422f0b0 100644 --- a/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/discovery/HomematicDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/discovery/HomematicDeviceDiscoveryService.java @@ -18,23 +18,21 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; -import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; +import org.eclipse.jdt.annotation.NonNull; import org.openhab.binding.homematic.internal.common.HomematicConfig; import org.openhab.binding.homematic.internal.communicator.HomematicGateway; import org.openhab.binding.homematic.internal.handler.HomematicBridgeHandler; import org.openhab.binding.homematic.internal.model.HmDevice; import org.openhab.binding.homematic.internal.type.UidUtils; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,44 +41,24 @@ * * @author Gerhard Riegler - Initial contribution */ -public class HomematicDeviceDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { +@Component(scope = ServiceScope.PROTOTYPE, service = HomematicDeviceDiscoveryService.class) +public class HomematicDeviceDiscoveryService + extends AbstractThingHandlerDiscoveryService<@NonNull HomematicBridgeHandler> { private final Logger logger = LoggerFactory.getLogger(HomematicDeviceDiscoveryService.class); private static final int DISCOVER_TIMEOUT_SECONDS = 300; - private @NonNullByDefault({}) HomematicBridgeHandler bridgeHandler; private Future loadDevicesFuture; private volatile boolean isInInstallMode = false; private volatile Object installModeSync = new Object(); public HomematicDeviceDiscoveryService() { - super(Set.of(new ThingTypeUID(BINDING_ID, "-")), DISCOVER_TIMEOUT_SECONDS, false); + super(HomematicBridgeHandler.class, Set.of(new ThingTypeUID(BINDING_ID, "-")), DISCOVER_TIMEOUT_SECONDS, false); } @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof HomematicBridgeHandler homematicBridgeHandler) { - this.bridgeHandler = homematicBridgeHandler; - this.bridgeHandler.setDiscoveryService(this); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - - /** - * Called on component activation. - */ - @Override - public void activate() { - super.activate(null); - } - - @Override - public void deactivate() { - super.deactivate(); + public void initialize() { + thingHandler.setDiscoveryService(this); + super.initialize(); } @Override @@ -96,13 +74,10 @@ protected void startScan() { */ private void enableInstallMode() { try { - HomematicGateway gateway = bridgeHandler.getGateway(); - ThingStatus bridgeStatus = null; + HomematicGateway gateway = thingHandler.getGateway(); + Thing bridge = thingHandler.getThing(); + ThingStatus bridgeStatus = bridge.getStatus(); - if (bridgeHandler != null) { - Thing bridge = bridgeHandler.getThing(); - bridgeStatus = bridge.getStatus(); - } if (ThingStatus.ONLINE == bridgeStatus) { gateway.setInstallMode(true, getInstallModeDuration()); @@ -122,10 +97,7 @@ private void enableInstallMode() { } private int getInstallModeDuration() { - if (bridgeHandler != null) { - return bridgeHandler.getThing().getConfiguration().as(HomematicConfig.class).getInstallModeDuration(); - } - return HomematicConfig.DEFAULT_INSTALL_MODE_DURATION; + return thingHandler.getThing().getConfiguration().as(HomematicConfig.class).getInstallModeDuration(); } @Override @@ -136,10 +108,8 @@ public int getScanTimeout() { @Override public synchronized void stopScan() { logger.debug("Stopping Homematic discovery scan"); - if (bridgeHandler != null && bridgeHandler.getGateway() != null) { - disableInstallMode(); - bridgeHandler.getGateway().cancelLoadAllDeviceMetadata(); - } + disableInstallMode(); + thingHandler.getGateway().cancelLoadAllDeviceMetadata(); waitForScanFinishing(); super.stopScan(); } @@ -150,7 +120,7 @@ private void disableInstallMode() { if (isInInstallMode) { isInInstallMode = false; installModeSync.notify(); - bridgeHandler.getGateway().setInstallMode(false, 0); + thingHandler.getGateway().setInstallMode(false, 0); } } @@ -192,6 +162,7 @@ public void waitForScanFinishing() { } catch (Exception ex) { logger.error("Error waiting for device discovery scan: {}", ex.getMessage(), ex); } + HomematicBridgeHandler bridgeHandler = thingHandler; String gatewayId = bridgeHandler != null && bridgeHandler.getGateway() != null ? bridgeHandler.getGateway().getId() : "UNKNOWN"; @@ -202,17 +173,17 @@ public void waitForScanFinishing() { * Starts a thread which loads all Homematic devices connected to the gateway. */ public void loadDevices() { - if (loadDevicesFuture == null && bridgeHandler.getGateway() != null) { + if (loadDevicesFuture == null && thingHandler.getGateway() != null) { loadDevicesFuture = scheduler.submit(() -> { try { - final HomematicGateway gateway = bridgeHandler.getGateway(); + final HomematicGateway gateway = thingHandler.getGateway(); gateway.loadAllDeviceMetadata(); - bridgeHandler.getTypeGenerator().validateFirmwares(); + thingHandler.getTypeGenerator().validateFirmwares(); } catch (Throwable ex) { logger.error("{}", ex.getMessage(), ex); } finally { loadDevicesFuture = null; - bridgeHandler.setOfflineStatus(); + thingHandler.setOfflineStatus(); removeOlderResults(getTimestampOfLastScan()); } }); @@ -225,7 +196,7 @@ public void loadDevices() { * Removes the Homematic device. */ public void deviceRemoved(HmDevice device) { - ThingUID thingUID = UidUtils.generateThingUID(device, bridgeHandler.getThing()); + ThingUID thingUID = UidUtils.generateThingUID(device, thingHandler.getThing()); thingRemoved(thingUID); } @@ -233,12 +204,11 @@ public void deviceRemoved(HmDevice device) { * Generates the DiscoveryResult from a Homematic device. */ public void deviceDiscovered(HmDevice device) { - ThingUID bridgeUID = bridgeHandler.getThing().getUID(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); ThingTypeUID typeUid = UidUtils.generateThingTypeUID(device); ThingUID thingUID = new ThingUID(typeUid, bridgeUID, device.getAddress()); String label = device.getName() != null ? device.getName() : device.getAddress(); - long timeToLive = bridgeHandler.getThing().getConfiguration().as(HomematicConfig.class) - .getDiscoveryTimeToLive(); + long timeToLive = thingHandler.getThing().getConfiguration().as(HomematicConfig.class).getDiscoveryTimeToLive(); DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withBridge(bridgeUID).withLabel(label) .withProperty(Thing.PROPERTY_SERIAL_NUMBER, device.getAddress()) diff --git a/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/action/DynamicsActions.java b/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/action/DynamicsActions.java index 87cb88325b42e..dd6fdcbcd921d 100644 --- a/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/action/DynamicsActions.java +++ b/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/action/DynamicsActions.java @@ -24,6 +24,8 @@ import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.types.Command; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,6 +35,7 @@ * * @author Andrew Fiddian-Green - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = DynamicsActions.class) @ThingActionsScope(name = "hue") @NonNullByDefault public class DynamicsActions implements ThingActions { diff --git a/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/action/LightActions.java b/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/action/LightActions.java index cfa2fcc069627..5207789a4755c 100644 --- a/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/action/LightActions.java +++ b/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/action/LightActions.java @@ -22,6 +22,8 @@ import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.types.Command; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -30,6 +32,7 @@ * * @author Jochen Leopold - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = LightActions.class) @ThingActionsScope(name = "hue") @NonNullByDefault public class LightActions implements ThingActions { diff --git a/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/discovery/Clip2ThingDiscoveryService.java b/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/discovery/Clip2ThingDiscoveryService.java index 4614e659ed978..75d8e86b76763 100644 --- a/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/discovery/Clip2ThingDiscoveryService.java +++ b/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/discovery/Clip2ThingDiscoveryService.java @@ -33,14 +33,14 @@ import org.openhab.binding.hue.internal.exceptions.ApiException; import org.openhab.binding.hue.internal.exceptions.AssetNotLoadedException; import org.openhab.binding.hue.internal.handler.Clip2BridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -49,9 +49,9 @@ * * @author Andrew Fiddian-Green - Initial Contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = Clip2ThingDiscoveryService.class) @NonNullByDefault -public class Clip2ThingDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { - +public class Clip2ThingDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(Clip2ThingDiscoveryService.class); private static final int DISCOVERY_TIMEOUT_SECONDS = 20; @@ -66,31 +66,24 @@ public class Clip2ThingDiscoveryService extends AbstractDiscoveryService impleme ResourceType.ZONE, THING_TYPE_ZONE, // ResourceType.BRIDGE_HOME, THING_TYPE_ZONE); - private @Nullable Clip2BridgeHandler bridgeHandler; private @Nullable ScheduledFuture discoveryTask; public Clip2ThingDiscoveryService() { - super(Set.of(THING_TYPE_DEVICE, THING_TYPE_ROOM, THING_TYPE_ZONE), DISCOVERY_TIMEOUT_SECONDS, true); + super(Clip2BridgeHandler.class, Set.of(THING_TYPE_DEVICE, THING_TYPE_ROOM, THING_TYPE_ZONE), + DISCOVERY_TIMEOUT_SECONDS, true); } @Override - public void activate() { - Clip2BridgeHandler bridgeHandler = this.bridgeHandler; - if (Objects.nonNull(bridgeHandler)) { - bridgeHandler.registerDiscoveryService(this); - } - super.activate(null); + public void initialize() { + thingHandler.registerDiscoveryService(this); + super.initialize(); } @Override - public void deactivate() { - super.deactivate(); - Clip2BridgeHandler bridgeHandler = this.bridgeHandler; - if (Objects.nonNull(bridgeHandler)) { - bridgeHandler.unregisterDiscoveryService(); - removeOlderResults(new Date().getTime(), bridgeHandler.getThing().getBridgeUID()); - this.bridgeHandler = null; - } + public void dispose() { + super.dispose(); + thingHandler.unregisterDiscoveryService(); + removeOlderResults(new Date().getTime(), thingHandler.getThing().getBridgeUID()); } /** @@ -98,12 +91,11 @@ public void deactivate() { * as OH things, and announce those respective things by calling the core 'thingDiscovered()' method. */ private synchronized void discoverThings() { - Clip2BridgeHandler bridgeHandler = this.bridgeHandler; - if (Objects.nonNull(bridgeHandler) && bridgeHandler.getThing().getStatus() == ThingStatus.ONLINE) { + if (thingHandler.getThing().getStatus() == ThingStatus.ONLINE) { try { - ThingUID bridgeUID = bridgeHandler.getThing().getUID(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); for (Entry entry : DISCOVERY_TYPES.entrySet()) { - for (Resource resource : bridgeHandler.getResources(new ResourceReference().setType(entry.getKey())) + for (Resource resource : thingHandler.getResources(new ResourceReference().setType(entry.getKey())) .getResources()) { MetaData metaData = resource.getMetaData(); @@ -122,10 +114,10 @@ private synchronized void discoverThings() { // special zone 'all lights' if (resource.getType() == ResourceType.BRIDGE_HOME) { - thingLabel = bridgeHandler.getLocalizedText(ALL_LIGHTS_KEY); + thingLabel = thingHandler.getLocalizedText(ALL_LIGHTS_KEY); } - Optional legacyThingOptional = bridgeHandler.getLegacyThing(idv1); + Optional legacyThingOptional = thingHandler.getLegacyThing(idv1); if (legacyThingOptional.isPresent()) { Thing legacyThing = legacyThingOptional.get(); legacyThingUID = legacyThing.getUID().getAsString(); @@ -157,18 +149,6 @@ private synchronized void discoverThings() { stopScan(); } - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - - @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof Clip2BridgeHandler) { - bridgeHandler = (Clip2BridgeHandler) handler; - } - } - @Override protected void startBackgroundDiscovery() { ScheduledFuture discoveryTask = this.discoveryTask; diff --git a/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/discovery/HueDeviceDiscoveryService.java b/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/discovery/HueDeviceDiscoveryService.java index 5b3cc13151603..99a203e14d9f5 100644 --- a/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/discovery/HueDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/discovery/HueDeviceDiscoveryService.java @@ -39,14 +39,17 @@ import org.openhab.binding.hue.internal.handler.sensors.PresenceHandler; import org.openhab.binding.hue.internal.handler.sensors.TapSwitchHandler; import org.openhab.binding.hue.internal.handler.sensors.TemperatureHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; +import org.openhab.core.i18n.LocaleProvider; +import org.openhab.core.i18n.TranslationProvider; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -64,9 +67,9 @@ * @author Meng Yiqi - Added support for CLIP sensor * @author Laurent Garnier - Added support for groups */ +@Component(scope = ServiceScope.PROTOTYPE, service = HueDeviceDiscoveryService.class) @NonNullByDefault -public class HueDeviceDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { - +public class HueDeviceDiscoveryService extends AbstractThingHandlerDiscoveryService { public static final Set SUPPORTED_THING_TYPES = Stream .of(HueLightHandler.SUPPORTED_THING_TYPES.stream(), DimmerSwitchHandler.SUPPORTED_THING_TYPES.stream(), TapSwitchHandler.SUPPORTED_THING_TYPES.stream(), PresenceHandler.SUPPORTED_THING_TYPES.stream(), @@ -98,44 +101,34 @@ public class HueDeviceDiscoveryService extends AbstractDiscoveryService implemen private final Logger logger = LoggerFactory.getLogger(HueDeviceDiscoveryService.class); - private @Nullable HueBridgeHandler hueBridgeHandler; private @Nullable ThingUID bridgeUID; public HueDeviceDiscoveryService() { - super(SUPPORTED_THING_TYPES, SEARCH_TIME); + super(HueBridgeHandler.class, SUPPORTED_THING_TYPES, SEARCH_TIME); } - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof HueBridgeHandler) { - HueBridgeHandler localHandler = (HueBridgeHandler) handler; - hueBridgeHandler = localHandler; - bridgeUID = handler.getThing().getUID(); - i18nProvider = localHandler.getI18nProvider(); - localeProvider = localHandler.getLocaleProvider(); - } + @Reference(unbind = "-") + public void bindTranslationProvider(TranslationProvider translationProvider) { + this.i18nProvider = translationProvider; } - @Override - public @Nullable ThingHandler getThingHandler() { - return hueBridgeHandler; + @Reference(unbind = "-") + public void bindLocaleProvider(LocaleProvider localeProvider) { + this.localeProvider = localeProvider; } @Override - public void activate() { - final HueBridgeHandler handler = hueBridgeHandler; - if (handler != null) { - handler.registerDiscoveryListener(this); - } + public void initialize() { + bridgeUID = thingHandler.getThing().getUID(); + thingHandler.registerDiscoveryListener(this); + super.initialize(); } @Override - public void deactivate() { + public void dispose() { + super.dispose(); removeOlderResults(new Date().getTime(), bridgeUID); - final HueBridgeHandler handler = hueBridgeHandler; - if (handler != null) { - handler.unregisterDiscoveryListener(); - } + thingHandler.unregisterDiscoveryListener(); } @Override @@ -145,32 +138,26 @@ public Set getSupportedThingTypes() { @Override public void startScan() { - final HueBridgeHandler handler = hueBridgeHandler; - if (handler != null) { - List lights = handler.getFullLights(); - for (FullLight l : lights) { - addLightDiscovery(l); - } - List sensors = handler.getFullSensors(); - for (FullSensor s : sensors) { - addSensorDiscovery(s); - } - List groups = handler.getFullGroups(); - for (FullGroup g : groups) { - addGroupDiscovery(g); - } - // search for unpaired lights - handler.startSearch(); + List lights = thingHandler.getFullLights(); + for (FullLight l : lights) { + addLightDiscovery(l); } + List sensors = thingHandler.getFullSensors(); + for (FullSensor s : sensors) { + addSensorDiscovery(s); + } + List groups = thingHandler.getFullGroups(); + for (FullGroup g : groups) { + addGroupDiscovery(g); + } + // search for unpaired lights + thingHandler.startSearch(); } @Override protected synchronized void stopScan() { super.stopScan(); - final HueBridgeHandler handler = hueBridgeHandler; - if (handler != null) { - removeOlderResults(getTimestampOfLastScan(), handler.getThing().getUID()); - } + removeOlderResults(getTimestampOfLastScan(), thingHandler.getThing().getUID()); } public void addLightDiscovery(FullLight light) { diff --git a/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/factory/HueThingHandlerFactory.java b/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/factory/HueThingHandlerFactory.java index 8b254d6dbbb26..d12a446f0bfd1 100644 --- a/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/factory/HueThingHandlerFactory.java +++ b/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/factory/HueThingHandlerFactory.java @@ -191,7 +191,7 @@ private ThingUID getThingUID(ThingTypeUID thingTypeUID, String id, @Nullable Thi itemChannelLinkRegistry); } else if (HueBridgeHandler.SUPPORTED_THING_TYPES.contains(thingTypeUID)) { return new HueBridgeHandler((Bridge) thing, httpClientFactory.getCommonHttpClient(), - stateDescriptionProvider, i18nProvider, localeProvider); + stateDescriptionProvider); } else if (HueLightHandler.SUPPORTED_THING_TYPES.contains(thingTypeUID)) { return new HueLightHandler(thing, stateDescriptionProvider); } else if (DimmerSwitchHandler.SUPPORTED_THING_TYPES.contains(thingTypeUID)) { diff --git a/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/handler/HueBridgeHandler.java b/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/handler/HueBridgeHandler.java index d602ee8c085ff..678437ac18c4c 100644 --- a/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/handler/HueBridgeHandler.java +++ b/bundles/org.openhab.binding.hue/src/main/java/org/openhab/binding/hue/internal/handler/HueBridgeHandler.java @@ -59,8 +59,6 @@ import org.openhab.core.config.core.status.ConfigStatusMessage; import org.openhab.core.i18n.CommunicationException; import org.openhab.core.i18n.ConfigurationException; -import org.openhab.core.i18n.LocaleProvider; -import org.openhab.core.i18n.TranslationProvider; import org.openhab.core.io.net.http.TlsTrustManagerProvider; import org.openhab.core.library.types.HSBType; import org.openhab.core.library.types.OnOffType; @@ -109,8 +107,6 @@ public class HueBridgeHandler extends ConfigStatusBridgeHandler implements HueCl private @Nullable ServiceRegistration serviceRegistration; private final HttpClient httpClient; private final HueStateDescriptionProvider stateDescriptionOptionProvider; - private final TranslationProvider i18nProvider; - private final LocaleProvider localeProvider; private final Map lastLightStates = new ConcurrentHashMap<>(); private final Map lastSensorStates = new ConcurrentHashMap<>(); @@ -424,13 +420,10 @@ private void setBridgeSceneChannelStateOptions(List scenes, Map consoleScenesList = new ArrayList<>(); public HueBridgeHandler(Bridge bridge, HttpClient httpClient, - HueStateDescriptionProvider stateDescriptionOptionProvider, TranslationProvider i18nProvider, - LocaleProvider localeProvider) { + HueStateDescriptionProvider stateDescriptionOptionProvider) { super(bridge); this.httpClient = httpClient; this.stateDescriptionOptionProvider = stateDescriptionOptionProvider; - this.i18nProvider = i18nProvider; - this.localeProvider = localeProvider; } @Override @@ -1079,12 +1072,4 @@ public Collection getConfigStatus() { return List.of(); } } - - public TranslationProvider getI18nProvider() { - return i18nProvider; - } - - public LocaleProvider getLocaleProvider() { - return localeProvider; - } } diff --git a/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/discovery/HydrawiseCloudControllerDiscoveryService.java b/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/discovery/HydrawiseCloudControllerDiscoveryService.java index fe8c8c11e0626..ec1deb335a74c 100644 --- a/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/discovery/HydrawiseCloudControllerDiscoveryService.java +++ b/bundles/org.openhab.binding.hydrawise/src/main/java/org/openhab/binding/hydrawise/internal/discovery/HydrawiseCloudControllerDiscoveryService.java @@ -17,18 +17,17 @@ import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.hydrawise.internal.HydrawiseBindingConstants; import org.openhab.binding.hydrawise.internal.HydrawiseControllerListener; import org.openhab.binding.hydrawise.internal.api.graphql.dto.Controller; import org.openhab.binding.hydrawise.internal.api.graphql.dto.Customer; import org.openhab.binding.hydrawise.internal.handler.HydrawiseAccountHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * @@ -37,44 +36,33 @@ */ @NonNullByDefault -@Component(service = ThingHandlerService.class) -public class HydrawiseCloudControllerDiscoveryService extends AbstractDiscoveryService - implements HydrawiseControllerListener, ThingHandlerService { - +@Component(scope = ServiceScope.PROTOTYPE, service = ThingHandlerService.class) +public class HydrawiseCloudControllerDiscoveryService + extends AbstractThingHandlerDiscoveryService implements HydrawiseControllerListener { private static final int TIMEOUT = 5; - @Nullable - HydrawiseAccountHandler handler; public HydrawiseCloudControllerDiscoveryService() { - super(Set.of(HydrawiseBindingConstants.THING_TYPE_CONTROLLER), TIMEOUT, true); + super(HydrawiseAccountHandler.class, Set.of(HydrawiseBindingConstants.THING_TYPE_CONTROLLER), TIMEOUT, true); } @Override protected void startScan() { - HydrawiseAccountHandler localHandler = this.handler; - if (localHandler != null) { - Customer data = localHandler.lastData(); - if (data != null) { - data.controllers.forEach(controller -> addDiscoveryResults(controller)); - } + Customer data = thingHandler.lastData(); + if (data != null) { + data.controllers.forEach(controller -> addDiscoveryResults(controller)); } } @Override - public void deactivate() { - HydrawiseAccountHandler localHandler = this.handler; - if (localHandler != null) { - removeOlderResults(new Date().getTime(), localHandler.getThing().getUID()); - } + public void dispose() { + super.dispose(); + removeOlderResults(new Date().getTime(), thingHandler.getThing().getUID()); } @Override protected synchronized void stopScan() { super.stopScan(); - HydrawiseAccountHandler localHandler = this.handler; - if (localHandler != null) { - removeOlderResults(getTimestampOfLastScan(), localHandler.getThing().getUID()); - } + removeOlderResults(getTimestampOfLastScan(), thingHandler.getThing().getUID()); } @Override @@ -83,27 +71,19 @@ public void onData(List controllers) { } @Override - public void setThingHandler(ThingHandler handler) { - this.handler = (HydrawiseAccountHandler) handler; - this.handler.addControllerListeners(this); - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return handler; + public void initialize() { + thingHandler.addControllerListeners(this); + super.initialize(); } private void addDiscoveryResults(Controller controller) { - HydrawiseAccountHandler localHandler = this.handler; - if (localHandler != null) { - String label = String.format("Hydrawise Controller %s", controller.name); - int id = controller.id; - ThingUID bridgeUID = localHandler.getThing().getUID(); - ThingUID thingUID = new ThingUID(HydrawiseBindingConstants.THING_TYPE_CONTROLLER, bridgeUID, - String.valueOf(id)); - thingDiscovered(DiscoveryResultBuilder.create(thingUID).withLabel(label).withBridge(bridgeUID) - .withProperty(HydrawiseBindingConstants.CONFIG_CONTROLLER_ID, id) - .withRepresentationProperty(HydrawiseBindingConstants.CONFIG_CONTROLLER_ID).build()); - } + String label = String.format("Hydrawise Controller %s", controller.name); + int id = controller.id; + ThingUID bridgeUID = thingHandler.getThing().getUID(); + ThingUID thingUID = new ThingUID(HydrawiseBindingConstants.THING_TYPE_CONTROLLER, bridgeUID, + String.valueOf(id)); + thingDiscovered(DiscoveryResultBuilder.create(thingUID).withLabel(label).withBridge(bridgeUID) + .withProperty(HydrawiseBindingConstants.CONFIG_CONTROLLER_ID, id) + .withRepresentationProperty(HydrawiseBindingConstants.CONFIG_CONTROLLER_ID).build()); } } diff --git a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/IpCameraActions.java b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/IpCameraActions.java index 1579b272ccf06..837f9e52bd25d 100644 --- a/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/IpCameraActions.java +++ b/bundles/org.openhab.binding.ipcamera/src/main/java/org/openhab/binding/ipcamera/internal/IpCameraActions.java @@ -20,6 +20,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,7 +30,7 @@ * * @author Matthew Skinner - Initial contribution */ - +@Component(scope = ServiceScope.PROTOTYPE, service = IpCameraActions.class) @ThingActionsScope(name = "ipcamera") @NonNullByDefault public class IpCameraActions implements ThingActions { diff --git a/bundles/org.openhab.binding.jablotron/src/main/java/org/openhab/binding/jablotron/internal/discovery/JablotronDiscoveryService.java b/bundles/org.openhab.binding.jablotron/src/main/java/org/openhab/binding/jablotron/internal/discovery/JablotronDiscoveryService.java index 595a55f0dea96..b2157f90ea4fe 100644 --- a/bundles/org.openhab.binding.jablotron/src/main/java/org/openhab/binding/jablotron/internal/discovery/JablotronDiscoveryService.java +++ b/bundles/org.openhab.binding.jablotron/src/main/java/org/openhab/binding/jablotron/internal/discovery/JablotronDiscoveryService.java @@ -25,14 +25,13 @@ import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.jablotron.internal.handler.JablotronBridgeHandler; import org.openhab.binding.jablotron.internal.model.JablotronDiscoveredService; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,39 +41,25 @@ * * @author Ondrej Pecta - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = JablotronDiscoveryService.class) @NonNullByDefault -public class JablotronDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { +public class JablotronDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(JablotronDiscoveryService.class); - private @Nullable JablotronBridgeHandler bridgeHandler; - private @Nullable ScheduledFuture discoveryJob = null; public JablotronDiscoveryService() { - super(DISCOVERY_TIMEOUT_SEC); + super(JablotronBridgeHandler.class, DISCOVERY_TIMEOUT_SEC); logger.debug("Creating discovery service"); } private void startDiscovery() { - JablotronBridgeHandler localBridgeHandler = bridgeHandler; + JablotronBridgeHandler localBridgeHandler = thingHandler; if (localBridgeHandler != null && ThingStatus.ONLINE == localBridgeHandler.getThing().getStatus()) { discoverServices(); } } - @Override - public void setThingHandler(@Nullable ThingHandler thingHandler) { - if (thingHandler instanceof JablotronBridgeHandler bridgeHandler) { - this.bridgeHandler = bridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - @Override protected void stopBackgroundDiscovery() { super.stopBackgroundDiscovery(); @@ -93,16 +78,6 @@ protected void startBackgroundDiscovery() { } } - @Override - public void activate() { - super.activate(null); - } - - @Override - public void deactivate() { - super.deactivate(); - } - @Override public Set getSupportedThingTypes() { return SUPPORTED_THING_TYPES_UIDS; @@ -115,7 +90,7 @@ protected void startScan() { } public void oasisDiscovered(String label, String serviceId) { - JablotronBridgeHandler localBridgeHandler = bridgeHandler; + JablotronBridgeHandler localBridgeHandler = thingHandler; if (localBridgeHandler != null) { ThingUID thingUID = new ThingUID(THING_TYPE_OASIS, localBridgeHandler.getThing().getUID(), serviceId); @@ -130,7 +105,7 @@ public void oasisDiscovered(String label, String serviceId) { } public void ja100Discovered(String label, String serviceId) { - JablotronBridgeHandler localBridgeHandler = bridgeHandler; + JablotronBridgeHandler localBridgeHandler = thingHandler; if (localBridgeHandler != null) { ThingUID thingUID = new ThingUID(THING_TYPE_JA100, localBridgeHandler.getThing().getUID(), serviceId); Map properties = new HashMap<>(); @@ -144,7 +119,7 @@ public void ja100Discovered(String label, String serviceId) { } public void ja100fDiscovered(String label, String serviceId) { - JablotronBridgeHandler localBridgeHandler = bridgeHandler; + JablotronBridgeHandler localBridgeHandler = thingHandler; if (localBridgeHandler != null) { ThingUID thingUID = new ThingUID(THING_TYPE_JA100F, localBridgeHandler.getThing().getUID(), serviceId); Map properties = new HashMap<>(); @@ -158,7 +133,7 @@ public void ja100fDiscovered(String label, String serviceId) { } private synchronized void discoverServices() { - JablotronBridgeHandler localBridgeHandler = bridgeHandler; + JablotronBridgeHandler localBridgeHandler = thingHandler; if (localBridgeHandler != null) { List services = localBridgeHandler.discoverServices(); diff --git a/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/discovery/JellyfinClientDiscoveryService.java b/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/discovery/JellyfinClientDiscoveryService.java index 6c74bef40ea39..b49b9fa8bb7a9 100644 --- a/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/discovery/JellyfinClientDiscoveryService.java +++ b/bundles/org.openhab.binding.jellyfin/src/main/java/org/openhab/binding/jellyfin/internal/discovery/JellyfinClientDiscoveryService.java @@ -21,19 +21,18 @@ import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.jellyfin.sdk.api.client.exception.ApiClientException; import org.jellyfin.sdk.api.client.exception.InvalidStatusException; import org.jellyfin.sdk.model.api.SessionInfo; import org.openhab.binding.jellyfin.internal.handler.JellyfinServerHandler; import org.openhab.binding.jellyfin.internal.util.SyncCallback; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,29 +41,24 @@ * * @author Miguel Alvarez - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = JellyfinClientDiscoveryService.class) @NonNullByDefault -public class JellyfinClientDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class JellyfinClientDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(JellyfinClientDiscoveryService.class); - private @Nullable JellyfinServerHandler bridgeHandler; public JellyfinClientDiscoveryService() throws IllegalArgumentException { - super(Set.of(THING_TYPE_SERVER), 60); + super(JellyfinServerHandler.class, Set.of(THING_TYPE_SERVER), 60); } @Override protected void startScan() { - var bridgeHandler = this.bridgeHandler; - if (bridgeHandler == null) { - logger.warn("missing bridge aborting"); + if (!thingHandler.getThing().getStatus().equals(ThingStatus.ONLINE)) { + logger.warn("Server handler {} is not online.", thingHandler.getThing().getLabel()); return; } - if (!bridgeHandler.getThing().getStatus().equals(ThingStatus.ONLINE)) { - logger.warn("Server handler {} is not online.", bridgeHandler.getThing().getLabel()); - return; - } - logger.debug("Searching devices for server {}", bridgeHandler.getThing().getLabel()); + logger.debug("Searching devices for server {}", thingHandler.getThing().getLabel()); try { - bridgeHandler.getControllableSessions().forEach(this::discoverDevice); + thingHandler.getControllableSessions().forEach(this::discoverDevice); } catch (SyncCallback.SyncCallbackError syncCallbackError) { logger.error("Unexpected error: {}", syncCallbackError.getMessage()); } catch (InvalidStatusException e) { @@ -80,13 +74,8 @@ public void discoverDevice(SessionInfo info) { logger.warn("missing device id aborting"); return; } - var bridgeHandler = this.bridgeHandler; - if (bridgeHandler == null) { - logger.warn("missing bridge aborting"); - return; - } logger.debug("Client discovered: [{}] {}", id, info.getDeviceName()); - var bridgeUID = bridgeHandler.getThing().getUID(); + var bridgeUID = thingHandler.getThing().getUID(); Map properties = new HashMap<>(); properties.put(Thing.PROPERTY_SERIAL_NUMBER, id); var appVersion = info.getApplicationVersion(); @@ -102,26 +91,4 @@ public void discoverDevice(SessionInfo info) { .withTTL(DISCOVERY_RESULT_TTL_SEC).withRepresentationProperty(Thing.PROPERTY_SERIAL_NUMBER) .withProperties(properties).withLabel(info.getDeviceName()).build()); } - - @Override - public void setThingHandler(ThingHandler thingHandler) { - if (thingHandler instanceof JellyfinServerHandler bridgeHandler) { - this.bridgeHandler = bridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return null; - } - - @Override - public void activate() { - activate(new HashMap<>()); - } - - @Override - public void deactivate() { - super.deactivate(); - } } diff --git a/bundles/org.openhab.binding.juicenet/src/main/java/org/openhab/binding/juicenet/internal/discovery/JuiceNetDiscoveryService.java b/bundles/org.openhab.binding.juicenet/src/main/java/org/openhab/binding/juicenet/internal/discovery/JuiceNetDiscoveryService.java index 930d8e7acd9c3..65ba918910d06 100644 --- a/bundles/org.openhab.binding.juicenet/src/main/java/org/openhab/binding/juicenet/internal/discovery/JuiceNetDiscoveryService.java +++ b/bundles/org.openhab.binding.juicenet/src/main/java/org/openhab/binding/juicenet/internal/discovery/JuiceNetDiscoveryService.java @@ -14,20 +14,17 @@ import static org.openhab.binding.juicenet.internal.JuiceNetBindingConstants.*; -import java.util.Objects; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.juicenet.internal.handler.JuiceNetBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -38,53 +35,24 @@ * * @author Jeff James - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = JuiceNetDiscoveryService.class) @NonNullByDefault -public class JuiceNetDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { +public class JuiceNetDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(JuiceNetDiscoveryService.class); - private @Nullable JuiceNetBridgeHandler bridgeHandler; - private static final Set DISCOVERABLE_THING_TYPES_UIDS = Set.of(DEVICE_THING_TYPE); public JuiceNetDiscoveryService() { - super(DISCOVERABLE_THING_TYPES_UIDS, 0, false); - } - - @Override - public void activate() { - super.activate(null); - } - - @Override - public void deactivate() { - super.deactivate(); + super(JuiceNetBridgeHandler.class, DISCOVERABLE_THING_TYPES_UIDS, 0, false); } @Override protected synchronized void startScan() { - Objects.requireNonNull(bridgeHandler).iterateApiDevices(); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof JuiceNetBridgeHandler bridgeHandler) { - bridgeHandler.setDiscoveryService(this); - this.bridgeHandler = bridgeHandler; - } else { - this.bridgeHandler = null; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return this.bridgeHandler; + thingHandler.iterateApiDevices(); } public void notifyDiscoveryDevice(String id, String name) { - JuiceNetBridgeHandler bridgeHandler = this.bridgeHandler; - Objects.requireNonNull(bridgeHandler, "Discovery with null bridgehandler."); - ThingUID bridgeUID = bridgeHandler.getThing().getUID(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); ThingUID uid = new ThingUID(DEVICE_THING_TYPE, bridgeUID, id); diff --git a/bundles/org.openhab.binding.kaleidescape/src/main/java/org/openhab/binding/kaleidescape/internal/KaleidescapeThingActions.java b/bundles/org.openhab.binding.kaleidescape/src/main/java/org/openhab/binding/kaleidescape/internal/KaleidescapeThingActions.java index f963c31935ead..21196819023da 100644 --- a/bundles/org.openhab.binding.kaleidescape/src/main/java/org/openhab/binding/kaleidescape/internal/KaleidescapeThingActions.java +++ b/bundles/org.openhab.binding.kaleidescape/src/main/java/org/openhab/binding/kaleidescape/internal/KaleidescapeThingActions.java @@ -20,6 +20,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,6 +30,7 @@ * * @author Michael Lobstein - initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = KaleidescapeThingActions.class) @ThingActionsScope(name = "kaleidescape") @NonNullByDefault public class KaleidescapeThingActions implements ThingActions { diff --git a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnModuleActions.java b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnModuleActions.java index 444f3af89329a..c99e9669ab3ae 100644 --- a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnModuleActions.java +++ b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnModuleActions.java @@ -28,6 +28,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -36,6 +38,7 @@ * * @author Fabian Wolter - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = LcnModuleActions.class) @ThingActionsScope(name = "lcn") @NonNullByDefault public class LcnModuleActions implements ThingActions { diff --git a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnModuleDiscoveryService.java b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnModuleDiscoveryService.java index 6399c6175b02c..361387d854796 100644 --- a/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnModuleDiscoveryService.java +++ b/bundles/org.openhab.binding.lcn/src/main/java/org/openhab/binding/lcn/internal/LcnModuleDiscoveryService.java @@ -31,14 +31,13 @@ import org.openhab.binding.lcn.internal.connection.Connection; import org.openhab.binding.lcn.internal.subhandler.LcnModuleMetaAckSubHandler; import org.openhab.binding.lcn.internal.subhandler.LcnModuleMetaFirmwareSubHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -55,9 +54,9 @@ * * @author Fabian Wolter - Initial Contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = LcnModuleDiscoveryService.class) @NonNullByDefault -public class LcnModuleDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { +public class LcnModuleDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(LcnModuleDiscoveryService.class); private static final Pattern NAME_PATTERN = Pattern .compile("=M(?\\d{3})(?\\d{3}).N(?[1-2]{1})(?.*)"); @@ -67,7 +66,6 @@ public class LcnModuleDiscoveryService extends AbstractDiscoveryService private static final int DISCOVERY_TIMEOUT_SEC = 90; private static final int ACK_TIMEOUT_MS = 1000; private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(LcnBindingConstants.THING_TYPE_MODULE); - private @Nullable PckGatewayHandler bridgeHandler; private final Map> moduleNames = new HashMap<>(); private final Map discoveryResultBuilders = new ConcurrentHashMap<>(); private final List successfullyDiscovered = new LinkedList<>(); @@ -77,57 +75,39 @@ public class LcnModuleDiscoveryService extends AbstractDiscoveryService private @Nullable ScheduledFuture builderTask; public LcnModuleDiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIMEOUT_SEC, false); + super(PckGatewayHandler.class, SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIMEOUT_SEC, false); } @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof PckGatewayHandler gatewayHandler) { - this.bridgeHandler = gatewayHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - - @Override - public void deactivate() { + public void dispose() { + super.dispose(); stopScan(); - super.deactivate(); } @Override @SuppressWarnings("PMD.CompareObjectsWithEquals") protected void startScan() { synchronized (this) { - PckGatewayHandler localBridgeHandler = bridgeHandler; - if (localBridgeHandler == null) { - logger.warn("Bridge handler not set"); - return; - } - ScheduledFuture localBuilderTask = builderTask; - if (localBridgeHandler.getConnection() == null && localBuilderTask != null) { + if (thingHandler.getConnection() == null && localBuilderTask != null) { localBuilderTask.cancel(true); } - localBridgeHandler.registerPckListener(data -> { + thingHandler.registerPckListener(data -> { Matcher matcher; if ((matcher = LcnModuleMetaAckSubHandler.PATTERN_POS.matcher(data)).matches() || (matcher = LcnModuleMetaFirmwareSubHandler.PATTERN.matcher(data)).matches() || (matcher = NAME_PATTERN.matcher(data)).matches()) { synchronized (LcnModuleDiscoveryService.this) { - Connection connection = localBridgeHandler.getConnection(); + Connection connection = thingHandler.getConnection(); if (connection == null) { return; } LcnAddrMod addr = new LcnAddrMod( - localBridgeHandler.toLogicalSegmentId(Integer.parseInt(matcher.group("segId"))), + thingHandler.toLogicalSegmentId(Integer.parseInt(matcher.group("segId"))), Integer.parseInt(matcher.group("modId"))); if (matcher.pattern() == LcnModuleMetaAckSubHandler.PATTERN_POS) { @@ -148,7 +128,7 @@ protected void startScan() { } else if (matcher.pattern() == LcnModuleMetaFirmwareSubHandler.PATTERN) { // Received a firmware version info frame - ThingUID bridgeUid = localBridgeHandler.getThing().getUID(); + ThingUID bridgeUid = thingHandler.getThing().getUID(); String serialNumber = matcher.group("sn"); String thingID = String.format("S%03dM%03d", addr.getSegmentId(), addr.getModuleId()); @@ -210,7 +190,7 @@ protected void startScan() { } }, 500, 500, TimeUnit.MILLISECONDS); - localBridgeHandler.sendModuleDiscoveryCommand(); + thingHandler.sendModuleDiscoveryCommand(); } } @@ -221,22 +201,19 @@ private synchronized void rescheduleQueueProcessor() { localQueueProcessor.cancel(true); } queueProcessor = scheduler.scheduleWithFixedDelay(() -> { - PckGatewayHandler localBridgeHandler = bridgeHandler; - if (localBridgeHandler != null) { - LcnAddrMod serial = serialNumberRequestQueue.poll(); - if (serial != null) { - localBridgeHandler.sendSerialNumberRequest(serial); - } + LcnAddrMod serial = serialNumberRequestQueue.poll(); + if (serial != null) { + thingHandler.sendSerialNumberRequest(serial); + } - LcnAddrMod name = moduleNameRequestQueue.poll(); - if (name != null) { - localBridgeHandler.sendModuleNameRequest(name); - } + LcnAddrMod name = moduleNameRequestQueue.poll(); + if (name != null) { + thingHandler.sendModuleNameRequest(name); + } - // stop scan when all LCN modules have been requested - if (serial == null && name == null) { - scheduler.schedule(this::stopScan, ACK_TIMEOUT_MS, TimeUnit.MILLISECONDS); - } + // stop scan when all LCN modules have been requested + if (serial == null && name == null) { + scheduler.schedule(this::stopScan, ACK_TIMEOUT_MS, TimeUnit.MILLISECONDS); } }, ACK_TIMEOUT_MS, ACK_TIMEOUT_MS, TimeUnit.MILLISECONDS); } @@ -251,10 +228,7 @@ public synchronized void stopScan() { if (localQueueProcessor != null) { localQueueProcessor.cancel(true); } - PckGatewayHandler localBridgeHandler = bridgeHandler; - if (localBridgeHandler != null) { - localBridgeHandler.removeAllPckListeners(); - } + thingHandler.removeAllPckListeners(); successfullyDiscovered.clear(); moduleNames.clear(); diff --git a/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/action/LGWebOSActions.java b/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/action/LGWebOSActions.java index 44d2ba948b008..7f651237c44cc 100644 --- a/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/action/LGWebOSActions.java +++ b/bundles/org.openhab.binding.lgwebos/src/main/java/org/openhab/binding/lgwebos/internal/action/LGWebOSActions.java @@ -41,6 +41,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -54,6 +56,7 @@ * @author Sebastian Prehn - Initial contribution * @author Laurent Garnier - new method invokeMethodOf + interface ILGWebOSActions */ +@Component(scope = ServiceScope.PROTOTYPE, service = LGWebOSActions.class) @ThingActionsScope(name = "lgwebos") @NonNullByDefault public class LGWebOSActions implements ThingActions { diff --git a/bundles/org.openhab.binding.livisismarthome/src/main/java/org/openhab/binding/livisismarthome/internal/discovery/LivisiDeviceDiscoveryService.java b/bundles/org.openhab.binding.livisismarthome/src/main/java/org/openhab/binding/livisismarthome/internal/discovery/LivisiDeviceDiscoveryService.java index 481aba0dfba96..f3ce4a1c10a24 100644 --- a/bundles/org.openhab.binding.livisismarthome/src/main/java/org/openhab/binding/livisismarthome/internal/discovery/LivisiDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.livisismarthome/src/main/java/org/openhab/binding/livisismarthome/internal/discovery/LivisiDeviceDiscoveryService.java @@ -21,18 +21,16 @@ import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.livisismarthome.internal.LivisiBindingConstants; import org.openhab.binding.livisismarthome.internal.client.api.entity.device.DeviceDTO; import org.openhab.binding.livisismarthome.internal.handler.LivisiBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,21 +40,19 @@ * @author Oliver Kuhl - Initial contribution * @author Sven Strohschein - Renamed from Innogy to Livisi */ +@Component(scope = ServiceScope.PROTOTYPE, service = LivisiDeviceDiscoveryService.class) @NonNullByDefault -public class LivisiDeviceDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { +public class LivisiDeviceDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int SEARCH_TIME_SECONDS = 60; private final Logger logger = LoggerFactory.getLogger(LivisiDeviceDiscoveryService.class); - private @Nullable LivisiBridgeHandler bridgeHandler; - /** * Construct a {@link LivisiDeviceDiscoveryService}. */ public LivisiDeviceDiscoveryService() { - super(SEARCH_TIME_SECONDS); + super(LivisiBridgeHandler.class, SEARCH_TIME_SECONDS); } /** @@ -67,7 +63,8 @@ public LivisiDeviceDiscoveryService() { * @see org.openhab.core.config.discovery.AbstractDiscoveryService#deactivate() */ @Override - public void deactivate() { + public void dispose() { + super.dispose(); removeOlderResults(new Date().getTime()); } @@ -79,11 +76,8 @@ public Set getSupportedThingTypes() { @Override protected void startScan() { logger.debug("SCAN for new LIVISI SmartHome devices started..."); - final LivisiBridgeHandler bridgeHandlerNonNullable = bridgeHandler; - if (bridgeHandlerNonNullable != null) { - for (final DeviceDTO d : bridgeHandlerNonNullable.loadDevices()) { - onDeviceAdded(d); - } + for (final DeviceDTO d : thingHandler.loadDevices()) { + onDeviceAdded(d); } } @@ -94,37 +88,34 @@ protected synchronized void stopScan() { } public void onDeviceAdded(DeviceDTO device) { - final LivisiBridgeHandler bridgeHandlerNonNullable = bridgeHandler; - if (bridgeHandlerNonNullable != null) { - final ThingUID bridgeUID = bridgeHandlerNonNullable.getThing().getUID(); - final Optional thingUID = getThingUID(bridgeUID, device); - final Optional thingTypeUID = getThingTypeUID(device); - - if (thingUID.isPresent() && thingTypeUID.isPresent()) { - String name = device.getConfig().getName(); - if (name.isEmpty()) { - name = device.getSerialNumber(); - } - - final Map properties = new HashMap<>(); - properties.put(PROPERTY_ID, device.getId()); - - final String label; - if (device.hasLocation()) { - label = device.getType() + ": " + name + " (" + device.getLocation().getName() + ")"; - } else { - label = device.getType() + ": " + name; - } - - final DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID.get()) - .withThingType(thingTypeUID.get()).withProperties(properties).withBridge(bridgeUID) - .withRepresentationProperty(PROPERTY_ID).withLabel(label).build(); - - thingDiscovered(discoveryResult); + final ThingUID bridgeUID = thingHandler.getThing().getUID(); + final Optional thingUID = getThingUID(bridgeUID, device); + final Optional thingTypeUID = getThingTypeUID(device); + + if (thingUID.isPresent() && thingTypeUID.isPresent()) { + String name = device.getConfig().getName(); + if (name.isEmpty()) { + name = device.getSerialNumber(); + } + + final Map properties = new HashMap<>(); + properties.put(PROPERTY_ID, device.getId()); + + final String label; + if (device.hasLocation()) { + label = device.getType() + ": " + name + " (" + device.getLocation().getName() + ")"; } else { - logger.debug("Discovered unsupported device of type '{}' and name '{}' with id {}", device.getType(), - device.getConfig().getName(), device.getId()); + label = device.getType() + ": " + name; } + + final DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID.get()) + .withThingType(thingTypeUID.get()).withProperties(properties).withBridge(bridgeUID) + .withRepresentationProperty(PROPERTY_ID).withLabel(label).build(); + + thingDiscovered(discoveryResult); + } else { + logger.debug("Discovered unsupported device of type '{}' and name '{}' with id {}", device.getType(), + device.getConfig().getName(), device.getId()); } } @@ -157,16 +148,4 @@ private Optional getThingTypeUID(DeviceDTO device) { } return Optional.empty(); } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof LivisiBridgeHandler livisiBridgeHandler) { - bridgeHandler = livisiBridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } } diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/action/DimmerActions.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/action/DimmerActions.java index df183554b98e3..0a0e2c8bf4b6a 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/action/DimmerActions.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/action/DimmerActions.java @@ -24,6 +24,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -32,6 +34,7 @@ * * @author Bob Adair - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = DimmerActions.class) @ThingActionsScope(name = "lutron") @NonNullByDefault public class DimmerActions implements ThingActions { diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LeapDeviceDiscoveryService.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LeapDeviceDiscoveryService.java index 4ca1ba946eb09..c8ad9797c3ffe 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LeapDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LeapDeviceDiscoveryService.java @@ -25,14 +25,13 @@ import org.openhab.binding.lutron.internal.protocol.leap.dto.Area; import org.openhab.binding.lutron.internal.protocol.leap.dto.Device; import org.openhab.binding.lutron.internal.protocol.leap.dto.OccupancyGroup; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,9 +40,9 @@ * * @author Bob Adair - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = LeapDeviceDiscoveryService.class) @NonNullByDefault -public class LeapDeviceDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { +public class LeapDeviceDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int DISCOVERY_SERVICE_TIMEOUT = 0; // seconds @@ -53,29 +52,20 @@ public class LeapDeviceDiscoveryService extends AbstractDiscoveryService private @Nullable Map areaMap; private @Nullable List oGroupList; - private @NonNullByDefault({}) LeapBridgeHandler bridgeHandler; - public LeapDeviceDiscoveryService() { - super(LutronHandlerFactory.DISCOVERABLE_DEVICE_TYPES_UIDS, DISCOVERY_SERVICE_TIMEOUT); - } - - @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof LeapBridgeHandler leapBridgeHandler) { - bridgeHandler = leapBridgeHandler; - bridgeHandler.setDiscoveryService(this); - } + super(LeapBridgeHandler.class, LutronHandlerFactory.DISCOVERABLE_DEVICE_TYPES_UIDS, DISCOVERY_SERVICE_TIMEOUT); } @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; + public void initialize() { + thingHandler.setDiscoveryService(this); + super.initialize(); } @Override protected void startScan() { logger.debug("Active discovery scan started"); - bridgeHandler.queryDiscoveryData(); + thingHandler.queryDiscoveryData(); } public void processDeviceDefinitions(List deviceList) { @@ -198,10 +188,10 @@ public void setAreas(List areaList) { private void notifyDiscovery(ThingTypeUID thingTypeUID, @Nullable Integer integrationId, String label, @Nullable String propName, @Nullable Object propValue) { if (integrationId == null) { - logger.debug("Discovered {} with no integration ID", label); + logger.debug("Discovered {} with no integration ID or thinghandler", label); return; } - ThingUID bridgeUID = this.bridgeHandler.getThing().getUID(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); ThingUID uid = new ThingUID(thingTypeUID, bridgeUID, integrationId.toString()); Map properties = new HashMap<>(); @@ -220,9 +210,4 @@ private void notifyDiscovery(ThingTypeUID thingTypeUID, @Nullable Integer integr private void notifyDiscovery(ThingTypeUID thingTypeUID, Integer integrationId, String label) { notifyDiscovery(thingTypeUID, integrationId, label, null, null); } - - @Override - public void deactivate() { - super.deactivate(); - } } diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LutronDeviceDiscoveryService.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LutronDeviceDiscoveryService.java index d2af1f2848cb6..89b7049312dfd 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LutronDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/discovery/LutronDeviceDiscoveryService.java @@ -83,7 +83,6 @@ */ @NonNullByDefault public class LutronDeviceDiscoveryService extends AbstractDiscoveryService { - private static final int DECLARATION_MAX_LEN = 80; private static final long HTTP_REQUEST_TIMEOUT = 60; // seconds private static final int DISCOVERY_SERVICE_TIMEOUT = 90; // seconds diff --git a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/hw/HwDiscoveryService.java b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/hw/HwDiscoveryService.java index 02dfc870bbd48..00a1ab8b1142e 100644 --- a/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/hw/HwDiscoveryService.java +++ b/bundles/org.openhab.binding.lutron/src/main/java/org/openhab/binding/lutron/internal/hw/HwDiscoveryService.java @@ -16,16 +16,12 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; -import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; +import org.eclipse.jdt.annotation.NonNull; import org.openhab.binding.lutron.internal.LutronHandlerFactory; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -38,38 +34,19 @@ * * @author Andrew Shilliday - Initial contribution */ -public class HwDiscoveryService extends AbstractDiscoveryService implements DiscoveryService, ThingHandlerService { +public class HwDiscoveryService extends AbstractThingHandlerDiscoveryService<@NonNull HwSerialBridgeHandler> { private Logger logger = LoggerFactory.getLogger(HwDiscoveryService.class); private final AtomicBoolean isScanning = new AtomicBoolean(false); - private @NonNullByDefault({}) HwSerialBridgeHandler handler; - public HwDiscoveryService() { - super(LutronHandlerFactory.HW_DISCOVERABLE_DEVICE_TYPES_UIDS, 10); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof HwSerialBridgeHandler bridgeHandler) { - this.handler = bridgeHandler; - this.handler.setDiscoveryService(this); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return handler; - } - - @Override - public void activate() { - super.activate(null); + super(HwSerialBridgeHandler.class, LutronHandlerFactory.HW_DISCOVERABLE_DEVICE_TYPES_UIDS, 10); } @Override - public void deactivate() { - super.deactivate(); + public void initialize() { + thingHandler.setDiscoveryService(this); + super.initialize(); } @Override @@ -81,7 +58,7 @@ protected void startScan() { for (int m = 1; m <= 8; m++) { // Modules for (int o = 1; o <= 4; o++) { // Outputs String address = String.format("[01:01:00:%02d:%02d]", m, o); - handler.sendCommand("RDL, " + address); + thingHandler.sendCommand("RDL, " + address); Thread.sleep(5); } } @@ -99,11 +76,11 @@ protected void startScan() { */ public void declareUnknownDimmer(String address) { if (address == null) { - logger.info("Discovered HomeWorks dimmer with no address"); + logger.info("Discovered HomeWorks dimmer with no address or thing handler"); return; } String addressUid = address.replaceAll("[\\[\\]]", "").replace(":", "-"); - ThingUID bridgeUID = this.handler.getThing().getUID(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); ThingUID uid = new ThingUID(HwConstants.THING_TYPE_HWDIMMER, bridgeUID, addressUid); Map props = new HashMap<>(); diff --git a/bundles/org.openhab.binding.mail/src/main/java/org/openhab/binding/mail/internal/action/SendMailActions.java b/bundles/org.openhab.binding.mail/src/main/java/org/openhab/binding/mail/internal/action/SendMailActions.java index b06b5623dfdfb..54b74704bd6d0 100644 --- a/bundles/org.openhab.binding.mail/src/main/java/org/openhab/binding/mail/internal/action/SendMailActions.java +++ b/bundles/org.openhab.binding.mail/src/main/java/org/openhab/binding/mail/internal/action/SendMailActions.java @@ -31,6 +31,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,6 +41,7 @@ * * @author Jan N. Klug - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = SendMailActions.class) @ThingActionsScope(name = "mail") @NonNullByDefault public class SendMailActions implements ThingActions { diff --git a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/actions/MaxCubeActions.java b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/actions/MaxCubeActions.java index b719cfb1b7773..7def8b8f76fa4 100644 --- a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/actions/MaxCubeActions.java +++ b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/actions/MaxCubeActions.java @@ -20,6 +20,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,6 +30,7 @@ * * @author Christoph Weitkamp - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = MaxCubeActions.class) @ThingActionsScope(name = "max-cube") @NonNullByDefault public class MaxCubeActions implements ThingActions { diff --git a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/actions/MaxDevicesActions.java b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/actions/MaxDevicesActions.java index 7b6b19a8cfada..0365a830a34c9 100644 --- a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/actions/MaxDevicesActions.java +++ b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/actions/MaxDevicesActions.java @@ -20,6 +20,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,6 +30,7 @@ * * @author Christoph Weitkamp - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = MaxDevicesActions.class) @ThingActionsScope(name = "max-devices") @NonNullByDefault public class MaxDevicesActions implements ThingActions { diff --git a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/discovery/MaxDeviceDiscoveryService.java b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/discovery/MaxDeviceDiscoveryService.java index 063c02888cb2f..31b1e3a8c27d7 100644 --- a/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/discovery/MaxDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.max/src/main/java/org/openhab/binding/max/internal/discovery/MaxDeviceDiscoveryService.java @@ -16,21 +16,19 @@ import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.max.internal.MaxBindingConstants; import org.openhab.binding.max.internal.device.Device; import org.openhab.binding.max.internal.handler.DeviceStatusListener; import org.openhab.binding.max.internal.handler.MaxCubeBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.Bridge; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,46 +38,29 @@ * * @author Marcel Verpaalen - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = MaxDeviceDiscoveryService.class) @NonNullByDefault -public class MaxDeviceDiscoveryService extends AbstractDiscoveryService - implements DeviceStatusListener, DiscoveryService, ThingHandlerService { +public class MaxDeviceDiscoveryService extends AbstractThingHandlerDiscoveryService + implements DeviceStatusListener { private static final int SEARCH_TIME = 60; private final Logger logger = LoggerFactory.getLogger(MaxDeviceDiscoveryService.class); - private @Nullable MaxCubeBridgeHandler maxCubeBridgeHandler; - public MaxDeviceDiscoveryService() { - super(MaxBindingConstants.SUPPORTED_DEVICE_THING_TYPES_UIDS, SEARCH_TIME, true); - } - - @Override - public void setThingHandler(@NonNullByDefault({}) ThingHandler handler) { - if (handler instanceof MaxCubeBridgeHandler maxCubeBridgeHandler) { - this.maxCubeBridgeHandler = maxCubeBridgeHandler; - } + super(MaxCubeBridgeHandler.class, MaxBindingConstants.SUPPORTED_DEVICE_THING_TYPES_UIDS, SEARCH_TIME, true); } @Override - public @Nullable ThingHandler getThingHandler() { - return maxCubeBridgeHandler; + public void initialize() { + thingHandler.registerDeviceStatusListener(this); + super.initialize(); } @Override - public void activate() { - MaxCubeBridgeHandler localMaxCubeBridgeHandler = maxCubeBridgeHandler; - if (localMaxCubeBridgeHandler != null) { - localMaxCubeBridgeHandler.registerDeviceStatusListener(this); - } - } - - @Override - public void deactivate() { - MaxCubeBridgeHandler localMaxCubeBridgeHandler = maxCubeBridgeHandler; - if (localMaxCubeBridgeHandler != null) { - localMaxCubeBridgeHandler.unregisterDeviceStatusListener(this); - removeOlderResults(new Date().getTime(), localMaxCubeBridgeHandler.getThing().getUID()); - } + public void dispose() { + super.dispose(); + thingHandler.unregisterDeviceStatusListener(this); + removeOlderResults(new Date().getTime(), thingHandler.getThing().getUID()); } @Override @@ -133,11 +114,8 @@ public void onDeviceAdded(Bridge bridge, Device device) { @Override protected void startScan() { - MaxCubeBridgeHandler localMaxCubeBridgeHandler = maxCubeBridgeHandler; - if (localMaxCubeBridgeHandler != null) { - localMaxCubeBridgeHandler.clearDeviceList(); - localMaxCubeBridgeHandler.deviceInclusion(); - } + thingHandler.clearDeviceList(); + thingHandler.deviceInclusion(); } @Override diff --git a/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/discovery/MeaterDiscoveryService.java b/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/discovery/MeaterDiscoveryService.java index 4fd1df175ca1f..0c22321b1aa77 100644 --- a/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/discovery/MeaterDiscoveryService.java +++ b/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/discovery/MeaterDiscoveryService.java @@ -14,17 +14,17 @@ import static org.openhab.binding.meater.internal.MeaterBindingConstants.*; -import java.util.Map; - import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.meater.internal.MeaterConfiguration; import org.openhab.binding.meater.internal.handler.MeaterBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; +import org.openhab.core.i18n.LocaleProvider; +import org.openhab.core.i18n.TranslationProvider; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ServiceScope; /** * The {@link MeaterDiscoveryService} searches for available @@ -32,51 +32,34 @@ * * @author Jan Gustafsson - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = MeaterDiscoveryService.class) @NonNullByDefault -public class MeaterDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class MeaterDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int SEARCH_TIME = 2; - private @Nullable MeaterBridgeHandler handler; public MeaterDiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME); + super(MeaterBridgeHandler.class, SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME); } - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof MeaterBridgeHandler bridgeHandler) { - this.handler = bridgeHandler; - i18nProvider = bridgeHandler.getI18nProvider(); - localeProvider = bridgeHandler.getLocaleProvider(); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return handler; + @Reference(unbind = "-") + public void bindTranslationProvider(TranslationProvider translationProvider) { + this.i18nProvider = translationProvider; } - @Override - public void activate(@Nullable Map configProperties) { - super.activate(configProperties); - } - - @Override - public void deactivate() { - super.deactivate(); + @Reference(unbind = "-") + public void bindLocaleProvider(LocaleProvider localeProvider) { + this.localeProvider = localeProvider; } @Override protected void startScan() { - MeaterBridgeHandler bridgeHandler = this.handler; - if (bridgeHandler != null) { - ThingUID bridgeUID = bridgeHandler.getThing().getUID(); - bridgeHandler.getMeaterThings().entrySet().stream().forEach(thing -> { - thingDiscovered( - DiscoveryResultBuilder.create(new ThingUID(THING_TYPE_MEATER_PROBE, bridgeUID, thing.getKey())) - .withLabel("@text/discovery.probe.label").withBridge(bridgeUID) - .withProperty(MeaterConfiguration.DEVICE_ID_LABEL, thing.getKey()) - .withRepresentationProperty(MeaterConfiguration.DEVICE_ID_LABEL).build()); - }); - } + ThingUID bridgeUID = thingHandler.getThing().getUID(); + thingHandler.getMeaterThings().entrySet().stream().forEach(thing -> { + thingDiscovered( + DiscoveryResultBuilder.create(new ThingUID(THING_TYPE_MEATER_PROBE, bridgeUID, thing.getKey())) + .withLabel("@text/discovery.probe.label").withBridge(bridgeUID) + .withProperty(MeaterConfiguration.DEVICE_ID_LABEL, thing.getKey()) + .withRepresentationProperty(MeaterConfiguration.DEVICE_ID_LABEL).build()); + }); } } diff --git a/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/handler/MeaterBridgeHandler.java b/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/handler/MeaterBridgeHandler.java index 45d3e23bd34ee..d05ab94af1953 100644 --- a/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/handler/MeaterBridgeHandler.java +++ b/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/handler/MeaterBridgeHandler.java @@ -29,7 +29,6 @@ import org.openhab.binding.meater.internal.discovery.MeaterDiscoveryService; import org.openhab.binding.meater.internal.dto.MeaterProbeDTO; import org.openhab.core.i18n.LocaleProvider; -import org.openhab.core.i18n.TranslationProvider; import org.openhab.core.thing.Bridge; import org.openhab.core.thing.ChannelUID; import org.openhab.core.thing.ThingStatus; @@ -59,7 +58,6 @@ public class MeaterBridgeHandler extends BaseBridgeHandler { private final Gson gson; private final HttpClient httpClient; - private final TranslationProvider i18nProvider; private final LocaleProvider localeProvider; private final Map meaterProbeThings = new ConcurrentHashMap<>(); @@ -67,12 +65,10 @@ public class MeaterBridgeHandler extends BaseBridgeHandler { private @Nullable MeaterRestAPI api; private @Nullable ScheduledFuture refreshJob; - public MeaterBridgeHandler(Bridge bridge, HttpClient httpClient, Gson gson, TranslationProvider i18nProvider, - LocaleProvider localeProvider) { + public MeaterBridgeHandler(Bridge bridge, HttpClient httpClient, Gson gson, LocaleProvider localeProvider) { super(bridge); this.httpClient = httpClient; this.gson = gson; - this.i18nProvider = i18nProvider; this.localeProvider = localeProvider; } @@ -154,12 +150,4 @@ public void handleCommand(ChannelUID channelUID, Command command) { } } } - - public TranslationProvider getI18nProvider() { - return i18nProvider; - } - - public LocaleProvider getLocaleProvider() { - return localeProvider; - } } diff --git a/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/handler/MeaterHandlerFactory.java b/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/handler/MeaterHandlerFactory.java index d473d51b60852..c81282b7fbd64 100644 --- a/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/handler/MeaterHandlerFactory.java +++ b/bundles/org.openhab.binding.meater/src/main/java/org/openhab/binding/meater/internal/handler/MeaterHandlerFactory.java @@ -21,7 +21,6 @@ import org.eclipse.jetty.client.HttpClient; import org.openhab.core.i18n.LocaleProvider; import org.openhab.core.i18n.TimeZoneProvider; -import org.openhab.core.i18n.TranslationProvider; import org.openhab.core.io.net.http.HttpClientFactory; import org.openhab.core.thing.Bridge; import org.openhab.core.thing.Thing; @@ -51,15 +50,12 @@ public class MeaterHandlerFactory extends BaseThingHandlerFactory { private final Gson gson; private final HttpClient httpClient; private final TimeZoneProvider timeZoneProvider; - private final TranslationProvider i18nProvider; private final LocaleProvider localeProvider; @Activate - public MeaterHandlerFactory(@Reference TimeZoneProvider timeZoneProvider, - final @Reference TranslationProvider i18nProvider, @Reference LocaleProvider localeProvider, + public MeaterHandlerFactory(@Reference TimeZoneProvider timeZoneProvider, @Reference LocaleProvider localeProvider, @Reference HttpClientFactory httpClientFactory) { this.timeZoneProvider = timeZoneProvider; - this.i18nProvider = i18nProvider; this.localeProvider = localeProvider; this.httpClient = httpClientFactory.getCommonHttpClient(); this.gson = new Gson(); @@ -77,7 +73,7 @@ public boolean supportsThingType(ThingTypeUID thingTypeUID) { if (THING_TYPE_MEATER_PROBE.equals(thingTypeUID)) { return new MeaterHandler(thing, timeZoneProvider); } else if (THING_TYPE_BRIDGE.equals(thingTypeUID)) { - return new MeaterBridgeHandler((Bridge) thing, httpClient, gson, i18nProvider, localeProvider); + return new MeaterBridgeHandler((Bridge) thing, httpClient, gson, localeProvider); } return null; diff --git a/bundles/org.openhab.binding.melcloud/src/main/java/org/openhab/binding/melcloud/internal/discovery/MelCloudDiscoveryService.java b/bundles/org.openhab.binding.melcloud/src/main/java/org/openhab/binding/melcloud/internal/discovery/MelCloudDiscoveryService.java index 165d248e8ff38..9134d8482e7b9 100644 --- a/bundles/org.openhab.binding.melcloud/src/main/java/org/openhab/binding/melcloud/internal/discovery/MelCloudDiscoveryService.java +++ b/bundles/org.openhab.binding.melcloud/src/main/java/org/openhab/binding/melcloud/internal/discovery/MelCloudDiscoveryService.java @@ -20,21 +20,19 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; -import org.eclipse.jdt.annotation.Nullable; +import org.eclipse.jdt.annotation.NonNull; import org.openhab.binding.melcloud.internal.MelCloudBindingConstants; import org.openhab.binding.melcloud.internal.api.json.Device; import org.openhab.binding.melcloud.internal.exceptions.MelCloudCommException; import org.openhab.binding.melcloud.internal.exceptions.MelCloudLoginException; import org.openhab.binding.melcloud.internal.handler.MelCloudAccountHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; -import org.osgi.service.component.annotations.Modified; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,38 +43,21 @@ * @author Pauli Anttila - Refactoring * @author Wietse van Buitenen - Check device type, added heatpump device */ -public class MelCloudDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { - +@Component(scope = ServiceScope.PROTOTYPE, service = MelCloudDiscoveryService.class) +public class MelCloudDiscoveryService extends AbstractThingHandlerDiscoveryService<@NonNull MelCloudAccountHandler> { private final Logger logger = LoggerFactory.getLogger(MelCloudDiscoveryService.class); private static final String PROPERTY_DEVICE_ID = "deviceID"; private static final int DISCOVER_TIMEOUT_SECONDS = 10; - private MelCloudAccountHandler melCloudHandler; private ScheduledFuture scanTask; /** * Creates a MelCloudDiscoveryService with enabled autostart. */ public MelCloudDiscoveryService() { - super(MelCloudBindingConstants.DISCOVERABLE_THING_TYPE_UIDS, DISCOVER_TIMEOUT_SECONDS, true); - } - - @Override - protected void activate(Map configProperties) { - super.activate(configProperties); - } - - @Override - public void deactivate() { - super.deactivate(); - } - - @Override - @Modified - protected void modified(Map configProperties) { - super.modified(configProperties); + super(MelCloudAccountHandler.class, MelCloudBindingConstants.DISCOVERABLE_THING_TYPE_UIDS, + DISCOVER_TIMEOUT_SECONDS, true); } @Override @@ -104,50 +85,47 @@ protected void stopScan() { private void discoverDevices() { logger.debug("Discover devices"); - - if (melCloudHandler != null) { - try { - List deviceList = melCloudHandler.getDeviceList(); - - if (deviceList == null) { - logger.debug("No devices found"); - } else { - ThingUID bridgeUID = melCloudHandler.getThing().getUID(); - - deviceList.forEach(device -> { - ThingTypeUID thingTypeUid = null; - if (device.getType() == 0) { - thingTypeUid = THING_TYPE_ACDEVICE; - } else if (device.getType() == 1) { - thingTypeUid = THING_TYPE_HEATPUMPDEVICE; - } else { - logger.debug("Unsupported device found: name {} : type: {}", device.getDeviceName(), - device.getType()); - return; - } - ThingUID deviceThing = new ThingUID(thingTypeUid, melCloudHandler.getThing().getUID(), - device.getDeviceID().toString()); - - Map deviceProperties = new HashMap<>(); - deviceProperties.put(PROPERTY_DEVICE_ID, device.getDeviceID().toString()); - deviceProperties.put(Thing.PROPERTY_SERIAL_NUMBER, device.getSerialNumber()); - deviceProperties.put(Thing.PROPERTY_MAC_ADDRESS, device.getMacAddress()); - deviceProperties.put("deviceName", device.getDeviceName()); - deviceProperties.put("buildingID", device.getBuildingID().toString()); - - String label = createLabel(device); - logger.debug("Found device: {} : {}", label, deviceProperties); - - thingDiscovered(DiscoveryResultBuilder.create(deviceThing).withLabel(label) - .withProperties(deviceProperties).withRepresentationProperty(PROPERTY_DEVICE_ID) - .withBridge(bridgeUID).build()); - }); - } - } catch (MelCloudLoginException e) { - logger.debug("Login error occurred during device list fetch, reason {}. ", e.getMessage(), e); - } catch (MelCloudCommException e) { - logger.debug("Error occurred during device list fetch, reason {}. ", e.getMessage(), e); + try { + List deviceList = thingHandler.getDeviceList(); + + if (deviceList == null) { + logger.debug("No devices found"); + } else { + ThingUID bridgeUID = thingHandler.getThing().getUID(); + + deviceList.forEach(device -> { + ThingTypeUID thingTypeUid = null; + if (device.getType() == 0) { + thingTypeUid = THING_TYPE_ACDEVICE; + } else if (device.getType() == 1) { + thingTypeUid = THING_TYPE_HEATPUMPDEVICE; + } else { + logger.debug("Unsupported device found: name {} : type: {}", device.getDeviceName(), + device.getType()); + return; + } + ThingUID deviceThing = new ThingUID(thingTypeUid, thingHandler.getThing().getUID(), + device.getDeviceID().toString()); + + Map deviceProperties = new HashMap<>(); + deviceProperties.put(PROPERTY_DEVICE_ID, device.getDeviceID().toString()); + deviceProperties.put(Thing.PROPERTY_SERIAL_NUMBER, device.getSerialNumber()); + deviceProperties.put(Thing.PROPERTY_MAC_ADDRESS, device.getMacAddress()); + deviceProperties.put("deviceName", device.getDeviceName()); + deviceProperties.put("buildingID", device.getBuildingID().toString()); + + String label = createLabel(device); + logger.debug("Found device: {} : {}", label, deviceProperties); + + thingDiscovered( + DiscoveryResultBuilder.create(deviceThing).withLabel(label).withProperties(deviceProperties) + .withRepresentationProperty(PROPERTY_DEVICE_ID).withBridge(bridgeUID).build()); + }); } + } catch (MelCloudLoginException e) { + logger.debug("Login error occurred during device list fetch, reason {}. ", e.getMessage(), e); + } catch (MelCloudCommException e) { + logger.debug("Error occurred during device list fetch, reason {}. ", e.getMessage(), e); } } @@ -164,16 +142,4 @@ private String createLabel(Device device) { sb.append(device.getDeviceName()); return sb.toString(); } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof MelCloudAccountHandler accountHandler) { - melCloudHandler = accountHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return melCloudHandler; - } } diff --git a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/discovery/ThingDiscoveryService.java b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/discovery/ThingDiscoveryService.java index bd6fd30c85699..d95927023c1aa 100644 --- a/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/discovery/ThingDiscoveryService.java +++ b/bundles/org.openhab.binding.mielecloud/src/main/java/org/openhab/binding/mielecloud/internal/discovery/ThingDiscoveryService.java @@ -15,6 +15,7 @@ import static org.openhab.binding.mielecloud.internal.MieleCloudBindingConstants.*; import static org.openhab.binding.mielecloud.internal.handler.MieleHandlerFactory.SUPPORTED_THING_TYPES; +import java.util.Map; import java.util.Optional; import org.eclipse.jdt.annotation.NonNullByDefault; @@ -22,15 +23,15 @@ import org.openhab.binding.mielecloud.internal.handler.MieleBridgeHandler; import org.openhab.binding.mielecloud.internal.webservice.api.DeviceState; import org.openhab.binding.mielecloud.internal.webservice.api.json.DeviceType; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,13 +41,11 @@ * @author Roland Edelhoff - Initial contribution * @author Björn Lange - Do not directly listen to webservice events */ +@Component(scope = ServiceScope.PROTOTYPE, service = ThingDiscoveryService.class) @NonNullByDefault -public class ThingDiscoveryService extends AbstractDiscoveryService implements DiscoveryService, ThingHandlerService { +public class ThingDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int BACKGROUND_DISCOVERY_TIMEOUT_IN_SECONDS = 5; - @Nullable - private MieleBridgeHandler bridgeHandler; - private final Logger logger = LoggerFactory.getLogger(this.getClass()); private boolean discoveringDevices = false; @@ -55,12 +54,12 @@ public class ThingDiscoveryService extends AbstractDiscoveryService implements D * Creates a new {@link ThingDiscoveryService}. */ public ThingDiscoveryService() { - super(SUPPORTED_THING_TYPES, BACKGROUND_DISCOVERY_TIMEOUT_IN_SECONDS); + super(MieleBridgeHandler.class, SUPPORTED_THING_TYPES, BACKGROUND_DISCOVERY_TIMEOUT_IN_SECONDS); } @Nullable private ThingUID getBridgeUid() { - var bridgeHandler = this.bridgeHandler; + var bridgeHandler = this.thingHandler; if (bridgeHandler == null) { return null; } else { @@ -74,12 +73,12 @@ protected void startScan() { @Override public void activate() { - startBackgroundDiscovery(); + super.activate(Map.of(DiscoveryService.CONFIG_PROPERTY_BACKGROUND_DISCOVERY, true)); } @Override - public void deactivate() { - stopBackgroundDiscovery(); + public void dispose() { + super.dispose(); removeOlderResults(System.currentTimeMillis(), getBridgeUid()); } @@ -100,16 +99,11 @@ public void onDeviceStateUpdated(DeviceState deviceState) { } private void createDiscoveryResult(DeviceState deviceState, ThingTypeUID thingTypeUid) { - MieleBridgeHandler bridgeHandler = this.bridgeHandler; - if (bridgeHandler == null) { - return; - } - - ThingUID thingUid = new ThingUID(thingTypeUid, bridgeHandler.getThing().getUID(), + ThingUID thingUid = new ThingUID(thingTypeUid, thingHandler.getThing().getUID(), deviceState.getDeviceIdentifier()); DiscoveryResultBuilder discoveryResultBuilder = DiscoveryResultBuilder.create(thingUid) - .withBridge(bridgeHandler.getThing().getUID()).withRepresentationProperty(Thing.PROPERTY_SERIAL_NUMBER) + .withBridge(thingHandler.getThing().getUID()).withRepresentationProperty(Thing.PROPERTY_SERIAL_NUMBER) .withLabel(getLabel(deviceState)); ThingInformationExtractor.extractProperties(thingTypeUid, deviceState).entrySet() @@ -199,15 +193,8 @@ private String getLabel(DeviceState deviceState) { } @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof MieleBridgeHandler bridgeHandler) { - bridgeHandler.setDiscoveryService(this); - this.bridgeHandler = bridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; + public void initialize() { + thingHandler.setDiscoveryService(this); + super.initialize(); } } diff --git a/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsActions.java b/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsActions.java index 646e7ff23eb90..101d46f0cf60f 100644 --- a/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsActions.java +++ b/bundles/org.openhab.binding.modbus.helioseasycontrols/src/main/java/org/openhab/binding/modbus/helioseasycontrols/internal/HeliosEasyControlsActions.java @@ -25,6 +25,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,6 +35,7 @@ * * @author Bernhard Bauer - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = HeliosEasyControlsActions.class) @ThingActionsScope(name = "modbus.helioseasycontrols") @NonNullByDefault public class HeliosEasyControlsActions implements ThingActions { diff --git a/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/discovery/internal/ModbusEndpointDiscoveryService.java b/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/discovery/internal/ModbusEndpointDiscoveryService.java index bebbcbecbf816..06625eb41526e 100644 --- a/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/discovery/internal/ModbusEndpointDiscoveryService.java +++ b/bundles/org.openhab.binding.modbus/src/main/java/org/openhab/binding/modbus/discovery/internal/ModbusEndpointDiscoveryService.java @@ -22,6 +22,8 @@ import org.openhab.binding.modbus.handler.ModbusEndpointThingHandler; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -35,6 +37,7 @@ * @author Nagy Attila Gabor - initial contribution * */ +@Component(scope = ServiceScope.PROTOTYPE, service = ModbusEndpointDiscoveryService.class) @NonNullByDefault public class ModbusEndpointDiscoveryService implements ModbusThingHandlerDiscoveryService { diff --git a/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/action/MPDActions.java b/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/action/MPDActions.java index e3dc89f207fb1..f937868554818 100644 --- a/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/action/MPDActions.java +++ b/bundles/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/internal/action/MPDActions.java @@ -20,6 +20,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,6 +30,7 @@ * * @author Stefan Röllin - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = MPDActions.class) @ThingActionsScope(name = "mpd") @NonNullByDefault public class MPDActions implements ThingActions { diff --git a/bundles/org.openhab.binding.mqtt/src/main/java/org/openhab/binding/mqtt/internal/action/MQTTActions.java b/bundles/org.openhab.binding.mqtt/src/main/java/org/openhab/binding/mqtt/internal/action/MQTTActions.java index c22716c6c4c5e..4db633c8e3f40 100644 --- a/bundles/org.openhab.binding.mqtt/src/main/java/org/openhab/binding/mqtt/internal/action/MQTTActions.java +++ b/bundles/org.openhab.binding.mqtt/src/main/java/org/openhab/binding/mqtt/internal/action/MQTTActions.java @@ -21,6 +21,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -29,6 +31,7 @@ * * @author David Graeff - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = MQTTActions.class) @ThingActionsScope(name = "mqtt") @NonNullByDefault public class MQTTActions implements ThingActions { diff --git a/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/discovery/VehicleDiscovery.java b/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/discovery/VehicleDiscovery.java index 2c3d066ad5a25..af3b31da0e691 100644 --- a/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/discovery/VehicleDiscovery.java +++ b/bundles/org.openhab.binding.mybmw/src/main/java/org/openhab/binding/mybmw/internal/discovery/VehicleDiscovery.java @@ -19,7 +19,6 @@ import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.mybmw.internal.MyBMWConstants; import org.openhab.binding.mybmw.internal.dto.vehicle.Vehicle; import org.openhab.binding.mybmw.internal.dto.vehicle.VehicleAttributes; @@ -31,12 +30,12 @@ import org.openhab.binding.mybmw.internal.utils.Constants; import org.openhab.binding.mybmw.internal.utils.VehicleStatusUtils; import org.openhab.core.config.core.Configuration; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -47,34 +46,26 @@ * @author Bernd Weymann - Initial contribution * @author Martin Grassl - refactoring */ +@Component(scope = ServiceScope.PROTOTYPE, service = VehicleDiscovery.class) @NonNullByDefault -public class VehicleDiscovery extends AbstractDiscoveryService implements ThingHandlerService { +public class VehicleDiscovery extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(VehicleDiscovery.class); private static final int DISCOVERY_TIMEOUT = 10; - private Optional bridgeHandler = Optional.empty(); private Optional myBMWProxy = Optional.empty(); - private Optional bridgeUid = Optional.empty(); + private @NonNullByDefault({}) ThingUID bridgeUid; public VehicleDiscovery() { - super(MyBMWConstants.SUPPORTED_THING_SET, DISCOVERY_TIMEOUT, false); + super(MyBMWBridgeHandler.class, MyBMWConstants.SUPPORTED_THING_SET, DISCOVERY_TIMEOUT, false); } @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof MyBMWBridgeHandler bmwBridgeHandler) { - logger.trace("VehicleDiscovery.setThingHandler for MybmwBridge"); - bridgeHandler = Optional.of(bmwBridgeHandler); - bridgeHandler.get().setVehicleDiscovery(this); - bridgeUid = Optional.of(bridgeHandler.get().getThing().getUID()); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler.orElse(null); + public void initialize() { + thingHandler.setVehicleDiscovery(this); + bridgeUid = thingHandler.getThing().getUID(); + super.initialize(); } @Override @@ -83,17 +74,10 @@ protected void startScan() { discoverVehicles(); } - @Override - public void deactivate() { - logger.trace("VehicleDiscovery.deactivate"); - - super.deactivate(); - } - public void discoverVehicles() { logger.trace("VehicleDiscovery.discoverVehicles"); - myBMWProxy = bridgeHandler.get().getMyBmwProxy(); + myBMWProxy = thingHandler.getMyBmwProxy(); try { Optional> vehicleList = myBMWProxy.map(prox -> { @@ -104,11 +88,11 @@ public void discoverVehicles() { } }); vehicleList.ifPresentOrElse(vehicles -> { - bridgeHandler.ifPresent(bridge -> bridge.vehicleDiscoverySuccess()); + thingHandler.vehicleDiscoverySuccess(); processVehicles(vehicles); - }, () -> bridgeHandler.ifPresent(bridge -> bridge.vehicleDiscoveryError())); + }, () -> thingHandler.vehicleDiscoveryError()); } catch (IllegalStateException ex) { - bridgeHandler.ifPresent(bridge -> bridge.vehicleDiscoveryError()); + thingHandler.vehicleDiscoveryError(); } } @@ -131,13 +115,13 @@ private void processVehicles(List vehicleList) { .toString(); MyBMWConstants.SUPPORTED_THING_SET.forEach(entry -> { if (entry.getId().equals(vehicleType)) { - ThingUID uid = new ThingUID(entry, vehicle.getVehicleBase().getVin(), bridgeUid.get().getId()); + ThingUID uid = new ThingUID(entry, vehicle.getVehicleBase().getVin(), bridgeUid.getId()); Map properties = generateProperties(vehicle); boolean thingFound = false; // Update Properties for already created Things - List vehicleThings = bridgeHandler.get().getThing().getThings(); + List vehicleThings = thingHandler.getThing().getThings(); for (Thing vehicleThing : vehicleThings) { Configuration configuration = vehicleThing.getConfiguration(); @@ -161,7 +145,7 @@ private void processVehicles(List vehicleList) { Integer.toString(MyBMWConstants.DEFAULT_REFRESH_INTERVAL_MINUTES)); String vehicleLabel = vehicleAttributes.getBrand() + " " + vehicleAttributes.getModel(); - thingDiscovered(DiscoveryResultBuilder.create(uid).withBridge(bridgeUid.get()) + thingDiscovered(DiscoveryResultBuilder.create(uid).withBridge(bridgeUid) .withRepresentationProperty(MyBMWConstants.VIN).withLabel(vehicleLabel) .withProperties(convertedProperties).build()); } diff --git a/bundles/org.openhab.binding.mybmw/src/test/java/org/openhab/binding/mybmw/internal/discovery/VehicleDiscoveryTest.java b/bundles/org.openhab.binding.mybmw/src/test/java/org/openhab/binding/mybmw/internal/discovery/VehicleDiscoveryTest.java index 5d8021481eb44..537cf12a0a8f6 100644 --- a/bundles/org.openhab.binding.mybmw/src/test/java/org/openhab/binding/mybmw/internal/discovery/VehicleDiscoveryTest.java +++ b/bundles/org.openhab.binding.mybmw/src/test/java/org/openhab/binding/mybmw/internal/discovery/VehicleDiscoveryTest.java @@ -83,6 +83,7 @@ public void testDiscovery() { when(bridgeHandler.getMyBmwProxy()).thenReturn(Optional.of(myBMWProxy)); vehicleDiscovery.setThingHandler(bridgeHandler); + vehicleDiscovery.initialize(); assertNotNull(vehicleDiscovery.getThingHandler()); DiscoveryListener listener = mock(DiscoveryListener.class); diff --git a/bundles/org.openhab.binding.mynice/src/main/java/org/openhab/binding/mynice/internal/discovery/MyNiceDiscoveryService.java b/bundles/org.openhab.binding.mynice/src/main/java/org/openhab/binding/mynice/internal/discovery/MyNiceDiscoveryService.java index 105e17583db1e..51ac3433ce2dc 100644 --- a/bundles/org.openhab.binding.mynice/src/main/java/org/openhab/binding/mynice/internal/discovery/MyNiceDiscoveryService.java +++ b/bundles/org.openhab.binding.mynice/src/main/java/org/openhab/binding/mynice/internal/discovery/MyNiceDiscoveryService.java @@ -15,21 +15,19 @@ import static org.openhab.binding.mynice.internal.MyNiceBindingConstants.*; import java.util.List; -import java.util.Optional; import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.mynice.internal.handler.It4WifiHandler; import org.openhab.binding.mynice.internal.handler.MyNiceDataListener; import org.openhab.binding.mynice.internal.xml.dto.CommandType; import org.openhab.binding.mynice.internal.xml.dto.Device; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,72 +37,56 @@ * * @author Gaël L'hopital - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = MyNiceDiscoveryService.class) @NonNullByDefault -public class MyNiceDiscoveryService extends AbstractDiscoveryService - implements MyNiceDataListener, ThingHandlerService { +public class MyNiceDiscoveryService extends AbstractThingHandlerDiscoveryService + implements MyNiceDataListener { private static final int SEARCH_TIME = 5; private final Logger logger = LoggerFactory.getLogger(MyNiceDiscoveryService.class); - private Optional bridgeHandler = Optional.empty(); - /** * Creates a MyNiceDiscoveryService with background discovery disabled. */ public MyNiceDiscoveryService() { - super(Set.of(THING_TYPE_SWING, THING_TYPE_SLIDING), SEARCH_TIME, false); - } - - @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof It4WifiHandler it4Handler) { - bridgeHandler = Optional.of(it4Handler); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler.orElse(null); + super(It4WifiHandler.class, Set.of(THING_TYPE_SWING, THING_TYPE_SLIDING), SEARCH_TIME, false); } @Override - public void activate() { - super.activate(null); - bridgeHandler.ifPresent(h -> h.registerDataListener(this)); + public void initialize() { + thingHandler.registerDataListener(this); + super.initialize(); } @Override - public void deactivate() { - bridgeHandler.ifPresent(h -> h.unregisterDataListener(this)); - bridgeHandler = Optional.empty(); - super.deactivate(); + public void dispose() { + super.dispose(); + thingHandler.unregisterDataListener(this); } @Override public void onDataFetched(List devices) { - bridgeHandler.ifPresent(handler -> { - ThingUID bridgeUID = handler.getThing().getUID(); - devices.stream().filter(device -> device.type != null).forEach(device -> { - ThingUID thingUID = switch (device.type) { - case SWING -> new ThingUID(THING_TYPE_SWING, bridgeUID, device.id); - case SLIDING -> new ThingUID(THING_TYPE_SLIDING, bridgeUID, device.id); - default -> null; - }; + ThingUID bridgeUID = thingHandler.getThing().getUID(); + devices.stream().filter(device -> device.type != null).forEach(device -> { + ThingUID thingUID = switch (device.type) { + case SWING -> new ThingUID(THING_TYPE_SWING, bridgeUID, device.id); + case SLIDING -> new ThingUID(THING_TYPE_SLIDING, bridgeUID, device.id); + default -> null; + }; - if (thingUID != null) { - DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withBridge(bridgeUID) - .withLabel(String.format("%s %s", device.manuf, device.prod)) - .withRepresentationProperty(DEVICE_ID).withProperty(DEVICE_ID, device.id).build(); - thingDiscovered(discoveryResult); - } else { - logger.info("`{}` type of device is not yet supported", device.type); - } - }); + if (thingUID != null) { + DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withBridge(bridgeUID) + .withLabel(String.format("%s %s", device.manuf, device.prod)) + .withRepresentationProperty(DEVICE_ID).withProperty(DEVICE_ID, device.id).build(); + thingDiscovered(discoveryResult); + } else { + logger.info("`{}` type of device is not yet supported", device.type); + } }); } @Override protected void startScan() { - bridgeHandler.ifPresent(h -> h.sendCommand(CommandType.INFO)); + thingHandler.sendCommand(CommandType.INFO); } } diff --git a/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/commanddescription/NanoleafCommandDescriptionProvider.java b/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/commanddescription/NanoleafCommandDescriptionProvider.java index a52f9d04fb37e..086574af37395 100644 --- a/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/commanddescription/NanoleafCommandDescriptionProvider.java +++ b/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/commanddescription/NanoleafCommandDescriptionProvider.java @@ -29,6 +29,7 @@ import org.openhab.core.thing.type.DynamicCommandDescriptionProvider; import org.openhab.core.types.CommandOption; import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * This class provides the available effects as dynamic options as they are read from the Nanoleaf controller. @@ -37,7 +38,8 @@ * */ @NonNullByDefault -@Component(service = { DynamicCommandDescriptionProvider.class }) +@Component(scope = ServiceScope.PROTOTYPE, service = { NanoleafCommandDescriptionProvider.class, + DynamicCommandDescriptionProvider.class }) public class NanoleafCommandDescriptionProvider extends BaseDynamicCommandDescriptionProvider implements NanoleafControllerListener, ThingHandlerService { @@ -62,12 +64,11 @@ public void setThingHandler(ThingHandler handler) { } @Override - public void deactivate() { + public void dispose() { NanoleafControllerHandler localHandler = this.bridgeHandler; if (localHandler != null) { localHandler.unregisterControllerListener(this); } - super.deactivate(); } @Override diff --git a/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/discovery/NanoleafPanelsDiscoveryService.java b/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/discovery/NanoleafPanelsDiscoveryService.java index 13d9475042582..780a0a2896bdd 100644 --- a/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/discovery/NanoleafPanelsDiscoveryService.java +++ b/bundles/org.openhab.binding.nanoleaf/src/main/java/org/openhab/binding/nanoleaf/internal/discovery/NanoleafPanelsDiscoveryService.java @@ -29,13 +29,13 @@ import org.openhab.binding.nanoleaf.internal.model.Layout; import org.openhab.binding.nanoleaf.internal.model.PanelLayout; import org.openhab.binding.nanoleaf.internal.model.PositionDatum; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.binding.BridgeHandler; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -46,31 +46,29 @@ * @author Martin Raepple - Initial contribution * @author Kai Kreuzer - Made it a ThingHandlerService */ +@Component(scope = ServiceScope.PROTOTYPE, service = NanoleafPanelsDiscoveryService.class) @NonNullByDefault -public class NanoleafPanelsDiscoveryService extends AbstractDiscoveryService - implements NanoleafControllerListener, ThingHandlerService { +public class NanoleafPanelsDiscoveryService extends AbstractThingHandlerDiscoveryService + implements NanoleafControllerListener { private static final int SEARCH_TIMEOUT_SECONDS = 60; private final Logger logger = LoggerFactory.getLogger(NanoleafPanelsDiscoveryService.class); - private @Nullable NanoleafControllerHandler bridgeHandler; private @Nullable ControllerInfo controllerInfo; /** * Constructs a new {@link NanoleafPanelsDiscoveryService}. */ public NanoleafPanelsDiscoveryService() { - super(NanoleafHandlerFactory.SUPPORTED_THING_TYPES_UIDS, SEARCH_TIMEOUT_SECONDS, false); + super(NanoleafControllerHandler.class, NanoleafHandlerFactory.SUPPORTED_THING_TYPES_UIDS, + SEARCH_TIMEOUT_SECONDS, false); } @Override - public void deactivate() { - NanoleafControllerHandler localBridgeHandler = bridgeHandler; - if (localBridgeHandler != null) { - Boolean result = localBridgeHandler.unregisterControllerListener(this); - logger.debug("unregistration of controller was {}", result ? "successful" : "unsuccessful"); - } - super.deactivate(); + public void dispose() { + super.dispose(); + boolean result = thingHandler.unregisterControllerListener(this); + logger.debug("unregistration of controller was {}", result ? "successful" : "unsuccessful"); } @Override @@ -92,7 +90,7 @@ public void onControllerInfoFetched(ThingUID bridge, ControllerInfo controllerIn private void createResultsFromControllerInfo() { ThingUID bridgeUID; - BridgeHandler localBridgeHandler = bridgeHandler; + BridgeHandler localBridgeHandler = thingHandler; if (localBridgeHandler != null) { bridgeUID = localBridgeHandler.getThing().getUID(); } else { @@ -137,15 +135,8 @@ private void createResultsFromControllerInfo() { } @Override - public void setThingHandler(ThingHandler handler) { - this.bridgeHandler = (NanoleafControllerHandler) handler; - NanoleafControllerHandler localBridgeHandler = (NanoleafControllerHandler) handler; - - localBridgeHandler.registerControllerListener(this); - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; + public void initialize() { + thingHandler.registerControllerListener(this); + super.initialize(); } } diff --git a/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/discovery/SDMDiscoveryService.java b/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/discovery/SDMDiscoveryService.java index 1aa5996bba9c3..c76e6f674f3db 100644 --- a/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/discovery/SDMDiscoveryService.java +++ b/bundles/org.openhab.binding.nest/src/main/java/org/openhab/binding/nest/internal/sdm/discovery/SDMDiscoveryService.java @@ -28,13 +28,12 @@ import org.openhab.binding.nest.internal.sdm.exception.InvalidSDMAccessTokenException; import org.openhab.binding.nest.internal.sdm.handler.SDMAccountHandler; import org.openhab.binding.nest.internal.sdm.handler.SDMBaseHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; -import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -47,36 +46,20 @@ * @see * https://developers.google.com/nest/device-access/reference/rest/v1/enterprises.devices/list */ +@Component(scope = ServiceScope.PROTOTYPE, service = SDMDiscoveryService.class) @NonNullByDefault -public class SDMDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { - +public class SDMDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(SDMDiscoveryService.class); - private @NonNullByDefault({}) SDMAccountHandler accountHandler; private @Nullable Future discoveryJob; public SDMDiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, 30, false); - } - - protected void activate(ComponentContext context) { + super(SDMAccountHandler.class, SUPPORTED_THING_TYPES_UIDS, 30, false); } @Override - public void deactivate() { + public void dispose() { + super.dispose(); cancelDiscoveryJob(); - super.deactivate(); - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return accountHandler; - } - - @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof SDMAccountHandler sdmAccountHandler) { - accountHandler = sdmAccountHandler; - } } @Override @@ -99,10 +82,10 @@ private void cancelDiscoveryJob() { } private void discoverDevices() { - ThingUID bridgeUID = accountHandler.getThing().getUID(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); logger.debug("Starting discovery scan for {}", bridgeUID); try { - accountHandler.getAPI().listDevices().forEach(device -> addDeviceDiscoveryResult(bridgeUID, device)); + thingHandler.getAPI().listDevices().forEach(device -> addDeviceDiscoveryResult(bridgeUID, device)); } catch (FailedSendingSDMDataException | InvalidSDMAccessTokenException e) { logger.debug("Exception during discovery scan for {}", bridgeUID, e); } diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/action/RoomActions.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/action/RoomActions.java index 93ef8572e4ae5..56010bdceb6c3 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/action/RoomActions.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/action/RoomActions.java @@ -26,6 +26,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,6 +36,7 @@ * * @author Markus Dillmann - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = RoomActions.class) @ThingActionsScope(name = "netatmo") @NonNullByDefault public class RoomActions implements ThingActions { diff --git a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/discovery/NetatmoDiscoveryService.java b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/discovery/NetatmoDiscoveryService.java index 648970a97683b..62efbdd4d66ff 100644 --- a/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/discovery/NetatmoDiscoveryService.java +++ b/bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/discovery/NetatmoDiscoveryService.java @@ -16,18 +16,16 @@ import java.util.stream.Collectors; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.netatmo.internal.api.data.ModuleType; import org.openhab.binding.netatmo.internal.api.dto.NAModule; import org.openhab.binding.netatmo.internal.config.NAThingConfiguration; import org.openhab.binding.netatmo.internal.handler.ApiBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -37,24 +35,20 @@ * @author Gaël L'hopital - Initial contribution * */ +@Component(scope = ServiceScope.PROTOTYPE, service = NetatmoDiscoveryService.class) @NonNullByDefault -public class NetatmoDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService, DiscoveryService { +public class NetatmoDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int DISCOVER_TIMEOUT_SECONDS = 3; private final Logger logger = LoggerFactory.getLogger(NetatmoDiscoveryService.class); - private @Nullable ApiBridgeHandler handler; - public NetatmoDiscoveryService() { - super(ModuleType.AS_SET.stream().filter(mt -> !mt.apiName.isBlank()).map(mt -> mt.thingTypeUID) - .collect(Collectors.toSet()), DISCOVER_TIMEOUT_SECONDS); + super(ApiBridgeHandler.class, ModuleType.AS_SET.stream().filter(mt -> !mt.apiName.isBlank()) + .map(mt -> mt.thingTypeUID).collect(Collectors.toSet()), DISCOVER_TIMEOUT_SECONDS); } @Override public void startScan() { - ApiBridgeHandler localHandler = handler; - if (localHandler != null) { - localHandler.identifyAllModulesAndApplyAction(this::createThing); - } + thingHandler.identifyAllModulesAndApplyAction(this::createThing); } private Optional findThingUID(ModuleType moduleType, String thingId, ThingUID bridgeUID) { @@ -76,21 +70,4 @@ private Optional createThing(NAModule module, ThingUID bridgeUID) { } return moduleUID; } - - @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof ApiBridgeHandler bridgeHandler) { - this.handler = bridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return handler; - } - - @Override - public void deactivate() { - super.deactivate(); - } } diff --git a/bundles/org.openhab.binding.network/src/main/java/org/openhab/binding/network/internal/action/NetworkActions.java b/bundles/org.openhab.binding.network/src/main/java/org/openhab/binding/network/internal/action/NetworkActions.java index 81692e9cf6788..27d6738450bc6 100644 --- a/bundles/org.openhab.binding.network/src/main/java/org/openhab/binding/network/internal/action/NetworkActions.java +++ b/bundles/org.openhab.binding.network/src/main/java/org/openhab/binding/network/internal/action/NetworkActions.java @@ -19,6 +19,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,6 +29,7 @@ * * @author Wouter Born - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = NetworkActions.class) @ThingActionsScope(name = "network") @NonNullByDefault public class NetworkActions implements ThingActions { diff --git a/bundles/org.openhab.binding.networkupstools/src/main/java/org/openhab/binding/networkupstools/internal/NUTChannelTypeProvider.java b/bundles/org.openhab.binding.networkupstools/src/main/java/org/openhab/binding/networkupstools/internal/NUTChannelTypeProvider.java index 8ad794b954425..d2ceb93c7aa3f 100644 --- a/bundles/org.openhab.binding.networkupstools/src/main/java/org/openhab/binding/networkupstools/internal/NUTChannelTypeProvider.java +++ b/bundles/org.openhab.binding.networkupstools/src/main/java/org/openhab/binding/networkupstools/internal/NUTChannelTypeProvider.java @@ -25,12 +25,15 @@ import org.openhab.core.thing.type.ChannelType; import org.openhab.core.thing.type.ChannelTypeProvider; import org.openhab.core.thing.type.ChannelTypeUID; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * Provider class to provide channel types for user configured channels. * * @author Hilbrand Bouwkamp - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = { NUTChannelTypeProvider.class, ChannelTypeProvider.class }) @NonNullByDefault public class NUTChannelTypeProvider implements ChannelTypeProvider, ThingHandlerService { diff --git a/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/discovery/NikobusDiscoveryService.java b/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/discovery/NikobusDiscoveryService.java index 2204816e5b335..bdeb9f8c9e90e 100644 --- a/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/discovery/NikobusDiscoveryService.java +++ b/bundles/org.openhab.binding.nikobus/src/main/java/org/openhab/binding/nikobus/internal/discovery/NikobusDiscoveryService.java @@ -19,14 +19,13 @@ import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.nikobus.internal.handler.NikobusPcLinkHandler; import org.openhab.binding.nikobus.internal.utils.Utils; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -37,14 +36,13 @@ * * @author Boris Krivonog - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = NikobusDiscoveryService.class) @NonNullByDefault -public class NikobusDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { - +public class NikobusDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(NikobusDiscoveryService.class); - private @Nullable NikobusPcLinkHandler bridgeHandler; public NikobusDiscoveryService() throws IllegalArgumentException { - super(Set.of(THING_TYPE_PUSH_BUTTON), 0); + super(NikobusPcLinkHandler.class, Set.of(THING_TYPE_PUSH_BUTTON), 0); } @Override @@ -53,18 +51,12 @@ protected void startScan() { @Override protected void stopBackgroundDiscovery() { - NikobusPcLinkHandler handler = bridgeHandler; - if (handler != null) { - handler.resetUnhandledCommandProcessor(); - } + thingHandler.resetUnhandledCommandProcessor(); } @Override protected void startBackgroundDiscovery() { - NikobusPcLinkHandler handler = bridgeHandler; - if (handler != null) { - handler.setUnhandledCommandProcessor(this::process); - } + thingHandler.setUnhandledCommandProcessor(this::process); } private void process(String command) { @@ -75,40 +67,15 @@ private void process(String command) { String address = command.substring(2); logger.debug("Received address = '{}'", address); - NikobusPcLinkHandler handler = bridgeHandler; - if (handler != null) { - ThingUID thingUID = new ThingUID(THING_TYPE_PUSH_BUTTON, handler.getThing().getUID(), address); + ThingUID thingUID = new ThingUID(THING_TYPE_PUSH_BUTTON, thingHandler.getThing().getUID(), address); - Map properties = new HashMap<>(); - properties.put(CONFIG_ADDRESS, address); + Map properties = new HashMap<>(); + properties.put(CONFIG_ADDRESS, address); - String humanReadableNikobusAddress = Utils.convertToHumanReadableNikobusAddress(address).toUpperCase(); - logger.debug("Detected Nikobus Push Button: '{}'", humanReadableNikobusAddress); - thingDiscovered(DiscoveryResultBuilder.create(thingUID).withThingType(THING_TYPE_PUSH_BUTTON) - .withLabel("Nikobus Push Button " + humanReadableNikobusAddress).withProperties(properties) - .withRepresentationProperty(CONFIG_ADDRESS).withBridge(handler.getThing().getUID()).build()); - } - } - - @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof NikobusPcLinkHandler pcLinkHandler) { - bridgeHandler = pcLinkHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - - @Override - public void activate() { - super.activate(null); - } - - @Override - public void deactivate() { - super.deactivate(); + String humanReadableNikobusAddress = Utils.convertToHumanReadableNikobusAddress(address).toUpperCase(); + logger.debug("Detected Nikobus Push Button: '{}'", humanReadableNikobusAddress); + thingDiscovered(DiscoveryResultBuilder.create(thingUID).withThingType(THING_TYPE_PUSH_BUTTON) + .withLabel("Nikobus Push Button " + humanReadableNikobusAddress).withProperties(properties) + .withRepresentationProperty(CONFIG_ADDRESS).withBridge(thingHandler.getThing().getUID()).build()); } } diff --git a/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/discovery/NikoHomeControlDiscoveryService.java b/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/discovery/NikoHomeControlDiscoveryService.java index 72affcedf1d19..4bb99486a2206 100644 --- a/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/discovery/NikoHomeControlDiscoveryService.java +++ b/bundles/org.openhab.binding.nikohomecontrol/src/main/java/org/openhab/binding/nikohomecontrol/internal/discovery/NikoHomeControlDiscoveryService.java @@ -26,11 +26,11 @@ import org.openhab.binding.nikohomecontrol.internal.protocol.NhcEnergyMeter; import org.openhab.binding.nikohomecontrol.internal.protocol.NhcThermostat; import org.openhab.binding.nikohomecontrol.internal.protocol.NikoHomeControlCommunication; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,9 +40,10 @@ * * @author Mark Herwege - Initial Contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = NikoHomeControlDiscoveryService.class) @NonNullByDefault -public class NikoHomeControlDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { - +public class NikoHomeControlDiscoveryService + extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(NikoHomeControlDiscoveryService.class); private volatile @Nullable ScheduledFuture nhcDiscoveryJob; @@ -53,40 +54,29 @@ public class NikoHomeControlDiscoveryService extends AbstractDiscoveryService im private static final int REFRESH_INTERVAL_S = 60; private @Nullable ThingUID bridgeUID; - private @Nullable NikoHomeControlBridgeHandler handler; public NikoHomeControlDiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, TIMEOUT_S, true); + super(NikoHomeControlBridgeHandler.class, SUPPORTED_THING_TYPES_UIDS, TIMEOUT_S, true); logger.debug("device discovery service started"); } @Override - public void activate() { - startBackgroundDiscovery(); - } - - @Override - public void deactivate() { + public void dispose() { + super.dispose(); removeOlderResults(Instant.now().toEpochMilli()); - super.deactivate(); } /** * Discovers devices connected to a Niko Home Control controller */ public void discoverDevices() { - NikoHomeControlBridgeHandler bridgeHandler = handler; - if (bridgeHandler == null) { - return; - } - - NikoHomeControlCommunication nhcComm = bridgeHandler.getCommunication(); + NikoHomeControlCommunication nhcComm = thingHandler.getCommunication(); if ((nhcComm == null) || !nhcComm.communicationActive()) { logger.warn("not connected"); return; } - logger.debug("getting devices on {}", bridgeHandler.getThing().getUID().getId()); + logger.debug("getting devices on {}", thingHandler.getThing().getUID().getId()); Map actions = nhcComm.getActions(); @@ -96,20 +86,19 @@ public void discoverDevices() { switch (nhcAction.getType()) { case TRIGGER: - addActionDevice(new ThingUID(THING_TYPE_PUSHBUTTON, bridgeHandler.getThing().getUID(), actionId), + addActionDevice(new ThingUID(THING_TYPE_PUSHBUTTON, thingHandler.getThing().getUID(), actionId), actionId, thingName, thingLocation); break; case RELAY: - addActionDevice(new ThingUID(THING_TYPE_ON_OFF_LIGHT, bridgeHandler.getThing().getUID(), actionId), + addActionDevice(new ThingUID(THING_TYPE_ON_OFF_LIGHT, thingHandler.getThing().getUID(), actionId), actionId, thingName, thingLocation); break; case DIMMER: - addActionDevice( - new ThingUID(THING_TYPE_DIMMABLE_LIGHT, bridgeHandler.getThing().getUID(), actionId), + addActionDevice(new ThingUID(THING_TYPE_DIMMABLE_LIGHT, thingHandler.getThing().getUID(), actionId), actionId, thingName, thingLocation); break; case ROLLERSHUTTER: - addActionDevice(new ThingUID(THING_TYPE_BLIND, bridgeHandler.getThing().getUID(), actionId), + addActionDevice(new ThingUID(THING_TYPE_BLIND, thingHandler.getThing().getUID(), actionId), actionId, thingName, thingLocation); break; default: @@ -122,7 +111,7 @@ public void discoverDevices() { thermostats.forEach((thermostatId, nhcThermostat) -> { String thingName = nhcThermostat.getName(); String thingLocation = nhcThermostat.getLocation(); - addThermostatDevice(new ThingUID(THING_TYPE_THERMOSTAT, bridgeHandler.getThing().getUID(), thermostatId), + addThermostatDevice(new ThingUID(THING_TYPE_THERMOSTAT, thingHandler.getThing().getUID(), thermostatId), thermostatId, thingName, thingLocation); }); @@ -131,7 +120,7 @@ public void discoverDevices() { energyMeters.forEach((energyMeterId, nhcEnergyMeter) -> { String thingName = nhcEnergyMeter.getName(); String thingLocation = nhcEnergyMeter.getLocation(); - addEnergyMeterDevice(new ThingUID(THING_TYPE_ENERGYMETER, bridgeHandler.getThing().getUID(), energyMeterId), + addEnergyMeterDevice(new ThingUID(THING_TYPE_ENERGYMETER, thingHandler.getThing().getUID(), energyMeterId), energyMeterId, thingName, thingLocation); }); } @@ -200,15 +189,8 @@ protected void stopBackgroundDiscovery() { } @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof NikoHomeControlBridgeHandler homeControlBridgeHandler) { - this.handler = homeControlBridgeHandler; - bridgeUID = handler.getThing().getUID(); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return handler; + public void initialize() { + bridgeUID = thingHandler.getThing().getUID(); + super.initialize(); } } diff --git a/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/NoboHubBridgeHandler.java b/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/NoboHubBridgeHandler.java index f4b6d29a9d63d..65649ac6e3cff 100644 --- a/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/NoboHubBridgeHandler.java +++ b/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/NoboHubBridgeHandler.java @@ -21,11 +21,13 @@ import java.time.Duration; import java.util.Collection; import java.util.Map; +import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.nobohub.internal.connection.HubCommunicationThread; import org.openhab.binding.nobohub.internal.connection.HubConnection; +import org.openhab.binding.nobohub.internal.discovery.NoboHubDiscoveryService; import org.openhab.binding.nobohub.internal.discovery.NoboThingDiscoveryService; import org.openhab.binding.nobohub.internal.model.Component; import org.openhab.binding.nobohub.internal.model.ComponentRegister; @@ -49,6 +51,7 @@ import org.openhab.core.thing.ThingStatusDetail; import org.openhab.core.thing.binding.BaseBridgeHandler; import org.openhab.core.thing.binding.ThingHandler; +import org.openhab.core.thing.binding.ThingHandlerService; import org.openhab.core.types.Command; import org.openhab.core.types.RefreshType; import org.slf4j.Logger; @@ -414,4 +417,9 @@ public Collection getWeekProfiles() { public void setStatusInfo(ThingStatus status, ThingStatusDetail statusDetail, @Nullable String description) { updateStatus(status, statusDetail, description); } + + @Override + public Collection> getServices() { + return Set.of(NoboHubDiscoveryService.class); + } } diff --git a/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/discovery/NoboHubDiscoveryService.java b/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/discovery/NoboHubDiscoveryService.java index fdea1c7bd772c..71e5c3b1699c0 100644 --- a/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/discovery/NoboHubDiscoveryService.java +++ b/bundles/org.openhab.binding.nobohub/src/main/java/org/openhab/binding/nobohub/internal/discovery/NoboHubDiscoveryService.java @@ -32,17 +32,14 @@ import java.util.Map; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.nobohub.internal.NoboHubBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -53,14 +50,12 @@ * @author Espen Fossen - Initial contribution */ @NonNullByDefault -@Component(service = DiscoveryService.class, immediate = true, configurationPid = "discovery.nobohub") -public class NoboHubDiscoveryService extends AbstractDiscoveryService implements DiscoveryService, ThingHandlerService { +@Component(scope = ServiceScope.PROTOTYPE, service = NoboHubDiscoveryService.class, configurationPid = "discovery.nobohub") +public class NoboHubDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(NoboHubDiscoveryService.class); - private @NonNullByDefault({}) NoboHubBridgeHandler hubBridgeHandler; - public NoboHubDiscoveryService() { - super(DISCOVERABLE_DEVICE_TYPES_UIDS, 10, true); + super(NoboHubBridgeHandler.class, DISCOVERABLE_DEVICE_TYPES_UIDS, 10, true); } @Override @@ -75,22 +70,11 @@ protected synchronized void stopScan() { } @Override - public void deactivate() { + public void dispose() { + super.dispose(); removeOlderResults(new Date().getTime()); } - @Override - public void setThingHandler(ThingHandler thingHandler) { - if (thingHandler instanceof NoboHubBridgeHandler bridgeHandler) { - this.hubBridgeHandler = bridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return hubBridgeHandler; - } - private final Runnable scanner = new Runnable() { @Override public void run() { diff --git a/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/discovery/NukiDeviceDiscoveryService.java b/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/discovery/NukiDeviceDiscoveryService.java index 780a39b5b870f..710e0aa27ed8e 100644 --- a/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/discovery/NukiDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.nuki/src/main/java/org/openhab/binding/nuki/internal/discovery/NukiDeviceDiscoveryService.java @@ -21,12 +21,12 @@ import org.openhab.binding.nuki.internal.dataexchange.BridgeListResponse; import org.openhab.binding.nuki.internal.dto.BridgeApiListDeviceDto; import org.openhab.binding.nuki.internal.handler.NukiBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -35,20 +35,19 @@ * * @author Jan Vybíral - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = NukiDeviceDiscoveryService.class) @NonNullByDefault -public class NukiDeviceDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class NukiDeviceDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(NukiDeviceDiscoveryService.class); - @Nullable - private NukiBridgeHandler bridge; public NukiDeviceDiscoveryService() { - super(Set.of(NukiBindingConstants.THING_TYPE_SMARTLOCK), 5, false); + super(NukiBridgeHandler.class, Set.of(NukiBindingConstants.THING_TYPE_SMARTLOCK), 5, false); } @Override protected void startScan() { - NukiBridgeHandler bridgeHandler = bridge; + NukiBridgeHandler bridgeHandler = thingHandler; if (bridgeHandler == null) { logger.warn("Cannot start Nuki discovery - no bridge available"); return; @@ -100,20 +99,4 @@ protected synchronized void stopScan() { super.stopScan(); removeOlderResults(getTimestampOfLastScan()); } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof NukiBridgeHandler bridgeHandler) { - bridge = bridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridge; - } - - @Override - public void deactivate() { - } } diff --git a/bundles/org.openhab.binding.nuvo/src/main/java/org/openhab/binding/nuvo/internal/NuvoThingActions.java b/bundles/org.openhab.binding.nuvo/src/main/java/org/openhab/binding/nuvo/internal/NuvoThingActions.java index 89f1b50059cb4..149f8df38d266 100644 --- a/bundles/org.openhab.binding.nuvo/src/main/java/org/openhab/binding/nuvo/internal/NuvoThingActions.java +++ b/bundles/org.openhab.binding.nuvo/src/main/java/org/openhab/binding/nuvo/internal/NuvoThingActions.java @@ -20,6 +20,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,6 +30,7 @@ * * @author Michael Lobstein - initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = NuvoThingActions.class) @ThingActionsScope(name = "nuvo") @NonNullByDefault public class NuvoThingActions implements ThingActions { diff --git a/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/services/OJDiscoveryService.java b/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/services/OJDiscoveryService.java index ecb6b87059df5..1a60564e4be38 100644 --- a/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/services/OJDiscoveryService.java +++ b/bundles/org.openhab.binding.ojelectronics/src/main/java/org/openhab/binding/ojelectronics/internal/services/OJDiscoveryService.java @@ -22,14 +22,12 @@ import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.ojelectronics.internal.OJCloudHandler; import org.openhab.binding.ojelectronics.internal.models.groups.GroupContentModel; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * DiscoveryService for OJ Components @@ -37,11 +35,9 @@ * @author Christian Kittel - Initial Contribution */ @NonNullByDefault -@Component(service = DiscoveryService.class, immediate = true, configurationPid = "discovery.ojelectronics") -public final class OJDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { - +@Component(scope = ServiceScope.PROTOTYPE, service = OJDiscoveryService.class, configurationPid = "discovery.ojelectronics") +public final class OJDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final Set SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_OJCLOUD); - private @Nullable OJCloudHandler bridgeHandler; private @Nullable Collection groupContents; /** @@ -49,7 +45,7 @@ public final class OJDiscoveryService extends AbstractDiscoveryService implement * */ public OJDiscoveryService() throws IllegalArgumentException { - super(SUPPORTED_THING_TYPES_UIDS, 10); + super(OJCloudHandler.class, SUPPORTED_THING_TYPES_UIDS, 10); } /** @@ -63,30 +59,17 @@ public void setScanResultForDiscovery(List groupContents) { @Override protected void startScan() { - final OJCloudHandler bridgeHandler = this.bridgeHandler; final Collection groupContents = this.groupContents; - if (groupContents != null && bridgeHandler != null) { + if (groupContents != null) { groupContents.stream().flatMap(content -> content.thermostats.stream()) - .forEach(thermostat -> thingDiscovered(bridgeHandler.getThing().getUID(), thermostat.serialNumber)); - } - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof OJCloudHandler bridgeHandler) { - this.bridgeHandler = bridgeHandler; - bridgeHandler.setDiscoveryService(this); + .forEach(thermostat -> thingDiscovered(thingHandler.getThing().getUID(), thermostat.serialNumber)); } } @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - - @Override - public void deactivate() { - super.deactivate(); + public void initialize() { + thingHandler.setDiscoveryService(this); + super.initialize(); } private void thingDiscovered(ThingUID bridgeUID, String serialNumber) { diff --git a/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/action/OmnilinkActions.java b/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/action/OmnilinkActions.java index 53a715c7531b1..f211454780b2c 100644 --- a/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/action/OmnilinkActions.java +++ b/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/action/OmnilinkActions.java @@ -25,6 +25,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,6 +35,7 @@ * * @author Ethan Dye - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = OmnilinkActions.class) @ThingActionsScope(name = "omnilink") @NonNullByDefault public class OmnilinkActions implements ThingActions { diff --git a/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/discovery/OmnilinkDiscoveryService.java b/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/discovery/OmnilinkDiscoveryService.java index 9b250d92c959d..9a4e44a286b7f 100644 --- a/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/discovery/OmnilinkDiscoveryService.java +++ b/bundles/org.openhab.binding.omnilink/src/main/java/org/openhab/binding/omnilink/internal/discovery/OmnilinkDiscoveryService.java @@ -28,13 +28,12 @@ import org.openhab.binding.omnilink.internal.SystemType; import org.openhab.binding.omnilink.internal.exceptions.BridgeOfflineException; import org.openhab.binding.omnilink.internal.handler.OmnilinkBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -57,12 +56,11 @@ * @author Craig Hamilton - Initial contribution * @author Ethan Dye - openHAB3 rewrite */ +@Component(scope = ServiceScope.PROTOTYPE, service = OmnilinkDiscoveryService.class) @NonNullByDefault -public class OmnilinkDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { +public class OmnilinkDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(OmnilinkDiscoveryService.class); private static final int DISCOVER_TIMEOUT_SECONDS = 30; - private @Nullable OmnilinkBridgeHandler bridgeHandler; private Optional systemType = Optional.empty(); private @Nullable List areas; @@ -70,50 +68,27 @@ public class OmnilinkDiscoveryService extends AbstractDiscoveryService * Creates an OmnilinkDiscoveryService. */ public OmnilinkDiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, DISCOVER_TIMEOUT_SECONDS, false); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof OmnilinkBridgeHandler omnilinkBridgeHandler) { - bridgeHandler = omnilinkBridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - - @Override - public void activate() { - } - - @Override - public void deactivate() { + super(OmnilinkBridgeHandler.class, SUPPORTED_THING_TYPES_UIDS, DISCOVER_TIMEOUT_SECONDS, false); } @Override protected synchronized void startScan() { - final OmnilinkBridgeHandler handler = bridgeHandler; - if (handler != null) { - logger.debug("Starting scan"); - try { - SystemInformation systemInformation = handler.reqSystemInformation(); - this.systemType = SystemType.getType(systemInformation.getModel()); - this.areas = discoverAreas(); - discoverUnits(); - discoverZones(); - discoverButtons(); - discoverThermostats(); - discoverAudioZones(); - discoverAudioSources(); - discoverTempSensors(); - discoverHumiditySensors(); - discoverLocks(); - } catch (OmniInvalidResponseException | OmniUnknownMessageTypeException | BridgeOfflineException e) { - logger.debug("Received error during discovery: {}", e.getMessage()); - } + logger.debug("Starting scan"); + try { + SystemInformation systemInformation = thingHandler.reqSystemInformation(); + this.systemType = SystemType.getType(systemInformation.getModel()); + this.areas = discoverAreas(); + discoverUnits(); + discoverZones(); + discoverButtons(); + discoverThermostats(); + discoverAudioZones(); + discoverAudioSources(); + discoverTempSensors(); + discoverHumiditySensors(); + discoverLocks(); + } catch (OmniInvalidResponseException | OmniUnknownMessageTypeException | BridgeOfflineException e) { + logger.debug("Received error during discovery: {}", e.getMessage()); } } @@ -137,35 +112,32 @@ private static int bitFilterForArea(AreaProperties areaProperties) { * Discovers OmniLink buttons */ private void discoverButtons() { - final OmnilinkBridgeHandler handler = bridgeHandler; - if (handler != null) { - final ThingUID bridgeUID = handler.getThing().getUID(); - final List areas = this.areas; + final ThingUID bridgeUID = thingHandler.getThing().getUID(); + final List areas = this.areas; - if (areas != null) { - for (AreaProperties areaProperties : areas) { - int areaFilter = bitFilterForArea(areaProperties); + if (areas != null) { + for (AreaProperties areaProperties : areas) { + int areaFilter = bitFilterForArea(areaProperties); - ObjectPropertyRequest objectPropertyRequest = ObjectPropertyRequest - .builder(handler, ObjectPropertyRequests.BUTTONS, 0, 1).selectNamed().areaFilter(areaFilter) - .build(); + ObjectPropertyRequest objectPropertyRequest = ObjectPropertyRequest + .builder(thingHandler, ObjectPropertyRequests.BUTTONS, 0, 1).selectNamed() + .areaFilter(areaFilter).build(); - for (ButtonProperties buttonProperties : objectPropertyRequest) { - String thingName = buttonProperties.getName(); - String thingID = Integer.toString(buttonProperties.getNumber()); + for (ButtonProperties buttonProperties : objectPropertyRequest) { + String thingName = buttonProperties.getName(); + String thingID = Integer.toString(buttonProperties.getNumber()); - Map properties = new HashMap<>(); - properties.put(THING_PROPERTIES_NAME, thingName); - properties.put(THING_PROPERTIES_AREA, areaProperties.getNumber()); + Map properties = new HashMap<>(); + properties.put(THING_PROPERTIES_NAME, thingName); + properties.put(THING_PROPERTIES_AREA, areaProperties.getNumber()); - ThingUID thingUID = new ThingUID(THING_TYPE_BUTTON, bridgeUID, thingID); + ThingUID thingUID = new ThingUID(THING_TYPE_BUTTON, bridgeUID, thingID); - DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID) - .withProperties(properties).withProperty(THING_PROPERTIES_NUMBER, thingID) - .withRepresentationProperty(THING_PROPERTIES_NUMBER).withBridge(bridgeUID) - .withLabel(thingName).build(); - thingDiscovered(discoveryResult); - } + DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withProperties(properties) + .withProperty(THING_PROPERTIES_NUMBER, thingID) + .withRepresentationProperty(THING_PROPERTIES_NUMBER).withBridge(bridgeUID) + .withLabel(thingName).build(); + thingDiscovered(discoveryResult); } } } @@ -175,27 +147,23 @@ private void discoverButtons() { * Discovers OmniLink locks */ private void discoverLocks() { - final OmnilinkBridgeHandler handler = bridgeHandler; - if (handler != null) { - final ThingUID bridgeUID = handler.getThing().getUID(); + final ThingUID bridgeUID = thingHandler.getThing().getUID(); - ObjectPropertyRequest objectPropertyRequest = ObjectPropertyRequest - .builder(handler, ObjectPropertyRequests.LOCK, 0, 1).selectNamed().build(); + ObjectPropertyRequest objectPropertyRequest = ObjectPropertyRequest + .builder(thingHandler, ObjectPropertyRequests.LOCK, 0, 1).selectNamed().build(); - for (AccessControlReaderProperties lockProperties : objectPropertyRequest) { - String thingName = lockProperties.getName(); - String thingID = Integer.toString(lockProperties.getNumber()); + for (AccessControlReaderProperties lockProperties : objectPropertyRequest) { + String thingName = lockProperties.getName(); + String thingID = Integer.toString(lockProperties.getNumber()); - Map properties = Map.of(THING_PROPERTIES_NAME, thingName); + Map properties = Map.of(THING_PROPERTIES_NAME, thingName); - ThingUID thingUID = new ThingUID(THING_TYPE_LOCK, bridgeUID, thingID); + ThingUID thingUID = new ThingUID(THING_TYPE_LOCK, bridgeUID, thingID); - DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withProperties(properties) - .withProperty(THING_PROPERTIES_NUMBER, thingID) - .withRepresentationProperty(THING_PROPERTIES_NUMBER).withBridge(bridgeUID).withLabel(thingName) - .build(); - thingDiscovered(discoveryResult); - } + DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withProperties(properties) + .withProperty(THING_PROPERTIES_NUMBER, thingID).withRepresentationProperty(THING_PROPERTIES_NUMBER) + .withBridge(bridgeUID).withLabel(thingName).build(); + thingDiscovered(discoveryResult); } } @@ -203,27 +171,23 @@ private void discoverLocks() { * Discovers OmniLink audio zones */ private void discoverAudioZones() { - final OmnilinkBridgeHandler handler = bridgeHandler; - if (handler != null) { - final ThingUID bridgeUID = handler.getThing().getUID(); + final ThingUID bridgeUID = thingHandler.getThing().getUID(); - ObjectPropertyRequest objectPropertyRequest = ObjectPropertyRequest - .builder(handler, ObjectPropertyRequests.AUDIO_ZONE, 0, 1).selectNamed().build(); + ObjectPropertyRequest objectPropertyRequest = ObjectPropertyRequest + .builder(thingHandler, ObjectPropertyRequests.AUDIO_ZONE, 0, 1).selectNamed().build(); - for (AudioZoneProperties audioZoneProperties : objectPropertyRequest) { - String thingName = audioZoneProperties.getName(); - String thingID = Integer.toString(audioZoneProperties.getNumber()); + for (AudioZoneProperties audioZoneProperties : objectPropertyRequest) { + String thingName = audioZoneProperties.getName(); + String thingID = Integer.toString(audioZoneProperties.getNumber()); - Map properties = Map.of(THING_PROPERTIES_NAME, thingName); + Map properties = Map.of(THING_PROPERTIES_NAME, thingName); - ThingUID thingUID = new ThingUID(THING_TYPE_AUDIO_ZONE, bridgeUID, thingID); + ThingUID thingUID = new ThingUID(THING_TYPE_AUDIO_ZONE, bridgeUID, thingID); - DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withProperties(properties) - .withProperty(THING_PROPERTIES_NUMBER, thingID) - .withRepresentationProperty(THING_PROPERTIES_NUMBER).withBridge(bridgeUID).withLabel(thingName) - .build(); - thingDiscovered(discoveryResult); - } + DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withProperties(properties) + .withProperty(THING_PROPERTIES_NUMBER, thingID).withRepresentationProperty(THING_PROPERTIES_NUMBER) + .withBridge(bridgeUID).withLabel(thingName).build(); + thingDiscovered(discoveryResult); } } @@ -231,27 +195,23 @@ private void discoverAudioZones() { * Discovers OmniLink audio sources */ private void discoverAudioSources() { - final OmnilinkBridgeHandler handler = bridgeHandler; - if (handler != null) { - final ThingUID bridgeUID = handler.getThing().getUID(); + final ThingUID bridgeUID = thingHandler.getThing().getUID(); - ObjectPropertyRequest objectPropertyRequest = ObjectPropertyRequest - .builder(handler, ObjectPropertyRequests.AUDIO_SOURCE, 0, 1).selectNamed().build(); + ObjectPropertyRequest objectPropertyRequest = ObjectPropertyRequest + .builder(thingHandler, ObjectPropertyRequests.AUDIO_SOURCE, 0, 1).selectNamed().build(); - for (AudioSourceProperties audioSourceProperties : objectPropertyRequest) { - String thingName = audioSourceProperties.getName(); - String thingID = Integer.toString(audioSourceProperties.getNumber()); + for (AudioSourceProperties audioSourceProperties : objectPropertyRequest) { + String thingName = audioSourceProperties.getName(); + String thingID = Integer.toString(audioSourceProperties.getNumber()); - Map properties = Map.of(THING_PROPERTIES_NAME, thingName); + Map properties = Map.of(THING_PROPERTIES_NAME, thingName); - ThingUID thingUID = new ThingUID(THING_TYPE_AUDIO_SOURCE, bridgeUID, thingID); + ThingUID thingUID = new ThingUID(THING_TYPE_AUDIO_SOURCE, bridgeUID, thingID); - DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withProperties(properties) - .withProperty(THING_PROPERTIES_NUMBER, thingID) - .withRepresentationProperty(THING_PROPERTIES_NUMBER).withBridge(bridgeUID).withLabel(thingName) - .build(); - thingDiscovered(discoveryResult); - } + DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withProperties(properties) + .withProperty(THING_PROPERTIES_NUMBER, thingID).withRepresentationProperty(THING_PROPERTIES_NUMBER) + .withBridge(bridgeUID).withLabel(thingName).build(); + thingDiscovered(discoveryResult); } } @@ -259,37 +219,34 @@ private void discoverAudioSources() { * Discovers OmniLink temperature sensors */ private void discoverTempSensors() { - final OmnilinkBridgeHandler handler = bridgeHandler; - if (handler != null) { - final ThingUID bridgeUID = handler.getThing().getUID(); - final List areas = this.areas; - - if (areas != null) { - for (AreaProperties areaProperties : areas) { - int areaFilter = bitFilterForArea(areaProperties); - - ObjectPropertyRequest objectPropertyRequest = ObjectPropertyRequest - .builder(handler, ObjectPropertyRequests.AUX_SENSORS, 0, 1).selectNamed() - .areaFilter(areaFilter).build(); - - for (AuxSensorProperties auxSensorProperties : objectPropertyRequest) { - if (auxSensorProperties.getSensorType() != SENSOR_TYPE_PROGRAMMABLE_ENERGY_SAVER_MODULE - && auxSensorProperties.getSensorType() != SENSOR_TYPE_HUMIDITY) { - String thingName = auxSensorProperties.getName(); - String thingID = Integer.toString(auxSensorProperties.getNumber()); - - Map properties = new HashMap<>(); - properties.put(THING_PROPERTIES_NAME, thingName); - properties.put(THING_PROPERTIES_AREA, areaProperties.getNumber()); - - ThingUID thingUID = new ThingUID(THING_TYPE_TEMP_SENSOR, bridgeUID, thingID); - - DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID) - .withProperties(properties).withProperty(THING_PROPERTIES_NUMBER, thingID) - .withRepresentationProperty(THING_PROPERTIES_NUMBER).withBridge(bridgeUID) - .withLabel(thingName).build(); - thingDiscovered(discoveryResult); - } + final ThingUID bridgeUID = thingHandler.getThing().getUID(); + final List areas = this.areas; + + if (areas != null) { + for (AreaProperties areaProperties : areas) { + int areaFilter = bitFilterForArea(areaProperties); + + ObjectPropertyRequest objectPropertyRequest = ObjectPropertyRequest + .builder(thingHandler, ObjectPropertyRequests.AUX_SENSORS, 0, 1).selectNamed() + .areaFilter(areaFilter).build(); + + for (AuxSensorProperties auxSensorProperties : objectPropertyRequest) { + if (auxSensorProperties.getSensorType() != SENSOR_TYPE_PROGRAMMABLE_ENERGY_SAVER_MODULE + && auxSensorProperties.getSensorType() != SENSOR_TYPE_HUMIDITY) { + String thingName = auxSensorProperties.getName(); + String thingID = Integer.toString(auxSensorProperties.getNumber()); + + Map properties = new HashMap<>(); + properties.put(THING_PROPERTIES_NAME, thingName); + properties.put(THING_PROPERTIES_AREA, areaProperties.getNumber()); + + ThingUID thingUID = new ThingUID(THING_TYPE_TEMP_SENSOR, bridgeUID, thingID); + + DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID) + .withProperties(properties).withProperty(THING_PROPERTIES_NUMBER, thingID) + .withRepresentationProperty(THING_PROPERTIES_NUMBER).withBridge(bridgeUID) + .withLabel(thingName).build(); + thingDiscovered(discoveryResult); } } } @@ -300,36 +257,33 @@ private void discoverTempSensors() { * Discovers OmniLink humidity sensors */ private void discoverHumiditySensors() { - final OmnilinkBridgeHandler handler = bridgeHandler; - if (handler != null) { - final ThingUID bridgeUID = handler.getThing().getUID(); - final List areas = this.areas; - - if (areas != null) { - for (AreaProperties areaProperties : areas) { - int areaFilter = bitFilterForArea(areaProperties); - - ObjectPropertyRequest objectPropertyRequest = ObjectPropertyRequest - .builder(handler, ObjectPropertyRequests.AUX_SENSORS, 0, 1).selectNamed() - .areaFilter(areaFilter).build(); - - for (AuxSensorProperties auxSensorProperties : objectPropertyRequest) { - if (auxSensorProperties.getSensorType() == SENSOR_TYPE_HUMIDITY) { - String thingName = auxSensorProperties.getName(); - String thingID = Integer.toString(auxSensorProperties.getNumber()); - - Map properties = new HashMap<>(); - properties.put(THING_PROPERTIES_NAME, thingName); - properties.put(THING_PROPERTIES_AREA, areaProperties.getNumber()); - - ThingUID thingUID = new ThingUID(THING_TYPE_HUMIDITY_SENSOR, bridgeUID, thingID); - - DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID) - .withProperties(properties).withProperty(THING_PROPERTIES_NUMBER, thingID) - .withRepresentationProperty(THING_PROPERTIES_NUMBER).withBridge(bridgeUID) - .withLabel(thingName).build(); - thingDiscovered(discoveryResult); - } + final ThingUID bridgeUID = thingHandler.getThing().getUID(); + final List areas = this.areas; + + if (areas != null) { + for (AreaProperties areaProperties : areas) { + int areaFilter = bitFilterForArea(areaProperties); + + ObjectPropertyRequest objectPropertyRequest = ObjectPropertyRequest + .builder(thingHandler, ObjectPropertyRequests.AUX_SENSORS, 0, 1).selectNamed() + .areaFilter(areaFilter).build(); + + for (AuxSensorProperties auxSensorProperties : objectPropertyRequest) { + if (auxSensorProperties.getSensorType() == SENSOR_TYPE_HUMIDITY) { + String thingName = auxSensorProperties.getName(); + String thingID = Integer.toString(auxSensorProperties.getNumber()); + + Map properties = new HashMap<>(); + properties.put(THING_PROPERTIES_NAME, thingName); + properties.put(THING_PROPERTIES_AREA, areaProperties.getNumber()); + + ThingUID thingUID = new ThingUID(THING_TYPE_HUMIDITY_SENSOR, bridgeUID, thingID); + + DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID) + .withProperties(properties).withProperty(THING_PROPERTIES_NUMBER, thingID) + .withRepresentationProperty(THING_PROPERTIES_NUMBER).withBridge(bridgeUID) + .withLabel(thingName).build(); + thingDiscovered(discoveryResult); } } } @@ -340,35 +294,32 @@ private void discoverHumiditySensors() { * Discovers OmniLink thermostats */ private void discoverThermostats() { - final OmnilinkBridgeHandler handler = bridgeHandler; - if (handler != null) { - final ThingUID bridgeUID = handler.getThing().getUID(); - final List areas = this.areas; + final ThingUID bridgeUID = thingHandler.getThing().getUID(); + final List areas = this.areas; - if (areas != null) { - for (AreaProperties areaProperties : areas) { - int areaFilter = bitFilterForArea(areaProperties); + if (areas != null) { + for (AreaProperties areaProperties : areas) { + int areaFilter = bitFilterForArea(areaProperties); - ObjectPropertyRequest objectPropertyRequest = ObjectPropertyRequest - .builder(handler, ObjectPropertyRequests.THERMOSTAT, 0, 1).selectNamed() - .areaFilter(areaFilter).build(); + ObjectPropertyRequest objectPropertyRequest = ObjectPropertyRequest + .builder(thingHandler, ObjectPropertyRequests.THERMOSTAT, 0, 1).selectNamed() + .areaFilter(areaFilter).build(); - for (ThermostatProperties thermostatProperties : objectPropertyRequest) { - String thingName = thermostatProperties.getName(); - String thingID = Integer.toString(thermostatProperties.getNumber()); + for (ThermostatProperties thermostatProperties : objectPropertyRequest) { + String thingName = thermostatProperties.getName(); + String thingID = Integer.toString(thermostatProperties.getNumber()); - ThingUID thingUID = new ThingUID(THING_TYPE_THERMOSTAT, bridgeUID, thingID); + ThingUID thingUID = new ThingUID(THING_TYPE_THERMOSTAT, bridgeUID, thingID); - Map properties = new HashMap<>(); - properties.put(THING_PROPERTIES_NAME, thingName); - properties.put(THING_PROPERTIES_AREA, areaProperties.getNumber()); + Map properties = new HashMap<>(); + properties.put(THING_PROPERTIES_NAME, thingName); + properties.put(THING_PROPERTIES_AREA, areaProperties.getNumber()); - DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID) - .withProperties(properties).withProperty(THING_PROPERTIES_NUMBER, thingID) - .withRepresentationProperty(THING_PROPERTIES_NUMBER).withBridge(bridgeUID) - .withLabel(thingName).build(); - thingDiscovered(discoveryResult); - } + DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withProperties(properties) + .withProperty(THING_PROPERTIES_NUMBER, thingID) + .withRepresentationProperty(THING_PROPERTIES_NUMBER).withBridge(bridgeUID) + .withLabel(thingName).build(); + thingDiscovered(discoveryResult); } } } @@ -378,113 +329,142 @@ private void discoverThermostats() { * Discovers OmniLink areas */ private @Nullable List discoverAreas() { - final OmnilinkBridgeHandler handler = bridgeHandler; - if (handler != null) { - final ThingUID bridgeUID = handler.getThing().getUID(); - List areas = new LinkedList<>(); - - ObjectPropertyRequest objectPropertyRequest = ObjectPropertyRequest - .builder(handler, ObjectPropertyRequests.AREA, 0, 1).build(); - - for (AreaProperties areaProperties : objectPropertyRequest) { - int thingNumber = areaProperties.getNumber(); - String thingName = areaProperties.getName(); - String thingID = Integer.toString(thingNumber); - - /* - * It seems that for simple OmniLink Controller configurations there - * is only 1 area, without a name. So if there is no name for the - * first area, we will call that Main Area. If other area's name is - * blank, we will not create a thing. - */ - if (thingNumber == 1 && "".equals(thingName)) { - thingName = "Main Area"; - } else if ("".equals(thingName)) { - break; + final ThingUID bridgeUID = thingHandler.getThing().getUID(); + List areas = new LinkedList<>(); + + ObjectPropertyRequest objectPropertyRequest = ObjectPropertyRequest + .builder(thingHandler, ObjectPropertyRequests.AREA, 0, 1).build(); + + for (AreaProperties areaProperties : objectPropertyRequest) { + int thingNumber = areaProperties.getNumber(); + String thingName = areaProperties.getName(); + String thingID = Integer.toString(thingNumber); + + /* + * It seems that for simple OmniLink Controller configurations there + * is only 1 area, without a name. So if there is no name for the + * first area, we will call that Main Area. If other area's name is + * blank, we will not create a thing. + */ + if (thingNumber == 1 && "".equals(thingName)) { + thingName = "Main Area"; + } else if ("".equals(thingName)) { + break; + } + + Map properties = Map.of(THING_PROPERTIES_NAME, thingName); + + final String name = thingName; + systemType.ifPresentOrElse(t -> { + ThingUID thingUID = null; + switch (t) { + case LUMINA: + thingUID = new ThingUID(THING_TYPE_LUMINA_AREA, bridgeUID, thingID); + break; + default: + thingUID = new ThingUID(THING_TYPE_OMNI_AREA, bridgeUID, thingID); } + DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withProperties(properties) + .withProperty(THING_PROPERTIES_NUMBER, thingID) + .withRepresentationProperty(THING_PROPERTIES_NUMBER).withBridge(bridgeUID).withLabel(name) + .build(); + thingDiscovered(discoveryResult); + }, () -> { + logger.warn("Unknown System Type"); + }); + + areas.add(areaProperties); + } + return areas; + } + + /** + * Discovers OmniLink supported units + */ + private void discoverUnits() { + final ThingUID bridgeUID = thingHandler.getThing().getUID(); + final List areas = this.areas; - Map properties = Map.of(THING_PROPERTIES_NAME, thingName); + if (areas != null) { + for (AreaProperties areaProperties : areas) { + int areaFilter = bitFilterForArea(areaProperties); - final String name = thingName; - systemType.ifPresentOrElse(t -> { + ObjectPropertyRequest objectPropertyRequest = ObjectPropertyRequest + .builder(thingHandler, ObjectPropertyRequests.UNIT, 0, 1).selectNamed().areaFilter(areaFilter) + .selectAnyLoad().build(); + + for (UnitProperties unitProperties : objectPropertyRequest) { + int thingType = unitProperties.getUnitType(); + String thingName = unitProperties.getName(); + String thingID = Integer.toString(unitProperties.getNumber()); ThingUID thingUID = null; - switch (t) { - case LUMINA: - thingUID = new ThingUID(THING_TYPE_LUMINA_AREA, bridgeUID, thingID); + + Map properties = new HashMap<>(); + properties.put(THING_PROPERTIES_NAME, thingName); + properties.put(THING_PROPERTIES_AREA, areaProperties.getNumber()); + + switch (thingType) { + case UNIT_TYPE_HLC_ROOM: + case UNIT_TYPE_VIZIARF_ROOM: + thingUID = new ThingUID(THING_TYPE_ROOM, bridgeUID, thingID); + break; + case UNIT_TYPE_FLAG: + thingUID = new ThingUID(THING_TYPE_FLAG, bridgeUID, thingID); + break; + case UNIT_TYPE_OUTPUT: + thingUID = new ThingUID(THING_TYPE_OUTPUT, bridgeUID, thingID); + break; + case UNIT_TYPE_UPB: + case UNIT_TYPE_HLC_LOAD: + thingUID = new ThingUID(THING_TYPE_UNIT_UPB, bridgeUID, thingID); + break; + case UNIT_TYPE_CENTRALITE: + case UNIT_TYPE_RADIORA: + case UNIT_TYPE_VIZIARF_LOAD: + case UNIT_TYPE_COMPOSE: + thingUID = new ThingUID(THING_TYPE_DIMMABLE, bridgeUID, thingID); break; default: - thingUID = new ThingUID(THING_TYPE_OMNI_AREA, bridgeUID, thingID); + thingUID = new ThingUID(THING_TYPE_UNIT, bridgeUID, thingID); + logger.debug("Generic unit type: {}", thingType); + break; } + DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withProperties(properties) .withProperty(THING_PROPERTIES_NUMBER, thingID) - .withRepresentationProperty(THING_PROPERTIES_NUMBER).withBridge(bridgeUID).withLabel(name) - .build(); + .withRepresentationProperty(THING_PROPERTIES_NUMBER).withBridge(bridgeUID) + .withLabel(thingName).build(); thingDiscovered(discoveryResult); - }, () -> { - logger.warn("Unknown System Type"); - }); - - areas.add(areaProperties); + } } - return areas; - } else { - return null; } } /** - * Discovers OmniLink supported units + * Generates zone items */ - private void discoverUnits() { - final OmnilinkBridgeHandler handler = bridgeHandler; - if (handler != null) { - final ThingUID bridgeUID = handler.getThing().getUID(); - final List areas = this.areas; + private void discoverZones() { + final ThingUID bridgeUID = thingHandler.getThing().getUID(); + final List areas = this.areas; - if (areas != null) { - for (AreaProperties areaProperties : areas) { - int areaFilter = bitFilterForArea(areaProperties); + if (areas != null) { + for (AreaProperties areaProperties : areas) { + int areaFilter = bitFilterForArea(areaProperties); - ObjectPropertyRequest objectPropertyRequest = ObjectPropertyRequest - .builder(handler, ObjectPropertyRequests.UNIT, 0, 1).selectNamed().areaFilter(areaFilter) - .selectAnyLoad().build(); + ObjectPropertyRequest objectPropertyRequest = ObjectPropertyRequest + .builder(thingHandler, ObjectPropertyRequests.ZONE, 0, 1).selectNamed().areaFilter(areaFilter) + .build(); - for (UnitProperties unitProperties : objectPropertyRequest) { - int thingType = unitProperties.getUnitType(); - String thingName = unitProperties.getName(); - String thingID = Integer.toString(unitProperties.getNumber()); - ThingUID thingUID = null; + for (ZoneProperties zoneProperties : objectPropertyRequest) { + if (zoneProperties.getZoneType() <= SENSOR_TYPE_PROGRAMMABLE_ENERGY_SAVER_MODULE) { + String thingName = zoneProperties.getName(); + String thingID = Integer.toString(zoneProperties.getNumber()); Map properties = new HashMap<>(); properties.put(THING_PROPERTIES_NAME, thingName); properties.put(THING_PROPERTIES_AREA, areaProperties.getNumber()); - switch (thingType) { - case UNIT_TYPE_HLC_ROOM: - case UNIT_TYPE_VIZIARF_ROOM: - thingUID = new ThingUID(THING_TYPE_ROOM, bridgeUID, thingID); - break; - case UNIT_TYPE_FLAG: - thingUID = new ThingUID(THING_TYPE_FLAG, bridgeUID, thingID); - break; - case UNIT_TYPE_OUTPUT: - thingUID = new ThingUID(THING_TYPE_OUTPUT, bridgeUID, thingID); - break; - case UNIT_TYPE_UPB: - case UNIT_TYPE_HLC_LOAD: - thingUID = new ThingUID(THING_TYPE_UNIT_UPB, bridgeUID, thingID); - break; - case UNIT_TYPE_CENTRALITE: - case UNIT_TYPE_RADIORA: - case UNIT_TYPE_VIZIARF_LOAD: - case UNIT_TYPE_COMPOSE: - thingUID = new ThingUID(THING_TYPE_DIMMABLE, bridgeUID, thingID); - break; - default: - thingUID = new ThingUID(THING_TYPE_UNIT, bridgeUID, thingID); - logger.debug("Generic unit type: {}", thingType); - break; - } + ThingUID thingUID = new ThingUID(THING_TYPE_ZONE, bridgeUID, thingID); DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID) .withProperties(properties).withProperty(THING_PROPERTIES_NUMBER, thingID) @@ -496,44 +476,4 @@ private void discoverUnits() { } } } - - /** - * Generates zone items - */ - private void discoverZones() { - final OmnilinkBridgeHandler handler = bridgeHandler; - if (handler != null) { - final ThingUID bridgeUID = handler.getThing().getUID(); - final List areas = this.areas; - - if (areas != null) { - for (AreaProperties areaProperties : areas) { - int areaFilter = bitFilterForArea(areaProperties); - - ObjectPropertyRequest objectPropertyRequest = ObjectPropertyRequest - .builder(handler, ObjectPropertyRequests.ZONE, 0, 1).selectNamed().areaFilter(areaFilter) - .build(); - - for (ZoneProperties zoneProperties : objectPropertyRequest) { - if (zoneProperties.getZoneType() <= SENSOR_TYPE_PROGRAMMABLE_ENERGY_SAVER_MODULE) { - String thingName = zoneProperties.getName(); - String thingID = Integer.toString(zoneProperties.getNumber()); - - Map properties = new HashMap<>(); - properties.put(THING_PROPERTIES_NAME, thingName); - properties.put(THING_PROPERTIES_AREA, areaProperties.getNumber()); - - ThingUID thingUID = new ThingUID(THING_TYPE_ZONE, bridgeUID, thingID); - - DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID) - .withProperties(properties).withProperty(THING_PROPERTIES_NUMBER, thingID) - .withRepresentationProperty(THING_PROPERTIES_NUMBER).withBridge(bridgeUID) - .withLabel(thingName).build(); - thingDiscovered(discoveryResult); - } - } - } - } - } - } } diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/discovery/OwDiscoveryService.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/discovery/OwDiscoveryService.java index 965a36924111b..3312659dc5bba 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/discovery/OwDiscoveryService.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/discovery/OwDiscoveryService.java @@ -22,18 +22,17 @@ import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.onewire.internal.OwException; import org.openhab.binding.onewire.internal.SensorId; import org.openhab.binding.onewire.internal.device.OwSensorType; import org.openhab.binding.onewire.internal.handler.OwserverBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,18 +41,16 @@ * * @author Jan N. Klug - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = OwDiscoveryService.class) @NonNullByDefault -public class OwDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class OwDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(OwDiscoveryService.class); - private @Nullable OwserverBridgeHandler bridgeHandler; - Map owDiscoveryItems = new HashMap<>(); Set associatedSensors = new HashSet<>(); public OwDiscoveryService() { - super(SUPPORTED_THING_TYPES, 60, false); - logger.debug("registering discovery service for {}", bridgeHandler); + super(OwserverBridgeHandler.class, SUPPORTED_THING_TYPES, 60, false); } private void scanDirectory(OwserverBridgeHandler bridgeHandler, String baseDirectory) { @@ -95,15 +92,9 @@ private void scanDirectory(OwserverBridgeHandler bridgeHandler, String baseDirec @Override public void startScan() { - OwserverBridgeHandler bridgeHandler = this.bridgeHandler; - if (bridgeHandler == null) { - logger.warn("bridgeHandler not found"); - return; - } + ThingUID bridgeUID = thingHandler.getThing().getUID(); - ThingUID bridgeUID = bridgeHandler.getThing().getUID(); - - scanDirectory(bridgeHandler, "/"); + scanDirectory(thingHandler, "/"); // remove duplicates owDiscoveryItems.entrySet().removeIf(s -> associatedSensors.contains(s.getKey())); @@ -141,19 +132,8 @@ protected synchronized void stopScan() { } @Override - public void setThingHandler(ThingHandler thingHandler) { - if (thingHandler instanceof OwserverBridgeHandler serverBridgeHandler) { - this.bridgeHandler = serverBridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - - @Override - public void deactivate() { + public void dispose() { + super.dispose(); removeOlderResults(new Date().getTime()); } } diff --git a/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/automation/modules/OnkyoThingActions.java b/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/automation/modules/OnkyoThingActions.java index 7ee81158b8f0f..689e002dca8f8 100644 --- a/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/automation/modules/OnkyoThingActions.java +++ b/bundles/org.openhab.binding.onkyo/src/main/java/org/openhab/binding/onkyo/internal/automation/modules/OnkyoThingActions.java @@ -20,6 +20,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,6 +30,7 @@ * * @author David Masshardt - initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = OnkyoThingActions.class) @ThingActionsScope(name = "onkyo") @NonNullByDefault public class OnkyoThingActions implements ThingActions { diff --git a/bundles/org.openhab.binding.openuv/src/main/java/org/openhab/binding/openuv/internal/OpenUVHandlerFactory.java b/bundles/org.openhab.binding.openuv/src/main/java/org/openhab/binding/openuv/internal/OpenUVHandlerFactory.java index 89edf0ee384b5..5d57f3d2b0ac4 100644 --- a/bundles/org.openhab.binding.openuv/src/main/java/org/openhab/binding/openuv/internal/OpenUVHandlerFactory.java +++ b/bundles/org.openhab.binding.openuv/src/main/java/org/openhab/binding/openuv/internal/OpenUVHandlerFactory.java @@ -20,10 +20,7 @@ import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.openuv.internal.handler.OpenUVBridgeHandler; import org.openhab.binding.openuv.internal.handler.OpenUVReportHandler; -import org.openhab.core.i18n.LocaleProvider; -import org.openhab.core.i18n.LocationProvider; import org.openhab.core.i18n.TimeZoneProvider; -import org.openhab.core.i18n.TranslationProvider; import org.openhab.core.thing.Bridge; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingTypeUID; @@ -48,19 +45,10 @@ @NonNullByDefault @Component(service = ThingHandlerFactory.class, configurationPid = "binding.openuv") public class OpenUVHandlerFactory extends BaseThingHandlerFactory { - - private final LocationProvider locationProvider; - private final TranslationProvider i18nProvider; - private final LocaleProvider localeProvider; private final Gson gson; @Activate - public OpenUVHandlerFactory(@Reference TimeZoneProvider timeZoneProvider, - @Reference LocationProvider locationProvider, @Reference TranslationProvider i18nProvider, - @Reference LocaleProvider localeProvider) { - this.locationProvider = locationProvider; - this.i18nProvider = i18nProvider; - this.localeProvider = localeProvider; + public OpenUVHandlerFactory(@Reference TimeZoneProvider timeZoneProvider) { this.gson = new GsonBuilder() .registerTypeAdapter(ZonedDateTime.class, (JsonDeserializer) (json, type, jsonDeserializationContext) -> ZonedDateTime @@ -78,8 +66,7 @@ public boolean supportsThingType(ThingTypeUID thingTypeUID) { protected @Nullable ThingHandler createHandler(Thing thing) { ThingTypeUID thingTypeUID = thing.getThingTypeUID(); - return APIBRIDGE_THING_TYPE.equals(thingTypeUID) - ? new OpenUVBridgeHandler((Bridge) thing, locationProvider, i18nProvider, localeProvider, gson) + return APIBRIDGE_THING_TYPE.equals(thingTypeUID) ? new OpenUVBridgeHandler((Bridge) thing, gson) : LOCATION_REPORT_THING_TYPE.equals(thingTypeUID) ? new OpenUVReportHandler(thing) : null; } } diff --git a/bundles/org.openhab.binding.openuv/src/main/java/org/openhab/binding/openuv/internal/discovery/OpenUVDiscoveryService.java b/bundles/org.openhab.binding.openuv/src/main/java/org/openhab/binding/openuv/internal/discovery/OpenUVDiscoveryService.java index 84047f6b090d5..3ec5d791c5e92 100644 --- a/bundles/org.openhab.binding.openuv/src/main/java/org/openhab/binding/openuv/internal/discovery/OpenUVDiscoveryService.java +++ b/bundles/org.openhab.binding.openuv/src/main/java/org/openhab/binding/openuv/internal/discovery/OpenUVDiscoveryService.java @@ -16,14 +16,17 @@ import static org.openhab.binding.openuv.internal.config.ReportConfiguration.LOCATION; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.openuv.internal.handler.OpenUVBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; +import org.openhab.core.i18n.LocaleProvider; +import org.openhab.core.i18n.LocationProvider; +import org.openhab.core.i18n.TranslationProvider; import org.openhab.core.library.types.PointType; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -32,55 +35,45 @@ * * @author Gaël L'hopital - Initial Contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = OpenUVDiscoveryService.class) @NonNullByDefault -public class OpenUVDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class OpenUVDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int DISCOVER_TIMEOUT_SECONDS = 2; + private @NonNullByDefault({}) LocationProvider locationProvider; private final Logger logger = LoggerFactory.getLogger(OpenUVDiscoveryService.class); - private @Nullable OpenUVBridgeHandler bridgeHandler; - public OpenUVDiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, DISCOVER_TIMEOUT_SECONDS); + super(OpenUVBridgeHandler.class, SUPPORTED_THING_TYPES_UIDS, DISCOVER_TIMEOUT_SECONDS); } - @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof OpenUVBridgeHandler bridgeHandler) { - this.bridgeHandler = bridgeHandler; - this.i18nProvider = bridgeHandler.getI18nProvider(); - this.localeProvider = bridgeHandler.getLocaleProvider(); - } + @Reference(unbind = "-") + public void bindTranslationProvider(TranslationProvider translationProvider) { + this.i18nProvider = translationProvider; } - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; + @Reference(unbind = "-") + public void bindLocaleProvider(LocaleProvider localeProvider) { + this.localeProvider = localeProvider; } - @Override - public void deactivate() { - super.deactivate(); + @Reference(unbind = "-") + public void bindLocationProvider(LocationProvider locationProvider) { + this.locationProvider = locationProvider; } @Override protected void startScan() { logger.debug("Starting OpenUV discovery scan"); - OpenUVBridgeHandler bridge = bridgeHandler; - if (bridge != null) { - PointType location = bridge.getLocation(); - if (location != null) { - ThingUID bridgeUID = bridge.getThing().getUID(); - thingDiscovered( - DiscoveryResultBuilder.create(new ThingUID(LOCATION_REPORT_THING_TYPE, bridgeUID, LOCAL)) - .withLabel("@text/discovery.openuv.uvreport.local.label") - .withProperty(LOCATION, location.toString()).withRepresentationProperty(LOCATION) - .withBridge(bridgeUID).build()); - } else { - logger.debug("LocationProvider.getLocation() is not set -> Will not provide any discovery results"); - } + PointType location = locationProvider.getLocation(); + if (location != null) { + ThingUID bridgeUID = thingHandler.getThing().getUID(); + thingDiscovered(DiscoveryResultBuilder.create(new ThingUID(LOCATION_REPORT_THING_TYPE, bridgeUID, LOCAL)) + .withLabel("@text/discovery.openuv.uvreport.local.label") + .withProperty(LOCATION, location.toString()).withRepresentationProperty(LOCATION) + .withBridge(bridgeUID).build()); } else { - logger.debug("OpenUV Bridge Handler is not set -> Will not provide any discovery results"); + logger.debug("LocationProvider.getLocation() is not set -> Will not provide any discovery results"); } } } diff --git a/bundles/org.openhab.binding.openuv/src/main/java/org/openhab/binding/openuv/internal/handler/OpenUVBridgeHandler.java b/bundles/org.openhab.binding.openuv/src/main/java/org/openhab/binding/openuv/internal/handler/OpenUVBridgeHandler.java index 8a00513cdb5f1..e4ba66f79794e 100644 --- a/bundles/org.openhab.binding.openuv/src/main/java/org/openhab/binding/openuv/internal/handler/OpenUVBridgeHandler.java +++ b/bundles/org.openhab.binding.openuv/src/main/java/org/openhab/binding/openuv/internal/handler/OpenUVBridgeHandler.java @@ -31,11 +31,7 @@ import org.openhab.binding.openuv.internal.discovery.OpenUVDiscoveryService; import org.openhab.binding.openuv.internal.json.OpenUVResponse; import org.openhab.binding.openuv.internal.json.OpenUVResult; -import org.openhab.core.i18n.LocaleProvider; -import org.openhab.core.i18n.LocationProvider; -import org.openhab.core.i18n.TranslationProvider; import org.openhab.core.io.net.http.HttpUtil; -import org.openhab.core.library.types.PointType; import org.openhab.core.thing.Bridge; import org.openhab.core.thing.ChannelUID; import org.openhab.core.thing.ThingStatus; @@ -66,20 +62,13 @@ public class OpenUVBridgeHandler extends BaseBridgeHandler { private final Logger logger = LoggerFactory.getLogger(OpenUVBridgeHandler.class); private final Properties header = new Properties(); private final Gson gson; - private final LocationProvider locationProvider; - private final TranslationProvider i18nProvider; - private final LocaleProvider localeProvider; private Optional> reconnectJob = Optional.empty(); private boolean keyVerified; - public OpenUVBridgeHandler(Bridge bridge, LocationProvider locationProvider, TranslationProvider i18nProvider, - LocaleProvider localeProvider, Gson gson) { + public OpenUVBridgeHandler(Bridge bridge, Gson gson) { super(bridge); this.gson = gson; - this.locationProvider = locationProvider; - this.i18nProvider = i18nProvider; - this.localeProvider = localeProvider; } @Override @@ -178,16 +167,4 @@ private void freeReconnectJob() { public Collection> getServices() { return Set.of(OpenUVDiscoveryService.class); } - - public @Nullable PointType getLocation() { - return locationProvider.getLocation(); - } - - public TranslationProvider getI18nProvider() { - return i18nProvider; - } - - public LocaleProvider getLocaleProvider() { - return localeProvider; - } } diff --git a/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/actions/OpenWebNetCENActions.java b/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/actions/OpenWebNetCENActions.java index 534856167864d..dc4b4379fed6f 100644 --- a/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/actions/OpenWebNetCENActions.java +++ b/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/actions/OpenWebNetCENActions.java @@ -24,6 +24,8 @@ import org.openwebnet4j.communication.OWNException; import org.openwebnet4j.communication.Response; import org.openwebnet4j.message.CEN; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,6 +35,7 @@ * @author Massimo Valla - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = OpenWebNetCENActions.class) @ThingActionsScope(name = "openwebnet") @NonNullByDefault public class OpenWebNetCENActions implements ThingActions { diff --git a/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/discovery/OpenWebNetDeviceDiscoveryService.java b/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/discovery/OpenWebNetDeviceDiscoveryService.java index 9978803413bc1..5533350113937 100644 --- a/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/discovery/OpenWebNetDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.openwebnet/src/main/java/org/openhab/binding/openwebnet/internal/discovery/OpenWebNetDeviceDiscoveryService.java @@ -20,14 +20,11 @@ import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.openwebnet.internal.OpenWebNetBindingConstants; import org.openhab.binding.openwebnet.internal.handler.OpenWebNetBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; import org.openwebnet4j.OpenDeviceType; import org.openwebnet4j.message.BaseOpenMessage; import org.openwebnet4j.message.Where; @@ -35,6 +32,8 @@ import org.openwebnet4j.message.WhereThermo; import org.openwebnet4j.message.WhereZigBee; import org.openwebnet4j.message.Who; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -47,22 +46,20 @@ * @author Gilberto Cocchi - Thermoregulation * @author Giovanni Fabiani - Aux support */ +@Component(scope = ServiceScope.PROTOTYPE, service = OpenWebNetDeviceDiscoveryService.class) @NonNullByDefault -public class OpenWebNetDeviceDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { - +public class OpenWebNetDeviceDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(OpenWebNetDeviceDiscoveryService.class); private static final Set SUPPORTED_THING_TYPES = OpenWebNetBindingConstants.DEVICE_SUPPORTED_THING_TYPES; private static final int SEARCH_TIME_SEC = 60; - private @NonNullByDefault({}) OpenWebNetBridgeHandler bridgeHandler; private @NonNullByDefault({}) ThingUID bridgeUID; private boolean cuFound = false; public OpenWebNetDeviceDiscoveryService() { - super(SUPPORTED_THING_TYPES, SEARCH_TIME_SEC); + super(OpenWebNetBridgeHandler.class, SUPPORTED_THING_TYPES, SEARCH_TIME_SEC); } @Override @@ -72,22 +69,22 @@ public Set getSupportedThingTypes() { @Override protected void startScan() { - logger.info("------ SEARCHING for DEVICES on bridge '{}' ({}) ...", bridgeHandler.getThing().getLabel(), + logger.info("------ SEARCHING for DEVICES on bridge '{}' ({}) ...", thingHandler.getThing().getLabel(), bridgeUID); cuFound = false; - bridgeHandler.searchDevices(); + thingHandler.searchDevices(); } @Override protected void stopScan() { logger.debug("------ stopScan() on bridge '{}'", bridgeUID); - bridgeHandler.scanStopped(); + thingHandler.scanStopped(); } @Override public void abortScan() { logger.debug("------ abortScan() on bridge '{}'", bridgeUID); - bridgeHandler.scanStopped(); + thingHandler.scanStopped(); } /** @@ -225,15 +222,15 @@ public void newDiscoveryResult(@Nullable Where where, OpenDeviceType deviceType, return; } - String ownId = bridgeHandler.ownIdFromWhoWhere(deviceWho, w); + String ownId = thingHandler.ownIdFromWhoWhere(deviceWho, w); if (OpenWebNetBindingConstants.THING_TYPE_BUS_ON_OFF_SWITCH.equals(thingTypeUID)) { - if (bridgeHandler.getRegisteredDevice(ownId) != null) { + if (thingHandler.getRegisteredDevice(ownId) != null) { logger.debug("dimmer/switch with WHERE={} already registered, skipping this discovery result", w); return; } } - String tId = bridgeHandler.thingIdFromWhere(w); + String tId = thingHandler.thingIdFromWhere(w); ThingUID thingUID = new ThingUID(thingTypeUID, bridgeUID, tId); DiscoveryResult discoveryResult = null; @@ -296,22 +293,9 @@ public void newDiscoveryResult(@Nullable Where where, OpenDeviceType deviceType, } @Override - public void deactivate() { - super.deactivate(); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof OpenWebNetBridgeHandler openWebNetBridgeHandler) { - logger.debug("attaching {} to handler {} ", this, handler); - bridgeHandler = openWebNetBridgeHandler; - bridgeHandler.deviceDiscoveryService = this; - bridgeUID = bridgeHandler.getThing().getUID(); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; + public void initialize() { + thingHandler.deviceDiscoveryService = this; + bridgeUID = thingHandler.getThing().getUID(); + super.initialize(); } } diff --git a/bundles/org.openhab.binding.orbitbhyve/src/main/java/org/openhab/binding/orbitbhyve/internal/discovery/OrbitBhyveDiscoveryService.java b/bundles/org.openhab.binding.orbitbhyve/src/main/java/org/openhab/binding/orbitbhyve/internal/discovery/OrbitBhyveDiscoveryService.java index a395caac18bc8..0fe332c756720 100644 --- a/bundles/org.openhab.binding.orbitbhyve/src/main/java/org/openhab/binding/orbitbhyve/internal/discovery/OrbitBhyveDiscoveryService.java +++ b/bundles/org.openhab.binding.orbitbhyve/src/main/java/org/openhab/binding/orbitbhyve/internal/discovery/OrbitBhyveDiscoveryService.java @@ -25,15 +25,14 @@ import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.orbitbhyve.internal.handler.OrbitBhyveBridgeHandler; import org.openhab.binding.orbitbhyve.internal.model.OrbitBhyveDevice; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,21 +42,18 @@ * * @author Ondrej Pecta - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = OrbitBhyveDiscoveryService.class) @NonNullByDefault -public class OrbitBhyveDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { - +public class OrbitBhyveDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(OrbitBhyveDiscoveryService.class); - private @Nullable OrbitBhyveBridgeHandler bridgeHandler; - private @Nullable ScheduledFuture discoveryJob; private static final int DISCOVERY_TIMEOUT_SEC = 10; private static final int DISCOVERY_REFRESH_SEC = 1800; public OrbitBhyveDiscoveryService() { - super(DISCOVERY_TIMEOUT_SEC); + super(OrbitBhyveBridgeHandler.class, DISCOVERY_TIMEOUT_SEC); logger.debug("Creating discovery service"); } @@ -66,28 +62,6 @@ protected void startScan() { runDiscovery(); } - @Override - public void activate() { - super.activate(null); - } - - @Override - public void deactivate() { - super.deactivate(); - } - - @Override - public void setThingHandler(@Nullable ThingHandler thingHandler) { - if (thingHandler instanceof OrbitBhyveBridgeHandler bridgeHandler) { - this.bridgeHandler = bridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - @Override protected void startBackgroundDiscovery() { logger.debug("Starting Orbit B-Hyve background discovery"); @@ -109,9 +83,8 @@ protected void stopBackgroundDiscovery() { } private synchronized void runDiscovery() { - OrbitBhyveBridgeHandler localBridgeHandler = bridgeHandler; - if (localBridgeHandler != null && ThingStatus.ONLINE == localBridgeHandler.getThing().getStatus()) { - List devices = localBridgeHandler.getDevices(); + if (ThingStatus.ONLINE == thingHandler.getThing().getStatus()) { + List devices = thingHandler.getDevices(); logger.debug("Discovered total of {} devices", devices.size()); for (OrbitBhyveDevice device : devices) { sprinklerDiscovered(device); @@ -120,26 +93,22 @@ private synchronized void runDiscovery() { } private void sprinklerDiscovered(OrbitBhyveDevice device) { - OrbitBhyveBridgeHandler localBridgeHandler = bridgeHandler; - if (localBridgeHandler != null) { - Map properties = new HashMap<>(); - properties.put("id", device.getId()); - properties.put(Thing.PROPERTY_FIRMWARE_VERSION, device.getFwVersion()); - properties.put(Thing.PROPERTY_HARDWARE_VERSION, device.getHwVersion()); - properties.put(Thing.PROPERTY_MAC_ADDRESS, device.getMacAddress()); - properties.put(Thing.PROPERTY_MODEL_ID, device.getType()); - properties.put("Zones", device.getNumStations()); - properties.put("Active zones", device.getZones().size()); - - ThingUID thingUID = new ThingUID(THING_TYPE_SPRINKLER, localBridgeHandler.getThing().getUID(), - device.getId()); - - logger.debug("Detected a/an {} - label: {} id: {}", THING_TYPE_SPRINKLER.getId(), device.getName(), - device.getId()); - thingDiscovered(DiscoveryResultBuilder.create(thingUID).withThingType(THING_TYPE_SPRINKLER) - .withProperties(properties).withRepresentationProperty("id").withLabel(device.getName()) - .withBridge(localBridgeHandler.getThing().getUID()).build()); - } + Map properties = new HashMap<>(); + properties.put("id", device.getId()); + properties.put(Thing.PROPERTY_FIRMWARE_VERSION, device.getFwVersion()); + properties.put(Thing.PROPERTY_HARDWARE_VERSION, device.getHwVersion()); + properties.put(Thing.PROPERTY_MAC_ADDRESS, device.getMacAddress()); + properties.put(Thing.PROPERTY_MODEL_ID, device.getType()); + properties.put("Zones", device.getNumStations()); + properties.put("Active zones", device.getZones().size()); + + ThingUID thingUID = new ThingUID(THING_TYPE_SPRINKLER, thingHandler.getThing().getUID(), device.getId()); + + logger.debug("Detected a/an {} - label: {} id: {}", THING_TYPE_SPRINKLER.getId(), device.getName(), + device.getId()); + thingDiscovered(DiscoveryResultBuilder.create(thingUID).withThingType(THING_TYPE_SPRINKLER) + .withProperties(properties).withRepresentationProperty("id").withLabel(device.getName()) + .withBridge(thingHandler.getThing().getUID()).build()); } @Override diff --git a/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/discovery/PilightDeviceDiscoveryService.java b/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/discovery/PilightDeviceDiscoveryService.java index 053811417619b..de77d49d9fa87 100644 --- a/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/discovery/PilightDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.pilight/src/main/java/org/openhab/binding/pilight/internal/discovery/PilightDeviceDiscoveryService.java @@ -31,14 +31,14 @@ import org.openhab.binding.pilight.internal.dto.DeviceType; import org.openhab.binding.pilight.internal.dto.Status; import org.openhab.binding.pilight.internal.handler.PilightBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -48,9 +48,9 @@ * * @author Niklas Dörfler - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = PilightDeviceDiscoveryService.class) @NonNullByDefault -public class PilightDeviceDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { - +public class PilightDeviceDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final Set SUPPORTED_THING_TYPES_UIDS = PilightHandlerFactory.SUPPORTED_THING_TYPES_UIDS; private static final int AUTODISCOVERY_SEARCH_TIME_SEC = 10; @@ -58,81 +58,68 @@ public class PilightDeviceDiscoveryService extends AbstractDiscoveryService impl private final Logger logger = LoggerFactory.getLogger(PilightDeviceDiscoveryService.class); - private @Nullable PilightBridgeHandler pilightBridgeHandler; - private @Nullable ThingUID bridgeUID; + private @NonNullByDefault({}) ThingUID bridgeUID; private @Nullable ScheduledFuture backgroundDiscoveryJob; private CompletableFuture configFuture; private CompletableFuture> statusFuture; public PilightDeviceDiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, AUTODISCOVERY_SEARCH_TIME_SEC); + super(PilightBridgeHandler.class, SUPPORTED_THING_TYPES_UIDS, AUTODISCOVERY_SEARCH_TIME_SEC); configFuture = new CompletableFuture<>(); statusFuture = new CompletableFuture<>(); } @Override protected void startScan() { - if (pilightBridgeHandler != null) { - configFuture = new CompletableFuture<>(); - statusFuture = new CompletableFuture<>(); - - configFuture.thenAcceptBoth(statusFuture, (config, allStatus) -> { - removeOlderResults(getTimestampOfLastScan(), bridgeUID); - config.getDevices().forEach((deviceId, device) -> { - if (this.pilightBridgeHandler != null) { - final Optional status = allStatus.stream() - .filter(s -> s.getDevices().contains(deviceId)).findFirst(); - - final ThingTypeUID thingTypeUID; - final String typeString; - - if (status.isPresent()) { - if (status.get().getType().equals(DeviceType.SWITCH)) { - thingTypeUID = new ThingTypeUID(BINDING_ID, THING_TYPE_SWITCH.getId()); - typeString = "Switch"; - } else if (status.get().getType().equals(DeviceType.DIMMER)) { - thingTypeUID = new ThingTypeUID(BINDING_ID, THING_TYPE_DIMMER.getId()); - typeString = "Dimmer"; - } else if (status.get().getType().equals(DeviceType.VALUE)) { - thingTypeUID = new ThingTypeUID(BINDING_ID, THING_TYPE_GENERIC.getId()); - typeString = "Generic"; - } else if (status.get().getType().equals(DeviceType.CONTACT)) { - thingTypeUID = new ThingTypeUID(BINDING_ID, THING_TYPE_CONTACT.getId()); - typeString = "Contact"; - } else { - thingTypeUID = new ThingTypeUID(BINDING_ID, THING_TYPE_GENERIC.getId()); - typeString = "Generic"; - } - } else { - thingTypeUID = new ThingTypeUID(BINDING_ID, THING_TYPE_GENERIC.getId()); - typeString = "Generic"; - } - - final @Nullable PilightBridgeHandler pilightBridgeHandler = this.pilightBridgeHandler; - if (pilightBridgeHandler != null) { - final ThingUID thingUID = new ThingUID(thingTypeUID, - pilightBridgeHandler.getThing().getUID(), deviceId); - - final Map properties = new HashMap<>(); - properties.put(PROPERTY_NAME, deviceId); - - DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID) - .withThingType(thingTypeUID).withProperties(properties).withBridge(bridgeUID) - .withRepresentationProperty(PROPERTY_NAME) - .withLabel("Pilight " + typeString + " Device '" + deviceId + "'").build(); - - thingDiscovered(discoveryResult); - } + configFuture = new CompletableFuture<>(); + statusFuture = new CompletableFuture<>(); + + configFuture.thenAcceptBoth(statusFuture, (config, allStatus) -> { + removeOlderResults(getTimestampOfLastScan(), bridgeUID); + config.getDevices().forEach((deviceId, device) -> { + final Optional status = allStatus.stream().filter(s -> s.getDevices().contains(deviceId)) + .findFirst(); + + final ThingTypeUID thingTypeUID; + final String typeString; + + if (status.isPresent()) { + if (status.get().getType().equals(DeviceType.SWITCH)) { + thingTypeUID = new ThingTypeUID(BINDING_ID, THING_TYPE_SWITCH.getId()); + typeString = "Switch"; + } else if (status.get().getType().equals(DeviceType.DIMMER)) { + thingTypeUID = new ThingTypeUID(BINDING_ID, THING_TYPE_DIMMER.getId()); + typeString = "Dimmer"; + } else if (status.get().getType().equals(DeviceType.VALUE)) { + thingTypeUID = new ThingTypeUID(BINDING_ID, THING_TYPE_GENERIC.getId()); + typeString = "Generic"; + } else if (status.get().getType().equals(DeviceType.CONTACT)) { + thingTypeUID = new ThingTypeUID(BINDING_ID, THING_TYPE_CONTACT.getId()); + typeString = "Contact"; + } else { + thingTypeUID = new ThingTypeUID(BINDING_ID, THING_TYPE_GENERIC.getId()); + typeString = "Generic"; } - }); + } else { + thingTypeUID = new ThingTypeUID(BINDING_ID, THING_TYPE_GENERIC.getId()); + typeString = "Generic"; + } + + final ThingUID thingUID = new ThingUID(thingTypeUID, thingHandler.getThing().getUID(), deviceId); + + final Map properties = new HashMap<>(); + properties.put(PROPERTY_NAME, deviceId); + + DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID) + .withProperties(properties).withBridge(bridgeUID).withRepresentationProperty(PROPERTY_NAME) + .withLabel("Pilight " + typeString + " Device '" + deviceId + "'").build(); + + thingDiscovered(discoveryResult); }); + }); - final @Nullable PilightBridgeHandler pilightBridgeHandler = this.pilightBridgeHandler; - if (pilightBridgeHandler != null) { - pilightBridgeHandler.refreshConfigAndStatus(); - } - } + thingHandler.refreshConfigAndStatus(); } @Override @@ -140,9 +127,7 @@ protected synchronized void stopScan() { super.stopScan(); configFuture.cancel(true); statusFuture.cancel(true); - if (bridgeUID != null) { - removeOlderResults(getTimestampOfLastScan(), bridgeUID); - } + removeOlderResults(getTimestampOfLastScan(), bridgeUID); } @Override @@ -166,42 +151,22 @@ protected void stopBackgroundDiscovery() { } @Override - public void setThingHandler(final ThingHandler handler) { - if (handler instanceof PilightBridgeHandler pilightBridgeHandler) { - this.pilightBridgeHandler = pilightBridgeHandler; - bridgeUID = pilightBridgeHandler.getThing().getUID(); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return pilightBridgeHandler; - } - - @Override - public void activate() { - final @Nullable PilightBridgeHandler pilightBridgeHandler = this.pilightBridgeHandler; + public void initialize() { + bridgeUID = thingHandler.getThing().getUID(); boolean discoveryEnabled = false; - if (pilightBridgeHandler != null) { - removeOlderResults(new Date().getTime(), pilightBridgeHandler.getThing().getUID()); - discoveryEnabled = pilightBridgeHandler.isBackgroundDiscoveryEnabled(); - pilightBridgeHandler.registerDiscoveryListener(this); - } - super.activate(Map.of(DiscoveryService.CONFIG_PROPERTY_BACKGROUND_DISCOVERY, discoveryEnabled)); + removeOlderResults(new Date().getTime(), thingHandler.getThing().getUID()); + discoveryEnabled = thingHandler.isBackgroundDiscoveryEnabled(); + thingHandler.registerDiscoveryListener(this); + + super.initialize(); + super.modified(Map.of(DiscoveryService.CONFIG_PROPERTY_BACKGROUND_DISCOVERY, discoveryEnabled)); } @Override - public void deactivate() { - if (bridgeUID != null) { - removeOlderResults(getTimestampOfLastScan(), bridgeUID); - } - - final @Nullable PilightBridgeHandler pilightBridgeHandler = this.pilightBridgeHandler; - if (pilightBridgeHandler != null) { - pilightBridgeHandler.unregisterDiscoveryListener(); - } - - super.deactivate(); + public void dispose() { + super.dispose(); + removeOlderResults(getTimestampOfLastScan(), bridgeUID); + thingHandler.unregisterDiscoveryListener(); } /** diff --git a/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/PlugwiseThingDiscoveryService.java b/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/PlugwiseThingDiscoveryService.java index 579162c346084..01ddb6284f5db 100644 --- a/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/PlugwiseThingDiscoveryService.java +++ b/bundles/org.openhab.binding.plugwise/src/main/java/org/openhab/binding/plugwise/internal/PlugwiseThingDiscoveryService.java @@ -40,14 +40,14 @@ import org.openhab.binding.plugwise.internal.protocol.RoleCallResponseMessage; import org.openhab.binding.plugwise.internal.protocol.field.DeviceType; import org.openhab.binding.plugwise.internal.protocol.field.MACAddress; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -58,9 +58,10 @@ * * @author Wouter Born, Karel Goderis - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = PlugwiseThingDiscoveryService.class) @NonNullByDefault -public class PlugwiseThingDiscoveryService extends AbstractDiscoveryService - implements PlugwiseMessageListener, PlugwiseStickStatusListener, ThingHandlerService { +public class PlugwiseThingDiscoveryService extends AbstractThingHandlerDiscoveryService + implements PlugwiseMessageListener, PlugwiseStickStatusListener { private static class CurrentRoleCall { private boolean isRoleCalling; @@ -100,8 +101,6 @@ public boolean isDataComplete() { private final Logger logger = LoggerFactory.getLogger(PlugwiseThingDiscoveryService.class); - private @NonNullByDefault({}) PlugwiseStickHandler stickHandler; - private @Nullable ScheduledFuture discoveryJob; private @Nullable ScheduledFuture watchJob; private CurrentRoleCall currentRoleCall = new CurrentRoleCall(); @@ -109,7 +108,7 @@ public boolean isDataComplete() { private final Map discoveredNodes = new ConcurrentHashMap<>(); public PlugwiseThingDiscoveryService() throws IllegalArgumentException { - super(DISCOVERED_THING_TYPES_UIDS, 1, true); + super(PlugwiseStickHandler.class, DISCOVERED_THING_TYPES_UIDS, 1, true); } @Override @@ -120,14 +119,9 @@ public synchronized void abortScan() { stopDiscoveryWatchJob(); } - @Override - public void activate() { - super.activate(new HashMap<>()); - } - private void createDiscoveryResult(DiscoveredNode node) { String mac = node.macAddress.toString(); - ThingUID bridgeUID = stickHandler.getThing().getUID(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); ThingTypeUID thingTypeUID = PlugwiseUtils.getThingTypeUID(node.deviceType); if (thingTypeUID != null) { ThingUID thingUID = new ThingUID(thingTypeUID, bridgeUID, mac); @@ -141,10 +135,10 @@ private void createDiscoveryResult(DiscoveredNode node) { } @Override - public void deactivate() { - super.deactivate(); - stickHandler.removeMessageListener(this); - stickHandler.removeStickStatusListener(this); + public void dispose() { + super.dispose(); + thingHandler.removeMessageListener(this); + thingHandler.removeStickStatusListener(this); } private void discoverNewNodeDetails(MACAddress macAddress) { @@ -168,7 +162,7 @@ protected void discoverNodes() { } else if (currentRoleCall.isRoleCalling) { logger.debug("Discovery with role call not possible (already role calling)"); } else { - stickHandler.addMessageListener(this); + thingHandler.addMessageListener(this); discoveredNodes.clear(); currentRoleCall.isRoleCalling = true; currentRoleCall.currentNodeID = Integer.MIN_VALUE; @@ -182,16 +176,11 @@ protected void discoverNodes() { } private @Nullable MACAddress getCirclePlusMAC() { - return stickHandler.getCirclePlusMAC(); + return thingHandler.getCirclePlusMAC(); } private ThingStatus getStickStatus() { - return stickHandler.getThing().getStatus(); - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return stickHandler; + return thingHandler.getThing().getStatus(); } private void handleAnnounceAwakeRequest(AnnounceAwakeRequestMessage message) { @@ -254,7 +243,7 @@ private void handleRoleCallResponse(RoleCallResponseMessage message) { } private boolean isAlreadyDiscovered(MACAddress macAddress) { - Thing thing = stickHandler.getThingByMAC(macAddress); + Thing thing = thingHandler.getThingByMAC(macAddress); if (thing != null) { logger.debug("Node ({}) has existing thing: {}", macAddress, thing.getUID()); } @@ -284,15 +273,13 @@ private void roleCall(int nodeID) { } private void sendMessage(Message message) { - stickHandler.sendMessage(message, PlugwiseMessagePriority.UPDATE_AND_DISCOVERY); + thingHandler.sendMessage(message, PlugwiseMessagePriority.UPDATE_AND_DISCOVERY); } @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof PlugwiseStickHandler plugwiseStickHandler) { - stickHandler = plugwiseStickHandler; - stickHandler.addStickStatusListener(this); - } + public void initialize() { + thingHandler.addStickStatusListener(this); + super.initialize(); } @Override diff --git a/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/discovery/PlugwiseHADiscoveryService.java b/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/discovery/PlugwiseHADiscoveryService.java index 9120ff78bb5ec..051a85bc13339 100644 --- a/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/discovery/PlugwiseHADiscoveryService.java +++ b/bundles/org.openhab.binding.plugwiseha/src/main/java/org/openhab/binding/plugwiseha/internal/discovery/PlugwiseHADiscoveryService.java @@ -28,12 +28,12 @@ import org.openhab.binding.plugwiseha.internal.api.model.dto.DomainObjects; import org.openhab.binding.plugwiseha.internal.api.model.dto.Location; import org.openhab.binding.plugwiseha.internal.handler.PlugwiseHABridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,17 +44,17 @@ * @author Bas van Wetten - Initial contribution * @author Leo Siepel - finish initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = PlugwiseHADiscoveryService.class) @NonNullByDefault -public class PlugwiseHADiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class PlugwiseHADiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(PlugwiseHADiscoveryService.class); private static final int TIMEOUT_SECONDS = 5; private static final int REFRESH_SECONDS = 600; - private @Nullable PlugwiseHABridgeHandler bridgeHandler; private @Nullable ScheduledFuture discoveryFuture; public PlugwiseHADiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, TIMEOUT_SECONDS, true); + super(PlugwiseHABridgeHandler.class, SUPPORTED_THING_TYPES_UIDS, TIMEOUT_SECONDS, true); } @Override @@ -90,34 +90,13 @@ protected void stopBackgroundDiscovery() { if (localDiscoveryFuture != null) { if (!localDiscoveryFuture.isCancelled()) { localDiscoveryFuture.cancel(true); - localDiscoveryFuture = null; + discoveryFuture = null; } } } - @Override - public void deactivate() { - super.deactivate(); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof PlugwiseHABridgeHandler bridgeHandler) { - this.bridgeHandler = bridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - private void discoverDomainObjects() throws PlugwiseHAException { - PlugwiseHAController controller = null; - PlugwiseHABridgeHandler localBridgeHandler = this.bridgeHandler; - if (localBridgeHandler != null) { - controller = localBridgeHandler.getController(); - } + PlugwiseHAController controller = thingHandler.getController(); if (controller != null) { DomainObjects domainObjects = controller.getDomainObjects(); @@ -146,67 +125,60 @@ private void applianceDiscovery(Appliance appliance) { String applianceName = appliance.getName(); String applianceType = appliance.getType(); - PlugwiseHABridgeHandler localBridgeHandler = this.bridgeHandler; - if (localBridgeHandler != null) { - ThingUID bridgeUID = localBridgeHandler.getThing().getUID(); - - ThingUID uid; - - Map configProperties = new HashMap<>(); - - configProperties.put(APPLIANCE_CONFIG_ID, applianceId); - - switch (applianceType) { - case "thermostatic_radiator_valve": - uid = new ThingUID(PlugwiseHABindingConstants.THING_TYPE_APPLIANCE_VALVE, bridgeUID, applianceId); - configProperties.put(APPLIANCE_CONFIG_LOWBATTERY, 15); - break; - case "central_heating_pump": - uid = new ThingUID(PlugwiseHABindingConstants.THING_TYPE_APPLIANCE_PUMP, bridgeUID, applianceId); - break; - case "heater_central": - uid = new ThingUID(PlugwiseHABindingConstants.THING_TYPE_APPLIANCE_BOILER, bridgeUID, applianceId); - break; - case "zone_thermostat": - uid = new ThingUID(PlugwiseHABindingConstants.THING_TYPE_APPLIANCE_THERMOSTAT, bridgeUID, - applianceId); - configProperties.put(APPLIANCE_CONFIG_LOWBATTERY, 15); - break; - default: - return; - } + ThingUID bridgeUID = thingHandler.getThing().getUID(); + + ThingUID uid; + + Map configProperties = new HashMap<>(); + + configProperties.put(APPLIANCE_CONFIG_ID, applianceId); + + switch (applianceType) { + case "thermostatic_radiator_valve": + uid = new ThingUID(PlugwiseHABindingConstants.THING_TYPE_APPLIANCE_VALVE, bridgeUID, applianceId); + configProperties.put(APPLIANCE_CONFIG_LOWBATTERY, 15); + break; + case "central_heating_pump": + uid = new ThingUID(PlugwiseHABindingConstants.THING_TYPE_APPLIANCE_PUMP, bridgeUID, applianceId); + break; + case "heater_central": + uid = new ThingUID(PlugwiseHABindingConstants.THING_TYPE_APPLIANCE_BOILER, bridgeUID, applianceId); + break; + case "zone_thermostat": + uid = new ThingUID(PlugwiseHABindingConstants.THING_TYPE_APPLIANCE_THERMOSTAT, bridgeUID, applianceId); + configProperties.put(APPLIANCE_CONFIG_LOWBATTERY, 15); + break; + default: + return; + } - DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(uid).withBridge(bridgeUID) - .withLabel(applianceName).withProperties(configProperties) - .withRepresentationProperty(APPLIANCE_CONFIG_ID).build(); + DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(uid).withBridge(bridgeUID) + .withLabel(applianceName).withProperties(configProperties) + .withRepresentationProperty(APPLIANCE_CONFIG_ID).build(); - thingDiscovered(discoveryResult); + thingDiscovered(discoveryResult); - logger.debug("Discovered plugwise appliance type '{}' with name '{}' with id {} ({})", applianceType, - applianceName, applianceId, uid); - } + logger.debug("Discovered plugwise appliance type '{}' with name '{}' with id {} ({})", applianceType, + applianceName, applianceId, uid); } private void locationDiscovery(Location location) { String locationId = location.getId(); String locationName = location.getName(); - PlugwiseHABridgeHandler localBridgeHandler = this.bridgeHandler; - if (localBridgeHandler != null) { - ThingUID bridgeUID = localBridgeHandler.getThing().getUID(); - ThingUID uid = new ThingUID(PlugwiseHABindingConstants.THING_TYPE_ZONE, bridgeUID, locationId); + ThingUID bridgeUID = thingHandler.getThing().getUID(); + ThingUID uid = new ThingUID(PlugwiseHABindingConstants.THING_TYPE_ZONE, bridgeUID, locationId); - Map configProperties = new HashMap<>(); + Map configProperties = new HashMap<>(); - configProperties.put(ZONE_CONFIG_ID, locationId); + configProperties.put(ZONE_CONFIG_ID, locationId); - DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(uid).withBridge(bridgeUID) - .withLabel(locationName).withRepresentationProperty(ZONE_CONFIG_ID).withProperties(configProperties) - .build(); + DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(uid).withBridge(bridgeUID) + .withLabel(locationName).withRepresentationProperty(ZONE_CONFIG_ID).withProperties(configProperties) + .build(); - thingDiscovered(discoveryResult); + thingDiscovered(discoveryResult); - logger.debug("Discovered plugwise zone '{}' with id {} ({})", locationName, locationId, uid); - } + logger.debug("Discovered plugwise zone '{}' with id {} ({})", locationName, locationId, uid); } } diff --git a/bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/discovery/PowermaxDiscoveryService.java b/bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/discovery/PowermaxDiscoveryService.java index a5a474ca5b336..dffc7fab6608d 100644 --- a/bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/discovery/PowermaxDiscoveryService.java +++ b/bundles/org.openhab.binding.powermax/src/main/java/org/openhab/binding/powermax/internal/discovery/PowermaxDiscoveryService.java @@ -27,13 +27,14 @@ import org.openhab.binding.powermax.internal.state.PowermaxPanelSettingsListener; import org.openhab.binding.powermax.internal.state.PowermaxX10Settings; import org.openhab.binding.powermax.internal.state.PowermaxZoneSettings; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,66 +45,44 @@ * @author Laurent Garnier - Initial contribution * @author Laurent Garnier - Use ThingHandlerService */ +@Component(scope = ServiceScope.PROTOTYPE, service = PowermaxDiscoveryService.class) @NonNullByDefault -public class PowermaxDiscoveryService extends AbstractDiscoveryService - implements PowermaxPanelSettingsListener, ThingHandlerService { +public class PowermaxDiscoveryService extends AbstractThingHandlerDiscoveryService + implements PowermaxPanelSettingsListener { private static final int SEARCH_TIME = 5; private final Logger logger = LoggerFactory.getLogger(PowermaxDiscoveryService.class); - private @Nullable PowermaxBridgeHandler bridgeHandler; - /** * Creates a PowermaxDiscoveryService with background discovery disabled. */ public PowermaxDiscoveryService() { - super(PowermaxBindingConstants.SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME, true); - } - - @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof PowermaxBridgeHandler powermaxBridgeHandler) { - bridgeHandler = powermaxBridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; + super(PowermaxBridgeHandler.class, PowermaxBindingConstants.SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME, true); } /** * Activates the Discovery Service. */ @Override - public void activate() { - super.activate(null); - PowermaxBridgeHandler handler = bridgeHandler; - if (handler != null) { - handler.registerPanelSettingsListener(this); - } + public void initialize() { + thingHandler.registerPanelSettingsListener(this); + super.initialize(); } /** * Deactivates the Discovery Service. */ @Override - public void deactivate() { - PowermaxBridgeHandler handler = bridgeHandler; - if (handler != null) { - handler.unregisterPanelSettingsListener(this); - } - super.deactivate(); + public void dispose() { + super.dispose(); + thingHandler.unregisterPanelSettingsListener(this); } @Override protected void startScan() { logger.debug("Updating discovered things (new scan)"); - PowermaxBridgeHandler handler = bridgeHandler; - if (handler != null) { - updateFromSettings(handler.getPanelSettings()); - } + updateFromSettings(thingHandler.getPanelSettings()); } @Override @@ -120,8 +99,7 @@ public void onZoneSettingsUpdated(int zoneNumber, @Nullable PowermaxPanelSetting } private void updateFromSettings(@Nullable PowermaxPanelSettings settings) { - PowermaxBridgeHandler handler = bridgeHandler; - if (handler != null && settings != null) { + if (settings != null) { long beforeUpdate = new Date().getTime(); for (int i = 1; i <= settings.getNbZones(); i++) { @@ -135,15 +113,14 @@ private void updateFromSettings(@Nullable PowermaxPanelSettings settings) { } // Remove not updated discovered things - removeOlderResults(beforeUpdate, handler.getThing().getUID()); + removeOlderResults(beforeUpdate, thingHandler.getThing().getUID()); } } private void updateFromZoneSettings(int zoneNumber, @Nullable PowermaxZoneSettings zoneSettings) { - PowermaxBridgeHandler handler = bridgeHandler; - if (handler != null && zoneSettings != null) { + if (zoneSettings != null) { // Prevent for adding already known zone - for (Thing thing : handler.getThing().getThings()) { + for (Thing thing : thingHandler.getThing().getThings()) { ThingHandler thingHandler = thing.getHandler(); if (thing.getThingTypeUID().equals(PowermaxBindingConstants.THING_TYPE_ZONE) && thingHandler instanceof PowermaxThingHandler powermaxThingHandler) { @@ -154,7 +131,7 @@ private void updateFromZoneSettings(int zoneNumber, @Nullable PowermaxZoneSettin } } - ThingUID bridgeUID = handler.getThing().getUID(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); ThingUID thingUID = new ThingUID(PowermaxBindingConstants.THING_TYPE_ZONE, bridgeUID, String.valueOf(zoneNumber)); String sensorType = zoneSettings.getSensorType(); @@ -176,10 +153,9 @@ private void updateFromZoneSettings(int zoneNumber, @Nullable PowermaxZoneSettin } private void updateFromDeviceSettings(int deviceNumber, @Nullable PowermaxX10Settings deviceSettings) { - PowermaxBridgeHandler handler = bridgeHandler; - if (handler != null && deviceSettings != null && deviceSettings.isEnabled()) { + if (deviceSettings != null && deviceSettings.isEnabled()) { // Prevent for adding already known X10 device - for (Thing thing : handler.getThing().getThings()) { + for (Thing thing : thingHandler.getThing().getThings()) { ThingHandler thingHandler = thing.getHandler(); if (thing.getThingTypeUID().equals(PowermaxBindingConstants.THING_TYPE_X10) && thingHandler instanceof PowermaxThingHandler powermaxThingHandler) { @@ -190,7 +166,7 @@ private void updateFromDeviceSettings(int deviceNumber, @Nullable PowermaxX10Set } } - ThingUID bridgeUID = handler.getThing().getUID(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); ThingUID thingUID = new ThingUID(PowermaxBindingConstants.THING_TYPE_X10, bridgeUID, String.valueOf(deviceNumber)); String name = (deviceSettings.getName() != null) ? deviceSettings.getName() diff --git a/bundles/org.openhab.binding.prowl/src/main/java/org/openhab/binding/prowl/internal/action/ProwlActions.java b/bundles/org.openhab.binding.prowl/src/main/java/org/openhab/binding/prowl/internal/action/ProwlActions.java index 696790b716b36..21022ceb6f3ce 100644 --- a/bundles/org.openhab.binding.prowl/src/main/java/org/openhab/binding/prowl/internal/action/ProwlActions.java +++ b/bundles/org.openhab.binding.prowl/src/main/java/org/openhab/binding/prowl/internal/action/ProwlActions.java @@ -20,6 +20,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,6 +30,7 @@ * * @author Ondrej Pecta - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = ProwlActions.class) @ThingActionsScope(name = "prowl") @NonNullByDefault public class ProwlActions implements ThingActions { diff --git a/bundles/org.openhab.binding.pushbullet/src/main/java/org/openhab/binding/pushbullet/internal/action/PushbulletActions.java b/bundles/org.openhab.binding.pushbullet/src/main/java/org/openhab/binding/pushbullet/internal/action/PushbulletActions.java index de73158586cff..79f5afd071d64 100644 --- a/bundles/org.openhab.binding.pushbullet/src/main/java/org/openhab/binding/pushbullet/internal/action/PushbulletActions.java +++ b/bundles/org.openhab.binding.pushbullet/src/main/java/org/openhab/binding/pushbullet/internal/action/PushbulletActions.java @@ -21,6 +21,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -29,6 +31,7 @@ * * @author Hakan Tandogan - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = PushbulletActions.class) @ThingActionsScope(name = "pushbullet") @NonNullByDefault public class PushbulletActions implements ThingActions { diff --git a/bundles/org.openhab.binding.pushover/src/main/java/org/openhab/binding/pushover/internal/actions/PushoverActions.java b/bundles/org.openhab.binding.pushover/src/main/java/org/openhab/binding/pushover/internal/actions/PushoverActions.java index cd5f2c5fd7d6f..d3c2c3dbf3e68 100644 --- a/bundles/org.openhab.binding.pushover/src/main/java/org/openhab/binding/pushover/internal/actions/PushoverActions.java +++ b/bundles/org.openhab.binding.pushover/src/main/java/org/openhab/binding/pushover/internal/actions/PushoverActions.java @@ -27,6 +27,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -36,6 +38,7 @@ * @author Christoph Weitkamp - Initial contribution * @author Jacob Laursen - Added support for Expiring Messages */ +@Component(scope = ServiceScope.PROTOTYPE, service = PushoverActions.class) @ThingActionsScope(name = "pushover") @NonNullByDefault public class PushoverActions implements ThingActions { diff --git a/bundles/org.openhab.binding.pushover/src/main/java/org/openhab/binding/pushover/internal/config/PushoverConfigOptionProvider.java b/bundles/org.openhab.binding.pushover/src/main/java/org/openhab/binding/pushover/internal/config/PushoverConfigOptionProvider.java index bf56eec43535a..fd0394a52ae50 100644 --- a/bundles/org.openhab.binding.pushover/src/main/java/org/openhab/binding/pushover/internal/config/PushoverConfigOptionProvider.java +++ b/bundles/org.openhab.binding.pushover/src/main/java/org/openhab/binding/pushover/internal/config/PushoverConfigOptionProvider.java @@ -30,6 +30,7 @@ import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * The {@link PushoverConfigOptionProvider} class contains fields mapping thing configuration parameters. @@ -37,7 +38,7 @@ * @author Christoph Weitkamp - Initial contribution */ @NonNullByDefault -@Component(service = ConfigOptionProvider.class) +@Component(scope = ServiceScope.PROTOTYPE, service = { PushoverConfigOptionProvider.class, ConfigOptionProvider.class }) public class PushoverConfigOptionProvider implements ConfigOptionProvider, ThingHandlerService { private @Nullable PushoverAccountHandler accountHandler; diff --git a/bundles/org.openhab.binding.pushsafer/src/main/java/org/openhab/binding/pushsafer/internal/actions/PushsaferActions.java b/bundles/org.openhab.binding.pushsafer/src/main/java/org/openhab/binding/pushsafer/internal/actions/PushsaferActions.java index 3cabf46867e57..40763ac57d19c 100644 --- a/bundles/org.openhab.binding.pushsafer/src/main/java/org/openhab/binding/pushsafer/internal/actions/PushsaferActions.java +++ b/bundles/org.openhab.binding.pushsafer/src/main/java/org/openhab/binding/pushsafer/internal/actions/PushsaferActions.java @@ -26,6 +26,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,6 +36,7 @@ * * @author Kevin Siml - Initial contribution, forked from Christoph Weitkamp */ +@Component(scope = ServiceScope.PROTOTYPE, service = PushsaferActions.class) @ThingActionsScope(name = "pushsafer") @NonNullByDefault public class PushsaferActions implements ThingActions { diff --git a/bundles/org.openhab.binding.pushsafer/src/main/java/org/openhab/binding/pushsafer/internal/config/PushsaferConfigOptionProvider.java b/bundles/org.openhab.binding.pushsafer/src/main/java/org/openhab/binding/pushsafer/internal/config/PushsaferConfigOptionProvider.java index 20ec3c11b20b3..922500aeabad5 100644 --- a/bundles/org.openhab.binding.pushsafer/src/main/java/org/openhab/binding/pushsafer/internal/config/PushsaferConfigOptionProvider.java +++ b/bundles/org.openhab.binding.pushsafer/src/main/java/org/openhab/binding/pushsafer/internal/config/PushsaferConfigOptionProvider.java @@ -31,13 +31,15 @@ import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * The {@link PushsaferConfigOptionProvider} class contains fields mapping thing configuration parameters. * * @author Kevin Siml - Initial contribution, forked from Christoph Weitkamp */ -@Component(service = ConfigOptionProvider.class) +@Component(scope = ServiceScope.PROTOTYPE, service = { PushsaferConfigOptionProvider.class, + ConfigOptionProvider.class }) @NonNullByDefault public class PushsaferConfigOptionProvider implements ConfigOptionProvider, ThingHandlerService { diff --git a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/discovery/QolsysIQChildDiscoveryService.java b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/discovery/QolsysIQChildDiscoveryService.java index 687fde974ef53..a5a1a486b6731 100644 --- a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/discovery/QolsysIQChildDiscoveryService.java +++ b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/discovery/QolsysIQChildDiscoveryService.java @@ -15,17 +15,13 @@ import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.qolsysiq.internal.QolsysIQBindingConstants; import org.openhab.binding.qolsysiq.internal.handler.QolsysIQChildDiscoveryHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -36,48 +32,25 @@ * */ @NonNullByDefault -public class QolsysIQChildDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { +public class QolsysIQChildDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(QolsysIQChildDiscoveryService.class); private static final Set SUPPORTED_DISCOVERY_THING_TYPES_UIDS = Set .of(QolsysIQBindingConstants.THING_TYPE_PARTITION, QolsysIQBindingConstants.THING_TYPE_ZONE); - private @Nullable ThingHandler thingHandler; - public QolsysIQChildDiscoveryService() throws IllegalArgumentException { - super(SUPPORTED_DISCOVERY_THING_TYPES_UIDS, 5, false); + super(QolsysIQChildDiscoveryHandler.class, SUPPORTED_DISCOVERY_THING_TYPES_UIDS, 5, false); } @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof QolsysIQChildDiscoveryHandler childDiscoveryHandler) { - childDiscoveryHandler.setDiscoveryService(this); - this.thingHandler = handler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return thingHandler; + public void initialize() { + thingHandler.setDiscoveryService(this); + super.initialize(); } @Override protected void startScan() { - ThingHandler handler = this.thingHandler; - if (handler != null) { - ((QolsysIQChildDiscoveryHandler) handler).startDiscovery(); - } - } - - @Override - public void activate() { - super.activate(null); - } - - @Override - public void deactivate() { - super.deactivate(); + thingHandler.startDiscovery(); } public void discoverQolsysIQChildThing(ThingUID thingUID, ThingUID bridgeUID, Integer id, String label) { diff --git a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/handler/QolsysIQChildDiscoveryHandler.java b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/handler/QolsysIQChildDiscoveryHandler.java index 07e3e6c8c307c..d815071dbb9f5 100644 --- a/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/handler/QolsysIQChildDiscoveryHandler.java +++ b/bundles/org.openhab.binding.qolsysiq/src/main/java/org/openhab/binding/qolsysiq/internal/handler/QolsysIQChildDiscoveryHandler.java @@ -14,6 +14,7 @@ import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.binding.qolsysiq.internal.discovery.QolsysIQChildDiscoveryService; +import org.openhab.core.thing.binding.ThingHandler; /** * Callback for our custom discovery service @@ -22,7 +23,7 @@ * */ @NonNullByDefault -public interface QolsysIQChildDiscoveryHandler { +public interface QolsysIQChildDiscoveryHandler extends ThingHandler { /** * Sets a {@link QolsysIQChildDiscoveryService} to call when device information is received * diff --git a/bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/RadioThermostatThingActions.java b/bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/RadioThermostatThingActions.java index a9c485763f583..3e962ca70f94f 100644 --- a/bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/RadioThermostatThingActions.java +++ b/bundles/org.openhab.binding.radiothermostat/src/main/java/org/openhab/binding/radiothermostat/internal/RadioThermostatThingActions.java @@ -20,6 +20,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,6 +30,7 @@ * * @author Michael Lobstein - initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = RadioThermostatThingActions.class) @ThingActionsScope(name = "radiothermostat") @NonNullByDefault public class RadioThermostatThingActions implements ThingActions { diff --git a/bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/discovery/RemoteopenhabDiscoveryService.java b/bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/discovery/RemoteopenhabDiscoveryService.java index a5470106397d7..b0480523cf24f 100644 --- a/bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/discovery/RemoteopenhabDiscoveryService.java +++ b/bundles/org.openhab.binding.remoteopenhab/src/main/java/org/openhab/binding/remoteopenhab/internal/discovery/RemoteopenhabDiscoveryService.java @@ -26,13 +26,13 @@ import org.openhab.binding.remoteopenhab.internal.handler.RemoteopenhabBridgeHandler; import org.openhab.binding.remoteopenhab.internal.listener.RemoteopenhabThingsDataListener; import org.openhab.binding.remoteopenhab.internal.rest.RemoteopenhabRestClient; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,53 +42,42 @@ * * @author Laurent Garnier - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = RemoteopenhabDiscoveryService.class) @NonNullByDefault -public class RemoteopenhabDiscoveryService extends AbstractDiscoveryService - implements ThingHandlerService, RemoteopenhabThingsDataListener { +public class RemoteopenhabDiscoveryService extends AbstractThingHandlerDiscoveryService + implements RemoteopenhabThingsDataListener { private final Logger logger = LoggerFactory.getLogger(RemoteopenhabDiscoveryService.class); private static final int SEARCH_TIME = 10; - private @NonNullByDefault({}) RemoteopenhabBridgeHandler bridgeHandler; private @NonNullByDefault({}) RemoteopenhabRestClient restClient; public RemoteopenhabDiscoveryService() { - super(RemoteopenhabBindingConstants.SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME, false); + super(RemoteopenhabBridgeHandler.class, RemoteopenhabBindingConstants.SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME, + false); } @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof RemoteopenhabBridgeHandler remoteopenhabBridgeHandler) { - this.bridgeHandler = remoteopenhabBridgeHandler; - this.restClient = bridgeHandler.gestRestClient(); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - - @Override - public void activate() { - ThingHandlerService.super.activate(); + public void initialize() { + restClient = thingHandler.gestRestClient(); restClient.addThingsDataListener(this); + super.initialize(); } @Override - public void deactivate() { + public void dispose() { + super.dispose(); restClient.removeThingsDataListener(this); - super.deactivate(); } @Override protected void startScan() { logger.debug("Starting discovery scan for remote things"); - if (bridgeHandler.getThing().getStatus() == ThingStatus.ONLINE) { + if (thingHandler.getThing().getStatus() == ThingStatus.ONLINE) { try { List things = restClient.getRemoteThings(); - ThingUID bridgeUID = bridgeHandler.getThing().getUID(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); for (RemoteopenhabThing thing : things) { createDiscoveryResult(thing, bridgeUID); } @@ -101,7 +90,7 @@ protected void startScan() { @Override protected synchronized void stopScan() { super.stopScan(); - removeOlderResults(getTimestampOfLastScan(), bridgeHandler.getThing().getUID()); + removeOlderResults(getTimestampOfLastScan(), thingHandler.getThing().getUID()); } @Override @@ -111,12 +100,12 @@ public void onThingStatusUpdated(String thingUID, RemoteopenhabStatusInfo status @Override public void onThingAdded(RemoteopenhabThing thing) { - createDiscoveryResult(thing, bridgeHandler.getThing().getUID()); + createDiscoveryResult(thing, thingHandler.getThing().getUID()); } @Override public void onThingRemoved(RemoteopenhabThing thing) { - removeDiscoveryResult(thing, bridgeHandler.getThing().getUID()); + removeDiscoveryResult(thing, thingHandler.getThing().getUID()); } @Override diff --git a/bundles/org.openhab.binding.resol/src/main/java/org/openhab/binding/resol/internal/discovery/ResolDeviceDiscoveryService.java b/bundles/org.openhab.binding.resol/src/main/java/org/openhab/binding/resol/internal/discovery/ResolDeviceDiscoveryService.java index 786aa2bd2c262..94fea239f7293 100644 --- a/bundles/org.openhab.binding.resol/src/main/java/org/openhab/binding/resol/internal/discovery/ResolDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.resol/src/main/java/org/openhab/binding/resol/internal/discovery/ResolDeviceDiscoveryService.java @@ -17,16 +17,14 @@ import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.resol.handler.ResolBridgeHandler; import org.openhab.binding.resol.internal.ResolBindingConstants; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -36,18 +34,16 @@ * * @author Raphael Mack - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = ResolDeviceDiscoveryService.class) @NonNullByDefault -public class ResolDeviceDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { +public class ResolDeviceDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final String THING_PROPERTY_TYPE = "type"; private final Logger logger = LoggerFactory.getLogger(ResolDeviceDiscoveryService.class); - private @Nullable ResolBridgeHandler resolBridgeHandler; - public ResolDeviceDiscoveryService() throws IllegalArgumentException { - super(Set.of(ResolBindingConstants.THING_TYPE_UID_DEVICE), 15, false); + super(ResolBridgeHandler.class, Set.of(ResolBindingConstants.THING_TYPE_UID_DEVICE), 15, false); } public void addThing(ThingUID bridgeUID, String thingType, String type, String name) { @@ -76,47 +72,25 @@ public void addThing(ThingUID bridgeUID, String thingType, String type, String n } @Override - public void activate() { - ResolBridgeHandler resolBridgeHandler = this.resolBridgeHandler; - if (resolBridgeHandler != null) { - resolBridgeHandler.registerDiscoveryService(this); - } + public void initialize() { + thingHandler.registerDiscoveryService(this); + super.initialize(); } @Override - public void deactivate() { - ResolBridgeHandler resolBridgeHandler = this.resolBridgeHandler; - if (resolBridgeHandler != null) { - resolBridgeHandler.unregisterDiscoveryService(); - } + public void dispose() { + super.dispose(); + thingHandler.unregisterDiscoveryService(); } @Override protected void startScan() { - ResolBridgeHandler resolBridgeHandler = this.resolBridgeHandler; - if (resolBridgeHandler != null) { - resolBridgeHandler.startScan(); - } + thingHandler.startScan(); } @Override protected void stopScan() { - ResolBridgeHandler resolBridgeHandler = this.resolBridgeHandler; - if (resolBridgeHandler != null) { - resolBridgeHandler.stopScan(); - } + thingHandler.stopScan(); super.stopScan(); } - - @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof ResolBridgeHandler resolBridgeHandler) { - this.resolBridgeHandler = resolBridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return resolBridgeHandler; - } } diff --git a/bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/discovery/RFXComDeviceDiscoveryService.java b/bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/discovery/RFXComDeviceDiscoveryService.java index 8a970adb344c0..9bcbca77e0c7f 100644 --- a/bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/discovery/RFXComDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/discovery/RFXComDeviceDiscoveryService.java @@ -17,18 +17,17 @@ import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.rfxcom.internal.DeviceMessageListener; import org.openhab.binding.rfxcom.internal.RFXComBindingConstants; import org.openhab.binding.rfxcom.internal.exceptions.RFXComException; import org.openhab.binding.rfxcom.internal.handler.RFXComBridgeHandler; import org.openhab.binding.rfxcom.internal.messages.RFXComDeviceMessage; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,46 +38,27 @@ * @author Pauli Anttila - Initial contribution * @author Laurent Garnier - use ThingHandlerService */ +@Component(scope = ServiceScope.PROTOTYPE, service = RFXComDeviceDiscoveryService.class) @NonNullByDefault -public class RFXComDeviceDiscoveryService extends AbstractDiscoveryService - implements DeviceMessageListener, ThingHandlerService { +public class RFXComDeviceDiscoveryService extends AbstractThingHandlerDiscoveryService + implements DeviceMessageListener { private final Logger logger = LoggerFactory.getLogger(RFXComDeviceDiscoveryService.class); private final int DISCOVERY_TTL = 3600; - private @Nullable RFXComBridgeHandler bridgeHandler; - public RFXComDeviceDiscoveryService() { - super(null, 1, false); - } - - @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof RFXComBridgeHandler rfxComBridgeHandler) { - bridgeHandler = rfxComBridgeHandler; - } + super(RFXComBridgeHandler.class, null, 1, false); } @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; + public void initialize() { + thingHandler.registerDeviceStatusListener(this); + super.initialize(); } @Override - public void activate() { - super.activate(null); - RFXComBridgeHandler handler = bridgeHandler; - if (handler != null) { - handler.registerDeviceStatusListener(this); - } - } - - @Override - public void deactivate() { - RFXComBridgeHandler handler = bridgeHandler; - if (handler != null) { - handler.unregisterDeviceStatusListener(this); - } - super.deactivate(); + public void dispose() { + super.dispose(); + thingHandler.unregisterDeviceStatusListener(this); } @Override @@ -103,10 +83,7 @@ public void onDeviceMessageReceived(ThingUID bridge, RFXComDeviceMessage message } ThingUID thingUID = new ThingUID(uid, bridge, id.replace(ID_DELIMITER, "_")); - RFXComBridgeHandler handler = bridgeHandler; - if (handler == null) { - logger.trace("Ignoring RFXCOM {} with id '{}' - bridge handler is null", thingUID, id); - } else if (!handler.getConfiguration().disableDiscovery) { + if (!thingHandler.getConfiguration().disableDiscovery) { logger.trace("Adding new RFXCOM {} with id '{}' to inbox", thingUID, id); DiscoveryResultBuilder discoveryResultBuilder = DiscoveryResultBuilder.create(thingUID).withBridge(bridge) .withTTL(DISCOVERY_TTL); diff --git a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/action/SatelEventLogActions.java b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/action/SatelEventLogActions.java index 2a53ee23019b7..60349e0bbc6a5 100644 --- a/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/action/SatelEventLogActions.java +++ b/bundles/org.openhab.binding.satel/src/main/java/org/openhab/binding/satel/internal/action/SatelEventLogActions.java @@ -24,6 +24,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -33,6 +35,7 @@ * @author Krzysztof Goworek - Initial contribution * @see SatelEventLogHandler */ +@Component(scope = ServiceScope.PROTOTYPE, service = SatelEventLogActions.class) @ThingActionsScope(name = "satel") @NonNullByDefault public class SatelEventLogActions implements ThingActions { diff --git a/bundles/org.openhab.binding.sensibo/src/main/java/org/openhab/binding/sensibo/internal/CallbackChannelsTypeProvider.java b/bundles/org.openhab.binding.sensibo/src/main/java/org/openhab/binding/sensibo/internal/CallbackChannelsTypeProvider.java index 081494bd82003..e9bd52b20676b 100644 --- a/bundles/org.openhab.binding.sensibo/src/main/java/org/openhab/binding/sensibo/internal/CallbackChannelsTypeProvider.java +++ b/bundles/org.openhab.binding.sensibo/src/main/java/org/openhab/binding/sensibo/internal/CallbackChannelsTypeProvider.java @@ -27,12 +27,16 @@ import org.openhab.core.thing.type.ChannelType; import org.openhab.core.thing.type.ChannelTypeProvider; import org.openhab.core.thing.type.ChannelTypeUID; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * Channel Type Provider that does a callback the SensiboSkyHandler that initiated it. * * @author Arne Seime - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = { CallbackChannelsTypeProvider.class, ChannelTypeProvider.class, + ChannelGroupTypeProvider.class }) @NonNullByDefault public class CallbackChannelsTypeProvider implements ChannelTypeProvider, ChannelGroupTypeProvider, ThingHandlerService { diff --git a/bundles/org.openhab.binding.smsmodem/src/main/java/org/openhab/binding/smsmodem/internal/SMSConversationDiscoveryService.java b/bundles/org.openhab.binding.smsmodem/src/main/java/org/openhab/binding/smsmodem/internal/SMSConversationDiscoveryService.java index aa00b623492b6..211d160242c0c 100644 --- a/bundles/org.openhab.binding.smsmodem/src/main/java/org/openhab/binding/smsmodem/internal/SMSConversationDiscoveryService.java +++ b/bundles/org.openhab.binding.smsmodem/src/main/java/org/openhab/binding/smsmodem/internal/SMSConversationDiscoveryService.java @@ -15,41 +15,38 @@ import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.smsmodem.internal.handler.SMSConversationHandler; import org.openhab.binding.smsmodem.internal.handler.SMSModemBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * This class implements a discovery service for SMSConversation * * @author Gwendal ROULLEAU - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = SMSConversationDiscoveryService.class) @NonNullByDefault -public class SMSConversationDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { +public class SMSConversationDiscoveryService extends AbstractThingHandlerDiscoveryService { - private @NonNullByDefault({}) SMSModemBridgeHandler bridgeHandler; private @NonNullByDefault({}) ThingUID bridgeUid; public SMSConversationDiscoveryService() { - super(0); + this(0); } public SMSConversationDiscoveryService(int timeout) throws IllegalArgumentException { - super(timeout); + super(SMSModemBridgeHandler.class, timeout); } @Override protected void startScan() { - for (String msisdn : bridgeHandler.getAllSender()) { + for (String msisdn : thingHandler.getAllSender()) { buildDiscovery(msisdn); } } @@ -80,19 +77,9 @@ public Set getSupportedThingTypes() { } @Override - public void setThingHandler(ThingHandler handler) { - this.bridgeHandler = (SMSModemBridgeHandler) handler; - this.bridgeUid = handler.getThing().getUID(); - this.bridgeHandler.setDiscoveryService(this); - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - - @Override - public void deactivate() { - super.deactivate(); + public void initialize() { + bridgeUid = thingHandler.getThing().getUID(); + thingHandler.setDiscoveryService(this); + super.initialize(); } } diff --git a/bundles/org.openhab.binding.smsmodem/src/main/java/org/openhab/binding/smsmodem/internal/actions/SMSModemActions.java b/bundles/org.openhab.binding.smsmodem/src/main/java/org/openhab/binding/smsmodem/internal/actions/SMSModemActions.java index 52f2bcc4e3a85..84921273e1757 100644 --- a/bundles/org.openhab.binding.smsmodem/src/main/java/org/openhab/binding/smsmodem/internal/actions/SMSModemActions.java +++ b/bundles/org.openhab.binding.smsmodem/src/main/java/org/openhab/binding/smsmodem/internal/actions/SMSModemActions.java @@ -20,6 +20,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.smslib.message.AbstractMessage.Encoding; @@ -29,6 +31,7 @@ * * @author Gwendal ROULLEAU - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = SMSModemActions.class) @ThingActionsScope(name = "smsmodem") @NonNullByDefault public class SMSModemActions implements ThingActions { diff --git a/bundles/org.openhab.binding.sncf/src/main/java/org/openhab/binding/sncf/internal/SncfHandlerFactory.java b/bundles/org.openhab.binding.sncf/src/main/java/org/openhab/binding/sncf/internal/SncfHandlerFactory.java index 7f0749ad73849..f2cd063e01111 100644 --- a/bundles/org.openhab.binding.sncf/src/main/java/org/openhab/binding/sncf/internal/SncfHandlerFactory.java +++ b/bundles/org.openhab.binding.sncf/src/main/java/org/openhab/binding/sncf/internal/SncfHandlerFactory.java @@ -68,7 +68,7 @@ public boolean supportsThingType(ThingTypeUID thingTypeUID) { protected @Nullable ThingHandler createHandler(Thing thing) { ThingTypeUID thingTypeUID = thing.getThingTypeUID(); if (APIBRIDGE_THING_TYPE.equals(thingTypeUID)) { - return new SncfBridgeHandler((Bridge) thing, gson, locationProvider, httpClient); + return new SncfBridgeHandler((Bridge) thing, gson, httpClient); } else if (STATION_THING_TYPE.equals(thingTypeUID)) { return new StationHandler(thing, locationProvider); } diff --git a/bundles/org.openhab.binding.sncf/src/main/java/org/openhab/binding/sncf/internal/discovery/SncfDiscoveryService.java b/bundles/org.openhab.binding.sncf/src/main/java/org/openhab/binding/sncf/internal/discovery/SncfDiscoveryService.java index d56721135713d..4663bedb96b4c 100644 --- a/bundles/org.openhab.binding.sncf/src/main/java/org/openhab/binding/sncf/internal/discovery/SncfDiscoveryService.java +++ b/bundles/org.openhab.binding.sncf/src/main/java/org/openhab/binding/sncf/internal/discovery/SncfDiscoveryService.java @@ -19,19 +19,18 @@ import java.util.List; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.sncf.internal.SncfException; import org.openhab.binding.sncf.internal.dto.PlaceNearby; import org.openhab.binding.sncf.internal.handler.SncfBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.i18n.LocationProvider; import org.openhab.core.library.types.PointType; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,75 +40,57 @@ * * @author Gaël L'hopital - Initial contribution */ -@Component(service = ThingHandlerService.class) +@Component(scope = ServiceScope.PROTOTYPE, service = SncfDiscoveryService.class) @NonNullByDefault -public class SncfDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class SncfDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int SEARCH_TIME = 7; private final Logger logger = LoggerFactory.getLogger(SncfDiscoveryService.class); - private @Nullable LocationProvider locationProvider; - private @Nullable SncfBridgeHandler bridgeHandler; + private @NonNullByDefault({}) LocationProvider locationProvider; private int searchRange = 1500; @Activate public SncfDiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME, false); + super(SncfBridgeHandler.class, SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME, false); } - @Override - public void deactivate() { - super.deactivate(); + @Reference(unbind = "-") + public void setLocationProvider(LocationProvider locationProvider) { + this.locationProvider = locationProvider; } @Override public void startScan() { - SncfBridgeHandler handler = bridgeHandler; - LocationProvider provider = locationProvider; - if (provider != null && handler != null) { - PointType location = provider.getLocation(); - if (location != null) { - ThingUID bridgeUID = handler.getThing().getUID(); - searchRange += 500; - try { - List places = handler.discoverNearby(location, searchRange); - if (places != null && !places.isEmpty()) { - places.forEach(place -> { - // stop_point:SNCF:87386573:Bus - List idElts = new LinkedList(Arrays.asList(place.id.split(":"))); - idElts.remove(0); - idElts.remove(0); - thingDiscovered(DiscoveryResultBuilder - .create(new ThingUID(STATION_THING_TYPE, bridgeUID, String.join("_", idElts))) - .withLabel(String.format("%s (%s)", place.stopPoint.name, idElts.get(1)) - .replace("-", "_")) - .withBridge(bridgeUID).withRepresentationProperty(STOP_POINT_ID) - .withProperty(STOP_POINT_ID, place.id).build()); - }); - } else { - logger.info("No station found in a perimeter of {} m, extending search", searchRange); - startScan(); - } - } catch (SncfException e) { - logger.warn("Error calling SNCF Api : {}", e.getMessage()); + PointType location = locationProvider.getLocation(); + if (location != null) { + ThingUID bridgeUID = thingHandler.getThing().getUID(); + searchRange += 500; + try { + List places = thingHandler.discoverNearby(location, searchRange); + if (places != null && !places.isEmpty()) { + places.forEach(place -> { + // stop_point:SNCF:87386573:Bus + List idElts = new LinkedList(Arrays.asList(place.id.split(":"))); + idElts.remove(0); + idElts.remove(0); + thingDiscovered(DiscoveryResultBuilder + .create(new ThingUID(STATION_THING_TYPE, bridgeUID, String.join("_", idElts))) + .withLabel( + String.format("%s (%s)", place.stopPoint.name, idElts.get(1)).replace("-", "_")) + .withBridge(bridgeUID).withRepresentationProperty(STOP_POINT_ID) + .withProperty(STOP_POINT_ID, place.id).build()); + }); + } else { + logger.info("No station found in a perimeter of {} m, extending search", searchRange); + startScan(); } - } else { - logger.info("Please set a system location to enable station discovery"); + } catch (SncfException e) { + logger.warn("Error calling SNCF Api : {}", e.getMessage()); } + } else { + logger.info("Please set a system location to enable station discovery"); } } - - @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof SncfBridgeHandler sncfBridgeHandler) { - this.bridgeHandler = sncfBridgeHandler; - this.locationProvider = sncfBridgeHandler.getLocationProvider(); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } } diff --git a/bundles/org.openhab.binding.sncf/src/main/java/org/openhab/binding/sncf/internal/handler/SncfBridgeHandler.java b/bundles/org.openhab.binding.sncf/src/main/java/org/openhab/binding/sncf/internal/handler/SncfBridgeHandler.java index 68554c2f8f3c4..4e55785f6c4cf 100644 --- a/bundles/org.openhab.binding.sncf/src/main/java/org/openhab/binding/sncf/internal/handler/SncfBridgeHandler.java +++ b/bundles/org.openhab.binding.sncf/src/main/java/org/openhab/binding/sncf/internal/handler/SncfBridgeHandler.java @@ -40,7 +40,6 @@ import org.openhab.binding.sncf.internal.dto.StopPoint; import org.openhab.binding.sncf.internal.dto.StopPoints; import org.openhab.core.cache.ExpiringCacheMap; -import org.openhab.core.i18n.LocationProvider; import org.openhab.core.library.types.PointType; import org.openhab.core.thing.Bridge; import org.openhab.core.thing.ChannelUID; @@ -68,16 +67,14 @@ public class SncfBridgeHandler extends BaseBridgeHandler { public static final String SERVICE_URL = "https://api.sncf.com/v1/coverage/sncf/"; private final Logger logger = LoggerFactory.getLogger(SncfBridgeHandler.class); - private final LocationProvider locationProvider; private final ExpiringCacheMap cache = new ExpiringCacheMap<>(Duration.ofMinutes(1)); private final HttpClient httpClient; private final Gson gson; private @NonNullByDefault({}) String apiId; - public SncfBridgeHandler(Bridge bridge, Gson gson, LocationProvider locationProvider, HttpClient httpClient) { + public SncfBridgeHandler(Bridge bridge, Gson gson, HttpClient httpClient) { super(bridge); - this.locationProvider = locationProvider; this.httpClient = httpClient; this.gson = gson; } @@ -160,10 +157,6 @@ public Optional getNextPassage(String stopPointId, String expected) thr return passages != null && !passages.isEmpty() ? Optional.ofNullable(passages.get(0)) : Optional.empty(); } - public LocationProvider getLocationProvider() { - return locationProvider; - } - @Override public Collection> getServices() { return Set.of(SncfDiscoveryService.class); diff --git a/bundles/org.openhab.binding.solarwatt/src/main/java/org/openhab/binding/solarwatt/internal/discovery/SolarwattDevicesDiscoveryService.java b/bundles/org.openhab.binding.solarwatt/src/main/java/org/openhab/binding/solarwatt/internal/discovery/SolarwattDevicesDiscoveryService.java index 945f3c92a9088..3205845b8e0b0 100644 --- a/bundles/org.openhab.binding.solarwatt/src/main/java/org/openhab/binding/solarwatt/internal/discovery/SolarwattDevicesDiscoveryService.java +++ b/bundles/org.openhab.binding.solarwatt/src/main/java/org/openhab/binding/solarwatt/internal/discovery/SolarwattDevicesDiscoveryService.java @@ -39,15 +39,14 @@ import org.openhab.binding.solarwatt.internal.domain.model.PowerMeter; import org.openhab.binding.solarwatt.internal.domain.model.SmartHeater; import org.openhab.binding.solarwatt.internal.handler.EnergyManagerHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -56,14 +55,13 @@ * * @author Sven Carstens - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = SolarwattDevicesDiscoveryService.class) @NonNullByDefault -public class SolarwattDevicesDiscoveryService extends AbstractDiscoveryService - implements ThingHandlerService, DiscoveryService { +public class SolarwattDevicesDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int TIMEOUT_SECONDS = 20; private final Logger logger = LoggerFactory.getLogger(SolarwattDevicesDiscoveryService.class); - private @Nullable EnergyManagerHandler energyManagerHandler; /** * Job which will do the background scanning @@ -76,29 +74,12 @@ public class SolarwattDevicesDiscoveryService extends AbstractDiscoveryService private @Nullable ScheduledFuture scanningJob; public SolarwattDevicesDiscoveryService() { - super(TIMEOUT_SECONDS); + super(EnergyManagerHandler.class, TIMEOUT_SECONDS); this.scanningRunnable = new EnergymanagerScan(); this.activate(null); } - @Override - public void setThingHandler(final @Nullable ThingHandler handler) { - if (handler instanceof EnergyManagerHandler energyManagerHandler) { - this.energyManagerHandler = energyManagerHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return this.energyManagerHandler; - } - - @Override - public void deactivate() { - this.stopBackgroundDiscovery(); - } - @Override protected void startBackgroundDiscovery() { ScheduledFuture localScanningJob = this.scanningJob; @@ -120,11 +101,9 @@ protected void stopBackgroundDiscovery() { @Override protected synchronized void startScan() { this.removeOlderResults(this.getTimestampOfLastScan()); - final EnergyManagerHandler localEnergyManagerHandler = this.energyManagerHandler; - if (localEnergyManagerHandler == null - || localEnergyManagerHandler.getThing().getStatus() != ThingStatus.ONLINE) { - this.logger.warn("Energymanager handler not available: {}", localEnergyManagerHandler); + if (thingHandler.getThing().getStatus() != ThingStatus.ONLINE) { + this.logger.warn("Energymanager handler not available: {}", thingHandler.getThing().getUID()); return; } this.scanForDeviceThings(); @@ -136,38 +115,35 @@ protected synchronized void startScan() { * Walks through the list of devices and adds discovery results for the supported devices. */ private void scanForDeviceThings() { - EnergyManagerHandler localEnergyManagerHandler = this.energyManagerHandler; - if (localEnergyManagerHandler != null) { - final Map devices = localEnergyManagerHandler.getDevices(); - - final ThingUID bridgeUID = localEnergyManagerHandler.getThing().getUID(); - - if (devices == null) { - this.logger.warn("No device data for solarwatt devices in discovery for energy manager {}.", bridgeUID); - } else { - devices.forEach((key, entry) -> { - this.logger.debug("scanForDeviceThings: {}-{}", entry.getClass(), entry.getGuid()); - if (entry instanceof BatteryConverter) { - this.discover(bridgeUID, entry, THING_TYPE_BATTERYCONVERTER); - } else if (entry instanceof Inverter) { - this.discover(bridgeUID, entry, THING_TYPE_INVERTER); - } else if (entry instanceof PowerMeter) { - this.discover(bridgeUID, entry, THING_TYPE_POWERMETER); - } else if (entry instanceof EVStation) { - this.discover(bridgeUID, entry, THING_TYPE_EVSTATION); - } else if (entry instanceof Location) { - this.discover(bridgeUID, entry, THING_TYPE_LOCATION); - } else if (entry instanceof PVPlant) { - this.discover(bridgeUID, entry, THING_TYPE_PVPLANT); - } else if (entry instanceof GridFlow) { - this.discover(bridgeUID, entry, THING_TYPE_GRIDFLOW); - } else if (entry instanceof SmartHeater) { - this.discover(bridgeUID, entry, THING_TYPE_SMARTHEATER); - } else { - this.logger.debug("Found unhandled device"); - } - }); - } + final Map devices = thingHandler.getDevices(); + + final ThingUID bridgeUID = thingHandler.getThing().getUID(); + + if (devices == null) { + this.logger.warn("No device data for solarwatt devices in discovery for energy manager {}.", bridgeUID); + } else { + devices.forEach((key, entry) -> { + this.logger.debug("scanForDeviceThings: {}-{}", entry.getClass(), entry.getGuid()); + if (entry instanceof BatteryConverter) { + this.discover(bridgeUID, entry, THING_TYPE_BATTERYCONVERTER); + } else if (entry instanceof Inverter) { + this.discover(bridgeUID, entry, THING_TYPE_INVERTER); + } else if (entry instanceof PowerMeter) { + this.discover(bridgeUID, entry, THING_TYPE_POWERMETER); + } else if (entry instanceof EVStation) { + this.discover(bridgeUID, entry, THING_TYPE_EVSTATION); + } else if (entry instanceof Location) { + this.discover(bridgeUID, entry, THING_TYPE_LOCATION); + } else if (entry instanceof PVPlant) { + this.discover(bridgeUID, entry, THING_TYPE_PVPLANT); + } else if (entry instanceof GridFlow) { + this.discover(bridgeUID, entry, THING_TYPE_GRIDFLOW); + } else if (entry instanceof SmartHeater) { + this.discover(bridgeUID, entry, THING_TYPE_SMARTHEATER); + } else { + this.logger.debug("Found unhandled device"); + } + }); } } diff --git a/bundles/org.openhab.binding.somfymylink/src/main/java/org/openhab/binding/somfymylink/internal/discovery/SomfyMyLinkDeviceDiscoveryService.java b/bundles/org.openhab.binding.somfymylink/src/main/java/org/openhab/binding/somfymylink/internal/discovery/SomfyMyLinkDeviceDiscoveryService.java index d6a8bb36d2a33..9db06ac568902 100644 --- a/bundles/org.openhab.binding.somfymylink/src/main/java/org/openhab/binding/somfymylink/internal/discovery/SomfyMyLinkDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.somfymylink/src/main/java/org/openhab/binding/somfymylink/internal/discovery/SomfyMyLinkDeviceDiscoveryService.java @@ -27,18 +27,15 @@ import org.openhab.binding.somfymylink.internal.handler.SomfyMyLinkException; import org.openhab.binding.somfymylink.internal.model.SomfyMyLinkScene; import org.openhab.binding.somfymylink.internal.model.SomfyMyLinkShade; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.config.discovery.ScanListener; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; -import org.osgi.service.component.annotations.Activate; -import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -47,43 +44,18 @@ * * @author Chris Johnson - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = SomfyMyLinkDeviceDiscoveryService.class) @NonNullByDefault -public class SomfyMyLinkDeviceDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { +public class SomfyMyLinkDeviceDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int DISCOVERY_REFRESH_SEC = 900; private final Logger logger = LoggerFactory.getLogger(SomfyMyLinkDeviceDiscoveryService.class); - private @NonNullByDefault({}) SomfyMyLinkBridgeHandler mylinkHandler; private @Nullable Future scanTask; private @Nullable ScheduledFuture discoveryJob; public SomfyMyLinkDeviceDiscoveryService() { - super(SomfyMyLinkHandlerFactory.DISCOVERABLE_DEVICE_TYPES_UIDS, 10); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof SomfyMyLinkBridgeHandler bridgeHandler) { - this.mylinkHandler = bridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return mylinkHandler; - } - - @Override - @Activate - public void activate() { - super.activate(null); - } - - @Override - @Deactivate - public void deactivate() { - super.deactivate(); + super(SomfyMyLinkBridgeHandler.class, SomfyMyLinkHandlerFactory.DISCOVERABLE_DEVICE_TYPES_UIDS, 10); } @Override @@ -130,14 +102,14 @@ public void stopScan() { private synchronized void discoverDevices() { logger.info("Scanning for things..."); - if (this.mylinkHandler.getThing().getStatus() != ThingStatus.ONLINE) { - logger.info("Skipping device discover as bridge is {}", this.mylinkHandler.getThing().getStatus()); + if (thingHandler.getThing().getStatus() != ThingStatus.ONLINE) { + logger.info("Skipping device discover as bridge is {}", thingHandler.getThing().getStatus()); return; } try { // get the shade list - SomfyMyLinkShade[] shades = this.mylinkHandler.getShadeList(); + SomfyMyLinkShade[] shades = thingHandler.getShadeList(); for (SomfyMyLinkShade shade : shades) { String id = shade.getTargetID(); @@ -149,7 +121,7 @@ private synchronized void discoverDevices() { } } - SomfyMyLinkScene[] scenes = this.mylinkHandler.getSceneList(); + SomfyMyLinkScene[] scenes = thingHandler.getSceneList(); for (SomfyMyLinkScene scene : scenes) { String id = scene.getTargetID(); @@ -173,7 +145,7 @@ private void notifyThingDiscovery(ThingTypeUID thingTypeUID, String id, String l return; } - ThingUID bridgeUID = this.mylinkHandler.getThing().getUID(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); ThingUID uid = new ThingUID(thingTypeUID, bridgeUID, id); Map properties = new HashMap<>(); diff --git a/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/discovery/SomfyTahomaItemDiscoveryService.java b/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/discovery/SomfyTahomaItemDiscoveryService.java index 378a6099a10e5..a36a3d0eb59ba 100644 --- a/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/discovery/SomfyTahomaItemDiscoveryService.java +++ b/bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/discovery/SomfyTahomaItemDiscoveryService.java @@ -31,14 +31,13 @@ import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaSetup; import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaState; import org.openhab.binding.somfytahoma.internal.model.SomfyTahomaSubPlace; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -49,46 +48,22 @@ * @author Ondrej Pecta - Initial contribution * @author Laurent Garnier - Include the place into the inbox label (when defined for the device) */ +@Component(scope = ServiceScope.PROTOTYPE, service = SomfyTahomaItemDiscoveryService.class) @NonNullByDefault -public class SomfyTahomaItemDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { +public class SomfyTahomaItemDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int DISCOVERY_TIMEOUT_SEC = 10; private static final int DISCOVERY_REFRESH_SEC = 3600; private final Logger logger = LoggerFactory.getLogger(SomfyTahomaItemDiscoveryService.class); - private @Nullable SomfyTahomaBridgeHandler bridgeHandler; - private @Nullable ScheduledFuture discoveryJob; public SomfyTahomaItemDiscoveryService() { - super(DISCOVERY_TIMEOUT_SEC); + super(SomfyTahomaBridgeHandler.class, DISCOVERY_TIMEOUT_SEC); logger.debug("Creating discovery service"); } - @Override - public void activate() { - super.activate(null); - } - - @Override - public void deactivate() { - super.deactivate(); - } - - @Override - public void setThingHandler(@NonNullByDefault({}) ThingHandler handler) { - if (handler instanceof SomfyTahomaBridgeHandler tahomaBridgeHandler) { - bridgeHandler = tahomaBridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - @Override protected void startBackgroundDiscovery() { logger.debug("Starting SomfyTahoma background discovery"); @@ -122,9 +97,8 @@ protected void startScan() { private synchronized void runDiscovery() { logger.debug("Starting scanning for things..."); - SomfyTahomaBridgeHandler localBridgeHandler = bridgeHandler; - if (localBridgeHandler != null && ThingStatus.ONLINE == localBridgeHandler.getThing().getStatus()) { - SomfyTahomaSetup setup = localBridgeHandler.getSetup(); + if (ThingStatus.ONLINE == thingHandler.getThing().getStatus()) { + SomfyTahomaSetup setup = thingHandler.getSetup(); if (setup == null) { return; @@ -138,8 +112,8 @@ private synchronized void runDiscovery() { } // local mode does not have action groups - if (!localBridgeHandler.isDevModeReady()) { - List actions = localBridgeHandler.listActionGroups(); + if (!thingHandler.isDevModeReady()) { + List actions = thingHandler.listActionGroups(); for (SomfyTahomaActionGroup group : actions) { String oid = group.getOid(); @@ -468,16 +442,13 @@ private void deviceDiscovered(String label, String deviceURL, ThingTypeUID thing properties.put(RSSI_LEVEL_STATE, "-1"); } - SomfyTahomaBridgeHandler localBridgeHandler = bridgeHandler; - if (localBridgeHandler != null) { - ThingUID thingUID = new ThingUID(thingTypeUID, localBridgeHandler.getThing().getUID(), - deviceURL.replaceAll("[^a-zA-Z0-9_]", "")); + ThingUID thingUID = new ThingUID(thingTypeUID, thingHandler.getThing().getUID(), + deviceURL.replaceAll("[^a-zA-Z0-9_]", "")); - logger.debug("Detected a/an {} - label: {} device URL: {}", thingTypeUID.getId(), label, deviceURL); - thingDiscovered(DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID) - .withProperties(properties).withRepresentationProperty("url").withLabel(label) - .withBridge(localBridgeHandler.getThing().getUID()).build()); - } + logger.debug("Detected a/an {} - label: {} device URL: {}", thingTypeUID.getId(), label, deviceURL); + thingDiscovered(DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID).withProperties(properties) + .withRepresentationProperty("url").withLabel(label).withBridge(thingHandler.getThing().getUID()) + .build()); } private void actionGroupDiscovered(String label, String deviceURL) { @@ -491,15 +462,11 @@ private void gatewayDiscovered(SomfyTahomaGateway gw) { properties.put("id", id); properties.put("type", type); - SomfyTahomaBridgeHandler localBridgeHandler = bridgeHandler; - if (localBridgeHandler != null) { - ThingUID thingUID = new ThingUID(THING_TYPE_GATEWAY, localBridgeHandler.getThing().getUID(), id); + ThingUID thingUID = new ThingUID(THING_TYPE_GATEWAY, thingHandler.getThing().getUID(), id); - logger.debug("Detected a gateway with id: {} and type: {}", id, type); - thingDiscovered( - DiscoveryResultBuilder.create(thingUID).withThingType(THING_TYPE_GATEWAY).withProperties(properties) - .withRepresentationProperty("id").withLabel("Somfy Gateway (" + type + ")") - .withBridge(localBridgeHandler.getThing().getUID()).build()); - } + logger.debug("Detected a gateway with id: {} and type: {}", id, type); + thingDiscovered(DiscoveryResultBuilder.create(thingUID).withThingType(THING_TYPE_GATEWAY) + .withProperties(properties).withRepresentationProperty("id").withLabel("Somfy Gateway (" + type + ")") + .withBridge(thingHandler.getThing().getUID()).build()); } } diff --git a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/discovery/SoulissGatewayDiscovery.java b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/discovery/SoulissGatewayDiscovery.java index 7287c5a3576fe..48478be4517be 100644 --- a/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/discovery/SoulissGatewayDiscovery.java +++ b/bundles/org.openhab.binding.souliss/src/main/java/org/openhab/binding/souliss/internal/discovery/SoulissGatewayDiscovery.java @@ -23,13 +23,12 @@ import org.openhab.binding.souliss.internal.SoulissBindingConstants; import org.openhab.binding.souliss.internal.SoulissProtocolConstants; import org.openhab.binding.souliss.internal.handler.SoulissGatewayHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,27 +39,22 @@ * @author Tonino Fazio - Initial contribution * @author Luca Calcaterra - Refactor for OH3 */ +@Component(scope = ServiceScope.PROTOTYPE, service = SoulissGatewayDiscovery.class) @NonNullByDefault -public class SoulissGatewayDiscovery extends AbstractDiscoveryService - implements DiscoverResult, DiscoveryService, ThingHandlerService { +public class SoulissGatewayDiscovery extends AbstractThingHandlerDiscoveryService + implements DiscoverResult { private @Nullable ScheduledFuture discoveryJob = null; private final Logger logger = LoggerFactory.getLogger(SoulissGatewayDiscovery.class); private @Nullable SoulissDiscoverJob soulissDiscoverRunnableClass; - private @Nullable SoulissGatewayHandler soulissGwHandler; public SoulissGatewayDiscovery() { - super(SoulissBindingConstants.SUPPORTED_THING_TYPES_UIDS, SoulissBindingConstants.DISCOVERY_TIMEOUT_IN_SECONDS, - false); - } - - @Override - public void deactivate() { - super.deactivate(); + super(SoulissGatewayHandler.class, SoulissBindingConstants.SUPPORTED_THING_TYPES_UIDS, + SoulissBindingConstants.DISCOVERY_TIMEOUT_IN_SECONDS, false); } /** - * The {@link gatewayDetected} callback used to create the Gateway + * This callback used to create the Gateway */ @Override public void gatewayDetected(InetAddress addr, String id) { @@ -83,7 +77,7 @@ protected void startScan() { // create discovery class if (soulissDiscoverRunnableClass == null) { - soulissDiscoverRunnableClass = new SoulissDiscoverJob(this.soulissGwHandler); + soulissDiscoverRunnableClass = new SoulissDiscoverJob(thingHandler); // send command for gw struct (typicals).. must be not soo much quick.. discoveryJob = scheduler.scheduleWithFixedDelay(soulissDiscoverRunnableClass, 2, @@ -110,17 +104,14 @@ public void thingDetectedActionMessages(String topicNumber, String sTopicVariant DiscoveryResult discoveryResult; String sNodeID = topicNumber + SoulissBindingConstants.UUID_NODE_SLOT_SEPARATOR + sTopicVariant; - var localGwHandler = this.soulissGwHandler; - if (localGwHandler != null) { - var gatewayUID = localGwHandler.getThing().getUID(); - thingUID = new ThingUID(SoulissBindingConstants.TOPICS_THING_TYPE, gatewayUID, sNodeID); - label = "Topic. Number: " + topicNumber + ", Variant: " + sTopicVariant; + var gatewayUID = thingHandler.getThing().getUID(); + thingUID = new ThingUID(SoulissBindingConstants.TOPICS_THING_TYPE, gatewayUID, sNodeID); + label = "Topic. Number: " + topicNumber + ", Variant: " + sTopicVariant; - discoveryResult = DiscoveryResultBuilder.create(thingUID).withLabel(label) - .withProperty("number", topicNumber).withProperty("variant", sTopicVariant) - .withRepresentationProperty("number").withBridge(gatewayUID).build(); - thingDiscovered(discoveryResult); - } + discoveryResult = DiscoveryResultBuilder.create(thingUID).withLabel(label).withProperty("number", topicNumber) + .withProperty("variant", sTopicVariant).withRepresentationProperty("number").withBridge(gatewayUID) + .build(); + thingDiscovered(discoveryResult); } @Override @@ -128,12 +119,11 @@ public void thingDetectedTypicals(byte lastByteGatewayIP, byte typical, byte nod ThingUID thingUID = null; var label = ""; DiscoveryResult discoveryResult; - var gwHandler = this.soulissGwHandler; - if ((gwHandler != null) && (lastByteGatewayIP == (byte) Integer - .parseInt(gwHandler.getGwConfig().gatewayLanAddress.split("\\.")[3]))) { + if (lastByteGatewayIP == (byte) Integer + .parseInt(thingHandler.getGwConfig().gatewayLanAddress.split("\\.")[3])) { String sNodeId = node + SoulissBindingConstants.UUID_NODE_SLOT_SEPARATOR + slot; - ThingUID gatewayUID = gwHandler.getThing().getUID(); + ThingUID gatewayUID = thingHandler.getThing().getUID(); var nodeLabel = "node"; var slotLabel = "slot"; @@ -247,30 +237,23 @@ public void thingDetectedTypicals(byte lastByteGatewayIP, byte typical, byte nod } } if (thingUID != null) { - label = "[" + gwHandler.getThing().getUID().getAsString() + "] " + label; + label = "[" + thingHandler.getThing().getUID().getAsString() + "] " + label; var uniqueId = "N" + Byte.toString(node) + "S" + Byte.toString(slot); discoveryResult = DiscoveryResultBuilder.create(thingUID).withLabel(label) .withProperty(SoulissBindingConstants.PROPERTY_NODE, node) .withProperty(SoulissBindingConstants.PROPERTY_SLOT, slot) .withProperty(SoulissBindingConstants.PROPERTY_UNIQUEID, uniqueId) .withRepresentationProperty(SoulissBindingConstants.PROPERTY_UNIQUEID) - .withBridge(gwHandler.getThing().getUID()).build(); + .withBridge(thingHandler.getThing().getUID()).build(); thingDiscovered(discoveryResult); - gwHandler.setThereIsAThingDetection(); + thingHandler.setThereIsAThingDetection(); } } } @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof SoulissGatewayHandler localGwHandler) { - this.soulissGwHandler = localGwHandler; - localGwHandler.discoverResult = this; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return soulissGwHandler; + public void initialize() { + thingHandler.discoverResult = this; + super.initialize(); } } diff --git a/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/actions/SpotifyActions.java b/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/actions/SpotifyActions.java index 99d81aeff8d9c..09ce3cfdf90bc 100644 --- a/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/actions/SpotifyActions.java +++ b/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/actions/SpotifyActions.java @@ -21,12 +21,15 @@ import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * Spotify Rule Actions. * * @author Hilbrand Bouwkamp - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = SpotifyActions.class) @ThingActionsScope(name = "spotify") @NonNullByDefault public class SpotifyActions implements ThingActions, ThingHandlerService { diff --git a/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/discovery/SpotifyDeviceDiscoveryService.java b/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/discovery/SpotifyDeviceDiscoveryService.java index c56cd3baf3c30..049069c87296f 100644 --- a/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/discovery/SpotifyDeviceDiscoveryService.java +++ b/bundles/org.openhab.binding.spotify/src/main/java/org/openhab/binding/spotify/internal/discovery/SpotifyDeviceDiscoveryService.java @@ -27,14 +27,14 @@ import org.openhab.binding.spotify.internal.SpotifyAccountHandler; import org.openhab.binding.spotify.internal.SpotifyBindingConstants; import org.openhab.binding.spotify.internal.api.model.Device; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,9 +44,9 @@ * @author Andreas Stenlund - Initial contribution * @author Hilbrand Bouwkamp - Simplfied code to make call to shared code */ +@Component(scope = ServiceScope.PROTOTYPE, service = SpotifyDeviceDiscoveryService.class) @NonNullByDefault -public class SpotifyDeviceDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { +public class SpotifyDeviceDiscoveryService extends AbstractThingHandlerDiscoveryService { // id for device is derived by stripping id of device with this length private static final int PLAYER_ID_LENGTH = 4; @@ -60,14 +60,12 @@ public class SpotifyDeviceDiscoveryService extends AbstractDiscoveryService private static final long TTL_SECONDS = Duration.ofHours(1).toSeconds(); private final Logger logger = LoggerFactory.getLogger(SpotifyDeviceDiscoveryService.class); - - private @NonNullByDefault({}) SpotifyAccountHandler bridgeHandler; private @NonNullByDefault({}) ThingUID bridgeUID; private @Nullable ScheduledFuture backgroundFuture; public SpotifyDeviceDiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIME_SECONDS); + super(SpotifyAccountHandler.class, SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIME_SECONDS); } @Override @@ -83,21 +81,9 @@ public void activate() { } @Override - public void deactivate() { - super.deactivate(); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof SpotifyAccountHandler accountHandler) { - bridgeHandler = accountHandler; - bridgeUID = bridgeHandler.getUID(); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; + public void initialize() { + bridgeUID = thingHandler.getUID(); + super.initialize(); } @Override @@ -119,10 +105,10 @@ protected synchronized void stopBackgroundDiscovery() { protected void startScan() { // If the bridge is not online no other thing devices can be found, so no reason to scan at this moment. removeOlderResults(getTimestampOfLastScan()); - if (bridgeHandler.isOnline()) { + if (thingHandler.isOnline()) { logger.debug("Starting Spotify Device discovery for bridge {}", bridgeUID); try { - bridgeHandler.listDevices().forEach(this::thingDiscovered); + thingHandler.listDevices().forEach(this::thingDiscovered); } catch (final RuntimeException e) { logger.debug("Finding devices failed with message: {}", e.getMessage(), e); } diff --git a/bundles/org.openhab.binding.surepetcare/src/main/java/org/openhab/binding/surepetcare/internal/discovery/SurePetcareDiscoveryService.java b/bundles/org.openhab.binding.surepetcare/src/main/java/org/openhab/binding/surepetcare/internal/discovery/SurePetcareDiscoveryService.java index 6dfd8e4015d96..98ede0fdbf4ca 100644 --- a/bundles/org.openhab.binding.surepetcare/src/main/java/org/openhab/binding/surepetcare/internal/discovery/SurePetcareDiscoveryService.java +++ b/bundles/org.openhab.binding.surepetcare/src/main/java/org/openhab/binding/surepetcare/internal/discovery/SurePetcareDiscoveryService.java @@ -27,14 +27,14 @@ import org.openhab.binding.surepetcare.internal.dto.SurePetcareHousehold; import org.openhab.binding.surepetcare.internal.dto.SurePetcarePet; import org.openhab.binding.surepetcare.internal.handler.SurePetcareBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,9 +44,9 @@ * * @author Rene Scherer - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = SurePetcareDiscoveryService.class) @NonNullByDefault -public class SurePetcareDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { +public class SurePetcareDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(SurePetcareDiscoveryService.class); @@ -58,14 +58,13 @@ public class SurePetcareDiscoveryService extends AbstractDiscoveryService private @Nullable ScheduledFuture discoveryJob; - private @NonNullByDefault({}) SurePetcareBridgeHandler bridgeHandler; private @NonNullByDefault({}) ThingUID bridgeUID; /** * Creates a SurePetcareDiscoveryService with enabled autostart. */ public SurePetcareDiscoveryService() { - super(SUPPORTED_THING_TYPES, DISCOVER_TIMEOUT_SECONDS); + super(SurePetcareBridgeHandler.class, SUPPORTED_THING_TYPES, DISCOVER_TIMEOUT_SECONDS); } @Override @@ -80,23 +79,10 @@ public void activate() { super.activate(properties); } - /* We override this method to allow a call from the thing handler factory */ @Override - public void deactivate() { - super.deactivate(); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof SurePetcareBridgeHandler bridgeHandler) { - this.bridgeHandler = bridgeHandler; - bridgeUID = bridgeHandler.getUID(); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; + public void initialize() { + bridgeUID = thingHandler.getUID(); + super.initialize(); } @Override @@ -123,11 +109,11 @@ protected void startScan() { logger.debug("Starting Sure Petcare discovery scan"); // If the bridge is not online no other thing devices can be found, so no reason to scan at this moment. removeOlderResults(getTimestampOfLastScan()); - if (bridgeHandler.getThing().getStatus() == ThingStatus.ONLINE) { + if (thingHandler.getThing().getStatus() == ThingStatus.ONLINE) { logger.debug("Starting device discovery for bridge {}", bridgeUID); - bridgeHandler.listHouseholds().forEach(this::householdDiscovered); - bridgeHandler.listPets().forEach(this::petDiscovered); - bridgeHandler.listDevices().forEach(this::deviceDiscovered); + thingHandler.listHouseholds().forEach(this::householdDiscovered); + thingHandler.listPets().forEach(this::petDiscovered); + thingHandler.listDevices().forEach(this::deviceDiscovered); } } diff --git a/bundles/org.openhab.binding.tapocontrol/src/main/java/org/openhab/binding/tapocontrol/internal/TapoDiscoveryService.java b/bundles/org.openhab.binding.tapocontrol/src/main/java/org/openhab/binding/tapocontrol/internal/TapoDiscoveryService.java index b30e637075581..8fe5df702a6ba 100644 --- a/bundles/org.openhab.binding.tapocontrol/src/main/java/org/openhab/binding/tapocontrol/internal/TapoDiscoveryService.java +++ b/bundles/org.openhab.binding.tapocontrol/src/main/java/org/openhab/binding/tapocontrol/internal/TapoDiscoveryService.java @@ -20,17 +20,17 @@ import java.util.Map; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.tapocontrol.internal.device.TapoBridgeHandler; import org.openhab.binding.tapocontrol.internal.structures.TapoBridgeConfiguration; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; +import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,10 +43,10 @@ * * @author Christian Wild - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = TapoDiscoveryService.class) @NonNullByDefault -public class TapoDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class TapoDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(TapoDiscoveryService.class); - protected @NonNullByDefault({}) TapoBridgeHandler bridge; /*********************************** * @@ -58,39 +58,15 @@ public class TapoDiscoveryService extends AbstractDiscoveryService implements Th * INIT CLASS */ public TapoDiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, TAPO_DISCOVERY_TIMEOUT_S, false); + super(TapoBridgeHandler.class, SUPPORTED_THING_TYPES_UIDS, TAPO_DISCOVERY_TIMEOUT_S, false); } - /** - * activate - */ @Override - public void activate() { - TapoBridgeConfiguration config = bridge.getBridgeConfig(); - if (config.cloudDiscovery) { - startBackgroundDiscovery(); - } - } - - /** - * deactivate - */ - @Override - public void deactivate() { - super.deactivate(); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof TapoBridgeHandler tapoBridge) { - tapoBridge.setDiscoveryService(this); - this.bridge = tapoBridge; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return this.bridge; + public void initialize() { + thingHandler.setDiscoveryService(this); + TapoBridgeConfiguration config = thingHandler.getBridgeConfig(); + modified(Map.of(DiscoveryService.CONFIG_PROPERTY_BACKGROUND_DISCOVERY, config.cloudDiscovery)); + super.initialize(); } /*********************************** @@ -105,10 +81,8 @@ public void setThingHandler(@Nullable ThingHandler handler) { @Override public void startScan() { removeOlderResults(getTimestampOfLastScan()); - if (bridge != null) { - JsonArray jsonArray = bridge.getDeviceList(); - handleCloudDevices(jsonArray); - } + JsonArray jsonArray = thingHandler.getDeviceList(); + handleCloudDevices(jsonArray); } /*********************************** @@ -125,7 +99,6 @@ public void startScan() { * @return DiscoveryResult-Object */ public DiscoveryResult createResult(JsonObject device) { - TapoBridgeHandler tapoBridge = this.bridge; String deviceModel = getDeviceModel(device); String label = getDeviceLabel(device); String deviceMAC = device.get(CLOUD_JSON_KEY_MAC).getAsString(); @@ -141,17 +114,11 @@ public DiscoveryResult createResult(JsonObject device) { properties.put(Thing.PROPERTY_SERIAL_NUMBER, device.get(CLOUD_JSON_KEY_ID).getAsString()); logger.debug("device {} discovered", deviceModel); - if (tapoBridge != null) { - ThingUID bridgeUID = tapoBridge.getUID(); - ThingUID thingUID = new ThingUID(thingTypeUID, bridgeUID, deviceMAC); - return DiscoveryResultBuilder.create(thingUID).withProperties(properties) - .withRepresentationProperty(DEVICE_REPRESENTATION_PROPERTY).withBridge(bridgeUID).withLabel(label) - .build(); - } else { - ThingUID thingUID = new ThingUID(BINDING_ID, deviceMAC); - return DiscoveryResultBuilder.create(thingUID).withProperties(properties) - .withRepresentationProperty(DEVICE_REPRESENTATION_PROPERTY).withLabel(label).build(); - } + ThingUID bridgeUID = thingHandler.getUID(); + ThingUID thingUID = new ThingUID(thingTypeUID, bridgeUID, deviceMAC); + return DiscoveryResultBuilder.create(thingUID).withProperties(properties) + .withRepresentationProperty(DEVICE_REPRESENTATION_PROPERTY).withBridge(bridgeUID).withLabel(label) + .build(); } /** diff --git a/bundles/org.openhab.binding.telegram/src/main/java/org/openhab/binding/telegram/internal/action/TelegramActions.java b/bundles/org.openhab.binding.telegram/src/main/java/org/openhab/binding/telegram/internal/action/TelegramActions.java index ac7e17b264b00..4165895a11aa7 100644 --- a/bundles/org.openhab.binding.telegram/src/main/java/org/openhab/binding/telegram/internal/action/TelegramActions.java +++ b/bundles/org.openhab.binding.telegram/src/main/java/org/openhab/binding/telegram/internal/action/TelegramActions.java @@ -42,6 +42,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -61,6 +63,7 @@ * * @author Alexander Krasnogolowy - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = TelegramActions.class) @ThingActionsScope(name = "telegram") @NonNullByDefault public class TelegramActions implements ThingActions { diff --git a/bundles/org.openhab.binding.teleinfo/src/main/java/org/openhab/binding/teleinfo/internal/TeleinfoDiscoveryService.java b/bundles/org.openhab.binding.teleinfo/src/main/java/org/openhab/binding/teleinfo/internal/TeleinfoDiscoveryService.java index b1d8516a53c17..431f78b5c8474 100644 --- a/bundles/org.openhab.binding.teleinfo/src/main/java/org/openhab/binding/teleinfo/internal/TeleinfoDiscoveryService.java +++ b/bundles/org.openhab.binding.teleinfo/src/main/java/org/openhab/binding/teleinfo/internal/TeleinfoDiscoveryService.java @@ -19,20 +19,18 @@ import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.teleinfo.internal.data.Frame; import org.openhab.binding.teleinfo.internal.handler.TeleinfoAbstractControllerHandler; import org.openhab.binding.teleinfo.internal.handler.TeleinfoControllerHandlerListener; import org.openhab.binding.teleinfo.internal.reader.io.serialport.InvalidFrameException; import org.openhab.binding.teleinfo.internal.reader.io.serialport.Label; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,9 +39,10 @@ * * @author Nicolas SIBERIL - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = TeleinfoDiscoveryService.class) @NonNullByDefault -public class TeleinfoDiscoveryService extends AbstractDiscoveryService - implements TeleinfoControllerHandlerListener, ThingHandlerService, DiscoveryService { +public class TeleinfoDiscoveryService extends AbstractThingHandlerDiscoveryService + implements TeleinfoControllerHandlerListener { private static final Set SUPPORTED_THING_TYPES = Set.of(THING_HC_CBEMM_ELECTRICITY_METER_TYPE_UID, THING_BASE_CBEMM_ELECTRICITY_METER_TYPE_UID, THING_TEMPO_CBEMM_ELECTRICITY_METER_TYPE_UID, @@ -58,15 +57,14 @@ public class TeleinfoDiscoveryService extends AbstractDiscoveryService private static final int SCAN_DURATION_IN_S = 60; private final Logger logger = LoggerFactory.getLogger(TeleinfoDiscoveryService.class); - private @Nullable TeleinfoAbstractControllerHandler controllerHandler; public TeleinfoDiscoveryService() { - super(SCAN_DURATION_IN_S); + super(TeleinfoAbstractControllerHandler.class, SCAN_DURATION_IN_S); } public TeleinfoDiscoveryService(TeleinfoAbstractControllerHandler controllerHandler) { - super(SCAN_DURATION_IN_S); - this.controllerHandler = controllerHandler; + this(); + setThingHandler(controllerHandler); } @Override @@ -74,61 +72,26 @@ public Set getSupportedThingTypes() { return SUPPORTED_THING_TYPES; } - @Override - public void activate() { - TeleinfoAbstractControllerHandler controllerHandlerRef = controllerHandler; - if (controllerHandlerRef != null) { - logger.debug("Teleinfo discovery: Activate {}", controllerHandlerRef.getThing().getUID()); - } else { - logNullControllerHandler(); - } - } - - @Override - public void deactivate() { - TeleinfoAbstractControllerHandler controllerHandlerRef = controllerHandler; - if (controllerHandlerRef != null) { - logger.debug("Teleinfo discovery: Deactivate {}", controllerHandlerRef.getThing().getUID()); - } else { - logNullControllerHandler(); - } - } - @Override protected void startScan() { - TeleinfoAbstractControllerHandler controllerHandlerRef = controllerHandler; - if (controllerHandlerRef != null) { - logger.debug("Teleinfo discovery: Start {}", controllerHandlerRef.getThing().getUID()); + logger.debug("Teleinfo discovery: Start {}", thingHandler.getThing().getUID()); - // Start the search for new devices - controllerHandlerRef.addListener(this); - } else { - logNullControllerHandler(); - } + // Start the search for new devices + thingHandler.addListener(this); } @Override public synchronized void abortScan() { - TeleinfoAbstractControllerHandler controllerHandlerRef = controllerHandler; - if (controllerHandlerRef != null) { - logger.debug("Teleinfo discovery: Abort {}", controllerHandlerRef.getThing().getUID()); - controllerHandlerRef.removeListener(this); - super.abortScan(); - } else { - logNullControllerHandler(); - } + logger.debug("Teleinfo discovery: Abort {}", thingHandler.getThing().getUID()); + thingHandler.removeListener(this); + super.abortScan(); } @Override protected synchronized void stopScan() { - TeleinfoAbstractControllerHandler controllerHandlerRef = controllerHandler; - if (controllerHandlerRef != null) { - logger.debug("Teleinfo discovery: Stop {}", controllerHandlerRef.getThing().getUID()); - controllerHandlerRef.removeListener(this); - super.stopScan(); - } else { - logNullControllerHandler(); - } + logger.debug("Teleinfo discovery: Stop {}", thingHandler.getThing().getUID()); + thingHandler.removeListener(this); + super.stopScan(); } @Override @@ -137,30 +100,24 @@ public void onFrameReceived(Frame frame) { } private void detectNewElectricityMeterFromReceivedFrame(final Frame frameSample) { - TeleinfoAbstractControllerHandler controllerHandlerRef = controllerHandler; - if (controllerHandlerRef != null) { - logger.debug("New eletricity meter detection from frame {}", frameSample); - if (frameSample.get(Label.ADCO) == null && frameSample.get(Label.ADSC) == null) { - throw new IllegalStateException("Missing ADCO or ADSC key"); - } - - String adco = frameSample.get(Label.ADCO) != null ? frameSample.get(Label.ADCO) - : frameSample.get(Label.ADSC); - if (adco != null) { - ThingUID thingUID = new ThingUID(getThingTypeUID(frameSample), adco, - controllerHandlerRef.getThing().getUID().getId()); - - final Map properties = getThingProperties(adco); - final String representationProperty = THING_ELECTRICITY_METER_PROPERTY_ADCO; - DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withProperties(properties) - .withLabel("Teleinfo ADCO/ADSC " + adco).withThingType(getThingTypeUID(frameSample)) - .withBridge(controllerHandlerRef.getThing().getUID()) - .withRepresentationProperty(representationProperty).build(); - - thingDiscovered(discoveryResult); - } - } else { - logNullControllerHandler(); + logger.debug("New eletricity meter detection from frame {}", frameSample); + if (frameSample.get(Label.ADCO) == null && frameSample.get(Label.ADSC) == null) { + throw new IllegalStateException("Missing ADCO or ADSC key"); + } + + String adco = frameSample.get(Label.ADCO) != null ? frameSample.get(Label.ADCO) : frameSample.get(Label.ADSC); + if (adco != null) { + ThingUID thingUID = new ThingUID(getThingTypeUID(frameSample), adco, + thingHandler.getThing().getUID().getId()); + + final Map properties = getThingProperties(adco); + final String representationProperty = THING_ELECTRICITY_METER_PROPERTY_ADCO; + DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withProperties(properties) + .withLabel("Teleinfo ADCO/ADSC " + adco).withThingType(getThingTypeUID(frameSample)) + .withBridge(thingHandler.getThing().getUID()).withRepresentationProperty(representationProperty) + .build(); + + thingDiscovered(discoveryResult); } } @@ -184,20 +141,4 @@ private Map getThingProperties(String adco) { return properties; } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof TeleinfoAbstractControllerHandler teleinfoAbstractControllerHandler) { - controllerHandler = teleinfoAbstractControllerHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return controllerHandler; - } - - private void logNullControllerHandler() { - logger.warn("Null controller handler"); - } } diff --git a/bundles/org.openhab.binding.tesla/src/main/java/org/openhab/binding/tesla/internal/discovery/TeslaVehicleDiscoveryService.java b/bundles/org.openhab.binding.tesla/src/main/java/org/openhab/binding/tesla/internal/discovery/TeslaVehicleDiscoveryService.java index 2f575fdf64c89..74c10193e40e4 100644 --- a/bundles/org.openhab.binding.tesla/src/main/java/org/openhab/binding/tesla/internal/discovery/TeslaVehicleDiscoveryService.java +++ b/bundles/org.openhab.binding.tesla/src/main/java/org/openhab/binding/tesla/internal/discovery/TeslaVehicleDiscoveryService.java @@ -12,23 +12,20 @@ */ package org.openhab.binding.tesla.internal.discovery; -import java.util.Map; - +import org.eclipse.jdt.annotation.NonNull; import org.openhab.binding.tesla.internal.TeslaBindingConstants; import org.openhab.binding.tesla.internal.TeslaHandlerFactory; import org.openhab.binding.tesla.internal.handler.TeslaAccountHandler; import org.openhab.binding.tesla.internal.handler.VehicleListener; import org.openhab.binding.tesla.internal.protocol.Vehicle; import org.openhab.binding.tesla.internal.protocol.VehicleConfig; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,44 +36,30 @@ * @author Kai Kreuzer - Initial contribution * */ -@Component(service = ThingHandlerService.class) -public class TeslaVehicleDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, VehicleListener, ThingHandlerService { +@Component(scope = ServiceScope.PROTOTYPE, service = TeslaVehicleDiscoveryService.class) +public class TeslaVehicleDiscoveryService extends AbstractThingHandlerDiscoveryService<@NonNull TeslaAccountHandler> + implements VehicleListener { private final Logger logger = LoggerFactory.getLogger(TeslaVehicleDiscoveryService.class); public TeslaVehicleDiscoveryService() throws IllegalArgumentException { - super(TeslaHandlerFactory.SUPPORTED_THING_TYPES_UIDS, 10, true); - } - - private TeslaAccountHandler handler; - - @Override - public void setThingHandler(ThingHandler handler) { - this.handler = (TeslaAccountHandler) handler; - this.handler.addVehicleListener(this); + super(TeslaAccountHandler.class, TeslaHandlerFactory.SUPPORTED_THING_TYPES_UIDS, 10, true); } @Override - public ThingHandler getThingHandler() { - return handler; + public void initialize() { + thingHandler.addVehicleListener(this); + super.initialize(); } @Override protected void startScan() { - handler.scanForVehicles(); + thingHandler.scanForVehicles(); } @Override - public void activate(Map configProperties) { - super.activate(configProperties); - } - - @Override - public void deactivate() { - super.deactivate(); - if (handler != null) { - handler.removeVehicleListener(this); - } + public void dispose() { + super.dispose(); + thingHandler.removeVehicleListener(this); } @Override @@ -85,9 +68,9 @@ public void vehicleFound(Vehicle vehicle, VehicleConfig vehicleConfig) { : vehicleConfig.identifyModel(); if (type != null) { logger.debug("Found a {} vehicle", type.getId()); - ThingUID thingUID = new ThingUID(type, handler.getThing().getUID(), vehicle.vin); + ThingUID thingUID = new ThingUID(type, thingHandler.getThing().getUID(), vehicle.vin); DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withLabel(vehicle.display_name) - .withBridge(handler.getThing().getUID()).withProperty(TeslaBindingConstants.VIN, vehicle.vin) + .withBridge(thingHandler.getThing().getUID()).withProperty(TeslaBindingConstants.VIN, vehicle.vin) .build(); thingDiscovered(discoveryResult); } diff --git a/bundles/org.openhab.binding.touchwand/src/main/java/org/openhab/binding/touchwand/internal/discovery/TouchWandUnitDiscoveryService.java b/bundles/org.openhab.binding.touchwand/src/main/java/org/openhab/binding/touchwand/internal/discovery/TouchWandUnitDiscoveryService.java index b40e648878482..dd435fa6f336a 100644 --- a/bundles/org.openhab.binding.touchwand/src/main/java/org/openhab/binding/touchwand/internal/discovery/TouchWandUnitDiscoveryService.java +++ b/bundles/org.openhab.binding.touchwand/src/main/java/org/openhab/binding/touchwand/internal/discovery/TouchWandUnitDiscoveryService.java @@ -21,19 +21,18 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; -import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.touchwand.internal.TouchWandBridgeHandler; import org.openhab.binding.touchwand.internal.dto.TouchWandUnitData; import org.openhab.binding.touchwand.internal.dto.TouchWandUnitFromJson; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -47,32 +46,32 @@ * * @author Roie Geron - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = TouchWandUnitDiscoveryService.class) @NonNullByDefault -public class TouchWandUnitDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class TouchWandUnitDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int SEARCH_TIME_SEC = 10; private static final int SCAN_INTERVAL_SEC = 60; private static final int LINK_DISCOVERY_SERVICE_INITIAL_DELAY_SEC = 5; private static final String[] CONNECTIVITY_OPTIONS = { CONNECTIVITY_KNX, CONNECTIVITY_ZWAVE, CONNECTIVITY_RISCO, CONNECTIVITY_PIMA, CONNECTIVITY_ACWAND }; - private @NonNullByDefault({}) TouchWandBridgeHandler touchWandBridgeHandler; private final Logger logger = LoggerFactory.getLogger(TouchWandUnitDiscoveryService.class); private @Nullable ScheduledFuture scanningJob; public TouchWandUnitDiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME_SEC, true); + super(TouchWandBridgeHandler.class, SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME_SEC, true); } @Override protected void startScan() { - if (touchWandBridgeHandler.getThing().getStatus() != ThingStatus.ONLINE) { + if (thingHandler.getThing().getStatus() != ThingStatus.ONLINE) { logger.debug("Could not scan units while bridge offline"); return; } - logger.debug("Starting TouchWand discovery on bridge {}", touchWandBridgeHandler.getThing().getUID()); - String response = touchWandBridgeHandler.touchWandClient.cmdListUnits(); + logger.debug("Starting TouchWand discovery on bridge {}", thingHandler.getThing().getUID()); + String response = thingHandler.touchWandClient.cmdListUnits(); if (response.isEmpty()) { return; } @@ -85,7 +84,7 @@ protected void startScan() { TouchWandUnitData touchWandUnit; touchWandUnit = TouchWandUnitFromJson.parseResponse(unit.getAsJsonObject()); - if (!touchWandBridgeHandler.isAddSecondaryControllerUnits()) { + if (!thingHandler.isAddSecondaryControllerUnits()) { if (!Arrays.asList(CONNECTIVITY_OPTIONS).contains(touchWandUnit.getConnectivity())) { continue; } @@ -137,15 +136,15 @@ protected void stopScan() { } @Override - public void activate() { - super.activate(null); - removeOlderResults(new Date().getTime(), touchWandBridgeHandler.getThing().getUID()); + public void initialize() { + removeOlderResults(new Date().getTime(), thingHandler.getThing().getUID()); + super.initialize(); } @Override - public void deactivate() { - removeOlderResults(new Date().getTime(), touchWandBridgeHandler.getThing().getUID()); - super.deactivate(); + public void dispose() { + super.dispose(); + removeOlderResults(new Date().getTime(), thingHandler.getThing().getUID()); } @Override @@ -172,7 +171,7 @@ public int getScanTimeout() { } private void addDeviceDiscoveryResult(TouchWandUnitData unit, ThingTypeUID typeUID) { - ThingUID bridgeUID = touchWandBridgeHandler.getThing().getUID(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); ThingUID thingUID = new ThingUID(typeUID, bridgeUID, unit.getId().toString()); Map properties = new HashMap<>(); properties.put(HANDLER_PROPERTIES_ID, unit.getId().toString()); @@ -188,16 +187,4 @@ private void addDeviceDiscoveryResult(TouchWandUnitData unit, ThingTypeUID typeU ); // @formatter:on } - - @Override - public void setThingHandler(@NonNullByDefault({}) ThingHandler handler) { - if (handler instanceof TouchWandBridgeHandler touchWandBridgeHandler) { - this.touchWandBridgeHandler = touchWandBridgeHandler; - } - } - - @Override - public @NonNull ThingHandler getThingHandler() { - return touchWandBridgeHandler; - } } diff --git a/bundles/org.openhab.binding.tplinksmarthome/src/main/java/org/openhab/binding/tplinksmarthome/internal/handler/TPLinkSmartHomeActions.java b/bundles/org.openhab.binding.tplinksmarthome/src/main/java/org/openhab/binding/tplinksmarthome/internal/handler/TPLinkSmartHomeActions.java index f5fcad81b732d..45ba4b32000b9 100644 --- a/bundles/org.openhab.binding.tplinksmarthome/src/main/java/org/openhab/binding/tplinksmarthome/internal/handler/TPLinkSmartHomeActions.java +++ b/bundles/org.openhab.binding.tplinksmarthome/src/main/java/org/openhab/binding/tplinksmarthome/internal/handler/TPLinkSmartHomeActions.java @@ -23,6 +23,8 @@ import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,6 +33,7 @@ * * @author Hilbrand Bouwkamp - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = TPLinkSmartHomeActions.class) @ThingActionsScope(name = "tplinksmarthome") @NonNullByDefault public class TPLinkSmartHomeActions implements ThingActions, ThingHandlerService { diff --git a/bundles/org.openhab.binding.tr064/src/main/java/org/openhab/binding/tr064/internal/FritzboxActions.java b/bundles/org.openhab.binding.tr064/src/main/java/org/openhab/binding/tr064/internal/FritzboxActions.java index 4805506c4d183..37090da8aa713 100644 --- a/bundles/org.openhab.binding.tr064/src/main/java/org/openhab/binding/tr064/internal/FritzboxActions.java +++ b/bundles/org.openhab.binding.tr064/src/main/java/org/openhab/binding/tr064/internal/FritzboxActions.java @@ -41,6 +41,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -49,6 +51,7 @@ * * @author Jan N. Klug - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = FritzboxActions.class) @ThingActionsScope(name = "tr064") @NonNullByDefault public class FritzboxActions implements ThingActions { diff --git a/bundles/org.openhab.binding.tr064/src/main/java/org/openhab/binding/tr064/internal/Tr064DiscoveryService.java b/bundles/org.openhab.binding.tr064/src/main/java/org/openhab/binding/tr064/internal/Tr064DiscoveryService.java index 0b1d1bf1922e7..78d4aabaa6020 100644 --- a/bundles/org.openhab.binding.tr064/src/main/java/org/openhab/binding/tr064/internal/Tr064DiscoveryService.java +++ b/bundles/org.openhab.binding.tr064/src/main/java/org/openhab/binding/tr064/internal/Tr064DiscoveryService.java @@ -20,17 +20,15 @@ import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.tr064.internal.dto.scpd.root.SCPDDeviceType; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.BridgeHandler; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; import org.openhab.core.util.UIDUtils; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,38 +37,22 @@ * * @author Jan N. Klug - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = Tr064DiscoveryService.class) @NonNullByDefault -public class Tr064DiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class Tr064DiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int SEARCH_TIME = 5; public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_SUBDEVICE); private final Logger logger = LoggerFactory.getLogger(Tr064DiscoveryService.class); - private @Nullable Tr064RootHandler bridgeHandler; public Tr064DiscoveryService() { - super(SEARCH_TIME); + super(Tr064RootHandler.class, SEARCH_TIME); } @Override - public void setThingHandler(ThingHandler thingHandler) { - if (thingHandler instanceof Tr064RootHandler tr064RootHandler) { - this.bridgeHandler = tr064RootHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - - @Override - public void deactivate() { - BridgeHandler bridgeHandler = this.bridgeHandler; - if (bridgeHandler == null) { - logger.warn("Bridgehandler not found, could not cleanup discovery results."); - return; - } - removeOlderResults(new Date().getTime(), bridgeHandler.getThing().getUID()); + public void dispose() { + super.dispose(); + removeOlderResults(new Date().getTime(), thingHandler.getThing().getUID()); } @Override @@ -80,13 +62,8 @@ public Set getSupportedThingTypes() { @Override public void startScan() { - Tr064RootHandler bridgeHandler = this.bridgeHandler; - if (bridgeHandler == null) { - logger.warn("Could not start discovery, bridge handler not set"); - return; - } - List devices = bridgeHandler.getAllSubDevices(); - ThingUID bridgeUID = bridgeHandler.getThing().getUID(); + List devices = thingHandler.getAllSubDevices(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); devices.forEach(device -> { logger.trace("Trying to add {} to discovery results on {}", device, bridgeUID); String udn = device.getUDN(); diff --git a/bundles/org.openhab.binding.tradfri/src/main/java/org/openhab/binding/tradfri/internal/discovery/TradfriDiscoveryService.java b/bundles/org.openhab.binding.tradfri/src/main/java/org/openhab/binding/tradfri/internal/discovery/TradfriDiscoveryService.java index 89c20fe3d04cc..18d9881536e05 100644 --- a/bundles/org.openhab.binding.tradfri/src/main/java/org/openhab/binding/tradfri/internal/discovery/TradfriDiscoveryService.java +++ b/bundles/org.openhab.binding.tradfri/src/main/java/org/openhab/binding/tradfri/internal/discovery/TradfriDiscoveryService.java @@ -28,14 +28,13 @@ import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.tradfri.internal.DeviceUpdateListener; import org.openhab.binding.tradfri.internal.handler.TradfriGatewayHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -51,13 +50,12 @@ * @author Manuel Raffel - Added support for blinds * @author Vivien Boistuaud - Added support for Air Purifiers */ +@Component(scope = ServiceScope.PROTOTYPE, service = TradfriDiscoveryService.class) @NonNullByDefault -public class TradfriDiscoveryService extends AbstractDiscoveryService - implements DeviceUpdateListener, DiscoveryService, ThingHandlerService { +public class TradfriDiscoveryService extends AbstractThingHandlerDiscoveryService + implements DeviceUpdateListener { private final Logger logger = LoggerFactory.getLogger(TradfriDiscoveryService.class); - private @Nullable TradfriGatewayHandler handler; - private static final String REMOTE_CONTROLLER_MODEL = "TRADFRI remote control"; private static final Set COLOR_TEMP_MODELS = Collections @@ -70,12 +68,12 @@ public class TradfriDiscoveryService extends AbstractDiscoveryService private static final String[] COLOR_MODEL_IDENTIFIER_HINTS = new String[] { "CWS", " C/WS " }; public TradfriDiscoveryService() { - super(SUPPORTED_DEVICE_TYPES_UIDS, 10, true); + super(TradfriGatewayHandler.class, SUPPORTED_DEVICE_TYPES_UIDS, 10, true); } @Override protected void startScan() { - handler.startScan(); + thingHandler.startScan(); } @Override @@ -85,31 +83,21 @@ protected synchronized void stopScan() { } @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof TradfriGatewayHandler gatewayHandler) { - this.handler = gatewayHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return handler; - } - - @Override - public void activate() { - handler.registerDeviceUpdateListener(this); + public void initialize() { + thingHandler.registerDeviceUpdateListener(this); + super.initialize(); } @Override - public void deactivate() { + public void dispose() { + super.dispose(); removeOlderResults(new Date().getTime()); - handler.unregisterDeviceUpdateListener(this); + thingHandler.unregisterDeviceUpdateListener(this); } @Override public void onUpdate(@Nullable String instanceId, @Nullable JsonObject data) { - ThingUID bridge = handler.getThing().getUID(); + ThingUID bridge = thingHandler.getThing().getUID(); try { if (data != null && data.has(INSTANCE_ID)) { int id = data.get(INSTANCE_ID).getAsInt(); diff --git a/bundles/org.openhab.binding.unifi/src/main/java/org/openhab/binding/unifi/internal/action/UniFiSiteActions.java b/bundles/org.openhab.binding.unifi/src/main/java/org/openhab/binding/unifi/internal/action/UniFiSiteActions.java index 9ec4dc2f17dc2..64c8838f555a4 100644 --- a/bundles/org.openhab.binding.unifi/src/main/java/org/openhab/binding/unifi/internal/action/UniFiSiteActions.java +++ b/bundles/org.openhab.binding.unifi/src/main/java/org/openhab/binding/unifi/internal/action/UniFiSiteActions.java @@ -30,6 +30,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,6 +42,7 @@ * * @author Mark Herwege - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = UniFiSiteActions.class) @ThingActionsScope(name = "unifi") @NonNullByDefault public class UniFiSiteActions implements ThingActions { diff --git a/bundles/org.openhab.binding.unifi/src/main/java/org/openhab/binding/unifi/internal/handler/UniFiThingDiscoveryService.java b/bundles/org.openhab.binding.unifi/src/main/java/org/openhab/binding/unifi/internal/handler/UniFiThingDiscoveryService.java index f743c97a41f31..51cff7b931296 100644 --- a/bundles/org.openhab.binding.unifi/src/main/java/org/openhab/binding/unifi/internal/handler/UniFiThingDiscoveryService.java +++ b/bundles/org.openhab.binding.unifi/src/main/java/org/openhab/binding/unifi/internal/handler/UniFiThingDiscoveryService.java @@ -35,12 +35,11 @@ import org.openhab.binding.unifi.internal.api.dto.UniFiSite; import org.openhab.binding.unifi.internal.api.dto.UniFiSwitchPorts; import org.openhab.binding.unifi.internal.api.dto.UniFiWlan; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -49,9 +48,9 @@ * * @author Hilbrand Bouwkamp - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = UniFiThingDiscoveryService.class) @NonNullByDefault -public class UniFiThingDiscoveryService extends AbstractDiscoveryService - implements ThingHandlerService, DiscoveryService { +public class UniFiThingDiscoveryService extends AbstractThingHandlerDiscoveryService { /** * Timeout for discovery time. @@ -63,44 +62,22 @@ public class UniFiThingDiscoveryService extends AbstractDiscoveryService private final Logger logger = LoggerFactory.getLogger(UniFiThingDiscoveryService.class); - private @Nullable UniFiControllerThingHandler bridgeHandler; - public UniFiThingDiscoveryService() { - super(UniFiBindingConstants.THING_TYPE_SUPPORTED, UNIFI_DISCOVERY_TIMEOUT_SECONDS, false); - } - - @Override - public void deactivate() { - super.deactivate(); - } - - @Override - public void setThingHandler(final ThingHandler handler) { - if (handler instanceof UniFiControllerThingHandler controllerThingHandler) { - bridgeHandler = controllerThingHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; + super(UniFiControllerThingHandler.class, UniFiBindingConstants.THING_TYPE_SUPPORTED, + UNIFI_DISCOVERY_TIMEOUT_SECONDS, false); } @Override protected void startScan() { removeOlderResults(getTimestampOfLastScan()); - final UniFiControllerThingHandler bh = bridgeHandler; - if (bh == null) { - return; - } - final UniFiController controller = bh.getController(); + final UniFiController controller = thingHandler.getController(); if (controller == null) { return; } try { controller.refresh(); final UniFiControllerCache cache = controller.getCache(); - final ThingUID bridgeUID = bh.getThing().getUID(); + final ThingUID bridgeUID = thingHandler.getThing().getUID(); discoverSites(cache, bridgeUID); discoverWlans(cache, bridgeUID); diff --git a/bundles/org.openhab.binding.velbus/src/main/java/org/openhab/binding/velbus/internal/discovery/VelbusThingDiscoveryService.java b/bundles/org.openhab.binding.velbus/src/main/java/org/openhab/binding/velbus/internal/discovery/VelbusThingDiscoveryService.java index 677b49550ed9f..92b9cf5cbecb5 100644 --- a/bundles/org.openhab.binding.velbus/src/main/java/org/openhab/binding/velbus/internal/discovery/VelbusThingDiscoveryService.java +++ b/bundles/org.openhab.binding.velbus/src/main/java/org/openhab/binding/velbus/internal/discovery/VelbusThingDiscoveryService.java @@ -20,7 +20,6 @@ import java.util.Map; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.velbus.internal.VelbusChannelIdentifier; import org.openhab.binding.velbus.internal.VelbusFirstGenerationDeviceModuleAddress; import org.openhab.binding.velbus.internal.VelbusModule; @@ -29,12 +28,12 @@ import org.openhab.binding.velbus.internal.handler.VelbusBridgeHandler; import org.openhab.binding.velbus.internal.packets.VelbusPacket; import org.openhab.binding.velbus.internal.packets.VelbusScanPacket; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,29 +44,25 @@ * * @author Cedric Boon - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = VelbusThingDiscoveryService.class) @NonNullByDefault -public class VelbusThingDiscoveryService extends AbstractDiscoveryService - implements ThingHandlerService, VelbusPacketListener { +public class VelbusThingDiscoveryService extends AbstractThingHandlerDiscoveryService + implements VelbusPacketListener { private static final int SEARCH_TIME = 60; private final Logger logger = LoggerFactory.getLogger(VelbusThingDiscoveryService.class); private Map velbusModules = new HashMap<>(); - private @Nullable VelbusBridgeHandler velbusBridgeHandler; - public VelbusThingDiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME); + super(VelbusBridgeHandler.class, SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME); } @Override - public void deactivate() { + public void dispose() { + super.dispose(); removeOlderResults(new Date().getTime()); - - final VelbusBridgeHandler velbusBridgeHandler = this.velbusBridgeHandler; - if (velbusBridgeHandler != null) { - velbusBridgeHandler.clearDefaultPacketListener(); - } + thingHandler.clearDefaultPacketListener(); } @Override @@ -76,10 +71,7 @@ protected void startScan() { VelbusScanPacket packet = new VelbusScanPacket((byte) i); byte[] packetBytes = packet.getBytes(); - final VelbusBridgeHandler velbusBridgeHandler = this.velbusBridgeHandler; - if (velbusBridgeHandler != null) { - velbusBridgeHandler.sendPacket(packetBytes); - } + thingHandler.sendPacket(packetBytes); } } @@ -352,7 +344,7 @@ private void handleModuleSubtypeCommand(byte[] packet, byte address) { protected void registerVelbusModule(byte address, VelbusModule velbusModule) { velbusModules.put(address, velbusModule); notifyDiscoveredVelbusModule(velbusModule); - velbusModule.sendChannelNameRequests(velbusBridgeHandler); + velbusModule.sendChannelNameRequests(thingHandler); } private void handleChannelNameCommand(byte[] packet, byte address, byte length, int namePartNumber) { @@ -369,29 +361,18 @@ private void handleChannelNameCommand(byte[] packet, byte address, byte length, } private void notifyDiscoveredVelbusModule(VelbusModule velbusModule) { - final VelbusBridgeHandler velbusBridgeHandler = this.velbusBridgeHandler; - if (velbusBridgeHandler != null) { - ThingUID bridgeUID = velbusBridgeHandler.getThing().getUID(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); - DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(velbusModule.getThingUID(bridgeUID)) - .withThingType(velbusModule.getThingTypeUID()).withProperties(velbusModule.getProperties()) - .withRepresentationProperty(ADDRESS).withBridge(bridgeUID).withLabel(velbusModule.getLabel()) - .build(); + DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(velbusModule.getThingUID(bridgeUID)) + .withThingType(velbusModule.getThingTypeUID()).withProperties(velbusModule.getProperties()) + .withRepresentationProperty(ADDRESS).withBridge(bridgeUID).withLabel(velbusModule.getLabel()).build(); - thingDiscovered(discoveryResult); - } - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof VelbusBridgeHandler velbusBridgeHandler) { - this.velbusBridgeHandler = velbusBridgeHandler; - velbusBridgeHandler.setDefaultPacketListener(this); - } + thingDiscovered(discoveryResult); } @Override - public @Nullable ThingHandler getThingHandler() { - return this.velbusBridgeHandler; + public void initialize() { + thingHandler.setDefaultPacketListener(this); + super.initialize(); } } diff --git a/bundles/org.openhab.binding.velux/src/main/java/org/openhab/binding/velux/internal/action/VeluxActions.java b/bundles/org.openhab.binding.velux/src/main/java/org/openhab/binding/velux/internal/action/VeluxActions.java index f543405b333ce..3cbacdf8fcd11 100644 --- a/bundles/org.openhab.binding.velux/src/main/java/org/openhab/binding/velux/internal/action/VeluxActions.java +++ b/bundles/org.openhab.binding.velux/src/main/java/org/openhab/binding/velux/internal/action/VeluxActions.java @@ -23,6 +23,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,6 +33,7 @@ * * @author Andrew Fiddian-Green - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = VeluxActions.class) @ThingActionsScope(name = "velux") @NonNullByDefault public class VeluxActions implements ThingActions { diff --git a/bundles/org.openhab.binding.verisure/src/main/java/org/openhab/binding/verisure/internal/discovery/VerisureThingDiscoveryService.java b/bundles/org.openhab.binding.verisure/src/main/java/org/openhab/binding/verisure/internal/discovery/VerisureThingDiscoveryService.java index 77062e81bdef3..ca4e54a8a673f 100644 --- a/bundles/org.openhab.binding.verisure/src/main/java/org/openhab/binding/verisure/internal/discovery/VerisureThingDiscoveryService.java +++ b/bundles/org.openhab.binding.verisure/src/main/java/org/openhab/binding/verisure/internal/discovery/VerisureThingDiscoveryService.java @@ -22,13 +22,13 @@ import org.openhab.binding.verisure.internal.VerisureThingConfiguration; import org.openhab.binding.verisure.internal.dto.VerisureThingDTO; import org.openhab.binding.verisure.internal.handler.VerisureBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,33 +39,29 @@ * @author Jan Gustafsson - Further development * */ +@Component(scope = ServiceScope.PROTOTYPE, service = VerisureThingDiscoveryService.class) @NonNullByDefault -public class VerisureThingDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService { +public class VerisureThingDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int SEARCH_TIME_SECONDS = 60; private final Logger logger = LoggerFactory.getLogger(VerisureThingDiscoveryService.class); - - private @NonNullByDefault({}) VerisureBridgeHandler verisureBridgeHandler; private @NonNullByDefault({}) ThingUID bridgeUID; public VerisureThingDiscoveryService() { - super(VerisureHandlerFactory.SUPPORTED_THING_TYPES, SEARCH_TIME_SECONDS); + super(VerisureBridgeHandler.class, VerisureHandlerFactory.SUPPORTED_THING_TYPES, SEARCH_TIME_SECONDS); } @Override public void startScan() { logger.debug("VerisureThingDiscoveryService:startScan"); removeOlderResults(getTimestampOfLastScan()); - if (verisureBridgeHandler != null) { - VerisureSession session = verisureBridgeHandler.getSession(); - if (session != null) { - Collection verisureThings = session.getVerisureThings(); - verisureThings.stream().forEach(thing -> { - logger.debug("Discovered thing: {}", thing); - onThingAddedInternal(thing); - }); - } + VerisureSession session = thingHandler.getSession(); + if (session != null) { + Collection verisureThings = session.getVerisureThings(); + verisureThings.stream().forEach(thing -> { + logger.debug("Discovered thing: {}", thing); + onThingAddedInternal(thing); + }); } } @@ -74,21 +70,19 @@ private void onThingAddedInternal(VerisureThingDTO thing) { ThingUID thingUID = getThingUID(thing); String deviceId = thing.getDeviceId(); if (thingUID != null) { - if (verisureBridgeHandler != null) { - String className = thing.getClass().getSimpleName(); - String label = "Type: " + className + " Device Id: " + deviceId; - if (thing.getLocation() != null) { - label += ", Location: " + thing.getLocation(); - } - if (thing.getSiteName() != null) { - label += ", Site name: " + thing.getSiteName(); - } - DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withBridge(bridgeUID) - .withLabel(label).withProperty(VerisureThingConfiguration.DEVICE_ID_LABEL, deviceId) - .withRepresentationProperty(VerisureThingConfiguration.DEVICE_ID_LABEL).build(); - logger.debug("thinguid: {}, bridge {}, label {}", thingUID, bridgeUID, deviceId); - thingDiscovered(discoveryResult); + String className = thing.getClass().getSimpleName(); + String label = "Type: " + className + " Device Id: " + deviceId; + if (thing.getLocation() != null) { + label += ", Location: " + thing.getLocation(); + } + if (thing.getSiteName() != null) { + label += ", Site name: " + thing.getSiteName(); } + DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withBridge(bridgeUID) + .withLabel(label).withProperty(VerisureThingConfiguration.DEVICE_ID_LABEL, deviceId) + .withRepresentationProperty(VerisureThingConfiguration.DEVICE_ID_LABEL).build(); + logger.debug("thinguid: {}, bridge {}, label {}", thingUID, bridgeUID, deviceId); + thingDiscovered(discoveryResult); } else { logger.debug("Discovered unsupported thing of type '{}' with deviceId {}", thing.getClass(), deviceId); } @@ -96,12 +90,10 @@ private void onThingAddedInternal(VerisureThingDTO thing) { private @Nullable ThingUID getThingUID(VerisureThingDTO thing) { ThingUID thingUID = null; - if (verisureBridgeHandler != null) { - String deviceId = thing.getDeviceId(); - // Make sure device id is normalized, i.e. replace all non character/digits with empty string - deviceId = VerisureThingConfiguration.normalizeDeviceId(deviceId); - thingUID = new ThingUID(thing.getThingTypeUID(), bridgeUID, deviceId); - } + String deviceId = thing.getDeviceId(); + // Make sure device id is normalized, i.e. replace all non character/digits with empty string + deviceId = VerisureThingConfiguration.normalizeDeviceId(deviceId); + thingUID = new ThingUID(thing.getThingTypeUID(), bridgeUID, deviceId); return thingUID; } @@ -111,20 +103,8 @@ public void activate() { } @Override - public void deactivate() { - super.deactivate(); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof VerisureBridgeHandler verisureBridgeHandler) { - this.verisureBridgeHandler = verisureBridgeHandler; - bridgeUID = verisureBridgeHandler.getUID(); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return verisureBridgeHandler; + public void initialize() { + bridgeUID = thingHandler.getUID(); + super.initialize(); } } diff --git a/bundles/org.openhab.binding.vesync/src/main/java/org/openhab/binding/vesync/internal/discovery/VeSyncDiscoveryService.java b/bundles/org.openhab.binding.vesync/src/main/java/org/openhab/binding/vesync/internal/discovery/VeSyncDiscoveryService.java index f157abcdded9d..0bb8e36baf99c 100644 --- a/bundles/org.openhab.binding.vesync/src/main/java/org/openhab/binding/vesync/internal/discovery/VeSyncDiscoveryService.java +++ b/bundles/org.openhab.binding.vesync/src/main/java/org/openhab/binding/vesync/internal/discovery/VeSyncDiscoveryService.java @@ -19,20 +19,18 @@ import java.util.Set; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.vesync.internal.handlers.VeSyncBaseDeviceHandler; import org.openhab.binding.vesync.internal.handlers.VeSyncBridgeHandler; import org.openhab.binding.vesync.internal.handlers.VeSyncDeviceAirHumidifierHandler; import org.openhab.binding.vesync.internal.handlers.VeSyncDeviceAirPurifierHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * The {@link VeSyncDiscoveryService} is an implementation of a discovery service for VeSync devices. The meta-data is @@ -41,22 +39,20 @@ * @author David Godyear - Initial contribution */ @NonNullByDefault -@Component(service = DiscoveryService.class, immediate = true, configurationPid = "discovery.vesync") -public class VeSyncDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService, DeviceMetaDataUpdatedHandler { - +@Component(scope = ServiceScope.PROTOTYPE, service = VeSyncDiscoveryService.class, configurationPid = "discovery.vesync") +public class VeSyncDiscoveryService extends AbstractThingHandlerDiscoveryService + implements DeviceMetaDataUpdatedHandler { private static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BRIDGE); private static final int DISCOVER_TIMEOUT_SECONDS = 5; - private @NonNullByDefault({}) VeSyncBridgeHandler bridgeHandler; private @NonNullByDefault({}) ThingUID bridgeUID; /** * Creates a VeSyncDiscoveryService with enabled autostart. */ public VeSyncDiscoveryService() { - super(SUPPORTED_THING_TYPES, DISCOVER_TIMEOUT_SECONDS); + super(VeSyncBridgeHandler.class, SUPPORTED_THING_TYPES, DISCOVER_TIMEOUT_SECONDS); } @Override @@ -72,49 +68,33 @@ public void activate() { } @Override - public void deactivate() { - super.deactivate(); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof VeSyncBridgeHandler veSyncBridgeHandler) { - bridgeHandler = veSyncBridgeHandler; - bridgeUID = bridgeHandler.getUID(); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; + public void initialize() { + bridgeUID = thingHandler.getUID(); + super.initialize(); } @Override protected void startBackgroundDiscovery() { - if (bridgeHandler != null) { - bridgeHandler.registerMetaDataUpdatedHandler(this); - } + thingHandler.registerMetaDataUpdatedHandler(this); } @Override protected void stopBackgroundDiscovery() { - if (bridgeHandler != null) { - bridgeHandler.unregisterMetaDataUpdatedHandler(this); - } + thingHandler.unregisterMetaDataUpdatedHandler(this); } @Override protected void startScan() { // If the bridge is not online no other thing devices can be found, so no reason to scan at this moment. removeOlderResults(getTimestampOfLastScan()); - if (ThingStatus.ONLINE.equals(bridgeHandler.getThing().getStatus())) { - bridgeHandler.runDeviceScanSequenceNoAuthErrors(); + if (ThingStatus.ONLINE.equals(thingHandler.getThing().getStatus())) { + thingHandler.runDeviceScanSequenceNoAuthErrors(); } } @Override public void handleMetadataRetrieved(VeSyncBridgeHandler handler) { - bridgeHandler.getAirPurifiersMetadata().map(apMeta -> { + thingHandler.getAirPurifiersMetadata().map(apMeta -> { final Map properties = new HashMap<>(6); final String deviceUUID = apMeta.getUuid(); properties.put(DEVICE_PROP_DEVICE_NAME, apMeta.getDeviceName()); @@ -132,7 +112,7 @@ public void handleMetadataRetrieved(VeSyncBridgeHandler handler) { .withRepresentationProperty(DEVICE_PROP_DEVICE_MAC_ID).build(); }).forEach(this::thingDiscovered); - bridgeHandler.getAirHumidifiersMetadata().map(apMeta -> { + thingHandler.getAirHumidifiersMetadata().map(apMeta -> { final Map properties = new HashMap<>(6); final String deviceUUID = apMeta.getUuid(); properties.put(DEVICE_PROP_DEVICE_NAME, apMeta.getDeviceName()); diff --git a/bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/action/VolvoOnCallActions.java b/bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/action/VolvoOnCallActions.java index ad2bb46eeaa09..3d951fbed392f 100644 --- a/bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/action/VolvoOnCallActions.java +++ b/bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/action/VolvoOnCallActions.java @@ -23,6 +23,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -32,6 +34,7 @@ * * @author Gaël L'hopital - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = VolvoOnCallActions.class) @ThingActionsScope(name = "volvooncall") @NonNullByDefault public class VolvoOnCallActions implements ThingActions { diff --git a/bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/discovery/VolvoVehicleDiscoveryService.java b/bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/discovery/VolvoVehicleDiscoveryService.java index 190dfe23a584c..86b1fc4181072 100644 --- a/bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/discovery/VolvoVehicleDiscoveryService.java +++ b/bundles/org.openhab.binding.volvooncall/src/main/java/org/openhab/binding/volvooncall/internal/discovery/VolvoVehicleDiscoveryService.java @@ -26,11 +26,11 @@ import org.openhab.binding.volvooncall.internal.dto.CustomerAccounts; import org.openhab.binding.volvooncall.internal.dto.Vehicles; import org.openhab.binding.volvooncall.internal.handler.VolvoOnCallBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,26 +40,14 @@ * * @author Gaël L'hopital - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = VolvoVehicleDiscoveryService.class) @NonNullByDefault -public class VolvoVehicleDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class VolvoVehicleDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int SEARCH_TIME = 2; private final Logger logger = LoggerFactory.getLogger(VolvoVehicleDiscoveryService.class); - private @Nullable VolvoOnCallBridgeHandler handler; public VolvoVehicleDiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof VolvoOnCallBridgeHandler volvoOnCallBridgeHandler) { - this.handler = volvoOnCallBridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return handler; + super(VolvoOnCallBridgeHandler.class, SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME); } @Override @@ -74,37 +62,34 @@ public void deactivate() { @Override protected void startScan() { - VolvoOnCallBridgeHandler bridgeHandler = this.handler; - if (bridgeHandler != null) { - ThingUID bridgeUID = bridgeHandler.getThing().getUID(); - VocHttpApi api = bridgeHandler.getApi(); - if (api != null) { - try { - CustomerAccounts account = api.getURL("customeraccounts/", CustomerAccounts.class); - account.accountVehicleRelationsURL.forEach(relationURL -> { - try { - AccountVehicleRelation accountVehicle = api.getURL(relationURL, - AccountVehicleRelation.class); - logger.debug("Found vehicle : {}", accountVehicle.vehicleId); + ThingUID bridgeUID = thingHandler.getThing().getUID(); + VocHttpApi api = thingHandler.getApi(); + if (api != null) { + try { + CustomerAccounts account = api.getURL("customeraccounts/", CustomerAccounts.class); + account.accountVehicleRelationsURL.forEach(relationURL -> { + try { + AccountVehicleRelation accountVehicle = api.getURL(relationURL, AccountVehicleRelation.class); + logger.debug("Found vehicle : {}", accountVehicle.vehicleId); - Vehicles vehicle = api.getURL(accountVehicle.vehicleURL, Vehicles.class); - Attributes attributes = api.getURL(Attributes.class, vehicle.vehicleId); + Vehicles vehicle = api.getURL(accountVehicle.vehicleURL, Vehicles.class); + Attributes attributes = api.getURL(Attributes.class, vehicle.vehicleId); - thingDiscovered(DiscoveryResultBuilder - .create(new ThingUID(VEHICLE_THING_TYPE, bridgeUID, accountVehicle.vehicleId)) - .withLabel(attributes.vehicleType + " " + attributes.registrationNumber) - .withBridge(bridgeUID).withProperty(VehicleConfiguration.VIN, attributes.vin) - .withRepresentationProperty(VehicleConfiguration.VIN).build()); + thingDiscovered(DiscoveryResultBuilder + .create(new ThingUID(VEHICLE_THING_TYPE, bridgeUID, accountVehicle.vehicleId)) + .withLabel(attributes.vehicleType + " " + attributes.registrationNumber) + .withBridge(bridgeUID).withProperty(VehicleConfiguration.VIN, attributes.vin) + .withRepresentationProperty(VehicleConfiguration.VIN).build()); - } catch (VolvoOnCallException e) { - logger.warn("Error while getting vehicle informations : {}", e.getMessage()); - } - }); - } catch (VolvoOnCallException e) { - logger.warn("Error while discovering vehicle: {}", e.getMessage()); - } + } catch (VolvoOnCallException e) { + logger.warn("Error while getting vehicle informations : {}", e.getMessage()); + } + }); + } catch (VolvoOnCallException e) { + logger.warn("Error while discovering vehicle: {}", e.getMessage()); } } + stopScan(); } } diff --git a/bundles/org.openhab.binding.warmup/src/main/java/org/openhab/binding/warmup/internal/discovery/WarmupDiscoveryService.java b/bundles/org.openhab.binding.warmup/src/main/java/org/openhab/binding/warmup/internal/discovery/WarmupDiscoveryService.java index b43fa60b58e5e..d4777623c637d 100644 --- a/bundles/org.openhab.binding.warmup/src/main/java/org/openhab/binding/warmup/internal/discovery/WarmupDiscoveryService.java +++ b/bundles/org.openhab.binding.warmup/src/main/java/org/openhab/binding/warmup/internal/discovery/WarmupDiscoveryService.java @@ -25,28 +25,27 @@ import org.openhab.binding.warmup.internal.model.query.LocationDTO; import org.openhab.binding.warmup.internal.model.query.QueryResponseDTO; import org.openhab.binding.warmup.internal.model.query.RoomDTO; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * The {@link WarmupDiscoveryService} is used to discover devices that are connected to a My Warmup account. * * @author James Melville - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = WarmupDiscoveryService.class) @NonNullByDefault -public class WarmupDiscoveryService extends AbstractDiscoveryService - implements DiscoveryService, ThingHandlerService, WarmupRefreshListener { +public class WarmupDiscoveryService extends AbstractThingHandlerDiscoveryService + implements WarmupRefreshListener { - private @Nullable MyWarmupAccountHandler bridgeHandler; private @Nullable ThingUID bridgeUID; public WarmupDiscoveryService() { - super(DISCOVERABLE_THING_TYPES_UIDS, 5, false); + super(MyWarmupAccountHandler.class, DISCOVERABLE_THING_TYPES_UIDS, 5, false); } @Override @@ -55,11 +54,8 @@ public void deactivate() { @Override public void startScan() { - final MyWarmupAccountHandler handler = bridgeHandler; - if (handler != null) { - removeOlderResults(getTimestampOfLastScan()); - handler.setDiscoveryService(this); - } + removeOlderResults(getTimestampOfLastScan()); + thingHandler.setDiscoveryService(this); } /** @@ -100,20 +96,4 @@ private void discoverRoom(LocationDTO location, RoomDTO room, HashSet } } } - - @Override - public void setThingHandler(@Nullable final ThingHandler handler) { - if (handler instanceof MyWarmupAccountHandler accountHandler) { - bridgeHandler = accountHandler; - bridgeUID = handler.getThing().getUID(); - } else { - bridgeHandler = null; - bridgeUID = null; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } } diff --git a/bundles/org.openhab.binding.webexteams/src/main/java/org/openhab/binding/webexteams/internal/WebexTeamsActions.java b/bundles/org.openhab.binding.webexteams/src/main/java/org/openhab/binding/webexteams/internal/WebexTeamsActions.java index ac65950363448..feee6c1fe03dc 100644 --- a/bundles/org.openhab.binding.webexteams/src/main/java/org/openhab/binding/webexteams/internal/WebexTeamsActions.java +++ b/bundles/org.openhab.binding.webexteams/src/main/java/org/openhab/binding/webexteams/internal/WebexTeamsActions.java @@ -20,6 +20,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,6 +30,7 @@ * * @author Tom Deckers - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = WebexTeamsActions.class) @ThingActionsScope(name = "webexteams") @NonNullByDefault public class WebexTeamsActions implements ThingActions { diff --git a/bundles/org.openhab.binding.windcentrale/src/main/java/org/openhab/binding/windcentrale/internal/WindcentraleDiscoveryService.java b/bundles/org.openhab.binding.windcentrale/src/main/java/org/openhab/binding/windcentrale/internal/WindcentraleDiscoveryService.java index aceba18e25f3b..a8c939eda9fe7 100644 --- a/bundles/org.openhab.binding.windcentrale/src/main/java/org/openhab/binding/windcentrale/internal/WindcentraleDiscoveryService.java +++ b/bundles/org.openhab.binding.windcentrale/src/main/java/org/openhab/binding/windcentrale/internal/WindcentraleDiscoveryService.java @@ -32,14 +32,13 @@ import org.openhab.binding.windcentrale.internal.handler.WindcentraleAccountHandler; import org.openhab.binding.windcentrale.internal.handler.WindcentraleWindmillHandler; import org.openhab.binding.windcentrale.internal.listener.ThingStatusListener; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; -import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -49,39 +48,28 @@ * * @author Wouter Born - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = WindcentraleDiscoveryService.class) @NonNullByDefault -public class WindcentraleDiscoveryService extends AbstractDiscoveryService - implements ThingHandlerService, ThingStatusListener { - +public class WindcentraleDiscoveryService extends AbstractThingHandlerDiscoveryService + implements ThingStatusListener { private final Logger logger = LoggerFactory.getLogger(WindcentraleDiscoveryService.class); - private @NonNullByDefault({}) WindcentraleAccountHandler accountHandler; private @Nullable Future discoveryJob; public WindcentraleDiscoveryService() { - super(Set.of(THING_TYPE_WINDMILL), 10, false); - } - - protected void activate(ComponentContext context) { + super(WindcentraleAccountHandler.class, Set.of(THING_TYPE_WINDMILL), 10, false); } @Override - public void deactivate() { + public void dispose() { + super.dispose(); cancelDiscoveryJob(); - super.deactivate(); - accountHandler.removeThingStatusListener(this); + thingHandler.removeThingStatusListener(this); } @Override - public @Nullable ThingHandler getThingHandler() { - return accountHandler; - } - - @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof WindcentraleAccountHandler accountHandler) { - accountHandler.addThingStatusListener(this); - this.accountHandler = accountHandler; - } + public void initialize() { + thingHandler.addThingStatusListener(this); + super.initialize(); } @Override @@ -113,8 +101,8 @@ private void cancelDiscoveryJob() { } private void discoverWindmills() { - ThingUID bridgeUID = accountHandler.getThing().getUID(); - WindcentraleAPI api = accountHandler.getAPI(); + ThingUID bridgeUID = thingHandler.getThing().getUID(); + WindcentraleAPI api = thingHandler.getAPI(); if (api == null) { logger.debug("Cannot discover windmills because API is null for {}", bridgeUID); diff --git a/bundles/org.openhab.binding.wled/src/main/java/org/openhab/binding/wled/internal/WLedActions.java b/bundles/org.openhab.binding.wled/src/main/java/org/openhab/binding/wled/internal/WLedActions.java index d1f28681388ae..526724ba1543a 100644 --- a/bundles/org.openhab.binding.wled/src/main/java/org/openhab/binding/wled/internal/WLedActions.java +++ b/bundles/org.openhab.binding.wled/src/main/java/org/openhab/binding/wled/internal/WLedActions.java @@ -20,6 +20,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -29,6 +31,7 @@ * @author Matthew Skinner - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = WLedActions.class) @ThingActionsScope(name = "wled") @NonNullByDefault public class WLedActions implements ThingActions { diff --git a/bundles/org.openhab.binding.wled/src/main/java/org/openhab/binding/wled/internal/WLedSegmentDiscoveryService.java b/bundles/org.openhab.binding.wled/src/main/java/org/openhab/binding/wled/internal/WLedSegmentDiscoveryService.java index 85e4586cad1a1..bdabb0e5c292e 100644 --- a/bundles/org.openhab.binding.wled/src/main/java/org/openhab/binding/wled/internal/WLedSegmentDiscoveryService.java +++ b/bundles/org.openhab.binding.wled/src/main/java/org/openhab/binding/wled/internal/WLedSegmentDiscoveryService.java @@ -22,35 +22,36 @@ import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.wled.internal.api.WledApi; import org.openhab.binding.wled.internal.handlers.WLedBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.Thing; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * The {@link WLedSegmentDiscoveryService} Discovers and adds any Wled segments found by the bridge device. * * @author Matthew Skinner - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = WLedSegmentDiscoveryService.class) @NonNullByDefault -public class WLedSegmentDiscoveryService extends AbstractDiscoveryService +public class WLedSegmentDiscoveryService extends AbstractThingHandlerDiscoveryService implements DiscoveryService, ThingHandlerService { - private @Nullable WLedBridgeHandler bridgeHandler; private @Nullable ThingUID bridgeUID; private static final int SEARCH_TIME = 10; public WLedSegmentDiscoveryService() { - super(SUPPORTED_THING_TYPES, SEARCH_TIME); + super(WLedBridgeHandler.class, SUPPORTED_THING_TYPES, SEARCH_TIME); } public WLedSegmentDiscoveryService(Set supportedThingTypes, int timeout) throws IllegalArgumentException { - super(supportedThingTypes, timeout); + super(WLedBridgeHandler.class, supportedThingTypes, timeout); } private void buildThing(int segmentIndex, String segmentName) { @@ -70,32 +71,18 @@ private void buildThing(int segmentIndex, String segmentName) { @Override protected void startScan() { - WLedBridgeHandler localBridgeHandler = bridgeHandler; - if (localBridgeHandler != null) { - WledApi localAPI = localBridgeHandler.api; - if (localAPI != null) { - List names = localAPI.getSegmentNames(); - for (int count = 0; count < names.size(); count++) { - buildThing(count, names.get(count)); - } + WledApi localAPI = thingHandler.api; + if (localAPI != null) { + List names = localAPI.getSegmentNames(); + for (int count = 0; count < names.size(); count++) { + buildThing(count, names.get(count)); } } } @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof WLedBridgeHandler wLedBridgeHandler) { - bridgeHandler = wLedBridgeHandler; - bridgeUID = bridgeHandler.getThing().getUID(); - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - - @Override - public void deactivate() { + public void initialize() { + bridgeUID = thingHandler.getThing().getUID(); + super.initialize(); } } diff --git a/bundles/org.openhab.binding.wolfsmartset/src/main/java/org/openhab/binding/wolfsmartset/internal/discovery/WolfSmartsetAccountDiscoveryService.java b/bundles/org.openhab.binding.wolfsmartset/src/main/java/org/openhab/binding/wolfsmartset/internal/discovery/WolfSmartsetAccountDiscoveryService.java index 307894eae28e8..ccbe056bdabf5 100644 --- a/bundles/org.openhab.binding.wolfsmartset/src/main/java/org/openhab/binding/wolfsmartset/internal/discovery/WolfSmartsetAccountDiscoveryService.java +++ b/bundles/org.openhab.binding.wolfsmartset/src/main/java/org/openhab/binding/wolfsmartset/internal/discovery/WolfSmartsetAccountDiscoveryService.java @@ -24,14 +24,14 @@ import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.wolfsmartset.internal.dto.GetSystemListDTO; import org.openhab.binding.wolfsmartset.internal.handler.WolfSmartsetAccountBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,39 +41,17 @@ * * @author Bo Biene - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = WolfSmartsetAccountDiscoveryService.class) @NonNullByDefault -public class WolfSmartsetAccountDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class WolfSmartsetAccountDiscoveryService + extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(WolfSmartsetAccountDiscoveryService.class); - private @NonNullByDefault({}) WolfSmartsetAccountBridgeHandler bridgeHandler; - private @Nullable Future discoveryJob; public WolfSmartsetAccountDiscoveryService() { - super(SUPPORTED_SYSTEM_AND_UNIT_THING_TYPES_UIDS, 8, true); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof WolfSmartsetAccountBridgeHandler accountBridgeHandler) { - this.bridgeHandler = accountBridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - - @Override - public void activate() { - super.activate(null); - } - - @Override - public void deactivate() { - super.deactivate(); + super(WolfSmartsetAccountBridgeHandler.class, SUPPORTED_SYSTEM_AND_UNIT_THING_TYPES_UIDS, 8, true); } @Override @@ -109,14 +87,14 @@ public void startScan() { } private void backgroundDiscover() { - if (!bridgeHandler.isBackgroundDiscoveryEnabled()) { + if (!thingHandler.isBackgroundDiscoveryEnabled()) { return; } discover(); } private void discover() { - if (bridgeHandler.getThing().getStatus() != ThingStatus.ONLINE) { + if (thingHandler.getThing().getStatus() != ThingStatus.ONLINE) { logger.debug("WolfSmartsetDiscovery: Skipping discovery because Account Bridge thing is not ONLINE"); return; } @@ -126,7 +104,7 @@ private void discover() { private synchronized void discoverSystems() { logger.debug("WolfSmartsetDiscovery: Discovering systems"); - var registeredSytems = bridgeHandler.getRegisteredSystems(); + var registeredSytems = thingHandler.getRegisteredSystems(); if (registeredSytems != null) { for (GetSystemListDTO system : registeredSytems) { String name = system.getName(); @@ -135,7 +113,7 @@ private synchronized void discoverSystems() { identifier = system.getId().toString(); } if (identifier != null && name != null) { - ThingUID thingUID = new ThingUID(UID_SYSTEM_BRIDGE, bridgeHandler.getThing().getUID(), identifier); + ThingUID thingUID = new ThingUID(UID_SYSTEM_BRIDGE, thingHandler.getThing().getUID(), identifier); thingDiscovered(createSystemDiscoveryResult(thingUID, identifier, name)); logger.debug("WolfSmartsetDiscovery: System '{}' and name '{}' added with UID '{}'", identifier, name, thingUID); @@ -148,7 +126,7 @@ private DiscoveryResult createSystemDiscoveryResult(ThingUID systemUID, String i Map properties = new HashMap<>(); properties.put(CONFIG_SYSTEM_ID, identifier); return DiscoveryResultBuilder.create(systemUID).withProperties(properties) - .withRepresentationProperty(CONFIG_SYSTEM_ID).withBridge(bridgeHandler.getThing().getUID()) + .withRepresentationProperty(CONFIG_SYSTEM_ID).withBridge(thingHandler.getThing().getUID()) .withLabel(String.format("WolfSmartset System %s", name)).build(); } } diff --git a/bundles/org.openhab.binding.wolfsmartset/src/main/java/org/openhab/binding/wolfsmartset/internal/discovery/WolfSmartsetSystemDiscoveryService.java b/bundles/org.openhab.binding.wolfsmartset/src/main/java/org/openhab/binding/wolfsmartset/internal/discovery/WolfSmartsetSystemDiscoveryService.java index c9a5d90db4f4c..38195b898c253 100644 --- a/bundles/org.openhab.binding.wolfsmartset/src/main/java/org/openhab/binding/wolfsmartset/internal/discovery/WolfSmartsetSystemDiscoveryService.java +++ b/bundles/org.openhab.binding.wolfsmartset/src/main/java/org/openhab/binding/wolfsmartset/internal/discovery/WolfSmartsetSystemDiscoveryService.java @@ -25,14 +25,14 @@ import org.openhab.binding.wolfsmartset.internal.dto.GetSystemListDTO; import org.openhab.binding.wolfsmartset.internal.dto.SubMenuEntryWithMenuItemTabView; import org.openhab.binding.wolfsmartset.internal.handler.WolfSmartsetSystemBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,39 +42,17 @@ * * @author Bo Biene - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = WolfSmartsetSystemDiscoveryService.class) @NonNullByDefault -public class WolfSmartsetSystemDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class WolfSmartsetSystemDiscoveryService + extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(WolfSmartsetSystemDiscoveryService.class); - private @NonNullByDefault({}) WolfSmartsetSystemBridgeHandler bridgeHandler; - private @Nullable Future discoveryJob; public WolfSmartsetSystemDiscoveryService() { - super(SUPPORTED_SYSTEM_AND_UNIT_THING_TYPES_UIDS, 8, true); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof WolfSmartsetSystemBridgeHandler systemBridgeHandler) { - this.bridgeHandler = systemBridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; - } - - @Override - public void activate() { - super.activate(null); - } - - @Override - public void deactivate() { - super.deactivate(); + super(WolfSmartsetSystemBridgeHandler.class, SUPPORTED_SYSTEM_AND_UNIT_THING_TYPES_UIDS, 8, true); } @Override @@ -109,7 +87,7 @@ public void startScan() { } private void backgroundDiscover() { - var accountBridgeHandler = bridgeHandler.getAccountBridgeHandler(); + var accountBridgeHandler = thingHandler.getAccountBridgeHandler(); if (accountBridgeHandler == null || !accountBridgeHandler.isBackgroundDiscoveryEnabled()) { return; } @@ -117,7 +95,7 @@ private void backgroundDiscover() { } private void discover() { - if (bridgeHandler.getThing().getStatus() != ThingStatus.ONLINE) { + if (thingHandler.getThing().getStatus() != ThingStatus.ONLINE) { logger.debug("WolfSmartsetSystemDiscovery: Skipping discovery because Account Bridge thing is not ONLINE"); return; } @@ -126,21 +104,18 @@ private void discover() { } private synchronized void discoverUnits() { - if (this.bridgeHandler != null) { - String systemId = this.bridgeHandler.getSystemId(); - var systemConfig = this.bridgeHandler.getSystemConfig(); - if (systemConfig != null) { - logger.debug("WolfSmartsetSystemDiscovery: Discovering units for system '{}' (id {})", - systemConfig.getName(), systemId); - for (var unit : this.bridgeHandler.getUnits()) { - ThingUID bridgeUID = this.bridgeHandler.getThing().getUID(); - ThingUID unitUID = new ThingUID(UID_UNIT_THING, bridgeUID, - unit.menuItemTabViewDTO.bundleId.toString()); - thingDiscovered(createUnitDiscoveryResult(unitUID, bridgeUID, systemConfig, unit)); - logger.debug( - "WolfSmartsetSystemDiscovery: Unit for '{}' with id '{}' and name '{}' added with UID '{}'", - systemId, unit.menuItemTabViewDTO.bundleId, unit.menuItemTabViewDTO.tabName, unitUID); - } + String systemId = thingHandler.getSystemId(); + var systemConfig = thingHandler.getSystemConfig(); + if (systemConfig != null) { + logger.debug("WolfSmartsetSystemDiscovery: Discovering units for system '{}' (id {})", + systemConfig.getName(), systemId); + for (var unit : thingHandler.getUnits()) { + ThingUID bridgeUID = thingHandler.getThing().getUID(); + ThingUID unitUID = new ThingUID(UID_UNIT_THING, bridgeUID, unit.menuItemTabViewDTO.bundleId.toString()); + thingDiscovered(createUnitDiscoveryResult(unitUID, bridgeUID, systemConfig, unit)); + logger.debug( + "WolfSmartsetSystemDiscovery: Unit for '{}' with id '{}' and name '{}' added with UID '{}'", + systemId, unit.menuItemTabViewDTO.bundleId, unit.menuItemTabViewDTO.tabName, unitUID); } } } diff --git a/bundles/org.openhab.binding.x/src/main/java/org/openhab/binding/x/internal/action/XActions.java b/bundles/org.openhab.binding.x/src/main/java/org/openhab/binding/x/internal/action/XActions.java index 185cb08027bc0..9c0cb1d6e72f5 100644 --- a/bundles/org.openhab.binding.x/src/main/java/org/openhab/binding/x/internal/action/XActions.java +++ b/bundles/org.openhab.binding.x/src/main/java/org/openhab/binding/x/internal/action/XActions.java @@ -21,6 +21,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -29,6 +31,7 @@ * * @author Scott Hanson - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = XActions.class) @ThingActionsScope(name = "x") @NonNullByDefault public class XActions implements ThingActions { diff --git a/bundles/org.openhab.binding.xmltv/src/main/java/org/openhab/binding/xmltv/internal/discovery/XmlTVDiscoveryService.java b/bundles/org.openhab.binding.xmltv/src/main/java/org/openhab/binding/xmltv/internal/discovery/XmlTVDiscoveryService.java index e66ec738f3f9b..d973f7aa113b4 100644 --- a/bundles/org.openhab.binding.xmltv/src/main/java/org/openhab/binding/xmltv/internal/discovery/XmlTVDiscoveryService.java +++ b/bundles/org.openhab.binding.xmltv/src/main/java/org/openhab/binding/xmltv/internal/discovery/XmlTVDiscoveryService.java @@ -15,18 +15,16 @@ import static org.openhab.binding.xmltv.internal.XmlTVBindingConstants.*; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.xmltv.internal.configuration.XmlChannelConfiguration; import org.openhab.binding.xmltv.internal.handler.XmlTVHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -36,40 +34,33 @@ * * @author Gaël L'hopital - Initial contribution */ -@Component(service = ThingHandlerService.class) +@Component(scope = ServiceScope.PROTOTYPE, service = XmlTVDiscoveryService.class) @NonNullByDefault -public class XmlTVDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { +public class XmlTVDiscoveryService extends AbstractThingHandlerDiscoveryService { private static final int SEARCH_TIME = 5; private final Logger logger = LoggerFactory.getLogger(XmlTVDiscoveryService.class); - private @Nullable XmlTVHandler handler; /** * Creates a XmlTVDiscoveryService with background discovery disabled. */ @Activate public XmlTVDiscoveryService() { - super(SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME); - } - - @Override - public void deactivate() { - super.deactivate(); + super(XmlTVHandler.class, SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME); } @Override protected void startScan() { logger.debug("Starting XmlTV discovery scan"); - XmlTVHandler bridgeHandler = handler; - if (bridgeHandler != null && bridgeHandler.getThing().getStatus() == ThingStatus.ONLINE) { - bridgeHandler.getXmlFile().ifPresent(tv -> { + if (thingHandler.getThing().getStatus() == ThingStatus.ONLINE) { + thingHandler.getXmlFile().ifPresent(tv -> { tv.getMediaChannels().stream().forEach(channel -> { String channelId = channel.getId(); String uid = channelId.replaceAll("[^A-Za-z0-9_]", "_"); - ThingUID thingUID = new ThingUID(XMLTV_CHANNEL_THING_TYPE, bridgeHandler.getThing().getUID(), uid); + ThingUID thingUID = new ThingUID(XMLTV_CHANNEL_THING_TYPE, thingHandler.getThing().getUID(), uid); DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID) - .withBridge(bridgeHandler.getThing().getUID()) + .withBridge(thingHandler.getThing().getUID()) .withLabel(channel.getDisplayNames().get(0).getValue()).withRepresentationProperty(uid) .withProperty(XmlChannelConfiguration.CHANNEL_ID, channelId).build(); @@ -78,16 +69,4 @@ protected void startScan() { }); } } - - @Override - public void setThingHandler(ThingHandler handler) { - if (handler instanceof XmlTVHandler tvHandler) { - this.handler = tvHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return handler; - } } diff --git a/bundles/org.openhab.binding.xmppclient/src/main/java/org/openhab/binding/xmppclient/internal/action/XMPPActions.java b/bundles/org.openhab.binding.xmppclient/src/main/java/org/openhab/binding/xmppclient/internal/action/XMPPActions.java index 31fe78fadf249..9fac03a885914 100644 --- a/bundles/org.openhab.binding.xmppclient/src/main/java/org/openhab/binding/xmppclient/internal/action/XMPPActions.java +++ b/bundles/org.openhab.binding.xmppclient/src/main/java/org/openhab/binding/xmppclient/internal/action/XMPPActions.java @@ -21,6 +21,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -29,6 +31,7 @@ * * @author Pavel Gololobov - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = XMPPActions.class) @ThingActionsScope(name = "xmppclient") @NonNullByDefault public class XMPPActions implements ThingActions { diff --git a/bundles/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/ChannelsTypeProviderAvailableInputs.java b/bundles/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/ChannelsTypeProviderAvailableInputs.java index 1ef588acadc70..6255d3ce87296 100644 --- a/bundles/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/ChannelsTypeProviderAvailableInputs.java +++ b/bundles/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/ChannelsTypeProviderAvailableInputs.java @@ -34,6 +34,8 @@ import org.openhab.core.types.StateDescriptionFragment; import org.openhab.core.types.StateDescriptionFragmentBuilder; import org.openhab.core.types.StateOption; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * Provide a custom channel type for available inputs @@ -41,6 +43,8 @@ * @author David Graeff - Initial contribution * @author Tomasz Maruszak - Refactoring the input source names. */ +@Component(scope = ServiceScope.PROTOTYPE, service = { ChannelsTypeProviderAvailableInputs.class, + ChannelTypeProvider.class }) @NonNullByDefault public class ChannelsTypeProviderAvailableInputs implements ChannelTypeProvider, ThingHandlerService { private @NonNullByDefault({}) ChannelType channelType; diff --git a/bundles/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/ChannelsTypeProviderPreset.java b/bundles/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/ChannelsTypeProviderPreset.java index 92df31bc31198..e49939016e414 100644 --- a/bundles/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/ChannelsTypeProviderPreset.java +++ b/bundles/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/ChannelsTypeProviderPreset.java @@ -34,6 +34,8 @@ import org.openhab.core.types.StateDescriptionFragment; import org.openhab.core.types.StateDescriptionFragmentBuilder; import org.openhab.core.types.StateOption; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * Provide a custom channel type for the preset channel @@ -41,6 +43,7 @@ * @author David Graeff - Initial contribution * @author Tomasz Maruszak - RX-V3900 compatibility improvements */ +@Component(scope = ServiceScope.PROTOTYPE, service = { ChannelsTypeProviderPreset.class, ChannelTypeProvider.class }) @NonNullByDefault public class ChannelsTypeProviderPreset implements ChannelTypeProvider, ThingHandlerService { private @NonNullByDefault({}) ChannelType channelType; diff --git a/bundles/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/discovery/ZoneDiscoveryService.java b/bundles/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/discovery/ZoneDiscoveryService.java index 44edd256cea90..c8e1a3383b5c3 100644 --- a/bundles/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/discovery/ZoneDiscoveryService.java +++ b/bundles/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/discovery/ZoneDiscoveryService.java @@ -21,17 +21,15 @@ import java.util.Map; import org.eclipse.jdt.annotation.NonNullByDefault; -import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.yamahareceiver.internal.YamahaReceiverBindingConstants.Zone; import org.openhab.binding.yamahareceiver.internal.handler.YamahaBridgeHandler; import org.openhab.binding.yamahareceiver.internal.state.DeviceInformationState; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * After the AVR bridge thing has been added and a connection could be established, @@ -40,10 +38,9 @@ * @author David Gräff - Initial contribution * @author Tomasz Maruszak - Introduced config object */ +@Component(scope = ServiceScope.PROTOTYPE, service = ZoneDiscoveryService.class) @NonNullByDefault -public class ZoneDiscoveryService extends AbstractDiscoveryService implements DiscoveryService, ThingHandlerService { - - private @Nullable YamahaBridgeHandler handler; +public class ZoneDiscoveryService extends AbstractThingHandlerDiscoveryService { /** * Constructs a zone discovery service. @@ -51,17 +48,7 @@ public class ZoneDiscoveryService extends AbstractDiscoveryService implements Di * Call {@link ZoneDiscoveryService#destroy()} to unregister the service after use. */ public ZoneDiscoveryService() { - super(ZONE_THING_TYPES_UIDS, 0, false); - } - - @Override - public void activate() { - super.activate(null); - } - - @Override - public void deactivate() { - super.deactivate(); + super(YamahaBridgeHandler.class, ZONE_THING_TYPES_UIDS, 0, false); } @Override @@ -100,15 +87,8 @@ public void publishZones(DeviceInformationState state, ThingUID bridgeUid) { } @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof YamahaBridgeHandler bridgeHandler) { - bridgeHandler.setZoneDiscoveryService(this); - this.handler = bridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return handler; + public void initialize() { + thingHandler.setZoneDiscoveryService(this); + super.initialize(); } } diff --git a/bundles/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/handler/YamahaZoneThingHandler.java b/bundles/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/handler/YamahaZoneThingHandler.java index b5ae4c76ab1f6..192883f7c7a20 100644 --- a/bundles/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/handler/YamahaZoneThingHandler.java +++ b/bundles/org.openhab.binding.yamahareceiver/src/main/java/org/openhab/binding/yamahareceiver/internal/handler/YamahaZoneThingHandler.java @@ -18,11 +18,9 @@ import java.io.IOException; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.stream.Collectors; -import java.util.stream.Stream; import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.binding.yamahareceiver.internal.ChannelsTypeProviderAvailableInputs; @@ -124,9 +122,7 @@ public YamahaZoneThingHandler(Thing thing) { @Override public Collection> getServices() { - return Collections - .unmodifiableList(Stream.of(ChannelsTypeProviderAvailableInputs.class, ChannelsTypeProviderPreset.class) - .collect(Collectors.toList())); + return List.of(ChannelsTypeProviderAvailableInputs.class, ChannelsTypeProviderPreset.class); } /** diff --git a/bundles/org.openhab.binding.yioremote/src/main/java/org/openhab/binding/yioremote/internal/YIOremoteDockActions.java b/bundles/org.openhab.binding.yioremote/src/main/java/org/openhab/binding/yioremote/internal/YIOremoteDockActions.java index 355f5c8e53c39..512cdac591b3e 100644 --- a/bundles/org.openhab.binding.yioremote/src/main/java/org/openhab/binding/yioremote/internal/YIOremoteDockActions.java +++ b/bundles/org.openhab.binding.yioremote/src/main/java/org/openhab/binding/yioremote/internal/YIOremoteDockActions.java @@ -19,6 +19,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; /** * The {@link YIOremoteDockActions} is responsible for handling the action commands @@ -26,6 +28,7 @@ * * @author Michael Loercher - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = YIOremoteDockActions.class) @ThingActionsScope(name = "yioremote") @NonNullByDefault public class YIOremoteDockActions implements ThingActions { diff --git a/bundles/org.openhab.binding.zoneminder/src/main/java/org/openhab/binding/zoneminder/internal/action/ZmActions.java b/bundles/org.openhab.binding.zoneminder/src/main/java/org/openhab/binding/zoneminder/internal/action/ZmActions.java index 8c41537ab2b5b..08fe4d59ccccc 100644 --- a/bundles/org.openhab.binding.zoneminder/src/main/java/org/openhab/binding/zoneminder/internal/action/ZmActions.java +++ b/bundles/org.openhab.binding.zoneminder/src/main/java/org/openhab/binding/zoneminder/internal/action/ZmActions.java @@ -20,6 +20,8 @@ import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingHandler; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,6 +30,7 @@ * * @author Mark Hilbush - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = ZmActions.class) @ThingActionsScope(name = "zoneminder") @NonNullByDefault public class ZmActions implements ThingActions { diff --git a/bundles/org.openhab.binding.zoneminder/src/main/java/org/openhab/binding/zoneminder/internal/discovery/MonitorDiscoveryService.java b/bundles/org.openhab.binding.zoneminder/src/main/java/org/openhab/binding/zoneminder/internal/discovery/MonitorDiscoveryService.java index edfb640c312b4..6316eecb8ef55 100644 --- a/bundles/org.openhab.binding.zoneminder/src/main/java/org/openhab/binding/zoneminder/internal/discovery/MonitorDiscoveryService.java +++ b/bundles/org.openhab.binding.zoneminder/src/main/java/org/openhab/binding/zoneminder/internal/discovery/MonitorDiscoveryService.java @@ -24,14 +24,13 @@ import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.zoneminder.internal.handler.Monitor; import org.openhab.binding.zoneminder.internal.handler.ZmBridgeHandler; -import org.openhab.core.config.discovery.AbstractDiscoveryService; +import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService; import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResultBuilder; -import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingUID; -import org.openhab.core.thing.binding.ThingHandler; -import org.openhab.core.thing.binding.ThingHandlerService; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,8 +40,9 @@ * * @author Mark Hilbush - Initial contribution */ +@Component(scope = ServiceScope.PROTOTYPE, service = MonitorDiscoveryService.class) @NonNullByDefault -public class MonitorDiscoveryService extends AbstractDiscoveryService implements DiscoveryService, ThingHandlerService { +public class MonitorDiscoveryService extends AbstractThingHandlerDiscoveryService { private final Logger logger = LoggerFactory.getLogger(MonitorDiscoveryService.class); @@ -50,34 +50,10 @@ public class MonitorDiscoveryService extends AbstractDiscoveryService implements private static final int DISCOVERY_INITIAL_DELAY_SECONDS = 10; private static final int DISCOVERY_TIMEOUT_SECONDS = 6; - private @NonNullByDefault({}) ZmBridgeHandler bridgeHandler; - private @Nullable Future discoveryJob; public MonitorDiscoveryService() { - super(SUPPORTED_MONITOR_THING_TYPES_UIDS, DISCOVERY_TIMEOUT_SECONDS, true); - } - - @Override - public void activate() { - super.activate(null); - } - - @Override - public void deactivate() { - super.deactivate(); - } - - @Override - public void setThingHandler(@Nullable ThingHandler handler) { - if (handler instanceof ZmBridgeHandler zmBridgeHandler) { - bridgeHandler = zmBridgeHandler; - } - } - - @Override - public @Nullable ThingHandler getThingHandler() { - return bridgeHandler; + super(ZmBridgeHandler.class, SUPPORTED_MONITOR_THING_TYPES_UIDS, DISCOVERY_TIMEOUT_SECONDS, true); } @Override @@ -112,7 +88,7 @@ public void startScan() { } private void backgroundDiscoverMonitors() { - if (!bridgeHandler.isBackgroundDiscoveryEnabled()) { + if (!thingHandler.isBackgroundDiscoveryEnabled()) { return; } logger.debug("ZoneminderDiscovery: Running background discovery scan"); @@ -120,10 +96,10 @@ private void backgroundDiscoverMonitors() { } private synchronized void discoverMonitors() { - ThingUID bridgeUID = bridgeHandler.getThing().getUID(); - Integer alarmDuration = bridgeHandler.getDefaultAlarmDuration(); - Integer imageRefreshInterval = bridgeHandler.getDefaultImageRefreshInterval(); - for (Monitor monitor : bridgeHandler.getSavedMonitors()) { + ThingUID bridgeUID = thingHandler.getThing().getUID(); + Integer alarmDuration = thingHandler.getDefaultAlarmDuration(); + Integer imageRefreshInterval = thingHandler.getDefaultImageRefreshInterval(); + for (Monitor monitor : thingHandler.getSavedMonitors()) { String id = monitor.getId(); String name = monitor.getName(); ThingUID thingUID = new ThingUID(UID_MONITOR, bridgeUID, monitor.getId());