Adapt to core changes (ThingHandlerService) (#16107)

Related to: https://github.com/openhab/openhab-core/pull/3957

Signed-off-by: Jan N. Klug <github@klug.nrw>
Signed-off-by: Ciprian Pascu <contact@ciprianpascu.ro>
This commit is contained in:
J-N-K 2024-01-03 11:50:55 +01:00 committed by Ciprian Pascu
parent 52b1ad95d6
commit fc8fa6d119
188 changed files with 2280 additions and 4143 deletions

View File

@ -64,7 +64,6 @@ public class AirQualityHandlerFactory extends BaseThingHandlerFactory {
return THING_TYPE_STATION.equals(thingTypeUID) return THING_TYPE_STATION.equals(thingTypeUID)
? new AirQualityStationHandler(thing, timeZoneProvider, locationProvider) ? new AirQualityStationHandler(thing, timeZoneProvider, locationProvider)
: BRIDGE_TYPE_API.equals(thingTypeUID) ? new AirQualityBridgeHandler((Bridge) thing, locationProvider) : BRIDGE_TYPE_API.equals(thingTypeUID) ? new AirQualityBridgeHandler((Bridge) thing) : null;
: null;
} }
} }

View File

@ -18,18 +18,18 @@ import static org.openhab.binding.airquality.internal.config.AirQualityConfigura
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.airquality.internal.handler.AirQualityBridgeHandler; 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.DiscoveryResultBuilder;
import org.openhab.core.config.discovery.DiscoveryService;
import org.openhab.core.i18n.LocationProvider; import org.openhab.core.i18n.LocationProvider;
import org.openhab.core.library.types.PointType; import org.openhab.core.library.types.PointType;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.thing.binding.ThingHandlerService; 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.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -38,40 +38,28 @@ import org.slf4j.LoggerFactory;
* *
* @author Gaël L'hopital - Initial Contribution * @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 @NonNullByDefault
public class AirQualityDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { public class AirQualityDiscoveryService extends AbstractThingHandlerDiscoveryService<AirQualityBridgeHandler>
implements ThingHandlerService {
private static final int DISCOVER_TIMEOUT_SECONDS = 2; private static final int DISCOVER_TIMEOUT_SECONDS = 2;
private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_STATION); private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_STATION);
private final Logger logger = LoggerFactory.getLogger(AirQualityDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(AirQualityDiscoveryService.class);
private @Nullable LocationProvider locationProvider; private @NonNullByDefault({}) LocationProvider locationProvider;
private @Nullable AirQualityBridgeHandler bridgeHandler;
/** /**
* Creates an AirQualityDiscoveryService with enabled autostart. * Creates an AirQualityDiscoveryService with enabled autostart.
*/ */
@Activate
public AirQualityDiscoveryService() { public AirQualityDiscoveryService() {
super(SUPPORTED_THING_TYPES_UIDS, DISCOVER_TIMEOUT_SECONDS, false); super(AirQualityBridgeHandler.class, SUPPORTED_THING_TYPES_UIDS, DISCOVER_TIMEOUT_SECONDS, false);
} }
@Override @Reference(unbind = "-")
public void setThingHandler(@Nullable ThingHandler handler) { public void bindLocationProvider(LocationProvider locationProvider) {
if (handler instanceof AirQualityBridgeHandler bridgeHandlerInstance) { this.locationProvider = locationProvider;
this.bridgeHandler = bridgeHandlerInstance;
this.locationProvider = bridgeHandler.getLocationProvider();
}
}
@Override
public @Nullable ThingHandler getThingHandler() {
return bridgeHandler;
}
@Override
public void deactivate() {
super.deactivate();
} }
@Override @Override
@ -80,7 +68,7 @@ public class AirQualityDiscoveryService extends AbstractDiscoveryService impleme
LocationProvider provider = locationProvider; LocationProvider provider = locationProvider;
if (provider != null) { if (provider != null) {
PointType location = provider.getLocation(); PointType location = provider.getLocation();
AirQualityBridgeHandler bridge = this.bridgeHandler; AirQualityBridgeHandler bridge = this.thingHandler;
if (location == null || bridge == null) { if (location == null || bridge == null) {
logger.info("openHAB server location is not defined, will not provide any discovery results"); logger.info("openHAB server location is not defined, will not provide any discovery results");
return; return;

View File

@ -19,7 +19,6 @@ import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.airquality.internal.api.ApiBridge; import org.openhab.binding.airquality.internal.api.ApiBridge;
import org.openhab.binding.airquality.internal.discovery.AirQualityDiscoveryService; 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.Bridge;
import org.openhab.core.thing.ChannelUID; import org.openhab.core.thing.ChannelUID;
import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatus;
@ -36,12 +35,10 @@ import org.openhab.core.types.Command;
*/ */
@NonNullByDefault @NonNullByDefault
public class AirQualityBridgeHandler extends BaseBridgeHandler { public class AirQualityBridgeHandler extends BaseBridgeHandler {
private final LocationProvider locationProvider;
private @Nullable ApiBridge apiBridge; private @Nullable ApiBridge apiBridge;
public AirQualityBridgeHandler(Bridge bridge, LocationProvider locationProvider) { public AirQualityBridgeHandler(Bridge bridge) {
super(bridge); super(bridge);
this.locationProvider = locationProvider;
} }
@Override @Override
@ -69,8 +66,4 @@ public class AirQualityBridgeHandler extends BaseBridgeHandler {
public Collection<Class<? extends ThingHandlerService>> getServices() { public Collection<Class<? extends ThingHandlerService>> getServices() {
return Set.of(AirQualityDiscoveryService.class); return Set.of(AirQualityDiscoveryService.class);
} }
public LocationProvider getLocationProvider() {
return locationProvider;
}
} }

View File

@ -20,6 +20,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -28,6 +30,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Bob Adair - Initial contribution * @author Bob Adair - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = BridgeActions.class)
@ThingActionsScope(name = "alarmdecoder") @ThingActionsScope(name = "alarmdecoder")
@NonNullByDefault @NonNullByDefault
public class BridgeActions implements ThingActions { public class BridgeActions implements ThingActions {

View File

@ -24,8 +24,11 @@ import org.openhab.core.thing.binding.BaseDynamicStateDescriptionProvider;
import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.thing.binding.ThingHandlerService; import org.openhab.core.thing.binding.ThingHandlerService;
import org.openhab.core.thing.type.ChannelTypeUID; 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.StateDescription;
import org.openhab.core.types.StateOption; 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. * This class provides the list of valid inputs for the input channel of a source.
@ -33,6 +36,8 @@ import org.openhab.core.types.StateOption;
* @author Kai Kreuzer - Initial contribution * @author Kai Kreuzer - Initial contribution
* *
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = { DynamicStateDescriptionProvider.class,
InputStateOptionProvider.class })
@NonNullByDefault @NonNullByDefault
public class InputStateOptionProvider extends BaseDynamicStateDescriptionProvider implements ThingHandlerService { public class InputStateOptionProvider extends BaseDynamicStateDescriptionProvider implements ThingHandlerService {

View File

@ -24,8 +24,11 @@ import org.openhab.core.thing.binding.BaseDynamicCommandDescriptionProvider;
import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.thing.binding.ThingHandlerService; import org.openhab.core.thing.binding.ThingHandlerService;
import org.openhab.core.thing.type.ChannelTypeUID; 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.CommandDescription;
import org.openhab.core.types.CommandOption; 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. * This class provides the list of valid commands for the preset channel.
@ -33,6 +36,8 @@ import org.openhab.core.types.CommandOption;
* @author Kai Kreuzer - Initial contribution * @author Kai Kreuzer - Initial contribution
* *
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = { PresetCommandOptionProvider.class,
DynamicCommandDescriptionProvider.class })
@NonNullByDefault @NonNullByDefault
public class PresetCommandOptionProvider extends BaseDynamicCommandDescriptionProvider implements ThingHandlerService { public class PresetCommandOptionProvider extends BaseDynamicCommandDescriptionProvider implements ThingHandlerService {

View File

@ -30,6 +30,8 @@ import org.openhab.core.audio.UnsupportedAudioStreamException;
import org.openhab.core.library.types.PercentType; import org.openhab.core.library.types.PercentType;
import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.thing.binding.ThingHandlerService; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -39,6 +41,7 @@ import org.slf4j.LoggerFactory;
* @author Kai Kreuzer - Initial contribution * @author Kai Kreuzer - Initial contribution
* *
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = PAAudioSink.class)
@NonNullByDefault @NonNullByDefault
public class PAAudioSink extends AudioSinkSync implements ThingHandlerService { public class PAAudioSink extends AudioSinkSync implements ThingHandlerService {

View File

@ -16,19 +16,18 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; 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.AmpliPiBindingConstants;
import org.openhab.binding.amplipi.internal.AmpliPiHandler; import org.openhab.binding.amplipi.internal.AmpliPiHandler;
import org.openhab.binding.amplipi.internal.AmpliPiStatusChangeListener; import org.openhab.binding.amplipi.internal.AmpliPiStatusChangeListener;
import org.openhab.binding.amplipi.internal.model.Group; import org.openhab.binding.amplipi.internal.model.Group;
import org.openhab.binding.amplipi.internal.model.Status; import org.openhab.binding.amplipi.internal.model.Status;
import org.openhab.binding.amplipi.internal.model.Zone; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
/** /**
* This class discoveres the available zones and groups of the AmpliPi system. * This class discoveres the available zones and groups of the AmpliPi system.
@ -36,30 +35,26 @@ import org.openhab.core.thing.binding.ThingHandlerService;
* @author Kai Kreuzer - Initial contribution * @author Kai Kreuzer - Initial contribution
* *
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = AmpliPiZoneAndGroupDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class AmpliPiZoneAndGroupDiscoveryService extends AbstractDiscoveryService public class AmpliPiZoneAndGroupDiscoveryService extends AbstractThingHandlerDiscoveryService<AmpliPiHandler>
implements ThingHandlerService, AmpliPiStatusChangeListener { implements AmpliPiStatusChangeListener {
private static final int TIMEOUT = 10; private static final int TIMEOUT = 10;
private @Nullable AmpliPiHandler handler;
private List<Zone> zones = List.of(); private List<Zone> zones = List.of();
private List<Group> groups = List.of(); private List<Group> groups = List.of();
public AmpliPiZoneAndGroupDiscoveryService() throws IllegalArgumentException { 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 @Override
public void setThingHandler(ThingHandler handler) { public void initialize() {
AmpliPiHandler ampliPiHander = (AmpliPiHandler) handler; thingHandler.addStatusChangeListener(this);
ampliPiHander.addStatusChangeListener(this); super.initialize();
this.handler = ampliPiHander;
}
@Override
public @Nullable ThingHandler getThingHandler() {
return handler;
} }
@Override @Override
@ -75,33 +70,27 @@ public class AmpliPiZoneAndGroupDiscoveryService extends AbstractDiscoveryServic
} }
private void createZone(Zone z) { private void createZone(Zone z) {
if (handler != null) { ThingUID bridgeUID = thingHandler.getThing().getUID();
ThingUID bridgeUID = handler.getThing().getUID(); ThingUID uid = new ThingUID(AmpliPiBindingConstants.THING_TYPE_ZONE, bridgeUID, z.getId().toString());
ThingUID uid = new ThingUID(AmpliPiBindingConstants.THING_TYPE_ZONE, bridgeUID, z.getId().toString()); DiscoveryResult result = DiscoveryResultBuilder.create(uid).withLabel("AmpliPi Zone '" + z.getName() + "'")
DiscoveryResult result = DiscoveryResultBuilder.create(uid).withLabel("AmpliPi Zone '" + z.getName() + "'") .withProperty(AmpliPiBindingConstants.CFG_PARAM_ID, z.getId()).withBridge(bridgeUID)
.withProperty(AmpliPiBindingConstants.CFG_PARAM_ID, z.getId()).withBridge(bridgeUID) .withRepresentationProperty(AmpliPiBindingConstants.CFG_PARAM_ID).build();
.withRepresentationProperty(AmpliPiBindingConstants.CFG_PARAM_ID).build(); thingDiscovered(result);
thingDiscovered(result);
}
} }
private void createGroup(Group g) { private void createGroup(Group g) {
if (handler != null) { ThingUID bridgeUID = thingHandler.getThing().getUID();
ThingUID bridgeUID = handler.getThing().getUID(); ThingUID uid = new ThingUID(AmpliPiBindingConstants.THING_TYPE_GROUP, bridgeUID, g.getId().toString());
ThingUID uid = new ThingUID(AmpliPiBindingConstants.THING_TYPE_GROUP, bridgeUID, g.getId().toString()); DiscoveryResult result = DiscoveryResultBuilder.create(uid).withLabel("AmpliPi Group '" + g.getName() + "'")
DiscoveryResult result = DiscoveryResultBuilder.create(uid).withLabel("AmpliPi Group '" + g.getName() + "'") .withProperty(AmpliPiBindingConstants.CFG_PARAM_ID, g.getId()).withBridge(bridgeUID)
.withProperty(AmpliPiBindingConstants.CFG_PARAM_ID, g.getId()).withBridge(bridgeUID) .withRepresentationProperty(AmpliPiBindingConstants.CFG_PARAM_ID).build();
.withRepresentationProperty(AmpliPiBindingConstants.CFG_PARAM_ID).build(); thingDiscovered(result);
thingDiscovered(result);
}
} }
@Override @Override
public void deactivate() { public void dispose() {
if (handler != null) { super.dispose();
handler.removeStatusChangeListener(this); thingHandler.removeStatusChangeListener(this);
}
super.deactivate();
} }
@Override @Override

View File

@ -31,6 +31,8 @@ import org.openhab.core.library.types.QuantityType;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -39,6 +41,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Gaël L'hopital - Initial contribution * @author Gaël L'hopital - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = AstroActions.class)
@ThingActionsScope(name = "astro") @ThingActionsScope(name = "astro")
@NonNullByDefault @NonNullByDefault
public class AstroActions implements ThingActions { public class AstroActions implements ThingActions {

View File

@ -21,19 +21,19 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault; 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.AsuswrtClientInfo;
import org.openhab.binding.asuswrt.internal.structures.AsuswrtClientList; import org.openhab.binding.asuswrt.internal.structures.AsuswrtClientList;
import org.openhab.binding.asuswrt.internal.structures.AsuswrtInterfaceList; import org.openhab.binding.asuswrt.internal.structures.AsuswrtInterfaceList;
import org.openhab.binding.asuswrt.internal.structures.AsuswrtIpInfo; import org.openhab.binding.asuswrt.internal.structures.AsuswrtIpInfo;
import org.openhab.binding.asuswrt.internal.things.AsuswrtRouter; import org.openhab.binding.asuswrt.internal.things.AsuswrtRouter;
import org.openhab.core.config.discovery.AbstractDiscoveryService; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -42,38 +42,27 @@ import org.slf4j.LoggerFactory;
* *
* @author Christian Wild - Initial contribution * @author Christian Wild - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = AbstractDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class AsuswrtDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { public class AsuswrtDiscoveryService extends AbstractThingHandlerDiscoveryService<AsuswrtRouter> {
private final Logger logger = LoggerFactory.getLogger(AsuswrtDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(AsuswrtDiscoveryService.class);
private String uid = ""; private String uid = "";
protected @NonNullByDefault({}) AsuswrtRouter router;
public AsuswrtDiscoveryService() { public AsuswrtDiscoveryService() {
super(SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIMEOUT_S, false); super(AsuswrtRouter.class, SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIMEOUT_S, false);
} }
@Override @Override
public void activate() { public void dispose() {
} super.dispose();
@Override
public void deactivate() {
super.deactivate();
removeAllResults(); removeAllResults();
} }
@Override @Override
public void setThingHandler(@Nullable ThingHandler handler) { public void initialize() {
if (handler instanceof AsuswrtRouter router) { thingHandler.setDiscoveryService(this);
router.setDiscoveryService(this); uid = thingHandler.getThing().getUID().getAsString();
this.router = router; super.initialize();
this.uid = router.getUID().getAsString();
}
}
@Override
public @Nullable ThingHandler getThingHandler() {
return this.router;
} }
/* /*
@ -86,16 +75,14 @@ public class AsuswrtDiscoveryService extends AbstractDiscoveryService implements
@Override @Override
public void startScan() { public void startScan() {
logger.trace("{} starting scan", uid); logger.trace("{} starting scan", uid);
if (router != null) { /* query Data */
/* query Data */ thingHandler.queryDeviceData(false);
router.queryDeviceData(false); /* discover interfaces */
/* discover interfaces */ AsuswrtInterfaceList ifList = thingHandler.getInterfaces();
AsuswrtInterfaceList ifList = router.getInterfaces(); handleInterfaceScan(ifList);
handleInterfaceScan(ifList); /* discover clients */
/* discover clients */ AsuswrtClientList clientList = thingHandler.getClients();
AsuswrtClientList clientList = router.getClients(); handleClientScan(clientList);
handleClientScan(clientList);
}
} }
@Override @Override
@ -156,17 +143,12 @@ public class AsuswrtDiscoveryService extends AbstractDiscoveryService implements
properties.put(Thing.PROPERTY_MAC_ADDRESS, macAddress); properties.put(Thing.PROPERTY_MAC_ADDRESS, macAddress);
logger.debug("{} thing discovered: '{}", uid, label); logger.debug("{} thing discovered: '{}", uid, label);
if (this.router != null) {
ThingUID bridgeUID = router.getUID(); ThingUID bridgeUID = thingHandler.getUID();
ThingUID thingUID = new ThingUID(THING_TYPE_INTERFACE, bridgeUID, ifName); ThingUID thingUID = new ThingUID(THING_TYPE_INTERFACE, bridgeUID, ifName);
return DiscoveryResultBuilder.create(thingUID).withProperties(properties) return DiscoveryResultBuilder.create(thingUID).withProperties(properties)
.withRepresentationProperty(NETWORK_REPRESENTATION_PROPERTY).withBridge(bridgeUID).withLabel(label) .withRepresentationProperty(NETWORK_REPRESENTATION_PROPERTY).withBridge(bridgeUID).withLabel(label)
.build(); .build();
} else {
ThingUID thingUID = new ThingUID(BINDING_ID, ifName);
return DiscoveryResultBuilder.create(thingUID).withProperties(properties)
.withRepresentationProperty(NETWORK_REPRESENTATION_PROPERTY).withLabel(label).build();
}
} }
/** /**
@ -196,17 +178,10 @@ public class AsuswrtDiscoveryService extends AbstractDiscoveryService implements
properties.put(CHANNEL_CLIENT_NICKNAME, nickName); properties.put(CHANNEL_CLIENT_NICKNAME, nickName);
logger.debug("{} thing discovered: '{}", uid, label); logger.debug("{} thing discovered: '{}", uid, label);
if (this.router != null) { ThingUID bridgeUID = thingHandler.getUID();
ThingUID bridgeUID = router.getUID(); ThingUID thingUID = new ThingUID(THING_TYPE_CLIENT, bridgeUID, unformatedMac);
ThingUID thingUID = new ThingUID(THING_TYPE_CLIENT, bridgeUID, unformatedMac); return DiscoveryResultBuilder.create(thingUID).withProperties(properties)
return DiscoveryResultBuilder.create(thingUID).withProperties(properties) .withRepresentationProperty(CLIENT_REPRESENTATION_PROPERTY).withTTL(DISCOVERY_AUTOREMOVE_S)
.withRepresentationProperty(CLIENT_REPRESENTATION_PROPERTY).withTTL(DISCOVERY_AUTOREMOVE_S) .withBridge(bridgeUID).withLabel(label).build();
.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();
}
} }
} }

View File

@ -21,12 +21,15 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* @author Markus Pfleger - Initial contribution * @author Markus Pfleger - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = AutomowerActions.class)
@ThingActionsScope(name = "automower") @ThingActionsScope(name = "automower")
@NonNullByDefault @NonNullByDefault
public class AutomowerActions implements ThingActions { public class AutomowerActions implements ThingActions {

View File

@ -22,19 +22,18 @@ import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNullByDefault; 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.AVMFritzBaseModel;
import org.openhab.binding.avmfritz.internal.dto.GroupModel; import org.openhab.binding.avmfritz.internal.dto.GroupModel;
import org.openhab.binding.avmfritz.internal.handler.AVMFritzBaseBridgeHandler; import org.openhab.binding.avmfritz.internal.handler.AVMFritzBaseBridgeHandler;
import org.openhab.binding.avmfritz.internal.hardware.FritzAhaStatusListener; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.config.discovery.DiscoveryService;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -44,66 +43,50 @@ import org.slf4j.LoggerFactory;
* @author Robert Bausdorf - Initial contribution * @author Robert Bausdorf - Initial contribution
* @author Christoph Weitkamp - Added support for groups * @author Christoph Weitkamp - Added support for groups
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = AVMFritzDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class AVMFritzDiscoveryService extends AbstractDiscoveryService public class AVMFritzDiscoveryService extends AbstractThingHandlerDiscoveryService<AVMFritzBaseBridgeHandler>
implements FritzAhaStatusListener, DiscoveryService, ThingHandlerService { implements FritzAhaStatusListener, DiscoveryService {
private final Logger logger = LoggerFactory.getLogger(AVMFritzDiscoveryService.class); 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() { public AVMFritzDiscoveryService() {
super(Stream super(AVMFritzBaseBridgeHandler.class, Stream
.of(SUPPORTED_LIGHTING_THING_TYPES, SUPPORTED_BUTTON_THING_TYPES_UIDS, SUPPORTED_HEATING_THING_TYPES, .of(SUPPORTED_LIGHTING_THING_TYPES, SUPPORTED_BUTTON_THING_TYPES_UIDS, SUPPORTED_HEATING_THING_TYPES,
SUPPORTED_DEVICE_THING_TYPES_UIDS, SUPPORTED_GROUP_THING_TYPES_UIDS) SUPPORTED_DEVICE_THING_TYPES_UIDS, SUPPORTED_GROUP_THING_TYPES_UIDS)
.flatMap(Set::stream).collect(Collectors.toUnmodifiableSet()), 30); .flatMap(Set::stream).collect(Collectors.toUnmodifiableSet()), 30);
} }
@Override @Override
public void activate() { public void initialize() {
super.activate(null); thingHandler.registerStatusListener(this);
bridgeHandler.registerStatusListener(this); super.initialize();
} }
@Override @Override
public void deactivate() { public void dispose() {
bridgeHandler.unregisterStatusListener(this); super.dispose();
super.deactivate(); thingHandler.unregisterStatusListener(this);
} }
@Override @Override
public void startScan() { public void startScan() {
logger.debug("Start manual scan on bridge {}", bridgeHandler.getThing().getUID()); logger.debug("Start manual scan on bridge {}", thingHandler.getThing().getUID());
bridgeHandler.handleRefreshCommand(); thingHandler.handleRefreshCommand();
} }
@Override @Override
protected synchronized void stopScan() { 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(); super.stopScan();
} }
@Override
public void setThingHandler(@NonNullByDefault({}) ThingHandler handler) {
if (handler instanceof AVMFritzBaseBridgeHandler baseBridgeHandler) {
bridgeHandler = baseBridgeHandler;
}
}
@Override
public @Nullable ThingHandler getThingHandler() {
return bridgeHandler;
}
@Override @Override
public void onDeviceAdded(AVMFritzBaseModel device) { 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); ThingTypeUID thingTypeUID = id.isEmpty() ? null : new ThingTypeUID(BINDING_ID, id);
if (thingTypeUID != null && getSupportedThingTypes().contains(thingTypeUID)) { if (thingTypeUID != null && getSupportedThingTypes().contains(thingTypeUID)) {
ThingUID thingUID = new ThingUID(thingTypeUID, bridgeHandler.getThing().getUID(), ThingUID thingUID = new ThingUID(thingTypeUID, thingHandler.getThing().getUID(),
bridgeHandler.getThingName(device)); thingHandler.getThingName(device));
onDeviceAddedInternal(thingUID, device); onDeviceAddedInternal(thingUID, device);
} else { } else {
logger.debug("Discovered unsupported device: {}", device); logger.debug("Discovered unsupported device: {}", device);
@ -134,7 +117,7 @@ public class AVMFritzDiscoveryService extends AbstractDiscoveryService
} }
DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withProperties(properties) 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(); .withLabel(device.getName()).build();
thingDiscovered(discoveryResult); thingDiscovered(discoveryResult);

View File

@ -24,12 +24,12 @@ import org.openhab.binding.bondhome.internal.BondException;
import org.openhab.binding.bondhome.internal.api.BondDevice; import org.openhab.binding.bondhome.internal.api.BondDevice;
import org.openhab.binding.bondhome.internal.api.BondHttpApi; import org.openhab.binding.bondhome.internal.api.BondHttpApi;
import org.openhab.binding.bondhome.internal.handler.BondBridgeHandler; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -38,36 +38,24 @@ import org.slf4j.LoggerFactory;
* *
* @author Sara Geleskie Damiano - Initial contribution * @author Sara Geleskie Damiano - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = BondDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class BondDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { public class BondDiscoveryService extends AbstractThingHandlerDiscoveryService<BondBridgeHandler> {
private static final long REFRESH_INTERVAL_MINUTES = 60; private static final long REFRESH_INTERVAL_MINUTES = 60;
private final Logger logger = LoggerFactory.getLogger(BondDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(BondDiscoveryService.class);
private @Nullable ScheduledFuture<?> discoveryJob; private @Nullable ScheduledFuture<?> discoveryJob;
private @Nullable BondBridgeHandler bridgeHandler;
private @Nullable BondHttpApi api; private @Nullable BondHttpApi api;
public BondDiscoveryService() { public BondDiscoveryService() {
super(SUPPORTED_THING_TYPES, 10); super(BondBridgeHandler.class, SUPPORTED_THING_TYPES, 10);
this.discoveryJob = null; this.discoveryJob = null;
} }
@Override @Override
public void deactivate() { public void initialize() {
super.deactivate(); thingHandler.setDiscoveryService(this);
} api = thingHandler.getBridgeAPI();
super.initialize();
@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;
} }
@Override @Override
@ -87,6 +75,7 @@ public class BondDiscoveryService extends AbstractDiscoveryService implements Th
protected synchronized void startScan() { protected synchronized void startScan() {
logger.debug("Start scan for Bond devices."); logger.debug("Start scan for Bond devices.");
try { try {
BondBridgeHandler bridgeHandler = thingHandler;
final ThingUID bridgeUid = bridgeHandler.getThing().getUID(); final ThingUID bridgeUid = bridgeHandler.getThing().getUID();
api = bridgeHandler.getBridgeAPI(); api = bridgeHandler.getBridgeAPI();
List<String> deviceList = api.getDevices(); List<String> deviceList = api.getDevices();

View File

@ -19,19 +19,18 @@ import java.util.Collection;
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; 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.IndegoTypeDatabase;
import org.openhab.binding.boschindego.internal.dto.response.DevicePropertiesResponse; import org.openhab.binding.boschindego.internal.dto.response.DevicePropertiesResponse;
import org.openhab.binding.boschindego.internal.exceptions.IndegoException; import org.openhab.binding.boschindego.internal.exceptions.IndegoException;
import org.openhab.binding.boschindego.internal.handler.BoschAccountHandler; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -40,29 +39,15 @@ import org.slf4j.LoggerFactory;
* *
* @author Jacob Laursen - Initial contribution * @author Jacob Laursen - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = IndegoDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class IndegoDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { public class IndegoDiscoveryService extends AbstractThingHandlerDiscoveryService<BoschAccountHandler> {
private static final int TIMEOUT_SECONDS = 60; private static final int TIMEOUT_SECONDS = 60;
private final Logger logger = LoggerFactory.getLogger(IndegoDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(IndegoDiscoveryService.class);
private @NonNullByDefault({}) BoschAccountHandler accountHandler;
public IndegoDiscoveryService() { public IndegoDiscoveryService() {
super(Set.of(THING_TYPE_ACCOUNT), TIMEOUT_SECONDS, false); super(BoschAccountHandler.class, 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;
}
} }
@Override @Override
@ -73,9 +58,9 @@ public class IndegoDiscoveryService extends AbstractDiscoveryService implements
@Override @Override
public void startScan() { public void startScan() {
try { try {
Collection<DevicePropertiesResponse> devices = accountHandler.getDevices(); Collection<DevicePropertiesResponse> devices = thingHandler.getDevices();
ThingUID bridgeUID = accountHandler.getThing().getUID(); ThingUID bridgeUID = thingHandler.getThing().getUID();
for (DevicePropertiesResponse device : devices) { for (DevicePropertiesResponse device : devices) {
ThingUID thingUID = new ThingUID(THING_TYPE_INDEGO, bridgeUID, device.serialNumber); ThingUID thingUID = new ThingUID(THING_TYPE_INDEGO, bridgeUID, device.serialNumber);
DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID) DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID)
@ -97,7 +82,8 @@ public class IndegoDiscoveryService extends AbstractDiscoveryService implements
} }
@Override @Override
public void deactivate() { public void dispose() {
super.dispose();
removeOlderResults(Instant.now().getEpochSecond()); removeOlderResults(Instant.now().getEpochSecond());
} }
} }

View File

@ -25,12 +25,13 @@ import org.openhab.binding.boschshc.internal.devices.bridge.BridgeHandler;
import org.openhab.binding.boschshc.internal.devices.bridge.dto.Device; 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.Room;
import org.openhab.binding.boschshc.internal.devices.bridge.dto.UserDefinedState; 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.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.thing.binding.ThingHandlerService; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -48,12 +49,12 @@ import org.slf4j.LoggerFactory;
* *
* @author Gerd Zanker - Initial contribution * @author Gerd Zanker - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = ThingHandlerService.class)
@NonNullByDefault @NonNullByDefault
public class ThingDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { public class ThingDiscoveryService extends AbstractThingHandlerDiscoveryService<BridgeHandler> {
private static final int SEARCH_TIME = 1; private static final int SEARCH_TIME = 1;
private final Logger logger = LoggerFactory.getLogger(ThingDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(ThingDiscoveryService.class);
private @Nullable BridgeHandler shcBridgeHandler;
protected static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of( protected static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(
BoschSHCBindingConstants.THING_TYPE_INWALL_SWITCH, BoschSHCBindingConstants.THING_TYPE_TWINGUARD, BoschSHCBindingConstants.THING_TYPE_INWALL_SWITCH, BoschSHCBindingConstants.THING_TYPE_TWINGUARD,
@ -97,37 +98,28 @@ public class ThingDiscoveryService extends AbstractDiscoveryService implements T
// @formatter:on // @formatter:on
public ThingDiscoveryService() { public ThingDiscoveryService() {
super(SUPPORTED_THING_TYPES, SEARCH_TIME); super(BridgeHandler.class, SUPPORTED_THING_TYPES, SEARCH_TIME);
} }
@Override @Override
public void activate() { public void initialize() {
logger.trace("activate"); logger.trace("initialize");
final BridgeHandler handler = shcBridgeHandler; thingHandler.registerDiscoveryListener(this);
if (handler != null) { super.initialize();
handler.registerDiscoveryListener(this);
}
} }
@Override @Override
public void deactivate() { public void dispose() {
logger.trace("deactivate"); super.dispose();
final BridgeHandler handler = shcBridgeHandler; logger.trace("dispose");
if (handler != null) { removeOlderResults(new Date().getTime(), thingHandler.getThing().getUID());
removeOlderResults(new Date().getTime(), handler.getThing().getUID()); thingHandler.unregisterDiscoveryListener();
handler.unregisterDiscoveryListener();
}
super.deactivate(); super.deactivate();
} }
@Override @Override
protected void startScan() { protected void startScan() {
if (shcBridgeHandler == null) {
logger.debug("The shcBridgeHandler is empty, no manual scan is currently possible");
return;
}
try { try {
doScan(); doScan();
} catch (InterruptedException e) { } catch (InterruptedException e) {
@ -138,36 +130,19 @@ public class ThingDiscoveryService extends AbstractDiscoveryService implements T
@Override @Override
protected synchronized void stopScan() { protected synchronized void stopScan() {
logger.debug("Stop manual scan on bridge {}", logger.debug("Stop manual scan on bridge {}", thingHandler.getThing().getUID());
shcBridgeHandler != null ? shcBridgeHandler.getThing().getUID() : "?");
super.stopScan(); super.stopScan();
final BridgeHandler handler = shcBridgeHandler; removeOlderResults(getTimestampOfLastScan(), thingHandler.getThing().getUID());
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;
} }
public void doScan() throws InterruptedException { 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() // use shcBridgeHandler to getDevices()
List<Room> rooms = shcBridgeHandler.getRooms(); List<Room> rooms = thingHandler.getRooms();
logger.debug("SHC has {} rooms", rooms.size()); logger.debug("SHC has {} rooms", rooms.size());
List<Device> devices = shcBridgeHandler.getDevices(); List<Device> devices = thingHandler.getDevices();
logger.debug("SHC has {} devices", devices.size()); logger.debug("SHC has {} devices", devices.size());
List<UserDefinedState> userStates = shcBridgeHandler.getUserStates(); List<UserDefinedState> userStates = thingHandler.getUserStates();
logger.debug("SHC has {} user-defined states", userStates.size()); logger.debug("SHC has {} user-defined states", userStates.size());
// Write found devices into openhab.log to support manual configuration // Write found devices into openhab.log to support manual configuration
@ -195,9 +170,6 @@ public class ThingDiscoveryService extends AbstractDiscoveryService implements T
} }
private void addUserState(UserDefinedState userState) { 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("Discovering user-defined state {}", userState.getName());
logger.trace("- details: id {}, state {}", userState.getId(), userState.isState()); logger.trace("- details: id {}, state {}", userState.getId(), userState.isState());
@ -206,7 +178,7 @@ public class ThingDiscoveryService extends AbstractDiscoveryService implements T
logger.trace("- got thingTypeID '{}' for user-defined state '{}'", thingTypeUID.getId(), userState.getName()); 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(':', '_')); userState.getId().replace(':', '_'));
logger.trace("- got thingUID '{}' for user-defined state: '{}'", thingUID, userState); logger.trace("- got thingUID '{}' for user-defined state: '{}'", thingUID, userState);
@ -214,7 +186,7 @@ public class ThingDiscoveryService extends AbstractDiscoveryService implements T
DiscoveryResultBuilder discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID) DiscoveryResultBuilder discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID)
.withProperty("id", userState.getId()).withLabel(userState.getName()); .withProperty("id", userState.getId()).withLabel(userState.getName());
discoveryResult.withBridge(shcBridgeHandler.getThing().getUID()); discoveryResult.withBridge(thingHandler.getThing().getUID());
thingDiscovered(discoveryResult.build()); thingDiscovered(discoveryResult.build());
@ -234,8 +206,6 @@ public class ThingDiscoveryService extends AbstractDiscoveryService implements T
protected void addDevice(Device device, String roomName) { protected void addDevice(Device device, String roomName) {
// see startScan for the runtime null check of shcBridgeHandler // see startScan for the runtime null check of shcBridgeHandler
assert shcBridgeHandler != null;
logger.trace("Discovering device {}", device.name); logger.trace("Discovering device {}", device.name);
logger.trace("- details: id {}, roomId {}, deviceModel {}", device.id, device.roomId, device.deviceModel); logger.trace("- details: id {}, roomId {}, deviceModel {}", device.id, device.roomId, device.deviceModel);
@ -246,16 +216,13 @@ public class ThingDiscoveryService extends AbstractDiscoveryService implements T
logger.trace("- got thingTypeID '{}' for deviceModel '{}'", thingTypeUID.getId(), device.deviceModel); logger.trace("- got thingTypeID '{}' for deviceModel '{}'", thingTypeUID.getId(), device.deviceModel);
ThingUID thingUID = new ThingUID(thingTypeUID, shcBridgeHandler.getThing().getUID(), ThingUID thingUID = new ThingUID(thingTypeUID, thingHandler.getThing().getUID(), device.id.replace(':', '_'));
device.id.replace(':', '_'));
logger.trace("- got thingUID '{}' for device: '{}'", thingUID, device); logger.trace("- got thingUID '{}' for device: '{}'", thingUID, device);
DiscoveryResultBuilder discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID) DiscoveryResultBuilder discoveryResult = DiscoveryResultBuilder.create(thingUID).withThingType(thingTypeUID)
.withProperty("id", device.id).withLabel(getNiceName(device.name, roomName)); .withProperty("id", device.id).withLabel(getNiceName(device.name, roomName));
if (null != shcBridgeHandler) { discoveryResult.withBridge(thingHandler.getThing().getUID());
discoveryResult.withBridge(shcBridgeHandler.getThing().getUID());
}
if (!roomName.isEmpty()) { if (!roomName.isEmpty()) {
discoveryResult.withProperty("Location", roomName); discoveryResult.withProperty("Location", roomName);
} }

View File

@ -24,14 +24,14 @@ import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.bticinosmarther.internal.account.SmartherAccountHandler; 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.Location;
import org.openhab.binding.bticinosmarther.internal.api.dto.Module; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.config.discovery.DiscoveryService;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -41,9 +41,9 @@ import org.slf4j.LoggerFactory;
* *
* @author Fabio Possieri - Initial contribution * @author Fabio Possieri - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = SmartherModuleDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class SmartherModuleDiscoveryService extends AbstractDiscoveryService public class SmartherModuleDiscoveryService extends AbstractThingHandlerDiscoveryService<SmartherAccountHandler> {
implements DiscoveryService, ThingHandlerService {
// Only modules can be discovered. A bridge must be manually added. // Only modules can be discovered. A bridge must be manually added.
private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_MODULE); private static final Set<ThingTypeUID> 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 final Logger logger = LoggerFactory.getLogger(SmartherModuleDiscoveryService.class);
private @Nullable SmartherAccountHandler bridgeHandler;
private @Nullable ThingUID bridgeUID; private @Nullable ThingUID bridgeUID;
/** /**
* Constructs a {@code SmartherModuleDiscoveryService}. * Constructs a {@code SmartherModuleDiscoveryService}.
*/ */
public SmartherModuleDiscoveryService() { public SmartherModuleDiscoveryService() {
super(SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIME_SECONDS); super(SmartherAccountHandler.class, SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIME_SECONDS);
} }
@Override @Override
@ -71,31 +70,25 @@ public class SmartherModuleDiscoveryService extends AbstractDiscoveryService
@Override @Override
public void activate() { public void activate() {
logger.debug("Bridge[{}] Activating chronothermostat discovery service", this.bridgeUID);
Map<String, Object> properties = new HashMap<>(); Map<String, Object> properties = new HashMap<>();
properties.put(DiscoveryService.CONFIG_PROPERTY_BACKGROUND_DISCOVERY, Boolean.TRUE); properties.put(DiscoveryService.CONFIG_PROPERTY_BACKGROUND_DISCOVERY, Boolean.TRUE);
super.activate(properties); super.activate(properties);
} }
@Override @Override
public void deactivate() { public void initialize() {
logger.debug("Bridge[{}] Activating chronothermostat discovery service", this.bridgeUID);
this.bridgeUID = thingHandler.getThing().getUID();
super.initialize();
}
@Override
public void dispose() {
super.dispose();
logger.debug("Bridge[{}] Deactivating chronothermostat discovery service", this.bridgeUID); logger.debug("Bridge[{}] Deactivating chronothermostat discovery service", this.bridgeUID);
removeOlderResults(new Date().getTime()); removeOlderResults(new Date().getTime());
} }
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
if (handler instanceof SmartherAccountHandler localBridgeHandler) {
this.bridgeHandler = localBridgeHandler;
this.bridgeUID = localBridgeHandler.getUID();
}
}
@Override
public @Nullable ThingHandler getThingHandler() {
return this.bridgeHandler;
}
@Override @Override
protected void startBackgroundDiscovery() { protected void startBackgroundDiscovery() {
logger.debug("Bridge[{}] Performing background discovery scan for chronothermostats", this.bridgeUID); logger.debug("Bridge[{}] Performing background discovery scan for chronothermostats", this.bridgeUID);
@ -123,13 +116,10 @@ public class SmartherModuleDiscoveryService extends AbstractDiscoveryService
* Discovers Chronothermostat devices for the given bridge handler. * Discovers Chronothermostat devices for the given bridge handler.
*/ */
private synchronized void discoverChronothermostats() { private synchronized void discoverChronothermostats() {
final SmartherAccountHandler localBridgeHandler = this.bridgeHandler; // If the bridge is not online no other thing devices can be found, so no reason to scan at this moment
if (localBridgeHandler != null) { if (thingHandler.isOnline()) {
// If the bridge is not online no other thing devices can be found, so no reason to scan at this moment thingHandler.getLocations()
if (localBridgeHandler.isOnline()) { .forEach(l -> thingHandler.getLocationModules(l).forEach(m -> addDiscoveredDevice(l, m)));
localBridgeHandler.getLocations()
.forEach(l -> localBridgeHandler.getLocationModules(l).forEach(m -> addDiscoveredDevice(l, m)));
}
} }
} }

View File

@ -19,6 +19,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -28,6 +30,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Georgios Moutsos - Initial contribution * @author Georgios Moutsos - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = CaddxBridgeActions.class)
@ThingActionsScope(name = "caddx") @ThingActionsScope(name = "caddx")
@NonNullByDefault @NonNullByDefault
public class CaddxBridgeActions implements ThingActions { public class CaddxBridgeActions implements ThingActions {

View File

@ -20,6 +20,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -29,6 +31,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Georgios Moutsos - Initial contribution * @author Georgios Moutsos - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = CaddxKeypadActions.class)
@ThingActionsScope(name = "caddx") @ThingActionsScope(name = "caddx")
@NonNullByDefault @NonNullByDefault
public class CaddxKeypadActions implements ThingActions { public class CaddxKeypadActions implements ThingActions {

View File

@ -20,6 +20,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -29,6 +31,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Georgios Moutsos - Initial contribution * @author Georgios Moutsos - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = CaddxPanelActions.class)
@ThingActionsScope(name = "caddx") @ThingActionsScope(name = "caddx")
@NonNullByDefault @NonNullByDefault
public class CaddxPanelActions implements ThingActions { public class CaddxPanelActions implements ThingActions {

View File

@ -15,7 +15,6 @@ package org.openhab.binding.caddx.internal.discovery;
import java.util.Map; import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault; 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.CaddxBindingConstants;
import org.openhab.binding.caddx.internal.CaddxEvent; import org.openhab.binding.caddx.internal.CaddxEvent;
import org.openhab.binding.caddx.internal.config.CaddxKeypadConfiguration; import org.openhab.binding.caddx.internal.config.CaddxKeypadConfiguration;
@ -23,14 +22,13 @@ import org.openhab.binding.caddx.internal.config.CaddxPartitionConfiguration;
import org.openhab.binding.caddx.internal.config.CaddxZoneConfiguration; import org.openhab.binding.caddx.internal.config.CaddxZoneConfiguration;
import org.openhab.binding.caddx.internal.handler.CaddxBridgeHandler; import org.openhab.binding.caddx.internal.handler.CaddxBridgeHandler;
import org.openhab.binding.caddx.internal.handler.CaddxThingType; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; 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.Bridge;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -39,14 +37,13 @@ import org.slf4j.LoggerFactory;
* *
* @author Georgios Moutsos - Initial contribution * @author Georgios Moutsos - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = CaddxDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class CaddxDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService, DiscoveryService { public class CaddxDiscoveryService extends AbstractThingHandlerDiscoveryService<CaddxBridgeHandler> {
private final Logger logger = LoggerFactory.getLogger(CaddxDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(CaddxDiscoveryService.class);
private @Nullable CaddxBridgeHandler caddxBridgeHandler = null;
public CaddxDiscoveryService() { public CaddxDiscoveryService() {
super(CaddxBindingConstants.SUPPORTED_THING_TYPES_UIDS, 15, false); super(CaddxBridgeHandler.class, CaddxBindingConstants.SUPPORTED_THING_TYPES_UIDS, 15, false);
} }
@Override @Override
@ -133,33 +130,17 @@ public class CaddxDiscoveryService extends AbstractDiscoveryService implements T
* Activates the Discovery Service. * Activates the Discovery Service.
*/ */
@Override @Override
public void activate() { public void initialize() {
CaddxBridgeHandler handler = caddxBridgeHandler; thingHandler.registerDiscoveryService(this);
if (handler != null) { super.initialize();
handler.registerDiscoveryService(this);
}
} }
/** /**
* Deactivates the Discovery Service. * Deactivates the Discovery Service.
*/ */
@Override @Override
public void deactivate() { public void dispose() {
CaddxBridgeHandler handler = caddxBridgeHandler; super.dispose();
if (handler != null) { thingHandler.unregisterDiscoveryService();
handler.unregisterDiscoveryService();
}
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
if (handler instanceof CaddxBridgeHandler bridgeHandler) {
caddxBridgeHandler = bridgeHandler;
}
}
@Override
public @Nullable ThingHandler getThingHandler() {
return caddxBridgeHandler;
} }
} }

View File

@ -17,7 +17,6 @@ import static org.openhab.binding.caddx.internal.CaddxBindingConstants.SEND_COMM
import java.io.IOException; import java.io.IOException;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Collection; import java.util.Collection;
import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.TooManyListenersException; import java.util.TooManyListenersException;
@ -451,10 +450,7 @@ public class CaddxBridgeHandler extends BaseBridgeHandler implements CaddxPanelL
@Override @Override
public Collection<Class<? extends ThingHandlerService>> getServices() { public Collection<Class<? extends ThingHandlerService>> getServices() {
Set<Class<? extends ThingHandlerService>> set = new HashSet<Class<? extends ThingHandlerService>>(2); return Set.of(CaddxBridgeActions.class, CaddxDiscoveryService.class);
set.add(CaddxDiscoveryService.class);
set.add(CaddxBridgeActions.class);
return set;
} }
public void restart() { public void restart() {

View File

@ -26,6 +26,8 @@ import org.openhab.core.config.core.ConfigOptionProvider;
import org.openhab.core.config.core.ParameterOption; import org.openhab.core.config.core.ParameterOption;
import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.thing.binding.ThingHandlerService; 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 * The {@link ChatGPTModelOptionProvider} provides the available models from OpenAI as options for the channel
@ -33,6 +35,7 @@ import org.openhab.core.thing.binding.ThingHandlerService;
* *
* @author Kai Kreuzer - Initial contribution * @author Kai Kreuzer - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = { ChatGPTModelOptionProvider.class, ConfigOptionProvider.class })
@NonNullByDefault @NonNullByDefault
public class ChatGPTModelOptionProvider implements ThingHandlerService, ConfigOptionProvider { public class ChatGPTModelOptionProvider implements ThingHandlerService, ConfigOptionProvider {

View File

@ -21,6 +21,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -29,6 +31,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Scott Hanson - Initial contribution * @author Scott Hanson - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = ChromecastActions.class)
@ThingActionsScope(name = "chromecast") @ThingActionsScope(name = "chromecast")
@NonNullByDefault @NonNullByDefault
public class ChromecastActions implements ThingActions { public class ChromecastActions implements ThingActions {

View File

@ -30,12 +30,15 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* @author Joan Pujol - Initial contribution * @author Joan Pujol - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = DBQueryActions.class)
@ThingActionsScope(name = "dbquery") @ThingActionsScope(name = "dbquery")
@NonNullByDefault @NonNullByDefault
public class DBQueryActions implements IDBQueryActions, ThingActions { public class DBQueryActions implements IDBQueryActions, ThingActions {

View File

@ -25,6 +25,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -33,6 +35,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Jan N. Klug - Initial contribution * @author Jan N. Klug - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = BridgeActions.class)
@ThingActionsScope(name = "deconz") @ThingActionsScope(name = "deconz")
@NonNullByDefault @NonNullByDefault
public class BridgeActions implements ThingActions { public class BridgeActions implements ThingActions {

View File

@ -31,6 +31,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -43,6 +45,7 @@ import com.google.gson.reflect.TypeToken;
* *
* @author Jan N. Klug - Initial contribution * @author Jan N. Klug - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = GroupActions.class)
@ThingActionsScope(name = "deconz") @ThingActionsScope(name = "deconz")
@NonNullByDefault @NonNullByDefault
public class GroupActions implements ThingActions { public class GroupActions implements ThingActions {

View File

@ -35,15 +35,16 @@ import org.openhab.binding.deconz.internal.handler.SensorThermostatThingHandler;
import org.openhab.binding.deconz.internal.handler.SensorThingHandler; import org.openhab.binding.deconz.internal.handler.SensorThingHandler;
import org.openhab.binding.deconz.internal.types.GroupType; import org.openhab.binding.deconz.internal.types.GroupType;
import org.openhab.binding.deconz.internal.types.LightType; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.config.discovery.DiscoveryService;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Activate;
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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -53,36 +54,35 @@ import org.slf4j.LoggerFactory;
* *
* @author David Graeff - Initial contribution * @author David Graeff - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = ThingDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class ThingDiscoveryService extends AbstractDiscoveryService implements DiscoveryService, ThingHandlerService { public class ThingDiscoveryService extends AbstractThingHandlerDiscoveryService<DeconzBridgeHandler>
implements DiscoveryService {
private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Stream private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Stream
.of(LightThingHandler.SUPPORTED_THING_TYPE_UIDS, SensorThingHandler.SUPPORTED_THING_TYPES, .of(LightThingHandler.SUPPORTED_THING_TYPE_UIDS, SensorThingHandler.SUPPORTED_THING_TYPES,
SensorThermostatThingHandler.SUPPORTED_THING_TYPES) SensorThermostatThingHandler.SUPPORTED_THING_TYPES)
.flatMap(Set::stream).collect(Collectors.toSet()); .flatMap(Set::stream).collect(Collectors.toSet());
private final Logger logger = LoggerFactory.getLogger(ThingDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(ThingDiscoveryService.class);
private @Nullable DeconzBridgeHandler handler;
private @Nullable ScheduledFuture<?> scanningJob; private @Nullable ScheduledFuture<?> scanningJob;
private @Nullable ThingUID bridgeUID; private @Nullable ThingUID bridgeUID;
@Activate
public ThingDiscoveryService() { public ThingDiscoveryService() {
super(SUPPORTED_THING_TYPES_UIDS, 30); super(DeconzBridgeHandler.class, SUPPORTED_THING_TYPES_UIDS, 30);
} }
@Override @Override
public void startScan() { public void startScan() {
final DeconzBridgeHandler handler = this.handler; thingHandler.getBridgeFullState().thenAccept(fullState -> {
if (handler != null) { stopScan();
handler.getBridgeFullState().thenAccept(fullState -> { fullState.ifPresent(state -> {
stopScan(); state.sensors.forEach(this::addSensor);
fullState.ifPresent(state -> { state.lights.forEach(this::addLight);
state.sensors.forEach(this::addSensor); state.groups.forEach(this::addGroup);
state.lights.forEach(this::addLight);
state.groups.forEach(this::addGroup);
});
}); });
}
});
} }
@Override @Override
@ -290,26 +290,14 @@ public class ThingDiscoveryService extends AbstractDiscoveryService implements D
} }
@Override @Override
public void setThingHandler(@Nullable ThingHandler handler) { public void initialize() {
if (handler instanceof DeconzBridgeHandler bridgeHandler) { bridgeUID = thingHandler.getThing().getUID();
this.handler = bridgeHandler; super.initialize();
this.bridgeUID = handler.getThing().getUID();
}
} }
@Override @Override
public @Nullable ThingHandler getThingHandler() { public void dispose() {
return handler; super.dispose();
}
@Override
public void activate() {
super.activate(null);
}
@Override
public void deactivate() {
removeOlderResults(new Date().getTime()); removeOlderResults(new Date().getTime());
super.deactivate();
} }
} }

View File

@ -93,6 +93,7 @@ public class DeconzTest {
.getBridgeFullState(); .getBridgeFullState();
ThingDiscoveryService discoveryService = new ThingDiscoveryService(); ThingDiscoveryService discoveryService = new ThingDiscoveryService();
discoveryService.setThingHandler(bridgeHandler); discoveryService.setThingHandler(bridgeHandler);
discoveryService.initialize();
discoveryService.addDiscoveryListener(discoveryListener); discoveryService.addDiscoveryListener(discoveryListener);
discoveryService.startScan(); discoveryService.startScan();
Mockito.verify(discoveryListener, times(20)).thingDiscovered(any(), any()); Mockito.verify(discoveryListener, times(20)).thingDiscovered(any(), any());

View File

@ -19,7 +19,6 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; 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.AreaLabelRequest;
import org.openhab.binding.digiplex.internal.communication.AreaLabelResponse; import org.openhab.binding.digiplex.internal.communication.AreaLabelResponse;
import org.openhab.binding.digiplex.internal.communication.DigiplexMessageHandler; import org.openhab.binding.digiplex.internal.communication.DigiplexMessageHandler;
@ -27,13 +26,12 @@ import org.openhab.binding.digiplex.internal.communication.DigiplexRequest;
import org.openhab.binding.digiplex.internal.communication.ZoneLabelRequest; import org.openhab.binding.digiplex.internal.communication.ZoneLabelRequest;
import org.openhab.binding.digiplex.internal.communication.ZoneLabelResponse; import org.openhab.binding.digiplex.internal.communication.ZoneLabelResponse;
import org.openhab.binding.digiplex.internal.handler.DigiplexBridgeHandler; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; 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.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
/** /**
* Service for discovering things on Digiplex alarm systems * Service for discovering things on Digiplex alarm systems
@ -41,41 +39,40 @@ import org.openhab.core.thing.binding.ThingHandlerService;
* @author Robert Michalak - Initial contribution * @author Robert Michalak - Initial contribution
* *
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = DigiplexDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class DigiplexDiscoveryService extends AbstractDiscoveryService public class DigiplexDiscoveryService extends AbstractThingHandlerDiscoveryService<DigiplexBridgeHandler>
implements DiscoveryService, ThingHandlerService, DigiplexMessageHandler { implements DigiplexMessageHandler {
private static final int MAX_ZONE = 96; private static final int MAX_ZONE = 96;
private static final int MAX_AREA = 8; private static final int MAX_AREA = 8;
private static final int DISCOVERY_TIMEOUT = 30; private static final int DISCOVERY_TIMEOUT = 30;
private @Nullable DigiplexBridgeHandler bridgeHandler;
public DigiplexDiscoveryService() { public DigiplexDiscoveryService() {
super(Set.of(THING_TYPE_ZONE), DISCOVERY_TIMEOUT, false); super(DigiplexBridgeHandler.class, Set.of(THING_TYPE_ZONE), DISCOVERY_TIMEOUT, false);
} }
@Override @Override
@SuppressWarnings("null") @SuppressWarnings("null")
protected void startScan() { protected void startScan() {
bridgeHandler.registerMessageHandler(this); thingHandler.registerMessageHandler(this);
// find zones // find zones
for (int i = 1; i <= MAX_ZONE; i++) { for (int i = 1; i <= MAX_ZONE; i++) {
DigiplexRequest command = new ZoneLabelRequest(i); DigiplexRequest command = new ZoneLabelRequest(i);
bridgeHandler.sendRequest(command); thingHandler.sendRequest(command);
} }
// find areas // find areas
for (int i = 1; i <= MAX_AREA; i++) { for (int i = 1; i <= MAX_AREA; i++) {
DigiplexRequest command = new AreaLabelRequest(i); DigiplexRequest command = new AreaLabelRequest(i);
bridgeHandler.sendRequest(command); thingHandler.sendRequest(command);
} }
} }
@Override @Override
@SuppressWarnings("null") @SuppressWarnings("null")
protected synchronized void stopScan() { protected synchronized void stopScan() {
bridgeHandler.unregisterMessageHandler(this); thingHandler.unregisterMessageHandler(this);
super.stopScan(); super.stopScan();
} }
@ -86,8 +83,7 @@ public class DigiplexDiscoveryService extends AbstractDiscoveryService
if (isDefaultName(response)) { if (isDefaultName(response)) {
return; return;
} }
ThingUID bridgeUID = thingHandler.getThing().getUID();
ThingUID bridgeUID = bridgeHandler.getThing().getUID();
ThingUID thingUID = new ThingUID(THING_TYPE_ZONE, bridgeUID, String.format("zone%d", response.zoneNo)); ThingUID thingUID = new ThingUID(THING_TYPE_ZONE, bridgeUID, String.format("zone%d", response.zoneNo));
Map<String, Object> properties = new HashMap<>(1); Map<String, Object> properties = new HashMap<>(1);
@ -112,7 +108,7 @@ public class DigiplexDiscoveryService extends AbstractDiscoveryService
return; 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)); ThingUID thingUID = new ThingUID(THING_TYPE_AREA, bridgeUID, String.format("area%d", response.areaNo));
Map<String, Object> properties = new HashMap<>(1); Map<String, Object> properties = new HashMap<>(1);
@ -125,25 +121,8 @@ public class DigiplexDiscoveryService extends AbstractDiscoveryService
} }
@Override @Override
public void setThingHandler(@Nullable ThingHandler handler) { public void initialize() {
if (handler instanceof DigiplexBridgeHandler digiplexBridgeHandler) { thingHandler.registerMessageHandler(this);
bridgeHandler = digiplexBridgeHandler; super.initialize();
bridgeHandler.registerMessageHandler(this);
}
}
@Override
public @Nullable ThingHandler getThingHandler() {
return bridgeHandler;
}
@Override
public void activate() {
super.activate(null);
}
@Override
public void deactivate() {
super.deactivate();
} }
} }

View File

@ -20,6 +20,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -28,6 +30,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Jan N. Klug - Initial contribution * @author Jan N. Klug - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = DmxActions.class)
@ThingActionsScope(name = "dmx") @ThingActionsScope(name = "dmx")
@NonNullByDefault @NonNullByDefault
public class DmxActions implements ThingActions { public class DmxActions implements ThingActions {

View File

@ -20,6 +20,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -28,6 +30,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Mark Hilbush - Initial contribution * @author Mark Hilbush - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = DoorbirdActions.class)
@ThingActionsScope(name = "doorbird") @ThingActionsScope(name = "doorbird")
@NonNullByDefault @NonNullByDefault
public class DoorbirdActions implements ThingActions { public class DoorbirdActions implements ThingActions {

View File

@ -29,14 +29,13 @@ import org.openhab.binding.draytonwiser.internal.model.RoomDTO;
import org.openhab.binding.draytonwiser.internal.model.RoomStatDTO; import org.openhab.binding.draytonwiser.internal.model.RoomStatDTO;
import org.openhab.binding.draytonwiser.internal.model.SmartPlugDTO; import org.openhab.binding.draytonwiser.internal.model.SmartPlugDTO;
import org.openhab.binding.draytonwiser.internal.model.SmartValveDTO; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; 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.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -45,36 +44,23 @@ import org.slf4j.LoggerFactory;
* *
* @author Andrew Schofield - Initial contribution * @author Andrew Schofield - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = DraytonWiserDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class DraytonWiserDiscoveryService extends AbstractDiscoveryService public class DraytonWiserDiscoveryService extends AbstractThingHandlerDiscoveryService<HeatHubHandler>
implements DiscoveryService, ThingHandlerService, DraytonWiserRefreshListener { implements DraytonWiserRefreshListener {
private final Logger logger = LoggerFactory.getLogger(DraytonWiserDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(DraytonWiserDiscoveryService.class);
private @Nullable HeatHubHandler bridgeHandler;
private @Nullable ThingUID bridgeUID; private @Nullable ThingUID bridgeUID;
public DraytonWiserDiscoveryService() { public DraytonWiserDiscoveryService() {
super(SUPPORTED_THING_TYPES_UIDS, 30, false); super(HeatHubHandler.class, SUPPORTED_THING_TYPES_UIDS, 30, false);
}
@Override
public void activate() {
super.activate(null);
}
@Override
public void deactivate() {
super.deactivate();
} }
@Override @Override
protected void startScan() { protected void startScan() {
final HeatHubHandler handler = bridgeHandler; removeOlderResults(getTimestampOfLastScan());
if (handler != null) { thingHandler.setDiscoveryService(this);
removeOlderResults(getTimestampOfLastScan());
handler.setDiscoveryService(this);
}
} }
@Override @Override
@ -192,27 +178,13 @@ public class DraytonWiserDiscoveryService extends AbstractDiscoveryService
@Override @Override
public synchronized void stopScan() { public synchronized void stopScan() {
final HeatHubHandler handler = bridgeHandler; thingHandler.unsetDiscoveryService();
if (handler != null) {
handler.unsetDiscoveryService();
}
super.stopScan(); super.stopScan();
} }
@Override @Override
public void setThingHandler(@Nullable final ThingHandler handler) { public void initialize() {
if (handler instanceof HeatHubHandler hubHandler) { bridgeUID = thingHandler.getThing().getUID();
bridgeHandler = hubHandler; super.initialize();
bridgeUID = handler.getThing().getUID();
} else {
bridgeHandler = null;
bridgeUID = null;
}
}
@Override
public @Nullable ThingHandler getThingHandler() {
return bridgeHandler;
} }
} }

View File

@ -100,6 +100,7 @@ public class DraytonWiserDiscoveryServiceTest {
} }
}; };
service.setThingHandler(bridgeHandler); service.setThingHandler(bridgeHandler);
service.initialize();
final DomainDTO domain = api.getDomain(); final DomainDTO domain = api.getDomain();
if (domain == null) { if (domain == null) {

View File

@ -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;
}
}

View File

@ -30,10 +30,15 @@ import org.openhab.binding.dsmr.internal.handler.DSMRBridgeHandler;
import org.openhab.binding.dsmr.internal.handler.DSMRMeterHandler; import org.openhab.binding.dsmr.internal.handler.DSMRMeterHandler;
import org.openhab.binding.dsmr.internal.meter.DSMRMeterDescriptor; import org.openhab.binding.dsmr.internal.meter.DSMRMeterDescriptor;
import org.openhab.binding.dsmr.internal.meter.DSMRMeterType; 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.library.types.StringType;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.thing.binding.ThingHandlerService; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -43,6 +48,7 @@ import org.slf4j.LoggerFactory;
* @author M. Volaart - Initial contribution * @author M. Volaart - Initial contribution
* @author Hilbrand Bouwkamp - Refactored code to detect meters during actual discovery phase. * @author Hilbrand Bouwkamp - Refactored code to detect meters during actual discovery phase.
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = DSMRMeterDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class DSMRMeterDiscoveryService extends DSMRDiscoveryService implements P1TelegramListener, ThingHandlerService { public class DSMRMeterDiscoveryService extends DSMRDiscoveryService implements P1TelegramListener, ThingHandlerService {
@ -53,13 +59,14 @@ public class DSMRMeterDiscoveryService extends DSMRDiscoveryService implements P
*/ */
private @NonNullByDefault({}) DSMRBridgeHandler dsmrBridgeHandler; private @NonNullByDefault({}) DSMRBridgeHandler dsmrBridgeHandler;
/** @Reference(unbind = "-")
* Constructs a new {@link DSMRMeterDiscoveryService} attached to the give bridge handler. public void bindTranslationProvider(TranslationProvider translationProvider) {
*/ this.i18nProvider = translationProvider;
public DSMRMeterDiscoveryService() { }
super();
this.i18nProvider = DSMRI18nProviderTracker.i18nProvider; @Reference(unbind = "-")
this.localeProvider = DSMRI18nProviderTracker.localeProvider; public void bindLocaleProvider(LocaleProvider localeProvider) {
this.localeProvider = localeProvider;
} }
@Override @Override

View File

@ -21,12 +21,12 @@ import org.openhab.binding.easee.internal.Utils;
import org.openhab.binding.easee.internal.command.site.GetSite; import org.openhab.binding.easee.internal.command.site.GetSite;
import org.openhab.binding.easee.internal.connector.CommunicationStatus; import org.openhab.binding.easee.internal.connector.CommunicationStatus;
import org.openhab.binding.easee.internal.handler.EaseeSiteHandler; 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.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -40,38 +40,25 @@ import com.google.gson.JsonObject;
* @author Alexander Friese - initial contribution * @author Alexander Friese - initial contribution
* *
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = EaseeSiteDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class EaseeSiteDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { public class EaseeSiteDiscoveryService extends AbstractThingHandlerDiscoveryService<EaseeSiteHandler> {
private final Logger logger = LoggerFactory.getLogger(EaseeSiteDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(EaseeSiteDiscoveryService.class);
private @NonNullByDefault({}) EaseeSiteHandler bridgeHandler;
public EaseeSiteDiscoveryService() throws IllegalArgumentException { public EaseeSiteDiscoveryService() throws IllegalArgumentException {
super(EaseeBindingConstants.SUPPORTED_THING_TYPES_UIDS, 300, false); super(EaseeSiteHandler.class, EaseeBindingConstants.SUPPORTED_THING_TYPES_UIDS, 300, false);
} }
@Override @Override
protected void startScan() { protected void startScan() {
bridgeHandler.enqueueCommand(new GetSite(bridgeHandler, this::processSiteDiscoveryResult)); thingHandler.enqueueCommand(new GetSite(thingHandler, this::processSiteDiscoveryResult));
} }
@Override @Override
public void setThingHandler(ThingHandler handler) { public void initialize() {
if (handler instanceof EaseeSiteHandler siteHandler) { thingHandler.setDiscoveryService(this);
this.bridgeHandler = siteHandler; super.initialize();
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();
} }
/** /**
@ -157,7 +144,7 @@ public class EaseeSiteDiscoveryService extends AbstractDiscoveryService implemen
*/ */
private DiscoveryResultBuilder initDiscoveryResultBuilder(String deviceType, String deviceId, private DiscoveryResultBuilder initDiscoveryResultBuilder(String deviceType, String deviceId,
@Nullable String deviceName) { @Nullable String deviceName) {
ThingUID bridgeUID = bridgeHandler.getThing().getUID(); ThingUID bridgeUID = thingHandler.getThing().getUID();
ThingTypeUID typeUid = new ThingTypeUID(BINDING_ID, deviceType); ThingTypeUID typeUid = new ThingTypeUID(BINDING_ID, deviceType);
ThingUID thingUID = new ThingUID(typeUid, bridgeUID, deviceId); ThingUID thingUID = new ThingUID(typeUid, bridgeUID, deviceId);

View File

@ -23,90 +23,52 @@ import static org.openhab.binding.echonetlite.internal.EchonetLiteBindingConstan
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.openhab.core.config.discovery.AbstractThingHandlerDiscoveryService;
import org.openhab.core.config.discovery.AbstractDiscoveryService;
import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* @author Michael Barker - Initial contribution * @author Michael Barker - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = EchonetDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class EchonetDiscoveryService extends AbstractDiscoveryService public class EchonetDiscoveryService extends AbstractThingHandlerDiscoveryService<EchonetLiteBridgeHandler>
implements EchonetDiscoveryListener, ThingHandlerService { implements EchonetDiscoveryListener {
private final Logger logger = LoggerFactory.getLogger(EchonetDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(EchonetDiscoveryService.class);
@Nullable
private EchonetLiteBridgeHandler bridgeHandler;
public EchonetDiscoveryService() { public EchonetDiscoveryService() {
super(Set.of(THING_TYPE_ECHONET_DEVICE), 10); super(EchonetLiteBridgeHandler.class, Set.of(THING_TYPE_ECHONET_DEVICE), 10);
} }
@Override @Override
protected void startScan() { protected void startScan() {
final EchonetLiteBridgeHandler bridgeHandler = this.bridgeHandler; logger.debug("startScan: {}", thingHandler);
logger.debug("startScan: {}", bridgeHandler); thingHandler.startDiscovery(this);
if (null != bridgeHandler) {
bridgeHandler.startDiscovery(this);
}
} }
@Override @Override
protected synchronized void stopScan() { protected synchronized void stopScan() {
final EchonetLiteBridgeHandler bridgeHandler = this.bridgeHandler; logger.debug("stopScan: {}", thingHandler);
logger.debug("stopScan: {}", bridgeHandler); thingHandler.stopDiscovery();
if (null != bridgeHandler) {
bridgeHandler.stopDiscovery();
}
} }
@Override @Override
public void onDeviceFound(String identifier, InstanceKey instanceKey) { public void onDeviceFound(String identifier, InstanceKey instanceKey) {
final EchonetLiteBridgeHandler bridgeHandler = this.bridgeHandler;
if (null == bridgeHandler) {
return;
}
final DiscoveryResult discoveryResult = DiscoveryResultBuilder 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_INSTANCE_KEY, instanceKey.representationProperty())
.withProperty(PROPERTY_NAME_HOSTNAME, instanceKey.address.getAddress().getHostAddress()) .withProperty(PROPERTY_NAME_HOSTNAME, instanceKey.address.getAddress().getHostAddress())
.withProperty(PROPERTY_NAME_PORT, instanceKey.address.getPort()) .withProperty(PROPERTY_NAME_PORT, instanceKey.address.getPort())
.withProperty(PROPERTY_NAME_GROUP_CODE, instanceKey.klass.groupCode()) .withProperty(PROPERTY_NAME_GROUP_CODE, instanceKey.klass.groupCode())
.withProperty(PROPERTY_NAME_CLASS_CODE, instanceKey.klass.classCode()) .withProperty(PROPERTY_NAME_CLASS_CODE, instanceKey.klass.classCode())
.withProperty(PROPERTY_NAME_INSTANCE, instanceKey.instance) .withProperty(PROPERTY_NAME_INSTANCE, instanceKey.instance).withBridge(thingHandler.getThing().getUID())
.withBridge(bridgeHandler.getThing().getUID()).withRepresentationProperty(PROPERTY_NAME_INSTANCE_KEY) .withRepresentationProperty(PROPERTY_NAME_INSTANCE_KEY).build();
.build();
thingDiscovered(discoveryResult); 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;
}
} }

View File

@ -45,6 +45,8 @@ import org.openhab.core.library.types.QuantityType;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -55,6 +57,7 @@ import org.slf4j.LoggerFactory;
* @author Mark Hilbush - Adapted for OH2/3 * @author Mark Hilbush - Adapted for OH2/3
* @author Connor Petty - Proxy method for invoking actions * @author Connor Petty - Proxy method for invoking actions
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = EcobeeActions.class)
@ThingActionsScope(name = "ecobee") @ThingActionsScope(name = "ecobee")
@NonNullByDefault @NonNullByDefault
public class EcobeeActions implements ThingActions { public class EcobeeActions implements ThingActions {

View File

@ -27,15 +27,15 @@ import org.openhab.binding.ecobee.internal.dto.thermostat.RemoteSensorDTO;
import org.openhab.binding.ecobee.internal.dto.thermostat.ThermostatDTO; import org.openhab.binding.ecobee.internal.dto.thermostat.ThermostatDTO;
import org.openhab.binding.ecobee.internal.handler.EcobeeAccountBridgeHandler; import org.openhab.binding.ecobee.internal.handler.EcobeeAccountBridgeHandler;
import org.openhab.binding.ecobee.internal.handler.EcobeeThermostatBridgeHandler; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -46,39 +46,16 @@ import org.slf4j.LoggerFactory;
* *
* @author Mark Hilbush - Initial contribution * @author Mark Hilbush - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = EcobeeDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class EcobeeDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { public class EcobeeDiscoveryService extends AbstractThingHandlerDiscoveryService<EcobeeAccountBridgeHandler> {
private final Logger logger = LoggerFactory.getLogger(EcobeeDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(EcobeeDiscoveryService.class);
private @NonNullByDefault({}) EcobeeAccountBridgeHandler bridgeHandler;
private @Nullable Future<?> discoveryJob; private @Nullable Future<?> discoveryJob;
public EcobeeDiscoveryService() { public EcobeeDiscoveryService() {
super(SUPPORTED_THERMOSTAT_AND_SENSOR_THING_TYPES_UIDS, 8, true); super(EcobeeAccountBridgeHandler.class, 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();
} }
@Override @Override
@ -113,14 +90,14 @@ public class EcobeeDiscoveryService extends AbstractDiscoveryService implements
} }
private void backgroundDiscover() { private void backgroundDiscover() {
if (!bridgeHandler.isBackgroundDiscoveryEnabled()) { if (!thingHandler.isBackgroundDiscoveryEnabled()) {
return; return;
} }
discover(); discover();
} }
private void 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"); logger.debug("EcobeeDiscovery: Skipping discovery because Account Bridge thing is not ONLINE");
return; return;
} }
@ -131,11 +108,11 @@ public class EcobeeDiscoveryService extends AbstractDiscoveryService implements
private synchronized void discoverThermostats() { private synchronized void discoverThermostats() {
logger.debug("EcobeeDiscovery: Discovering thermostats"); logger.debug("EcobeeDiscovery: Discovering thermostats");
for (ThermostatDTO thermostat : bridgeHandler.getRegisteredThermostats()) { for (ThermostatDTO thermostat : thingHandler.getRegisteredThermostats()) {
String name = thermostat.name; String name = thermostat.name;
String identifier = thermostat.identifier; String identifier = thermostat.identifier;
if (identifier != null && name != null) { 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)); thingDiscovered(createThermostatDiscoveryResult(thingUID, identifier, name));
logger.debug("EcobeeDiscovery: Thermostat '{}' and name '{}' added with UID '{}'", identifier, name, logger.debug("EcobeeDiscovery: Thermostat '{}' and name '{}' added with UID '{}'", identifier, name,
thingUID); thingUID);
@ -144,6 +121,10 @@ public class EcobeeDiscoveryService extends AbstractDiscoveryService implements
} }
private DiscoveryResult createThermostatDiscoveryResult(ThingUID thermostatUID, String identifier, String name) { private DiscoveryResult createThermostatDiscoveryResult(ThingUID thermostatUID, String identifier, String name) {
EcobeeAccountBridgeHandler bridgeHandler = thingHandler;
if (bridgeHandler == null) {
throw new IllegalStateException("thingHandler must not be null");
}
Map<String, Object> properties = new HashMap<>(); Map<String, Object> properties = new HashMap<>();
properties.put(CONFIG_THERMOSTAT_ID, identifier); properties.put(CONFIG_THERMOSTAT_ID, identifier);
return DiscoveryResultBuilder.create(thermostatUID).withProperties(properties) return DiscoveryResultBuilder.create(thermostatUID).withProperties(properties)
@ -152,7 +133,7 @@ public class EcobeeDiscoveryService extends AbstractDiscoveryService implements
} }
private synchronized void discoverSensors() { private synchronized void discoverSensors() {
List<Thing> thermostatThings = bridgeHandler.getThing().getThings(); List<Thing> thermostatThings = thingHandler.getThing().getThings();
if (thermostatThings.isEmpty()) { if (thermostatThings.isEmpty()) {
logger.debug("EcobeeDiscovery: Skipping sensor discovery because there are no thermostat things"); logger.debug("EcobeeDiscovery: Skipping sensor discovery because there are no thermostat things");
return; return;

View File

@ -25,12 +25,15 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* @author Danny Baumann - Initial contribution * @author Danny Baumann - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = EcovacsVacuumActions.class)
@ThingActionsScope(name = "ecovacs") @ThingActionsScope(name = "ecovacs")
@NonNullByDefault @NonNullByDefault
public class EcovacsVacuumActions implements ThingActions { public class EcovacsVacuumActions implements ThingActions {

View File

@ -19,21 +19,19 @@ import java.util.Optional;
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; 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.EcovacsApi;
import org.openhab.binding.ecovacs.internal.api.EcovacsApiException; import org.openhab.binding.ecovacs.internal.api.EcovacsApiException;
import org.openhab.binding.ecovacs.internal.api.EcovacsDevice; import org.openhab.binding.ecovacs.internal.api.EcovacsDevice;
import org.openhab.binding.ecovacs.internal.api.util.SchedulerTask; import org.openhab.binding.ecovacs.internal.api.util.SchedulerTask;
import org.openhab.binding.ecovacs.internal.handler.EcovacsApiHandler; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.config.discovery.DiscoveryService;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingUID; 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.Component;
import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -43,13 +41,11 @@ import org.slf4j.LoggerFactory;
* @author Danny Baumann - Initial contribution * @author Danny Baumann - Initial contribution
*/ */
@NonNullByDefault @NonNullByDefault
@Component(service = DiscoveryService.class, configurationPid = "discovery.ecovacs") @Component(scope = ServiceScope.PROTOTYPE, service = DiscoveryService.class, configurationPid = "discovery.ecovacs")
public class EcovacsDeviceDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { public class EcovacsDeviceDiscoveryService extends AbstractThingHandlerDiscoveryService<EcovacsApiHandler> {
private final Logger logger = LoggerFactory.getLogger(EcovacsDeviceDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(EcovacsDeviceDiscoveryService.class);
private static final int DISCOVER_TIMEOUT_SECONDS = 10; private static final int DISCOVER_TIMEOUT_SECONDS = 10;
private @NonNullByDefault({}) EcovacsApiHandler apiHandler;
private Optional<EcovacsApi> api = Optional.empty(); private Optional<EcovacsApi> api = Optional.empty();
private final SchedulerTask onDemandScanTask = new SchedulerTask(scheduler, logger, "OnDemandScan", private final SchedulerTask onDemandScanTask = new SchedulerTask(scheduler, logger, "OnDemandScan",
this::scanForDevices); this::scanForDevices);
@ -57,30 +53,13 @@ public class EcovacsDeviceDiscoveryService extends AbstractDiscoveryService impl
this::scanForDevices); this::scanForDevices);
public EcovacsDeviceDiscoveryService() { public EcovacsDeviceDiscoveryService() {
super(Set.of(THING_TYPE_VACUUM), DISCOVER_TIMEOUT_SECONDS, true); super(EcovacsApiHandler.class, Set.of(THING_TYPE_VACUUM), DISCOVER_TIMEOUT_SECONDS, true);
} }
@Override @Override
public void setThingHandler(@Nullable ThingHandler handler) { public void initialize() {
if (handler instanceof EcovacsApiHandler ecovacsApiHandler) { thingHandler.setDiscoveryService(this);
this.apiHandler = ecovacsApiHandler; super.initialize();
this.apiHandler.setDiscoveryService(this);
}
}
@Override
public @Nullable ThingHandler getThingHandler() {
return apiHandler;
}
@Override
public void activate() {
super.activate(null);
}
@Override
public void deactivate() {
super.deactivate();
} }
@Override @Override
@ -123,7 +102,7 @@ public class EcovacsDeviceDiscoveryService extends AbstractDiscoveryService impl
for (EcovacsDevice device : devices) { for (EcovacsDevice device : devices) {
deviceDiscovered(device); deviceDiscovered(device);
} }
for (Thing thing : apiHandler.getThing().getThings()) { for (Thing thing : thingHandler.getThing().getThings()) {
String serial = thing.getUID().getId(); String serial = thing.getUID().getId();
if (!devices.stream().anyMatch(d -> serial.equals(d.getSerialNumber()))) { if (!devices.stream().anyMatch(d -> serial.equals(d.getSerialNumber()))) {
thingRemoved(thing.getUID()); thingRemoved(thing.getUID());
@ -140,9 +119,9 @@ public class EcovacsDeviceDiscoveryService extends AbstractDiscoveryService impl
} }
private void deviceDiscovered(EcovacsDevice device) { 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) 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_SERIAL_NUMBER, device.getSerialNumber())
.withProperty(Thing.PROPERTY_MODEL_ID, device.getModelName()) .withProperty(Thing.PROPERTY_MODEL_ID, device.getModelName())
.withRepresentationProperty(Thing.PROPERTY_SERIAL_NUMBER).build(); .withRepresentationProperty(Thing.PROPERTY_SERIAL_NUMBER).build();

View File

@ -14,18 +14,14 @@ package org.openhab.binding.electroluxair.internal.discovery;
import static org.openhab.binding.electroluxair.internal.ElectroluxAirBindingConstants.*; import static org.openhab.binding.electroluxair.internal.ElectroluxAirBindingConstants.*;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault; 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.ElectroluxAirConfiguration;
import org.openhab.binding.electroluxair.internal.handler.ElectroluxAirBridgeHandler; 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.DiscoveryResultBuilder;
import org.openhab.core.config.discovery.DiscoveryService;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
/** /**
* The {@link ElectroluxAirDiscoveryService} searches for available * The {@link ElectroluxAirDiscoveryService} searches for available
@ -33,51 +29,26 @@ import org.openhab.core.thing.binding.ThingHandlerService;
* *
* @author Jan Gustafsson - Initial contribution * @author Jan Gustafsson - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = ElectroluxAirDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class ElectroluxAirDiscoveryService extends AbstractDiscoveryService public class ElectroluxAirDiscoveryService extends AbstractThingHandlerDiscoveryService<ElectroluxAirBridgeHandler> {
implements ThingHandlerService, DiscoveryService {
private static final int SEARCH_TIME = 2; private static final int SEARCH_TIME = 2;
private @Nullable ElectroluxAirBridgeHandler handler;
public ElectroluxAirDiscoveryService() { public ElectroluxAirDiscoveryService() {
super(SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME); super(ElectroluxAirBridgeHandler.class, 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<String, Object> configProperties) {
super.activate(configProperties);
}
@Override
public void deactivate() {
super.deactivate();
} }
@Override @Override
protected void startScan() { protected void startScan() {
ElectroluxAirBridgeHandler bridgeHandler = this.handler; ThingUID bridgeUID = thingHandler.getThing().getUID();
if (bridgeHandler != null) { thingHandler.getElectroluxAirThings().entrySet().stream().forEach(thing -> {
ThingUID bridgeUID = bridgeHandler.getThing().getUID(); thingDiscovered(DiscoveryResultBuilder
bridgeHandler.getElectroluxAirThings().entrySet().stream().forEach(thing -> { .create(new ThingUID(THING_TYPE_ELECTROLUX_PURE_A9, bridgeUID, thing.getKey()))
thingDiscovered(DiscoveryResultBuilder .withLabel("Electrolux Pure A9").withBridge(bridgeUID)
.create(new ThingUID(THING_TYPE_ELECTROLUX_PURE_A9, bridgeUID, thing.getKey())) .withProperty(ElectroluxAirConfiguration.DEVICE_ID_LABEL, thing.getKey())
.withLabel("Electrolux Pure A9").withBridge(bridgeUID) .withRepresentationProperty(ElectroluxAirConfiguration.DEVICE_ID_LABEL).build());
.withProperty(ElectroluxAirConfiguration.DEVICE_ID_LABEL, thing.getKey()) });
.withRepresentationProperty(ElectroluxAirConfiguration.DEVICE_ID_LABEL).build());
});
}
stopScan(); stopScan();
} }
} }

View File

@ -25,12 +25,12 @@ import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.elroconnects.internal.ElroConnectsBindingConstants; import org.openhab.binding.elroconnects.internal.ElroConnectsBindingConstants;
import org.openhab.binding.elroconnects.internal.devices.ElroConnectsConnector; import org.openhab.binding.elroconnects.internal.devices.ElroConnectsConnector;
import org.openhab.binding.elroconnects.internal.handler.ElroConnectsAccountHandler; 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.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -39,13 +39,13 @@ import org.slf4j.LoggerFactory;
* *
* @author Mark Herwege - Initial Contribution * @author Mark Herwege - Initial Contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = ElroConnectsBridgeDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class ElroConnectsBridgeDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { public class ElroConnectsBridgeDiscoveryService
extends AbstractThingHandlerDiscoveryService<ElroConnectsAccountHandler> {
private final Logger logger = LoggerFactory.getLogger(ElroConnectsBridgeDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(ElroConnectsBridgeDiscoveryService.class);
private @Nullable ElroConnectsAccountHandler accountHandler;
private volatile @Nullable ScheduledFuture<?> discoveryJob; private volatile @Nullable ScheduledFuture<?> discoveryJob;
private static final int TIMEOUT_S = 5; private static final int TIMEOUT_S = 5;
@ -54,7 +54,7 @@ public class ElroConnectsBridgeDiscoveryService extends AbstractDiscoveryService
private static final int REFRESH_INTERVAL_S = 60; private static final int REFRESH_INTERVAL_S = 60;
public ElroConnectsBridgeDiscoveryService() { 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"); logger.debug("Bridge discovery service started");
} }
@ -67,14 +67,10 @@ public class ElroConnectsBridgeDiscoveryService extends AbstractDiscoveryService
private void discoverConnectors() { private void discoverConnectors() {
logger.debug("Starting hub discovery scan"); logger.debug("Starting hub discovery scan");
ElroConnectsAccountHandler account = accountHandler;
if (account == null) {
return;
}
ThingUID bridgeUID = account.getThing().getUID(); ThingUID bridgeUID = thingHandler.getThing().getUID();
Map<String, ElroConnectsConnector> connectors = account.getDevices(); Map<String, ElroConnectsConnector> connectors = thingHandler.getDevices();
if (connectors == null) { if (connectors == null) {
return; return;
} }
@ -134,21 +130,14 @@ public class ElroConnectsBridgeDiscoveryService extends AbstractDiscoveryService
} }
@Override @Override
public void deactivate() { public void dispose() {
super.dispose();
removeOlderResults(Instant.now().toEpochMilli()); removeOlderResults(Instant.now().toEpochMilli());
super.deactivate();
} }
@Override @Override
public void setThingHandler(@Nullable ThingHandler handler) { public void initialize() {
if (handler instanceof ElroConnectsAccountHandler accountHandler) { thingHandler.setDiscoveryService(this);
this.accountHandler = accountHandler; super.initialize();
accountHandler.setDiscoveryService(this);
}
}
@Override
public @Nullable ThingHandler getThingHandler() {
return accountHandler;
} }
} }

View File

@ -25,12 +25,12 @@ import org.openhab.binding.elroconnects.internal.ElroConnectsBindingConstants;
import org.openhab.binding.elroconnects.internal.ElroConnectsBindingConstants.ElroDeviceType; import org.openhab.binding.elroconnects.internal.ElroConnectsBindingConstants.ElroDeviceType;
import org.openhab.binding.elroconnects.internal.devices.ElroConnectsDevice; import org.openhab.binding.elroconnects.internal.devices.ElroConnectsDevice;
import org.openhab.binding.elroconnects.internal.handler.ElroConnectsBridgeHandler; 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.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -39,20 +39,19 @@ import org.slf4j.LoggerFactory;
* *
* @author Mark Herwege - Initial contribution * @author Mark Herwege - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = ElroConnectsDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class ElroConnectsDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { public class ElroConnectsDiscoveryService extends AbstractThingHandlerDiscoveryService<ElroConnectsBridgeHandler> {
private final Logger logger = LoggerFactory.getLogger(ElroConnectsDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(ElroConnectsDiscoveryService.class);
private @Nullable ElroConnectsBridgeHandler bridgeHandler;
private static final int TIMEOUT_S = 5; private static final int TIMEOUT_S = 5;
private static final int REFRESH_INTERVAL_S = 60; private static final int REFRESH_INTERVAL_S = 60;
private @Nullable ScheduledFuture<?> discoveryJob; private @Nullable ScheduledFuture<?> discoveryJob;
public ElroConnectsDiscoveryService() { 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"); logger.debug("Discovery service started");
} }
@ -63,28 +62,24 @@ public class ElroConnectsDiscoveryService extends AbstractDiscoveryService imple
private void discoverDevices() { private void discoverDevices() {
logger.debug("Starting device discovery scan"); logger.debug("Starting device discovery scan");
ElroConnectsBridgeHandler bridge = bridgeHandler; Map<Integer, ElroConnectsDevice> devices = thingHandler.getDevices();
if (bridge != null) { ThingUID bridgeUID = thingHandler.getThing().getUID();
Map<Integer, ElroConnectsDevice> devices = bridge.getDevices(); devices.entrySet().forEach(e -> {
ThingUID bridgeUID = bridge.getThing().getUID(); String deviceId = e.getKey().toString();
devices.entrySet().forEach(e -> { String deviceName = e.getValue().getDeviceName();
String deviceId = e.getKey().toString(); String deviceType = e.getValue().getDeviceType();
String deviceName = e.getValue().getDeviceName(); if (!deviceType.isEmpty()) {
String deviceType = e.getValue().getDeviceType(); ElroDeviceType type = TYPE_MAP.get(deviceType);
if (!deviceType.isEmpty()) { if (type != null) {
ElroDeviceType type = TYPE_MAP.get(deviceType); ThingTypeUID thingTypeUID = THING_TYPE_MAP.get(type);
if (type != null) { if (thingTypeUID != null) {
ThingTypeUID thingTypeUID = THING_TYPE_MAP.get(type); thingDiscovered(DiscoveryResultBuilder.create(new ThingUID(thingTypeUID, bridgeUID, deviceId))
if (thingTypeUID != null) { .withLabel(deviceName).withBridge(bridgeUID).withProperty(CONFIG_DEVICE_ID, deviceId)
thingDiscovered(DiscoveryResultBuilder .withRepresentationProperty(CONFIG_DEVICE_ID).build());
.create(new ThingUID(thingTypeUID, bridgeUID, deviceId)).withLabel(deviceName)
.withBridge(bridgeUID).withProperty(CONFIG_DEVICE_ID, deviceId)
.withRepresentationProperty(CONFIG_DEVICE_ID).build());
}
} }
} }
}); }
} });
} }
@Override @Override
@ -114,21 +109,14 @@ public class ElroConnectsDiscoveryService extends AbstractDiscoveryService imple
} }
@Override @Override
public void deactivate() { public void dispose() {
super.dispose();
removeOlderResults(Instant.now().toEpochMilli()); removeOlderResults(Instant.now().toEpochMilli());
super.deactivate();
} }
@Override @Override
public void setThingHandler(@Nullable ThingHandler handler) { public void initialize() {
if (handler instanceof ElroConnectsBridgeHandler bridgeHandler) { thingHandler.setDiscoveryService(this);
this.bridgeHandler = bridgeHandler; super.initialize();
bridgeHandler.setDiscoveryService(this);
}
}
@Override
public @Nullable ThingHandler getThingHandler() {
return bridgeHandler;
} }
} }

View File

@ -45,6 +45,8 @@ import org.openhab.core.library.unit.Units;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -53,6 +55,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Jacob Laursen - Initial contribution * @author Jacob Laursen - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = EnergiDataServiceActions.class)
@ThingActionsScope(name = "energidataservice") @ThingActionsScope(name = "energidataservice")
@NonNullByDefault @NonNullByDefault
public class EnergiDataServiceActions implements ThingActions { public class EnergiDataServiceActions implements ThingActions {

View File

@ -21,6 +21,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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 * This is the automation engine actions handler service for the
@ -28,6 +30,7 @@ import org.openhab.core.thing.binding.ThingHandler;
* *
* @author Guido Dolfen - Initial contribution * @author Guido Dolfen - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = Enigma2Actions.class)
@ThingActionsScope(name = "enigma2") @ThingActionsScope(name = "enigma2")
@NonNullByDefault @NonNullByDefault
public class Enigma2Actions implements ThingActions { public class Enigma2Actions implements ThingActions {

View File

@ -28,14 +28,13 @@ import org.openhab.binding.enphase.internal.EnphaseBindingConstants.EnphaseDevic
import org.openhab.binding.enphase.internal.dto.InventoryJsonDTO.DeviceDTO; import org.openhab.binding.enphase.internal.dto.InventoryJsonDTO.DeviceDTO;
import org.openhab.binding.enphase.internal.dto.InverterDTO; import org.openhab.binding.enphase.internal.dto.InverterDTO;
import org.openhab.binding.enphase.internal.handler.EnvoyBridgeHandler; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; 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.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -45,49 +44,28 @@ import org.slf4j.LoggerFactory;
* @author Thomas Hentschel - Initial contribution * @author Thomas Hentschel - Initial contribution
* @author Hilbrand Bouwkamp - Initial contribution * @author Hilbrand Bouwkamp - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = EnphaseDevicesDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class EnphaseDevicesDiscoveryService extends AbstractDiscoveryService public class EnphaseDevicesDiscoveryService extends AbstractThingHandlerDiscoveryService<EnvoyBridgeHandler> {
implements ThingHandlerService, DiscoveryService {
private static final int TIMEOUT_SECONDS = 20; private static final int TIMEOUT_SECONDS = 20;
private final Logger logger = LoggerFactory.getLogger(EnphaseDevicesDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(EnphaseDevicesDiscoveryService.class);
private @Nullable EnvoyBridgeHandler envoyHandler;
public EnphaseDevicesDiscoveryService() { public EnphaseDevicesDiscoveryService() {
super(Set.of(THING_TYPE_ENPHASE_INVERTER), TIMEOUT_SECONDS, false); super(EnvoyBridgeHandler.class, 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();
} }
@Override @Override
protected void startScan() { protected void startScan() {
removeOlderResults(getTimestampOfLastScan()); removeOlderResults(getTimestampOfLastScan());
final EnvoyBridgeHandler envoyHandler = this.envoyHandler; if (!thingHandler.isOnline()) {
logger.debug("Envoy handler not available or online: {}", thingHandler);
if (envoyHandler == null || !envoyHandler.isOnline()) {
logger.debug("Envoy handler not available or online: {}", envoyHandler);
return; return;
} }
final ThingUID uid = envoyHandler.getThing().getUID(); final ThingUID uid = thingHandler.getThing().getUID();
scanForInverterThings(envoyHandler, uid); scanForInverterThings(thingHandler, uid);
scanForDeviceThings(envoyHandler, uid); scanForDeviceThings(thingHandler, uid);
} }
private void scanForInverterThings(final EnvoyBridgeHandler envoyHandler, final ThingUID bridgeID) { private void scanForInverterThings(final EnvoyBridgeHandler envoyHandler, final ThingUID bridgeID) {

View File

@ -17,20 +17,18 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault; 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.FoobotApiException;
import org.openhab.binding.foobot.internal.FoobotBindingConstants; import org.openhab.binding.foobot.internal.FoobotBindingConstants;
import org.openhab.binding.foobot.internal.FoobotHandlerFactory; import org.openhab.binding.foobot.internal.FoobotHandlerFactory;
import org.openhab.binding.foobot.internal.handler.FoobotAccountHandler; import org.openhab.binding.foobot.internal.handler.FoobotAccountHandler;
import org.openhab.binding.foobot.internal.handler.FoobotDeviceHandler; import org.openhab.binding.foobot.internal.handler.FoobotDeviceHandler;
import org.openhab.binding.foobot.internal.json.FoobotDevice; 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.DiscoveryResultBuilder;
import org.openhab.core.config.discovery.DiscoveryService;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -41,19 +39,18 @@ import org.slf4j.LoggerFactory;
* @author George Katsis - Initial contribution * @author George Katsis - Initial contribution
* @author Hilbrand Bouwkamp - Completed implementation * @author Hilbrand Bouwkamp - Completed implementation
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = FoobotAccountDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class FoobotAccountDiscoveryService extends AbstractDiscoveryService public class FoobotAccountDiscoveryService extends AbstractThingHandlerDiscoveryService<FoobotAccountHandler> {
implements DiscoveryService, ThingHandlerService {
private static final int TIMEOUT_SECONDS = 5; private static final int TIMEOUT_SECONDS = 5;
private final Logger logger = LoggerFactory.getLogger(FoobotAccountDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(FoobotAccountDiscoveryService.class);
private @Nullable FoobotAccountHandler handler;
private @NonNullByDefault({}) ThingUID bridgeUID; private @NonNullByDefault({}) ThingUID bridgeUID;
public FoobotAccountDiscoveryService() { public FoobotAccountDiscoveryService() {
super(FoobotHandlerFactory.DISCOVERABLE_THING_TYPE_UIDS, TIMEOUT_SECONDS, false); super(FoobotAccountHandler.class, FoobotHandlerFactory.DISCOVERABLE_THING_TYPE_UIDS, TIMEOUT_SECONDS, false);
} }
@Override @Override
@ -62,13 +59,10 @@ public class FoobotAccountDiscoveryService extends AbstractDiscoveryService
} }
private void retrieveFoobots() { private void retrieveFoobots() {
if (handler == null) {
return;
}
try { try {
final List<FoobotDeviceHandler> footbotHandlers = handler.getFootbotHandlers(); final List<FoobotDeviceHandler> footbotHandlers = thingHandler.getFootbotHandlers();
handler.getDeviceList().stream() thingHandler.getDeviceList().stream()
.filter(d -> !footbotHandlers.stream().anyMatch(h -> h.getUuid().equals(d.getUuid()))) .filter(d -> !footbotHandlers.stream().anyMatch(h -> h.getUuid().equals(d.getUuid())))
.forEach(this::addThing); .forEach(this::addThing);
} catch (final FoobotApiException e) { } catch (final FoobotApiException e) {
@ -77,11 +71,6 @@ public class FoobotAccountDiscoveryService extends AbstractDiscoveryService
} }
} }
@Override
public void deactivate() {
super.deactivate();
}
private void addThing(final FoobotDevice foobot) { private void addThing(final FoobotDevice foobot) {
logger.debug("Adding new Foobot '{}' with uuid: {}", foobot.getName(), foobot.getUuid()); logger.debug("Adding new Foobot '{}' with uuid: {}", foobot.getName(), foobot.getUuid());
@ -95,16 +84,4 @@ public class FoobotAccountDiscoveryService extends AbstractDiscoveryService
thingDiscovered(DiscoveryResultBuilder.create(thingUID).withBridge(bridgeUID).withProperties(properties) thingDiscovered(DiscoveryResultBuilder.create(thingUID).withBridge(bridgeUID).withProperties(properties)
.withLabel(foobot.getName()).withRepresentationProperty(foobot.getUuid()).build()); .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;
}
} }

View File

@ -30,14 +30,14 @@ import org.openhab.binding.freebox.internal.config.FreeboxNetInterfaceConfigurat
import org.openhab.binding.freebox.internal.config.FreeboxServerConfiguration; import org.openhab.binding.freebox.internal.config.FreeboxServerConfiguration;
import org.openhab.binding.freebox.internal.handler.FreeboxHandler; import org.openhab.binding.freebox.internal.handler.FreeboxHandler;
import org.openhab.core.config.core.Configuration; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -50,17 +50,16 @@ import org.slf4j.LoggerFactory;
* @author Laurent Garnier - use new internal API manager * @author Laurent Garnier - use new internal API manager
* @author Laurent Garnier - use ThingHandlerService * @author Laurent Garnier - use ThingHandlerService
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = FreeboxDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class FreeboxDiscoveryService extends AbstractDiscoveryService public class FreeboxDiscoveryService extends AbstractThingHandlerDiscoveryService<FreeboxHandler>
implements FreeboxDataListener, ThingHandlerService { implements FreeboxDataListener {
private final Logger logger = LoggerFactory.getLogger(FreeboxDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(FreeboxDiscoveryService.class);
private static final int SEARCH_TIME = 10; private static final int SEARCH_TIME = 10;
private static final String PHONE_ID = "wired"; private static final String PHONE_ID = "wired";
private @Nullable FreeboxHandler bridgeHandler;
private boolean discoverPhone; private boolean discoverPhone;
private boolean discoverNetDevice; private boolean discoverNetDevice;
private boolean discoverNetInterface; private boolean discoverNetInterface;
@ -70,7 +69,7 @@ public class FreeboxDiscoveryService extends AbstractDiscoveryService
* Creates a FreeboxDiscoveryService with background discovery disabled. * Creates a FreeboxDiscoveryService with background discovery disabled.
*/ */
public FreeboxDiscoveryService() { 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.discoverPhone = true;
this.discoverNetDevice = true; this.discoverNetDevice = true;
this.discoverNetInterface = true; this.discoverNetInterface = true;
@ -78,58 +77,39 @@ public class FreeboxDiscoveryService extends AbstractDiscoveryService
} }
@Override @Override
public void setThingHandler(ThingHandler handler) { public void initialize() {
if (handler instanceof FreeboxHandler freeboxHandler) { Configuration config = thingHandler.getThing().getConfiguration();
bridgeHandler = freeboxHandler; 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 @Override
public @Nullable ThingHandler getThingHandler() { public void dispose() {
return bridgeHandler; super.dispose();
} thingHandler.unregisterDataListener(this);
@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();
} }
@Override @Override
protected void startScan() { protected void startScan() {
logger.debug("Starting Freebox discovery scan"); logger.debug("Starting Freebox discovery scan");
FreeboxHandler handler = bridgeHandler; if (thingHandler.getThing().getStatus() == ThingStatus.ONLINE) {
if (handler != null && handler.getThing().getStatus() == ThingStatus.ONLINE) {
try { try {
List<FreeboxLanHost> lanHosts = handler.getApiManager().getLanHosts(); List<FreeboxLanHost> lanHosts = thingHandler.getApiManager().getLanHosts();
List<FreeboxAirMediaReceiver> airPlayDevices = handler.getApiManager().getAirMediaReceivers(); List<FreeboxAirMediaReceiver> airPlayDevices = thingHandler.getApiManager().getAirMediaReceivers();
onDataFetched(handler.getThing().getUID(), lanHosts, airPlayDevices); onDataFetched(thingHandler.getThing().getUID(), lanHosts, airPlayDevices);
} catch (FreeboxException e) { } catch (FreeboxException e) {
logger.warn("Error while requesting data for things discovery", e); logger.warn("Error while requesting data for things discovery", e);
} }

View File

@ -18,6 +18,8 @@ import org.openhab.binding.freeboxos.internal.handler.PlayerHandler;
import org.openhab.core.automation.annotation.RuleAction; import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -26,6 +28,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Gaël L'hopital - Initial contribution * @author Gaël L'hopital - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = ActivePlayerActions.class)
@ThingActionsScope(name = "freeboxos") @ThingActionsScope(name = "freeboxos")
@NonNullByDefault @NonNullByDefault
public class ActivePlayerActions extends PlayerActions { public class ActivePlayerActions extends PlayerActions {

View File

@ -19,6 +19,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -27,6 +29,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Gaël L'hopital - Initial contribution * @author Gaël L'hopital - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = CallActions.class)
@ThingActionsScope(name = "freeboxos") @ThingActionsScope(name = "freeboxos")
@NonNullByDefault @NonNullByDefault
public class CallActions implements ThingActions { public class CallActions implements ThingActions {

View File

@ -19,6 +19,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -27,6 +29,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Gaël L'hopital - Initial contribution * @author Gaël L'hopital - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = FreeplugActions.class)
@ThingActionsScope(name = "freeboxos") @ThingActionsScope(name = "freeboxos")
@NonNullByDefault @NonNullByDefault
public class FreeplugActions implements ThingActions { public class FreeplugActions implements ThingActions {

View File

@ -19,6 +19,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -27,6 +29,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Gaël L'hopital - Initial contribution * @author Gaël L'hopital - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = HostActions.class)
@ThingActionsScope(name = "freeboxos") @ThingActionsScope(name = "freeboxos")
@NonNullByDefault @NonNullByDefault
public class HostActions implements ThingActions { public class HostActions implements ThingActions {

View File

@ -20,6 +20,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -28,6 +30,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Gaël L'hopital - Initial contribution * @author Gaël L'hopital - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = PlayerActions.class)
@ThingActionsScope(name = "freeboxos") @ThingActionsScope(name = "freeboxos")
@NonNullByDefault @NonNullByDefault
public class PlayerActions implements ThingActions { public class PlayerActions implements ThingActions {

View File

@ -19,6 +19,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -27,6 +29,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Gaël L'hopital - Initial contribution * @author Gaël L'hopital - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = RepeaterActions.class)
@ThingActionsScope(name = "freeboxos") @ThingActionsScope(name = "freeboxos")
@NonNullByDefault @NonNullByDefault
public class RepeaterActions implements ThingActions { public class RepeaterActions implements ThingActions {

View File

@ -19,6 +19,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -27,6 +29,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Gaël L'hopital - Initial contribution * @author Gaël L'hopital - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = ServerActions.class)
@ThingActionsScope(name = "freeboxos") @ThingActionsScope(name = "freeboxos")
@NonNullByDefault @NonNullByDefault
public class ServerActions implements ThingActions { public class ServerActions implements ThingActions {

View File

@ -24,7 +24,6 @@ import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNullByDefault; 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.FreeboxException;
import org.openhab.binding.freeboxos.internal.api.PermissionException; import org.openhab.binding.freeboxos.internal.api.PermissionException;
import org.openhab.binding.freeboxos.internal.api.rest.APManager; import org.openhab.binding.freeboxos.internal.api.rest.APManager;
@ -47,15 +46,15 @@ import org.openhab.binding.freeboxos.internal.config.FreeplugConfigurationBuilde
import org.openhab.binding.freeboxos.internal.config.NodeConfigurationBuilder; import org.openhab.binding.freeboxos.internal.config.NodeConfigurationBuilder;
import org.openhab.binding.freeboxos.internal.config.PhoneConfigurationBuilder; import org.openhab.binding.freeboxos.internal.config.PhoneConfigurationBuilder;
import org.openhab.binding.freeboxos.internal.handler.FreeboxOsHandler; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -67,48 +66,28 @@ import inet.ipaddr.mac.MACAddress;
* *
* @author Gaël L'hopital - Initial contribution * @author Gaël L'hopital - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = FreeboxOsDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class FreeboxOsDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { public class FreeboxOsDiscoveryService extends AbstractThingHandlerDiscoveryService<FreeboxOsHandler> {
private static final int DISCOVERY_TIME_SECONDS = 10; private static final int DISCOVERY_TIME_SECONDS = 10;
private final Logger logger = LoggerFactory.getLogger(FreeboxOsDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(FreeboxOsDiscoveryService.class);
private Optional<ScheduledFuture<?>> backgroundFuture = Optional.empty(); private Optional<ScheduledFuture<?>> backgroundFuture = Optional.empty();
private @Nullable FreeboxOsHandler bridgeHandler;
public FreeboxOsDiscoveryService() { 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); 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 @Override
protected void startBackgroundDiscovery() { protected void startBackgroundDiscovery() {
stopBackgroundDiscovery(); stopBackgroundDiscovery();
FreeboxOsHandler handler = bridgeHandler; int interval = thingHandler.getConfiguration().discoveryInterval;
if (handler != null) { if (interval > 0) {
int interval = handler.getConfiguration().discoveryInterval; backgroundFuture = Optional
if (interval > 0) { .of(scheduler.scheduleWithFixedDelay(this::startScan, 1, interval, TimeUnit.MINUTES));
backgroundFuture = Optional
.of(scheduler.scheduleWithFixedDelay(this::startScan, 1, interval, TimeUnit.MINUTES));
}
} }
} }
@ -121,23 +100,22 @@ public class FreeboxOsDiscoveryService extends AbstractDiscoveryService implemen
@Override @Override
protected void startScan() { protected void startScan() {
logger.debug("Starting Freebox discovery scan"); logger.debug("Starting Freebox discovery scan");
FreeboxOsHandler handler = bridgeHandler; if (thingHandler.getThing().getStatus() == ThingStatus.ONLINE) {
if (handler != null && handler.getThing().getStatus() == ThingStatus.ONLINE) {
try { try {
ThingUID bridgeUID = handler.getThing().getUID(); ThingUID bridgeUID = thingHandler.getThing().getUID();
List<LanHost> lanHosts = new ArrayList<>(handler.getManager(LanBrowserManager.class).getHosts().stream() List<LanHost> lanHosts = new ArrayList<>(thingHandler.getManager(LanBrowserManager.class).getHosts()
.filter(LanHost::reachable).toList()); .stream().filter(LanHost::reachable).toList());
discoverServer(handler.getManager(SystemManager.class), bridgeUID); discoverServer(thingHandler.getManager(SystemManager.class), bridgeUID);
discoverPhone(handler.getManager(PhoneManager.class), bridgeUID); discoverPhone(thingHandler.getManager(PhoneManager.class), bridgeUID);
discoverPlugs(handler.getManager(FreeplugManager.class), bridgeUID); discoverPlugs(thingHandler.getManager(FreeplugManager.class), bridgeUID);
discoverRepeater(handler.getManager(RepeaterManager.class), bridgeUID, lanHosts); discoverRepeater(thingHandler.getManager(RepeaterManager.class), bridgeUID, lanHosts);
discoverPlayer(handler.getManager(PlayerManager.class), bridgeUID, lanHosts); discoverPlayer(thingHandler.getManager(PlayerManager.class), bridgeUID, lanHosts);
discoverVM(handler.getManager(VmManager.class), bridgeUID, lanHosts); discoverVM(thingHandler.getManager(VmManager.class), bridgeUID, lanHosts);
discoverHome(handler.getManager(HomeManager.class), bridgeUID); discoverHome(thingHandler.getManager(HomeManager.class), bridgeUID);
if (handler.getConfiguration().discoverNetDevice) { if (thingHandler.getConfiguration().discoverNetDevice) {
discoverHosts(handler, bridgeUID, lanHosts); discoverHosts(thingHandler, bridgeUID, lanHosts);
} }
} catch (FreeboxException e) { } catch (FreeboxException e) {
logger.warn("Error while requesting data for things discovery: {}", e.getMessage()); logger.warn("Error while requesting data for things discovery: {}", e.getMessage());

View File

@ -28,15 +28,14 @@ import org.openhab.binding.gardena.internal.handler.GardenaAccountHandler;
import org.openhab.binding.gardena.internal.model.dto.Device; import org.openhab.binding.gardena.internal.model.dto.Device;
import org.openhab.binding.gardena.internal.util.PropertyUtils; import org.openhab.binding.gardena.internal.util.PropertyUtils;
import org.openhab.binding.gardena.internal.util.UidUtils; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; 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.Thing;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -45,45 +44,24 @@ import org.slf4j.LoggerFactory;
* *
* @author Gerhard Riegler - Initial contribution * @author Gerhard Riegler - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = GardenaDeviceDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class GardenaDeviceDiscoveryService extends AbstractDiscoveryService public class GardenaDeviceDiscoveryService extends AbstractThingHandlerDiscoveryService<GardenaAccountHandler> {
implements DiscoveryService, ThingHandlerService {
private final Logger logger = LoggerFactory.getLogger(GardenaDeviceDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(GardenaDeviceDiscoveryService.class);
private static final int DISCOVER_TIMEOUT_SECONDS = 5; private static final int DISCOVER_TIMEOUT_SECONDS = 5;
private @NonNullByDefault({}) GardenaAccountHandler accountHandler;
private @Nullable Future<?> scanFuture; private @Nullable Future<?> scanFuture;
public GardenaDeviceDiscoveryService() { 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); DISCOVER_TIMEOUT_SECONDS, false);
} }
@Override @Override
public void setThingHandler(@Nullable ThingHandler handler) { public void initialize() {
if (handler instanceof GardenaAccountHandler gardenaAccountHandler) { thingHandler.setDiscoveryService(this);
this.accountHandler = gardenaAccountHandler; super.initialize();
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();
} }
@Override @Override
@ -108,13 +86,13 @@ public class GardenaDeviceDiscoveryService extends AbstractDiscoveryService
private void loadDevices() { private void loadDevices() {
if (scanFuture == null) { if (scanFuture == null) {
scanFuture = scheduler.submit(() -> { scanFuture = scheduler.submit(() -> {
GardenaSmart gardena = accountHandler.getGardenaSmart(); GardenaSmart gardena = thingHandler.getGardenaSmart();
if (gardena != null) { if (gardena != null) {
for (Device device : gardena.getAllDevices()) { for (Device device : gardena.getAllDevices()) {
deviceDiscovered(device); deviceDiscovered(device);
} }
for (Thing thing : accountHandler.getThing().getThings()) { for (Thing thing : thingHandler.getThing().getThings()) {
try { try {
gardena.getDevice(UidUtils.getGardenaDeviceId(thing)); gardena.getDevice(UidUtils.getGardenaDeviceId(thing));
} catch (GardenaException ex) { } catch (GardenaException ex) {
@ -155,8 +133,8 @@ public class GardenaDeviceDiscoveryService extends AbstractDiscoveryService
*/ */
public void deviceDiscovered(Device device) { public void deviceDiscovered(Device device) {
if (device.active) { if (device.active) {
ThingUID accountUID = accountHandler.getThing().getUID(); ThingUID accountUID = thingHandler.getThing().getUID();
ThingUID thingUID = UidUtils.generateThingUID(device, accountHandler.getThing()); ThingUID thingUID = UidUtils.generateThingUID(device, thingHandler.getThing());
try { try {
DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withBridge(accountUID) DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withBridge(accountUID)

View File

@ -20,6 +20,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -28,6 +30,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Gaël L'hopital - Initial contribution * @author Gaël L'hopital - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = Ipx800Actions.class)
@ThingActionsScope(name = "gce") @ThingActionsScope(name = "gce")
@NonNullByDefault @NonNullByDefault
public class Ipx800Actions implements ThingActions { public class Ipx800Actions implements ThingActions {

View File

@ -25,14 +25,13 @@ import org.openhab.binding.groupepsa.internal.GroupePSABindingConstants;
import org.openhab.binding.groupepsa.internal.bridge.GroupePSABridgeHandler; 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.api.dto.Vehicle;
import org.openhab.binding.groupepsa.internal.rest.exceptions.GroupePSACommunicationException; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; 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.Component;
import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -42,48 +41,25 @@ import org.slf4j.LoggerFactory;
* *
* @author Arjan Mels - Initial contribution * @author Arjan Mels - Initial contribution
*/ */
@Component(service = ThingHandlerService.class) @Component(scope = ServiceScope.PROTOTYPE, service = GroupePSADiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class GroupePSADiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { public class GroupePSADiscoveryService extends AbstractThingHandlerDiscoveryService<GroupePSABridgeHandler> {
private final Logger logger = LoggerFactory.getLogger(GroupePSADiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(GroupePSADiscoveryService.class);
private @Nullable GroupePSABridgeHandler bridgeHandler;
public GroupePSADiscoveryService() { public GroupePSADiscoveryService() {
super(Set.of(THING_TYPE_VEHICLE), 10, false); super(GroupePSABridgeHandler.class, 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();
} }
@Override @Override
protected void startScan() { protected void startScan() {
try { try {
GroupePSABridgeHandler localBridgeHandler = bridgeHandler; List<Vehicle> vehicles = thingHandler.getVehicles();
if (localBridgeHandler == null) {
return;
}
List<Vehicle> vehicles = localBridgeHandler.getVehicles();
if (vehicles == null || vehicles.isEmpty()) { if (vehicles == null || vehicles.isEmpty()) {
logger.warn("No vehicles found"); logger.warn("No vehicles found");
return; return;
} }
for (Vehicle vehicle : vehicles) { for (Vehicle vehicle : vehicles) {
ThingUID bridgeUID = localBridgeHandler.getThing().getUID(); ThingUID bridgeUID = thingHandler.getThing().getUID();
ThingTypeUID thingTypeUID = THING_TYPE_VEHICLE; ThingTypeUID thingTypeUID = THING_TYPE_VEHICLE;
String id = vehicle.getId(); String id = vehicle.getId();
if (id != null) { if (id != null) {

View File

@ -27,14 +27,13 @@ import org.openhab.binding.haywardomnilogic.internal.HaywardBindingConstants;
import org.openhab.binding.haywardomnilogic.internal.HaywardException; import org.openhab.binding.haywardomnilogic.internal.HaywardException;
import org.openhab.binding.haywardomnilogic.internal.HaywardTypeToRequest; import org.openhab.binding.haywardomnilogic.internal.HaywardTypeToRequest;
import org.openhab.binding.haywardomnilogic.internal.handler.HaywardBridgeHandler; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; 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.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -43,34 +42,20 @@ import org.slf4j.LoggerFactory;
* *
* @author Matt Myers - Initial contribution * @author Matt Myers - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = HaywardDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class HaywardDiscoveryService extends AbstractDiscoveryService implements DiscoveryService, ThingHandlerService { public class HaywardDiscoveryService extends AbstractThingHandlerDiscoveryService<HaywardBridgeHandler> {
private final Logger logger = LoggerFactory.getLogger(HaywardDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(HaywardDiscoveryService.class);
private @Nullable HaywardBridgeHandler discoveryBridgehandler;
public HaywardDiscoveryService() { public HaywardDiscoveryService() {
super(THING_TYPES_UIDS, 0, false); super(HaywardBridgeHandler.class, THING_TYPES_UIDS, 0, false);
}
@Override
public void activate() {
super.activate(null);
}
@Override
public void deactivate() {
super.deactivate();
} }
@Override @Override
protected void startScan() { protected void startScan() {
HaywardBridgeHandler bridgehandler = discoveryBridgehandler;
try { try {
if (bridgehandler != null) { String xmlResults = thingHandler.getMspConfig();
String xmlResults = bridgehandler.getMspConfig(); mspConfigDiscovery(xmlResults);
mspConfigDiscovery(xmlResults);
}
} catch (HaywardException e) { } catch (HaywardException e) {
logger.warn("Exception during discovery scan: {}", e.getMessage()); logger.warn("Exception during discovery scan: {}", e.getMessage());
} catch (InterruptedException e) { } catch (InterruptedException e) {
@ -83,36 +68,30 @@ public class HaywardDiscoveryService extends AbstractDiscoveryService implements
List<String> names = new ArrayList<>(); List<String> names = new ArrayList<>();
Map<String, Object> backyardProperties = new HashMap<>(); Map<String, Object> backyardProperties = new HashMap<>();
Map<String, Object> bowProperties = new HashMap<>(); Map<String, Object> bowProperties = new HashMap<>();
HaywardBridgeHandler bridgehandler = discoveryBridgehandler;
if (bridgehandler == null) {
return;
}
// Find Backyard // Find Backyard
names = bridgehandler.evaluateXPath("//Backyard/Name/text()", xmlResponse); names = thingHandler.evaluateXPath("//Backyard/Name/text()", xmlResponse);
for (int i = 0; i < names.size(); i++) { for (int i = 0; i < names.size(); i++) {
backyardProperties.put(HaywardBindingConstants.PROPERTY_TYPE, HaywardTypeToRequest.BACKYARD); 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); onDeviceDiscovered(HaywardBindingConstants.THING_TYPE_BACKYARD, names.get(i), backyardProperties);
} }
// Find Bodies of Water // Find Bodies of Water
systemIDs = bridgehandler.evaluateXPath("//Body-of-water/System-Id/text()", xmlResponse); systemIDs = thingHandler.evaluateXPath("//Body-of-water/System-Id/text()", xmlResponse);
names = bridgehandler.evaluateXPath("//Body-of-water/Name/text()", xmlResponse); names = thingHandler.evaluateXPath("//Body-of-water/Name/text()", xmlResponse);
final List<String> bowProperty1 = bridgehandler.evaluateXPath("//Body-of-water/Type/text()", xmlResponse); final List<String> bowProperty1 = thingHandler.evaluateXPath("//Body-of-water/Type/text()", xmlResponse);
final List<String> bowProperty2 = bridgehandler.evaluateXPath("//Body-of-water/Shared-Type/text()", final List<String> bowProperty2 = thingHandler.evaluateXPath("//Body-of-water/Shared-Type/text()", xmlResponse);
final List<String> bowProperty3 = thingHandler.evaluateXPath("//Body-of-water/Shared-Priority/text()",
xmlResponse); xmlResponse);
final List<String> bowProperty3 = bridgehandler.evaluateXPath("//Body-of-water/Shared-Priority/text()", final List<String> bowProperty4 = thingHandler
xmlResponse);
final List<String> bowProperty4 = bridgehandler
.evaluateXPath("//Body-of-water/Shared-Equipment-System-ID/text()", xmlResponse); .evaluateXPath("//Body-of-water/Shared-Equipment-System-ID/text()", xmlResponse);
final List<String> bowProperty5 = bridgehandler.evaluateXPath("//Body-of-water/Supports-Spillover/text()", final List<String> bowProperty5 = thingHandler.evaluateXPath("//Body-of-water/Supports-Spillover/text()",
xmlResponse); xmlResponse);
final List<String> bowProperty6 = bridgehandler.evaluateXPath("//Body-of-water/Size-In-Gallons/text()", final List<String> bowProperty6 = thingHandler.evaluateXPath("//Body-of-water/Size-In-Gallons/text()",
xmlResponse); xmlResponse);
for (int i = 0; i < systemIDs.size(); i++) { for (int i = 0; i < systemIDs.size(); i++) {
@ -129,16 +108,16 @@ public class HaywardDiscoveryService extends AbstractDiscoveryService implements
} }
// Find Chlorinators // Find Chlorinators
final List<String> chlorinatorProperty1 = bridgehandler final List<String> chlorinatorProperty1 = thingHandler
.evaluateXPath("//Body-of-water/Chlorinator/Shared-Type/text()", xmlResponse); .evaluateXPath("//Body-of-water/Chlorinator/Shared-Type/text()", xmlResponse);
final List<String> chlorinatorProperty2 = bridgehandler.evaluateXPath("//Body-of-water/Chlorinator/Mode/text()", final List<String> chlorinatorProperty2 = thingHandler.evaluateXPath("//Body-of-water/Chlorinator/Mode/text()",
xmlResponse); xmlResponse);
final List<String> chlorinatorProperty3 = bridgehandler final List<String> chlorinatorProperty3 = thingHandler
.evaluateXPath("//Body-of-water/Chlorinator/Cell-Type/text()", xmlResponse); .evaluateXPath("//Body-of-water/Chlorinator/Cell-Type/text()", xmlResponse);
final List<String> chlorinatorProperty4 = bridgehandler final List<String> chlorinatorProperty4 = thingHandler
.evaluateXPath("//Body-of-water/Chlorinator/Dispenser-Type/text()", xmlResponse); .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) -> { HaywardBindingConstants.THING_TYPE_CHLORINATOR, (props, i) -> {
props.put(HaywardBindingConstants.PROPERTY_CHLORINATOR_SHAREDTYPE, chlorinatorProperty1.get(i)); props.put(HaywardBindingConstants.PROPERTY_CHLORINATOR_SHAREDTYPE, chlorinatorProperty1.get(i));
props.put(HaywardBindingConstants.PROPERTY_CHLORINATOR_MODE, chlorinatorProperty2.get(i)); props.put(HaywardBindingConstants.PROPERTY_CHLORINATOR_MODE, chlorinatorProperty2.get(i));
@ -147,41 +126,41 @@ public class HaywardDiscoveryService extends AbstractDiscoveryService implements
}); });
// Find ColorLogic Lights // Find ColorLogic Lights
final List<String> colorLogicProperty1 = bridgehandler.evaluateXPath("//Backyard//ColorLogic-Light/Type/text()", final List<String> colorLogicProperty1 = thingHandler.evaluateXPath("//Backyard//ColorLogic-Light/Type/text()",
xmlResponse); xmlResponse);
discoverDevices(bridgehandler, xmlResponse, "ColorLogic-Light", HaywardTypeToRequest.COLORLOGIC, discoverDevices(thingHandler, xmlResponse, "ColorLogic-Light", HaywardTypeToRequest.COLORLOGIC,
HaywardBindingConstants.THING_TYPE_COLORLOGIC, (props, i) -> { HaywardBindingConstants.THING_TYPE_COLORLOGIC, (props, i) -> {
props.put(HaywardBindingConstants.PROPERTY_COLORLOGIC_TYPE, colorLogicProperty1.get(i)); props.put(HaywardBindingConstants.PROPERTY_COLORLOGIC_TYPE, colorLogicProperty1.get(i));
}); });
// Find Filters // Find Filters
final List<String> filterProperty1 = bridgehandler.evaluateXPath("//Body-of-water/Filter/Shared-Type/text()", final List<String> filterProperty1 = thingHandler.evaluateXPath("//Body-of-water/Filter/Shared-Type/text()",
xmlResponse); xmlResponse);
final List<String> filterProperty2 = bridgehandler.evaluateXPath("//Body-of-water/Filter/Filter-Type/text()", final List<String> filterProperty2 = thingHandler.evaluateXPath("//Body-of-water/Filter/Filter-Type/text()",
xmlResponse); xmlResponse);
final List<String> filterProperty3 = bridgehandler final List<String> filterProperty3 = thingHandler.evaluateXPath("//Body-of-water/Filter/Priming-Enabled/text()",
.evaluateXPath("//Body-of-water/Filter/Priming-Enabled/text()", xmlResponse);
final List<String> filterProperty4 = bridgehandler.evaluateXPath("//Body-of-water/Filter/Min-Pump-Speed/text()",
xmlResponse); xmlResponse);
final List<String> filterProperty5 = bridgehandler.evaluateXPath("//Body-of-water/Filter/Max-Pump-Speed/text()", final List<String> filterProperty4 = thingHandler.evaluateXPath("//Body-of-water/Filter/Min-Pump-Speed/text()",
xmlResponse); xmlResponse);
final List<String> filterProperty6 = bridgehandler.evaluateXPath("//Body-of-water/Filter/Min-Pump-RPM/text()", final List<String> filterProperty5 = thingHandler.evaluateXPath("//Body-of-water/Filter/Max-Pump-Speed/text()",
xmlResponse); xmlResponse);
final List<String> filterProperty7 = bridgehandler.evaluateXPath("//Body-of-water/Filter/Max-Pump-RPM/text()", final List<String> filterProperty6 = thingHandler.evaluateXPath("//Body-of-water/Filter/Min-Pump-RPM/text()",
xmlResponse); xmlResponse);
final List<String> filterProperty8 = bridgehandler final List<String> filterProperty7 = thingHandler.evaluateXPath("//Body-of-water/Filter/Max-Pump-RPM/text()",
xmlResponse);
final List<String> filterProperty8 = thingHandler
.evaluateXPath("//Body-of-water/Filter/Vsp-Low-Pump-Speed/text()", xmlResponse); .evaluateXPath("//Body-of-water/Filter/Vsp-Low-Pump-Speed/text()", xmlResponse);
final List<String> filterProperty9 = bridgehandler final List<String> filterProperty9 = thingHandler
.evaluateXPath("//Body-of-water/Filter/Vsp-Medium-Pump-Speed/text()", xmlResponse); .evaluateXPath("//Body-of-water/Filter/Vsp-Medium-Pump-Speed/text()", xmlResponse);
final List<String> filterProperty10 = bridgehandler final List<String> filterProperty10 = thingHandler
.evaluateXPath("//Body-of-water/Filter/Vsp-High-Pump-Speed/text()", xmlResponse); .evaluateXPath("//Body-of-water/Filter/Vsp-High-Pump-Speed/text()", xmlResponse);
final List<String> filterProperty11 = bridgehandler final List<String> filterProperty11 = thingHandler
.evaluateXPath("//Body-of-water/Filter/Vsp-Custom-Pump-Speed/text()", xmlResponse); .evaluateXPath("//Body-of-water/Filter/Vsp-Custom-Pump-Speed/text()", xmlResponse);
final List<String> filterProperty12 = bridgehandler final List<String> filterProperty12 = thingHandler
.evaluateXPath("//Body-of-water/Filter/Freeze-Protect-Override-Interval/text()", xmlResponse); .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) -> { HaywardBindingConstants.THING_TYPE_FILTER, (props, i) -> {
props.put(HaywardBindingConstants.PROPERTY_FILTER_SHAREDTYPE, filterProperty1.get(i)); props.put(HaywardBindingConstants.PROPERTY_FILTER_SHAREDTYPE, filterProperty1.get(i));
props.put(HaywardBindingConstants.PROPERTY_FILTER_FILTERTYPE, filterProperty2.get(i)); props.put(HaywardBindingConstants.PROPERTY_FILTER_FILTERTYPE, filterProperty2.get(i));
@ -199,14 +178,14 @@ public class HaywardDiscoveryService extends AbstractDiscoveryService implements
}); });
// Find Heaters // Find Heaters
final List<String> heaterProperty1 = bridgehandler final List<String> heaterProperty1 = thingHandler
.evaluateXPath("//Body-of-water/Heater/Operation/Heater-Equipment/Type/text()", xmlResponse); .evaluateXPath("//Body-of-water/Heater/Operation/Heater-Equipment/Type/text()", xmlResponse);
final List<String> heaterProperty2 = bridgehandler final List<String> heaterProperty2 = thingHandler
.evaluateXPath("//Body-of-water/Heater/Operation/Heater-Equipment/Heater-Type/text()", xmlResponse); .evaluateXPath("//Body-of-water/Heater/Operation/Heater-Equipment/Heater-Type/text()", xmlResponse);
final List<String> heaterProperty3 = bridgehandler.evaluateXPath( final List<String> heaterProperty3 = thingHandler.evaluateXPath(
"//Body-of-water/Heater/Operation/Heater-Equipment/Shared-Equipment-System-ID/text()", xmlResponse); "//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) -> { HaywardBindingConstants.THING_TYPE_HEATER, (props, i) -> {
props.put(HaywardBindingConstants.PROPERTY_HEATER_TYPE, heaterProperty1.get(i)); props.put(HaywardBindingConstants.PROPERTY_HEATER_TYPE, heaterProperty1.get(i));
props.put(HaywardBindingConstants.PROPERTY_HEATER_HEATERTYPE, heaterProperty2.get(i)); props.put(HaywardBindingConstants.PROPERTY_HEATER_HEATERTYPE, heaterProperty2.get(i));
@ -214,29 +193,29 @@ public class HaywardDiscoveryService extends AbstractDiscoveryService implements
}); });
// Find Pumps // Find Pumps
final List<String> pumpProperty1 = bridgehandler.evaluateXPath("//Body-of-water/Pump/Type/text()", xmlResponse); final List<String> pumpProperty1 = thingHandler.evaluateXPath("//Body-of-water/Pump/Type/text()", xmlResponse);
final List<String> pumpProperty2 = bridgehandler.evaluateXPath("//Body-of-water/Pump/Function/text()", final List<String> pumpProperty2 = thingHandler.evaluateXPath("//Body-of-water/Pump/Function/text()",
xmlResponse); xmlResponse);
final List<String> pumpProperty3 = bridgehandler.evaluateXPath("//Body-of-water/Pump/Priming-Enabled/text()", final List<String> pumpProperty3 = thingHandler.evaluateXPath("//Body-of-water/Pump/Priming-Enabled/text()",
xmlResponse); xmlResponse);
final List<String> pumpProperty4 = bridgehandler.evaluateXPath("//Body-of-water/Pump/Min-Pump-Speed/text()", final List<String> pumpProperty4 = thingHandler.evaluateXPath("//Body-of-water/Pump/Min-Pump-Speed/text()",
xmlResponse); xmlResponse);
final List<String> pumpProperty5 = bridgehandler.evaluateXPath("//Body-of-water/Pump/Max-Pump-Speed/text()", final List<String> pumpProperty5 = thingHandler.evaluateXPath("//Body-of-water/Pump/Max-Pump-Speed/text()",
xmlResponse); xmlResponse);
final List<String> pumpProperty6 = bridgehandler.evaluateXPath("//Body-of-water/Pump/Min-Pump-RPM/text()", final List<String> pumpProperty6 = thingHandler.evaluateXPath("//Body-of-water/Pump/Min-Pump-RPM/text()",
xmlResponse); xmlResponse);
final List<String> pumpProperty7 = bridgehandler.evaluateXPath("//Body-of-water/Pump/Max-Pump-RPM/text()", final List<String> pumpProperty7 = thingHandler.evaluateXPath("//Body-of-water/Pump/Max-Pump-RPM/text()",
xmlResponse); xmlResponse);
final List<String> pumpProperty8 = bridgehandler.evaluateXPath("//Body-of-water/Pump/Vsp-Low-Pump-Speed/text()", final List<String> pumpProperty8 = thingHandler.evaluateXPath("//Body-of-water/Pump/Vsp-Low-Pump-Speed/text()",
xmlResponse); xmlResponse);
final List<String> pumpProperty9 = bridgehandler final List<String> pumpProperty9 = thingHandler
.evaluateXPath("//Body-of-water/Pump/Vsp-Medium-Pump-Speed/text()", xmlResponse); .evaluateXPath("//Body-of-water/Pump/Vsp-Medium-Pump-Speed/text()", xmlResponse);
final List<String> pumpProperty10 = bridgehandler final List<String> pumpProperty10 = thingHandler
.evaluateXPath("//Body-of-water/Pump/Vsp-High-Pump-Speed/text()", xmlResponse); .evaluateXPath("//Body-of-water/Pump/Vsp-High-Pump-Speed/text()", xmlResponse);
final List<String> pumpProperty11 = bridgehandler final List<String> pumpProperty11 = thingHandler
.evaluateXPath("//Body-of-water/Pump/Vsp-Custom-Pump-Speed/text()", xmlResponse); .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) -> { HaywardBindingConstants.THING_TYPE_PUMP, (props, i) -> {
props.put(HaywardBindingConstants.PROPERTY_PUMP_TYPE, pumpProperty1.get(i)); props.put(HaywardBindingConstants.PROPERTY_PUMP_TYPE, pumpProperty1.get(i));
props.put(HaywardBindingConstants.PROPERTY_PUMP_FUNCTION, pumpProperty2.get(i)); props.put(HaywardBindingConstants.PROPERTY_PUMP_FUNCTION, pumpProperty2.get(i));
@ -252,27 +231,27 @@ public class HaywardDiscoveryService extends AbstractDiscoveryService implements
}); });
// Find Relays // Find Relays
final List<String> relayProperty1 = bridgehandler.evaluateXPath("//Backyard//Relay/Type/text()", xmlResponse); final List<String> relayProperty1 = thingHandler.evaluateXPath("//Backyard//Relay/Type/text()", xmlResponse);
final List<String> relayProperty2 = bridgehandler.evaluateXPath("//Backyard//Relay/Function/text()", final List<String> relayProperty2 = thingHandler.evaluateXPath("//Backyard//Relay/Function/text()",
xmlResponse); xmlResponse);
discoverDevices(bridgehandler, xmlResponse, "Relay", HaywardTypeToRequest.RELAY, discoverDevices(thingHandler, xmlResponse, "Relay", HaywardTypeToRequest.RELAY,
HaywardBindingConstants.THING_TYPE_RELAY, (props, i) -> { HaywardBindingConstants.THING_TYPE_RELAY, (props, i) -> {
props.put(HaywardBindingConstants.PROPERTY_RELAY_TYPE, relayProperty1.get(i)); props.put(HaywardBindingConstants.PROPERTY_RELAY_TYPE, relayProperty1.get(i));
props.put(HaywardBindingConstants.PROPERTY_RELAY_FUNCTION, relayProperty2.get(i)); props.put(HaywardBindingConstants.PROPERTY_RELAY_FUNCTION, relayProperty2.get(i));
}); });
// Find Virtual Heaters // Find Virtual Heaters
final List<String> virtualHeaterProperty1 = bridgehandler final List<String> virtualHeaterProperty1 = thingHandler
.evaluateXPath("//Body-of-water/Heater/Shared-Type/text()", xmlResponse); .evaluateXPath("//Body-of-water/Heater/Shared-Type/text()", xmlResponse);
final List<String> virtualHeaterProperty2 = bridgehandler final List<String> virtualHeaterProperty2 = thingHandler
.evaluateXPath("//Body-of-water/Heater/Min-Settable-Water-Temp/text()", xmlResponse); .evaluateXPath("//Body-of-water/Heater/Min-Settable-Water-Temp/text()", xmlResponse);
final List<String> virtualHeaterProperty3 = bridgehandler final List<String> virtualHeaterProperty3 = thingHandler
.evaluateXPath("//Body-of-water/Heater/Max-Settable-Water-Temp/text()", xmlResponse); .evaluateXPath("//Body-of-water/Heater/Max-Settable-Water-Temp/text()", xmlResponse);
final List<String> virtualHeaterProperty4 = bridgehandler final List<String> virtualHeaterProperty4 = thingHandler
.evaluateXPath("//Body-of-water/Heater/Max-Water-Temp/text()", xmlResponse); .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) -> { HaywardBindingConstants.THING_TYPE_VIRTUALHEATER, (props, i) -> {
props.put(HaywardBindingConstants.PROPERTY_VIRTUALHEATER_SHAREDTYPE, virtualHeaterProperty1.get(i)); props.put(HaywardBindingConstants.PROPERTY_VIRTUALHEATER_SHAREDTYPE, virtualHeaterProperty1.get(i));
props.put(HaywardBindingConstants.PROPERTY_VIRTUALHEATER_MINSETTABLEWATERTEMP, props.put(HaywardBindingConstants.PROPERTY_VIRTUALHEATER_MINSETTABLEWATERTEMP,
@ -333,7 +312,7 @@ public class HaywardDiscoveryService extends AbstractDiscoveryService implements
} }
public void onDeviceDiscovered(ThingTypeUID thingType, String label, Map<String, Object> properties) { public void onDeviceDiscovered(ThingTypeUID thingType, String label, Map<String, Object> properties) {
HaywardBridgeHandler bridgehandler = discoveryBridgehandler; HaywardBridgeHandler bridgehandler = thingHandler;
String systemID = (String) properties.get(HaywardBindingConstants.PROPERTY_SYSTEM_ID); String systemID = (String) properties.get(HaywardBindingConstants.PROPERTY_SYSTEM_ID);
if (bridgehandler != null) { if (bridgehandler != null) {
if (systemID != null) { if (systemID != null) {
@ -346,16 +325,4 @@ public class HaywardDiscoveryService extends AbstractDiscoveryService implements
} }
} }
} }
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
if (handler instanceof HaywardBridgeHandler bridgeHandler) {
this.discoveryBridgehandler = bridgeHandler;
}
}
@Override
public @Nullable ThingHandler getThingHandler() {
return discoveryBridgehandler;
}
} }

View File

@ -25,6 +25,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -33,6 +35,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Martin van Wingerden - Initial contribution * @author Martin van Wingerden - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = HeosActions.class)
@ThingActionsScope(name = "heos") @ThingActionsScope(name = "heos")
@NonNullByDefault @NonNullByDefault
public class HeosActions implements ThingActions { public class HeosActions implements ThingActions {

View File

@ -24,14 +24,13 @@ import org.openhab.binding.homeconnect.internal.client.exception.AuthorizationEx
import org.openhab.binding.homeconnect.internal.client.exception.CommunicationException; import org.openhab.binding.homeconnect.internal.client.exception.CommunicationException;
import org.openhab.binding.homeconnect.internal.client.model.HomeAppliance; import org.openhab.binding.homeconnect.internal.client.model.HomeAppliance;
import org.openhab.binding.homeconnect.internal.handler.HomeConnectBridgeHandler; import org.openhab.binding.homeconnect.internal.handler.HomeConnectBridgeHandler;
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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; 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.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -40,95 +39,71 @@ import org.slf4j.LoggerFactory;
* *
* @author Jonas Brüstel - Initial contribution * @author Jonas Brüstel - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = HomeConnectDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class HomeConnectDiscoveryService extends AbstractDiscoveryService public class HomeConnectDiscoveryService extends AbstractThingHandlerDiscoveryService<HomeConnectBridgeHandler> {
implements DiscoveryService, ThingHandlerService {
private static final int SEARCH_TIME_SEC = 20; private static final int SEARCH_TIME_SEC = 20;
private final Logger logger = LoggerFactory.getLogger(HomeConnectDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(HomeConnectDiscoveryService.class);
private @Nullable HomeConnectBridgeHandler bridgeHandler;
/** /**
* Construct a {@link HomeConnectDiscoveryService}. * Construct a {@link HomeConnectDiscoveryService}.
* *
*/ */
public HomeConnectDiscoveryService() { public HomeConnectDiscoveryService() {
super(DISCOVERABLE_DEVICE_THING_TYPES_UIDS, SEARCH_TIME_SEC, true); super(HomeConnectBridgeHandler.class, 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;
} }
@Override @Override
protected void startScan() { protected void startScan() {
logger.debug("Starting device scan."); logger.debug("Starting device scan.");
var bridgeHandler = this.bridgeHandler; HomeConnectApiClient apiClient = thingHandler.getApiClient();
if (bridgeHandler != null) {
HomeConnectApiClient apiClient = bridgeHandler.getApiClient();
try { try {
List<HomeAppliance> appliances = apiClient.getHomeAppliances(); List<HomeAppliance> appliances = apiClient.getHomeAppliances();
logger.debug("Scan found {} devices.", appliances.size()); logger.debug("Scan found {} devices.", appliances.size());
// add found devices // add found devices
for (HomeAppliance appliance : appliances) { for (HomeAppliance appliance : appliances) {
@Nullable @Nullable
ThingTypeUID thingTypeUID = getThingTypeUID(appliance); ThingTypeUID thingTypeUID = getThingTypeUID(appliance);
if (thingTypeUID != null) { if (thingTypeUID != null) {
logger.debug("Found {} ({}).", appliance.getHaId(), appliance.getType().toUpperCase()); logger.debug("Found {} ({}).", appliance.getHaId(), appliance.getType().toUpperCase());
Map<String, Object> properties = Map.of(HA_ID, appliance.getHaId()); Map<String, Object> properties = Map.of(HA_ID, appliance.getHaId());
String name = appliance.getBrand() + " " + appliance.getName() + " (" + appliance.getHaId() String name = appliance.getBrand() + " " + appliance.getName() + " (" + appliance.getHaId() + ")";
+ ")";
DiscoveryResult discoveryResult = DiscoveryResultBuilder DiscoveryResult discoveryResult = DiscoveryResultBuilder
.create(new ThingUID(BINDING_ID, appliance.getType(), .create(new ThingUID(BINDING_ID, appliance.getType(),
bridgeHandler.getThing().getUID().getId(), appliance.getHaId())) thingHandler.getThing().getUID().getId(), appliance.getHaId()))
.withThingType(thingTypeUID).withProperties(properties) .withThingType(thingTypeUID).withProperties(properties).withRepresentationProperty(HA_ID)
.withRepresentationProperty(HA_ID).withBridge(bridgeHandler.getThing().getUID()) .withBridge(thingHandler.getThing().getUID()).withLabel(name).build();
.withLabel(name).build(); thingDiscovered(discoveryResult);
thingDiscovered(discoveryResult); } else {
} else { logger.debug("Ignoring unsupported device {} of type {}.", appliance.getHaId(),
logger.debug("Ignoring unsupported device {} of type {}.", appliance.getHaId(), appliance.getType());
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."); logger.debug("Finished device scan.");
} }
@Override @Override
public void deactivate() { public void dispose() {
super.deactivate(); super.dispose();
var bridgeHandler = this.bridgeHandler; removeOlderResults(System.currentTimeMillis(), thingHandler.getThing().getUID());
if (bridgeHandler != null) {
removeOlderResults(System.currentTimeMillis(), bridgeHandler.getThing().getUID());
}
} }
@Override @Override
protected synchronized void stopScan() { protected synchronized void stopScan() {
super.stopScan(); super.stopScan();
var bridgeHandler = this.bridgeHandler; removeOlderResults(getTimestampOfLastScan(), thingHandler.getThing().getUID());
if (bridgeHandler != null) {
removeOlderResults(getTimestampOfLastScan(), bridgeHandler.getThing().getUID());
}
} }
private @Nullable ThingTypeUID getThingTypeUID(HomeAppliance appliance) { private @Nullable ThingTypeUID getThingTypeUID(HomeAppliance appliance) {

View File

@ -18,23 +18,21 @@ import java.util.Set;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.homematic.internal.common.HomematicConfig; import org.openhab.binding.homematic.internal.common.HomematicConfig;
import org.openhab.binding.homematic.internal.communicator.HomematicGateway; import org.openhab.binding.homematic.internal.communicator.HomematicGateway;
import org.openhab.binding.homematic.internal.handler.HomematicBridgeHandler; import org.openhab.binding.homematic.internal.handler.HomematicBridgeHandler;
import org.openhab.binding.homematic.internal.model.HmDevice; import org.openhab.binding.homematic.internal.model.HmDevice;
import org.openhab.binding.homematic.internal.type.UidUtils; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; 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.Thing;
import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -43,44 +41,24 @@ import org.slf4j.LoggerFactory;
* *
* @author Gerhard Riegler - Initial contribution * @author Gerhard Riegler - Initial contribution
*/ */
public class HomematicDeviceDiscoveryService extends AbstractDiscoveryService @Component(scope = ServiceScope.PROTOTYPE, service = HomematicDeviceDiscoveryService.class)
implements DiscoveryService, ThingHandlerService { public class HomematicDeviceDiscoveryService
extends AbstractThingHandlerDiscoveryService<@NonNull HomematicBridgeHandler> {
private final Logger logger = LoggerFactory.getLogger(HomematicDeviceDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(HomematicDeviceDiscoveryService.class);
private static final int DISCOVER_TIMEOUT_SECONDS = 300; private static final int DISCOVER_TIMEOUT_SECONDS = 300;
private @NonNullByDefault({}) HomematicBridgeHandler bridgeHandler;
private Future<?> loadDevicesFuture; private Future<?> loadDevicesFuture;
private volatile boolean isInInstallMode = false; private volatile boolean isInInstallMode = false;
private volatile Object installModeSync = new Object(); private volatile Object installModeSync = new Object();
public HomematicDeviceDiscoveryService() { 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 @Override
public void setThingHandler(@Nullable ThingHandler handler) { public void initialize() {
if (handler instanceof HomematicBridgeHandler homematicBridgeHandler) { thingHandler.setDiscoveryService(this);
this.bridgeHandler = homematicBridgeHandler; super.initialize();
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();
} }
@Override @Override
@ -96,13 +74,10 @@ public class HomematicDeviceDiscoveryService extends AbstractDiscoveryService
*/ */
private void enableInstallMode() { private void enableInstallMode() {
try { try {
HomematicGateway gateway = bridgeHandler.getGateway(); HomematicGateway gateway = thingHandler.getGateway();
ThingStatus bridgeStatus = null; Thing bridge = thingHandler.getThing();
ThingStatus bridgeStatus = bridge.getStatus();
if (bridgeHandler != null) {
Thing bridge = bridgeHandler.getThing();
bridgeStatus = bridge.getStatus();
}
if (ThingStatus.ONLINE == bridgeStatus) { if (ThingStatus.ONLINE == bridgeStatus) {
gateway.setInstallMode(true, getInstallModeDuration()); gateway.setInstallMode(true, getInstallModeDuration());
@ -122,10 +97,7 @@ public class HomematicDeviceDiscoveryService extends AbstractDiscoveryService
} }
private int getInstallModeDuration() { private int getInstallModeDuration() {
if (bridgeHandler != null) { return thingHandler.getThing().getConfiguration().as(HomematicConfig.class).getInstallModeDuration();
return bridgeHandler.getThing().getConfiguration().as(HomematicConfig.class).getInstallModeDuration();
}
return HomematicConfig.DEFAULT_INSTALL_MODE_DURATION;
} }
@Override @Override
@ -136,10 +108,8 @@ public class HomematicDeviceDiscoveryService extends AbstractDiscoveryService
@Override @Override
public synchronized void stopScan() { public synchronized void stopScan() {
logger.debug("Stopping Homematic discovery scan"); logger.debug("Stopping Homematic discovery scan");
if (bridgeHandler != null && bridgeHandler.getGateway() != null) { disableInstallMode();
disableInstallMode(); thingHandler.getGateway().cancelLoadAllDeviceMetadata();
bridgeHandler.getGateway().cancelLoadAllDeviceMetadata();
}
waitForScanFinishing(); waitForScanFinishing();
super.stopScan(); super.stopScan();
} }
@ -150,7 +120,7 @@ public class HomematicDeviceDiscoveryService extends AbstractDiscoveryService
if (isInInstallMode) { if (isInInstallMode) {
isInInstallMode = false; isInInstallMode = false;
installModeSync.notify(); installModeSync.notify();
bridgeHandler.getGateway().setInstallMode(false, 0); thingHandler.getGateway().setInstallMode(false, 0);
} }
} }
@ -192,6 +162,7 @@ public class HomematicDeviceDiscoveryService extends AbstractDiscoveryService
} catch (Exception ex) { } catch (Exception ex) {
logger.error("Error waiting for device discovery scan: {}", ex.getMessage(), ex); logger.error("Error waiting for device discovery scan: {}", ex.getMessage(), ex);
} }
HomematicBridgeHandler bridgeHandler = thingHandler;
String gatewayId = bridgeHandler != null && bridgeHandler.getGateway() != null String gatewayId = bridgeHandler != null && bridgeHandler.getGateway() != null
? bridgeHandler.getGateway().getId() ? bridgeHandler.getGateway().getId()
: "UNKNOWN"; : "UNKNOWN";
@ -202,17 +173,17 @@ public class HomematicDeviceDiscoveryService extends AbstractDiscoveryService
* Starts a thread which loads all Homematic devices connected to the gateway. * Starts a thread which loads all Homematic devices connected to the gateway.
*/ */
public void loadDevices() { public void loadDevices() {
if (loadDevicesFuture == null && bridgeHandler.getGateway() != null) { if (loadDevicesFuture == null && thingHandler.getGateway() != null) {
loadDevicesFuture = scheduler.submit(() -> { loadDevicesFuture = scheduler.submit(() -> {
try { try {
final HomematicGateway gateway = bridgeHandler.getGateway(); final HomematicGateway gateway = thingHandler.getGateway();
gateway.loadAllDeviceMetadata(); gateway.loadAllDeviceMetadata();
bridgeHandler.getTypeGenerator().validateFirmwares(); thingHandler.getTypeGenerator().validateFirmwares();
} catch (Throwable ex) { } catch (Throwable ex) {
logger.error("{}", ex.getMessage(), ex); logger.error("{}", ex.getMessage(), ex);
} finally { } finally {
loadDevicesFuture = null; loadDevicesFuture = null;
bridgeHandler.setOfflineStatus(); thingHandler.setOfflineStatus();
removeOlderResults(getTimestampOfLastScan()); removeOlderResults(getTimestampOfLastScan());
} }
}); });
@ -225,7 +196,7 @@ public class HomematicDeviceDiscoveryService extends AbstractDiscoveryService
* Removes the Homematic device. * Removes the Homematic device.
*/ */
public void deviceRemoved(HmDevice device) { public void deviceRemoved(HmDevice device) {
ThingUID thingUID = UidUtils.generateThingUID(device, bridgeHandler.getThing()); ThingUID thingUID = UidUtils.generateThingUID(device, thingHandler.getThing());
thingRemoved(thingUID); thingRemoved(thingUID);
} }
@ -233,12 +204,11 @@ public class HomematicDeviceDiscoveryService extends AbstractDiscoveryService
* Generates the DiscoveryResult from a Homematic device. * Generates the DiscoveryResult from a Homematic device.
*/ */
public void deviceDiscovered(HmDevice device) { public void deviceDiscovered(HmDevice device) {
ThingUID bridgeUID = bridgeHandler.getThing().getUID(); ThingUID bridgeUID = thingHandler.getThing().getUID();
ThingTypeUID typeUid = UidUtils.generateThingTypeUID(device); ThingTypeUID typeUid = UidUtils.generateThingTypeUID(device);
ThingUID thingUID = new ThingUID(typeUid, bridgeUID, device.getAddress()); ThingUID thingUID = new ThingUID(typeUid, bridgeUID, device.getAddress());
String label = device.getName() != null ? device.getName() : device.getAddress(); String label = device.getName() != null ? device.getName() : device.getAddress();
long timeToLive = bridgeHandler.getThing().getConfiguration().as(HomematicConfig.class) long timeToLive = thingHandler.getThing().getConfiguration().as(HomematicConfig.class).getDiscoveryTimeToLive();
.getDiscoveryTimeToLive();
DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withBridge(bridgeUID).withLabel(label) DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withBridge(bridgeUID).withLabel(label)
.withProperty(Thing.PROPERTY_SERIAL_NUMBER, device.getAddress()) .withProperty(Thing.PROPERTY_SERIAL_NUMBER, device.getAddress())

View File

@ -24,6 +24,8 @@ import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.types.Command; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -33,6 +35,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Andrew Fiddian-Green - Initial contribution * @author Andrew Fiddian-Green - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = DynamicsActions.class)
@ThingActionsScope(name = "hue") @ThingActionsScope(name = "hue")
@NonNullByDefault @NonNullByDefault
public class DynamicsActions implements ThingActions { public class DynamicsActions implements ThingActions {

View File

@ -22,6 +22,8 @@ import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.types.Command; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -30,6 +32,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Jochen Leopold - Initial contribution * @author Jochen Leopold - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = LightActions.class)
@ThingActionsScope(name = "hue") @ThingActionsScope(name = "hue")
@NonNullByDefault @NonNullByDefault
public class LightActions implements ThingActions { public class LightActions implements ThingActions {

View File

@ -33,14 +33,14 @@ import org.openhab.binding.hue.internal.api.dto.clip2.enums.ResourceType;
import org.openhab.binding.hue.internal.exceptions.ApiException; import org.openhab.binding.hue.internal.exceptions.ApiException;
import org.openhab.binding.hue.internal.exceptions.AssetNotLoadedException; import org.openhab.binding.hue.internal.exceptions.AssetNotLoadedException;
import org.openhab.binding.hue.internal.handler.Clip2BridgeHandler; 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.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -49,9 +49,9 @@ import org.slf4j.LoggerFactory;
* *
* @author Andrew Fiddian-Green - Initial Contribution * @author Andrew Fiddian-Green - Initial Contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = Clip2ThingDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class Clip2ThingDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { public class Clip2ThingDiscoveryService extends AbstractThingHandlerDiscoveryService<Clip2BridgeHandler> {
private final Logger logger = LoggerFactory.getLogger(Clip2ThingDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(Clip2ThingDiscoveryService.class);
private static final int DISCOVERY_TIMEOUT_SECONDS = 20; private static final int DISCOVERY_TIMEOUT_SECONDS = 20;
@ -66,31 +66,24 @@ public class Clip2ThingDiscoveryService extends AbstractDiscoveryService impleme
ResourceType.ZONE, THING_TYPE_ZONE, // ResourceType.ZONE, THING_TYPE_ZONE, //
ResourceType.BRIDGE_HOME, THING_TYPE_ZONE); ResourceType.BRIDGE_HOME, THING_TYPE_ZONE);
private @Nullable Clip2BridgeHandler bridgeHandler;
private @Nullable ScheduledFuture<?> discoveryTask; private @Nullable ScheduledFuture<?> discoveryTask;
public Clip2ThingDiscoveryService() { 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 @Override
public void activate() { public void initialize() {
Clip2BridgeHandler bridgeHandler = this.bridgeHandler; thingHandler.registerDiscoveryService(this);
if (Objects.nonNull(bridgeHandler)) { super.initialize();
bridgeHandler.registerDiscoveryService(this);
}
super.activate(null);
} }
@Override @Override
public void deactivate() { public void dispose() {
super.deactivate(); super.dispose();
Clip2BridgeHandler bridgeHandler = this.bridgeHandler; thingHandler.unregisterDiscoveryService();
if (Objects.nonNull(bridgeHandler)) { removeOlderResults(new Date().getTime(), thingHandler.getThing().getBridgeUID());
bridgeHandler.unregisterDiscoveryService();
removeOlderResults(new Date().getTime(), bridgeHandler.getThing().getBridgeUID());
this.bridgeHandler = null;
}
} }
/** /**
@ -98,12 +91,11 @@ public class Clip2ThingDiscoveryService extends AbstractDiscoveryService impleme
* as OH things, and announce those respective things by calling the core 'thingDiscovered()' method. * as OH things, and announce those respective things by calling the core 'thingDiscovered()' method.
*/ */
private synchronized void discoverThings() { private synchronized void discoverThings() {
Clip2BridgeHandler bridgeHandler = this.bridgeHandler; if (thingHandler.getThing().getStatus() == ThingStatus.ONLINE) {
if (Objects.nonNull(bridgeHandler) && bridgeHandler.getThing().getStatus() == ThingStatus.ONLINE) {
try { try {
ThingUID bridgeUID = bridgeHandler.getThing().getUID(); ThingUID bridgeUID = thingHandler.getThing().getUID();
for (Entry<ResourceType, ThingTypeUID> entry : DISCOVERY_TYPES.entrySet()) { for (Entry<ResourceType, ThingTypeUID> 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()) { .getResources()) {
MetaData metaData = resource.getMetaData(); MetaData metaData = resource.getMetaData();
@ -122,10 +114,10 @@ public class Clip2ThingDiscoveryService extends AbstractDiscoveryService impleme
// special zone 'all lights' // special zone 'all lights'
if (resource.getType() == ResourceType.BRIDGE_HOME) { if (resource.getType() == ResourceType.BRIDGE_HOME) {
thingLabel = bridgeHandler.getLocalizedText(ALL_LIGHTS_KEY); thingLabel = thingHandler.getLocalizedText(ALL_LIGHTS_KEY);
} }
Optional<Thing> legacyThingOptional = bridgeHandler.getLegacyThing(idv1); Optional<Thing> legacyThingOptional = thingHandler.getLegacyThing(idv1);
if (legacyThingOptional.isPresent()) { if (legacyThingOptional.isPresent()) {
Thing legacyThing = legacyThingOptional.get(); Thing legacyThing = legacyThingOptional.get();
legacyThingUID = legacyThing.getUID().getAsString(); legacyThingUID = legacyThing.getUID().getAsString();
@ -157,18 +149,6 @@ public class Clip2ThingDiscoveryService extends AbstractDiscoveryService impleme
stopScan(); stopScan();
} }
@Override
public @Nullable ThingHandler getThingHandler() {
return bridgeHandler;
}
@Override
public void setThingHandler(ThingHandler handler) {
if (handler instanceof Clip2BridgeHandler) {
bridgeHandler = (Clip2BridgeHandler) handler;
}
}
@Override @Override
protected void startBackgroundDiscovery() { protected void startBackgroundDiscovery() {
ScheduledFuture<?> discoveryTask = this.discoveryTask; ScheduledFuture<?> discoveryTask = this.discoveryTask;

View File

@ -39,14 +39,17 @@ import org.openhab.binding.hue.internal.handler.sensors.LightLevelHandler;
import org.openhab.binding.hue.internal.handler.sensors.PresenceHandler; 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.TapSwitchHandler;
import org.openhab.binding.hue.internal.handler.sensors.TemperatureHandler; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; 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.Thing;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -64,9 +67,9 @@ import org.slf4j.LoggerFactory;
* @author Meng Yiqi - Added support for CLIP sensor * @author Meng Yiqi - Added support for CLIP sensor
* @author Laurent Garnier - Added support for groups * @author Laurent Garnier - Added support for groups
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = HueDeviceDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class HueDeviceDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { public class HueDeviceDiscoveryService extends AbstractThingHandlerDiscoveryService<HueBridgeHandler> {
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Stream public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Stream
.of(HueLightHandler.SUPPORTED_THING_TYPES.stream(), DimmerSwitchHandler.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(), 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 final Logger logger = LoggerFactory.getLogger(HueDeviceDiscoveryService.class);
private @Nullable HueBridgeHandler hueBridgeHandler;
private @Nullable ThingUID bridgeUID; private @Nullable ThingUID bridgeUID;
public HueDeviceDiscoveryService() { public HueDeviceDiscoveryService() {
super(SUPPORTED_THING_TYPES, SEARCH_TIME); super(HueBridgeHandler.class, SUPPORTED_THING_TYPES, SEARCH_TIME);
}
@Reference(unbind = "-")
public void bindTranslationProvider(TranslationProvider translationProvider) {
this.i18nProvider = translationProvider;
}
@Reference(unbind = "-")
public void bindLocaleProvider(LocaleProvider localeProvider) {
this.localeProvider = localeProvider;
} }
@Override @Override
public void setThingHandler(@Nullable ThingHandler handler) { public void initialize() {
if (handler instanceof HueBridgeHandler) { bridgeUID = thingHandler.getThing().getUID();
HueBridgeHandler localHandler = (HueBridgeHandler) handler; thingHandler.registerDiscoveryListener(this);
hueBridgeHandler = localHandler; super.initialize();
bridgeUID = handler.getThing().getUID();
i18nProvider = localHandler.getI18nProvider();
localeProvider = localHandler.getLocaleProvider();
}
} }
@Override @Override
public @Nullable ThingHandler getThingHandler() { public void dispose() {
return hueBridgeHandler; super.dispose();
}
@Override
public void activate() {
final HueBridgeHandler handler = hueBridgeHandler;
if (handler != null) {
handler.registerDiscoveryListener(this);
}
}
@Override
public void deactivate() {
removeOlderResults(new Date().getTime(), bridgeUID); removeOlderResults(new Date().getTime(), bridgeUID);
final HueBridgeHandler handler = hueBridgeHandler; thingHandler.unregisterDiscoveryListener();
if (handler != null) {
handler.unregisterDiscoveryListener();
}
} }
@Override @Override
@ -145,32 +138,26 @@ public class HueDeviceDiscoveryService extends AbstractDiscoveryService implemen
@Override @Override
public void startScan() { public void startScan() {
final HueBridgeHandler handler = hueBridgeHandler; List<FullLight> lights = thingHandler.getFullLights();
if (handler != null) { for (FullLight l : lights) {
List<FullLight> lights = handler.getFullLights(); addLightDiscovery(l);
for (FullLight l : lights) {
addLightDiscovery(l);
}
List<FullSensor> sensors = handler.getFullSensors();
for (FullSensor s : sensors) {
addSensorDiscovery(s);
}
List<FullGroup> groups = handler.getFullGroups();
for (FullGroup g : groups) {
addGroupDiscovery(g);
}
// search for unpaired lights
handler.startSearch();
} }
List<FullSensor> sensors = thingHandler.getFullSensors();
for (FullSensor s : sensors) {
addSensorDiscovery(s);
}
List<FullGroup> groups = thingHandler.getFullGroups();
for (FullGroup g : groups) {
addGroupDiscovery(g);
}
// search for unpaired lights
thingHandler.startSearch();
} }
@Override @Override
protected synchronized void stopScan() { protected synchronized void stopScan() {
super.stopScan(); super.stopScan();
final HueBridgeHandler handler = hueBridgeHandler; removeOlderResults(getTimestampOfLastScan(), thingHandler.getThing().getUID());
if (handler != null) {
removeOlderResults(getTimestampOfLastScan(), handler.getThing().getUID());
}
} }
public void addLightDiscovery(FullLight light) { public void addLightDiscovery(FullLight light) {

View File

@ -191,7 +191,7 @@ public class HueThingHandlerFactory extends BaseThingHandlerFactory {
itemChannelLinkRegistry); itemChannelLinkRegistry);
} else if (HueBridgeHandler.SUPPORTED_THING_TYPES.contains(thingTypeUID)) { } else if (HueBridgeHandler.SUPPORTED_THING_TYPES.contains(thingTypeUID)) {
return new HueBridgeHandler((Bridge) thing, httpClientFactory.getCommonHttpClient(), return new HueBridgeHandler((Bridge) thing, httpClientFactory.getCommonHttpClient(),
stateDescriptionProvider, i18nProvider, localeProvider); stateDescriptionProvider);
} else if (HueLightHandler.SUPPORTED_THING_TYPES.contains(thingTypeUID)) { } else if (HueLightHandler.SUPPORTED_THING_TYPES.contains(thingTypeUID)) {
return new HueLightHandler(thing, stateDescriptionProvider); return new HueLightHandler(thing, stateDescriptionProvider);
} else if (DimmerSwitchHandler.SUPPORTED_THING_TYPES.contains(thingTypeUID)) { } else if (DimmerSwitchHandler.SUPPORTED_THING_TYPES.contains(thingTypeUID)) {

View File

@ -59,8 +59,6 @@ import org.openhab.core.config.core.Configuration;
import org.openhab.core.config.core.status.ConfigStatusMessage; import org.openhab.core.config.core.status.ConfigStatusMessage;
import org.openhab.core.i18n.CommunicationException; import org.openhab.core.i18n.CommunicationException;
import org.openhab.core.i18n.ConfigurationException; 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.io.net.http.TlsTrustManagerProvider;
import org.openhab.core.library.types.HSBType; import org.openhab.core.library.types.HSBType;
import org.openhab.core.library.types.OnOffType; import org.openhab.core.library.types.OnOffType;
@ -109,8 +107,6 @@ public class HueBridgeHandler extends ConfigStatusBridgeHandler implements HueCl
private @Nullable ServiceRegistration<?> serviceRegistration; private @Nullable ServiceRegistration<?> serviceRegistration;
private final HttpClient httpClient; private final HttpClient httpClient;
private final HueStateDescriptionProvider stateDescriptionOptionProvider; private final HueStateDescriptionProvider stateDescriptionOptionProvider;
private final TranslationProvider i18nProvider;
private final LocaleProvider localeProvider;
private final Map<String, FullLight> lastLightStates = new ConcurrentHashMap<>(); private final Map<String, FullLight> lastLightStates = new ConcurrentHashMap<>();
private final Map<String, FullSensor> lastSensorStates = new ConcurrentHashMap<>(); private final Map<String, FullSensor> lastSensorStates = new ConcurrentHashMap<>();
@ -424,13 +420,10 @@ public class HueBridgeHandler extends ConfigStatusBridgeHandler implements HueCl
private List<String> consoleScenesList = new ArrayList<>(); private List<String> consoleScenesList = new ArrayList<>();
public HueBridgeHandler(Bridge bridge, HttpClient httpClient, public HueBridgeHandler(Bridge bridge, HttpClient httpClient,
HueStateDescriptionProvider stateDescriptionOptionProvider, TranslationProvider i18nProvider, HueStateDescriptionProvider stateDescriptionOptionProvider) {
LocaleProvider localeProvider) {
super(bridge); super(bridge);
this.httpClient = httpClient; this.httpClient = httpClient;
this.stateDescriptionOptionProvider = stateDescriptionOptionProvider; this.stateDescriptionOptionProvider = stateDescriptionOptionProvider;
this.i18nProvider = i18nProvider;
this.localeProvider = localeProvider;
} }
@Override @Override
@ -1079,12 +1072,4 @@ public class HueBridgeHandler extends ConfigStatusBridgeHandler implements HueCl
return List.of(); return List.of();
} }
} }
public TranslationProvider getI18nProvider() {
return i18nProvider;
}
public LocaleProvider getLocaleProvider() {
return localeProvider;
}
} }

View File

@ -17,18 +17,17 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; 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.HydrawiseBindingConstants;
import org.openhab.binding.hydrawise.internal.HydrawiseControllerListener; 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.Controller;
import org.openhab.binding.hydrawise.internal.api.graphql.dto.Customer; import org.openhab.binding.hydrawise.internal.api.graphql.dto.Customer;
import org.openhab.binding.hydrawise.internal.handler.HydrawiseAccountHandler; 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.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.thing.binding.ThingHandlerService; import org.openhab.core.thing.binding.ThingHandlerService;
import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ServiceScope;
/** /**
* *
@ -37,44 +36,33 @@ import org.osgi.service.component.annotations.Component;
*/ */
@NonNullByDefault @NonNullByDefault
@Component(service = ThingHandlerService.class) @Component(scope = ServiceScope.PROTOTYPE, service = ThingHandlerService.class)
public class HydrawiseCloudControllerDiscoveryService extends AbstractDiscoveryService public class HydrawiseCloudControllerDiscoveryService
implements HydrawiseControllerListener, ThingHandlerService { extends AbstractThingHandlerDiscoveryService<HydrawiseAccountHandler> implements HydrawiseControllerListener {
private static final int TIMEOUT = 5; private static final int TIMEOUT = 5;
@Nullable
HydrawiseAccountHandler handler;
public HydrawiseCloudControllerDiscoveryService() { public HydrawiseCloudControllerDiscoveryService() {
super(Set.of(HydrawiseBindingConstants.THING_TYPE_CONTROLLER), TIMEOUT, true); super(HydrawiseAccountHandler.class, Set.of(HydrawiseBindingConstants.THING_TYPE_CONTROLLER), TIMEOUT, true);
} }
@Override @Override
protected void startScan() { protected void startScan() {
HydrawiseAccountHandler localHandler = this.handler; Customer data = thingHandler.lastData();
if (localHandler != null) { if (data != null) {
Customer data = localHandler.lastData(); data.controllers.forEach(controller -> addDiscoveryResults(controller));
if (data != null) {
data.controllers.forEach(controller -> addDiscoveryResults(controller));
}
} }
} }
@Override @Override
public void deactivate() { public void dispose() {
HydrawiseAccountHandler localHandler = this.handler; super.dispose();
if (localHandler != null) { removeOlderResults(new Date().getTime(), thingHandler.getThing().getUID());
removeOlderResults(new Date().getTime(), localHandler.getThing().getUID());
}
} }
@Override @Override
protected synchronized void stopScan() { protected synchronized void stopScan() {
super.stopScan(); super.stopScan();
HydrawiseAccountHandler localHandler = this.handler; removeOlderResults(getTimestampOfLastScan(), thingHandler.getThing().getUID());
if (localHandler != null) {
removeOlderResults(getTimestampOfLastScan(), localHandler.getThing().getUID());
}
} }
@Override @Override
@ -83,27 +71,19 @@ public class HydrawiseCloudControllerDiscoveryService extends AbstractDiscoveryS
} }
@Override @Override
public void setThingHandler(ThingHandler handler) { public void initialize() {
this.handler = (HydrawiseAccountHandler) handler; thingHandler.addControllerListeners(this);
this.handler.addControllerListeners(this); super.initialize();
}
@Override
public @Nullable ThingHandler getThingHandler() {
return handler;
} }
private void addDiscoveryResults(Controller controller) { private void addDiscoveryResults(Controller controller) {
HydrawiseAccountHandler localHandler = this.handler; String label = String.format("Hydrawise Controller %s", controller.name);
if (localHandler != null) { int id = controller.id;
String label = String.format("Hydrawise Controller %s", controller.name); ThingUID bridgeUID = thingHandler.getThing().getUID();
int id = controller.id; ThingUID thingUID = new ThingUID(HydrawiseBindingConstants.THING_TYPE_CONTROLLER, bridgeUID,
ThingUID bridgeUID = localHandler.getThing().getUID(); String.valueOf(id));
ThingUID thingUID = new ThingUID(HydrawiseBindingConstants.THING_TYPE_CONTROLLER, bridgeUID, thingDiscovered(DiscoveryResultBuilder.create(thingUID).withLabel(label).withBridge(bridgeUID)
String.valueOf(id)); .withProperty(HydrawiseBindingConstants.CONFIG_CONTROLLER_ID, id)
thingDiscovered(DiscoveryResultBuilder.create(thingUID).withLabel(label).withBridge(bridgeUID) .withRepresentationProperty(HydrawiseBindingConstants.CONFIG_CONTROLLER_ID).build());
.withProperty(HydrawiseBindingConstants.CONFIG_CONTROLLER_ID, id)
.withRepresentationProperty(HydrawiseBindingConstants.CONFIG_CONTROLLER_ID).build());
}
} }
} }

View File

@ -20,6 +20,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -28,7 +30,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Matthew Skinner - Initial contribution * @author Matthew Skinner - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = IpCameraActions.class)
@ThingActionsScope(name = "ipcamera") @ThingActionsScope(name = "ipcamera")
@NonNullByDefault @NonNullByDefault
public class IpCameraActions implements ThingActions { public class IpCameraActions implements ThingActions {

View File

@ -25,14 +25,13 @@ import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.jablotron.internal.handler.JablotronBridgeHandler; import org.openhab.binding.jablotron.internal.handler.JablotronBridgeHandler;
import org.openhab.binding.jablotron.internal.model.JablotronDiscoveredService; 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.DiscoveryResultBuilder;
import org.openhab.core.config.discovery.DiscoveryService;
import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -42,39 +41,25 @@ import org.slf4j.LoggerFactory;
* *
* @author Ondrej Pecta - Initial contribution * @author Ondrej Pecta - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = JablotronDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class JablotronDiscoveryService extends AbstractDiscoveryService public class JablotronDiscoveryService extends AbstractThingHandlerDiscoveryService<JablotronBridgeHandler> {
implements DiscoveryService, ThingHandlerService {
private final Logger logger = LoggerFactory.getLogger(JablotronDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(JablotronDiscoveryService.class);
private @Nullable JablotronBridgeHandler bridgeHandler;
private @Nullable ScheduledFuture<?> discoveryJob = null; private @Nullable ScheduledFuture<?> discoveryJob = null;
public JablotronDiscoveryService() { public JablotronDiscoveryService() {
super(DISCOVERY_TIMEOUT_SEC); super(JablotronBridgeHandler.class, DISCOVERY_TIMEOUT_SEC);
logger.debug("Creating discovery service"); logger.debug("Creating discovery service");
} }
private void startDiscovery() { private void startDiscovery() {
JablotronBridgeHandler localBridgeHandler = bridgeHandler; JablotronBridgeHandler localBridgeHandler = thingHandler;
if (localBridgeHandler != null && ThingStatus.ONLINE == localBridgeHandler.getThing().getStatus()) { if (localBridgeHandler != null && ThingStatus.ONLINE == localBridgeHandler.getThing().getStatus()) {
discoverServices(); discoverServices();
} }
} }
@Override
public void setThingHandler(@Nullable ThingHandler thingHandler) {
if (thingHandler instanceof JablotronBridgeHandler bridgeHandler) {
this.bridgeHandler = bridgeHandler;
}
}
@Override
public @Nullable ThingHandler getThingHandler() {
return bridgeHandler;
}
@Override @Override
protected void stopBackgroundDiscovery() { protected void stopBackgroundDiscovery() {
super.stopBackgroundDiscovery(); super.stopBackgroundDiscovery();
@ -93,16 +78,6 @@ public class JablotronDiscoveryService extends AbstractDiscoveryService
} }
} }
@Override
public void activate() {
super.activate(null);
}
@Override
public void deactivate() {
super.deactivate();
}
@Override @Override
public Set<ThingTypeUID> getSupportedThingTypes() { public Set<ThingTypeUID> getSupportedThingTypes() {
return SUPPORTED_THING_TYPES_UIDS; return SUPPORTED_THING_TYPES_UIDS;
@ -115,7 +90,7 @@ public class JablotronDiscoveryService extends AbstractDiscoveryService
} }
public void oasisDiscovered(String label, String serviceId) { public void oasisDiscovered(String label, String serviceId) {
JablotronBridgeHandler localBridgeHandler = bridgeHandler; JablotronBridgeHandler localBridgeHandler = thingHandler;
if (localBridgeHandler != null) { if (localBridgeHandler != null) {
ThingUID thingUID = new ThingUID(THING_TYPE_OASIS, localBridgeHandler.getThing().getUID(), serviceId); ThingUID thingUID = new ThingUID(THING_TYPE_OASIS, localBridgeHandler.getThing().getUID(), serviceId);
@ -130,7 +105,7 @@ public class JablotronDiscoveryService extends AbstractDiscoveryService
} }
public void ja100Discovered(String label, String serviceId) { public void ja100Discovered(String label, String serviceId) {
JablotronBridgeHandler localBridgeHandler = bridgeHandler; JablotronBridgeHandler localBridgeHandler = thingHandler;
if (localBridgeHandler != null) { if (localBridgeHandler != null) {
ThingUID thingUID = new ThingUID(THING_TYPE_JA100, localBridgeHandler.getThing().getUID(), serviceId); ThingUID thingUID = new ThingUID(THING_TYPE_JA100, localBridgeHandler.getThing().getUID(), serviceId);
Map<String, Object> properties = new HashMap<>(); Map<String, Object> properties = new HashMap<>();
@ -144,7 +119,7 @@ public class JablotronDiscoveryService extends AbstractDiscoveryService
} }
public void ja100fDiscovered(String label, String serviceId) { public void ja100fDiscovered(String label, String serviceId) {
JablotronBridgeHandler localBridgeHandler = bridgeHandler; JablotronBridgeHandler localBridgeHandler = thingHandler;
if (localBridgeHandler != null) { if (localBridgeHandler != null) {
ThingUID thingUID = new ThingUID(THING_TYPE_JA100F, localBridgeHandler.getThing().getUID(), serviceId); ThingUID thingUID = new ThingUID(THING_TYPE_JA100F, localBridgeHandler.getThing().getUID(), serviceId);
Map<String, Object> properties = new HashMap<>(); Map<String, Object> properties = new HashMap<>();
@ -158,7 +133,7 @@ public class JablotronDiscoveryService extends AbstractDiscoveryService
} }
private synchronized void discoverServices() { private synchronized void discoverServices() {
JablotronBridgeHandler localBridgeHandler = bridgeHandler; JablotronBridgeHandler localBridgeHandler = thingHandler;
if (localBridgeHandler != null) { if (localBridgeHandler != null) {
List<JablotronDiscoveredService> services = localBridgeHandler.discoverServices(); List<JablotronDiscoveredService> services = localBridgeHandler.discoverServices();

View File

@ -21,19 +21,18 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; 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.ApiClientException;
import org.jellyfin.sdk.api.client.exception.InvalidStatusException; import org.jellyfin.sdk.api.client.exception.InvalidStatusException;
import org.jellyfin.sdk.model.api.SessionInfo; import org.jellyfin.sdk.model.api.SessionInfo;
import org.openhab.binding.jellyfin.internal.handler.JellyfinServerHandler; import org.openhab.binding.jellyfin.internal.handler.JellyfinServerHandler;
import org.openhab.binding.jellyfin.internal.util.SyncCallback; 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.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -42,29 +41,24 @@ import org.slf4j.LoggerFactory;
* *
* @author Miguel Alvarez - Initial contribution * @author Miguel Alvarez - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = JellyfinClientDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class JellyfinClientDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { public class JellyfinClientDiscoveryService extends AbstractThingHandlerDiscoveryService<JellyfinServerHandler> {
private final Logger logger = LoggerFactory.getLogger(JellyfinClientDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(JellyfinClientDiscoveryService.class);
private @Nullable JellyfinServerHandler bridgeHandler;
public JellyfinClientDiscoveryService() throws IllegalArgumentException { public JellyfinClientDiscoveryService() throws IllegalArgumentException {
super(Set.of(THING_TYPE_SERVER), 60); super(JellyfinServerHandler.class, Set.of(THING_TYPE_SERVER), 60);
} }
@Override @Override
protected void startScan() { protected void startScan() {
var bridgeHandler = this.bridgeHandler; if (!thingHandler.getThing().getStatus().equals(ThingStatus.ONLINE)) {
if (bridgeHandler == null) { logger.warn("Server handler {} is not online.", thingHandler.getThing().getLabel());
logger.warn("missing bridge aborting");
return; return;
} }
if (!bridgeHandler.getThing().getStatus().equals(ThingStatus.ONLINE)) { logger.debug("Searching devices for server {}", thingHandler.getThing().getLabel());
logger.warn("Server handler {} is not online.", bridgeHandler.getThing().getLabel());
return;
}
logger.debug("Searching devices for server {}", bridgeHandler.getThing().getLabel());
try { try {
bridgeHandler.getControllableSessions().forEach(this::discoverDevice); thingHandler.getControllableSessions().forEach(this::discoverDevice);
} catch (SyncCallback.SyncCallbackError syncCallbackError) { } catch (SyncCallback.SyncCallbackError syncCallbackError) {
logger.error("Unexpected error: {}", syncCallbackError.getMessage()); logger.error("Unexpected error: {}", syncCallbackError.getMessage());
} catch (InvalidStatusException e) { } catch (InvalidStatusException e) {
@ -80,13 +74,8 @@ public class JellyfinClientDiscoveryService extends AbstractDiscoveryService imp
logger.warn("missing device id aborting"); logger.warn("missing device id aborting");
return; return;
} }
var bridgeHandler = this.bridgeHandler;
if (bridgeHandler == null) {
logger.warn("missing bridge aborting");
return;
}
logger.debug("Client discovered: [{}] {}", id, info.getDeviceName()); logger.debug("Client discovered: [{}] {}", id, info.getDeviceName());
var bridgeUID = bridgeHandler.getThing().getUID(); var bridgeUID = thingHandler.getThing().getUID();
Map<String, Object> properties = new HashMap<>(); Map<String, Object> properties = new HashMap<>();
properties.put(Thing.PROPERTY_SERIAL_NUMBER, id); properties.put(Thing.PROPERTY_SERIAL_NUMBER, id);
var appVersion = info.getApplicationVersion(); var appVersion = info.getApplicationVersion();
@ -102,26 +91,4 @@ public class JellyfinClientDiscoveryService extends AbstractDiscoveryService imp
.withTTL(DISCOVERY_RESULT_TTL_SEC).withRepresentationProperty(Thing.PROPERTY_SERIAL_NUMBER) .withTTL(DISCOVERY_RESULT_TTL_SEC).withRepresentationProperty(Thing.PROPERTY_SERIAL_NUMBER)
.withProperties(properties).withLabel(info.getDeviceName()).build()); .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();
}
} }

View File

@ -14,20 +14,17 @@ package org.openhab.binding.juicenet.internal.discovery;
import static org.openhab.binding.juicenet.internal.JuiceNetBindingConstants.*; import static org.openhab.binding.juicenet.internal.JuiceNetBindingConstants.*;
import java.util.Objects;
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.juicenet.internal.handler.JuiceNetBridgeHandler; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; 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.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -38,53 +35,24 @@ import org.slf4j.LoggerFactory;
* *
* @author Jeff James - Initial contribution * @author Jeff James - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = JuiceNetDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class JuiceNetDiscoveryService extends AbstractDiscoveryService public class JuiceNetDiscoveryService extends AbstractThingHandlerDiscoveryService<JuiceNetBridgeHandler> {
implements DiscoveryService, ThingHandlerService {
private final Logger logger = LoggerFactory.getLogger(JuiceNetDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(JuiceNetDiscoveryService.class);
private @Nullable JuiceNetBridgeHandler bridgeHandler;
private static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPES_UIDS = Set.of(DEVICE_THING_TYPE); private static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPES_UIDS = Set.of(DEVICE_THING_TYPE);
public JuiceNetDiscoveryService() { public JuiceNetDiscoveryService() {
super(DISCOVERABLE_THING_TYPES_UIDS, 0, false); super(JuiceNetBridgeHandler.class, DISCOVERABLE_THING_TYPES_UIDS, 0, false);
}
@Override
public void activate() {
super.activate(null);
}
@Override
public void deactivate() {
super.deactivate();
} }
@Override @Override
protected synchronized void startScan() { protected synchronized void startScan() {
Objects.requireNonNull(bridgeHandler).iterateApiDevices(); thingHandler.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;
} }
public void notifyDiscoveryDevice(String id, String name) { public void notifyDiscoveryDevice(String id, String name) {
JuiceNetBridgeHandler bridgeHandler = this.bridgeHandler; ThingUID bridgeUID = thingHandler.getThing().getUID();
Objects.requireNonNull(bridgeHandler, "Discovery with null bridgehandler.");
ThingUID bridgeUID = bridgeHandler.getThing().getUID();
ThingUID uid = new ThingUID(DEVICE_THING_TYPE, bridgeUID, id); ThingUID uid = new ThingUID(DEVICE_THING_TYPE, bridgeUID, id);

View File

@ -20,6 +20,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -28,6 +30,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Michael Lobstein - initial contribution * @author Michael Lobstein - initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = KaleidescapeThingActions.class)
@ThingActionsScope(name = "kaleidescape") @ThingActionsScope(name = "kaleidescape")
@NonNullByDefault @NonNullByDefault
public class KaleidescapeThingActions implements ThingActions { public class KaleidescapeThingActions implements ThingActions {

View File

@ -28,6 +28,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -36,6 +38,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Fabian Wolter - Initial contribution * @author Fabian Wolter - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = LcnModuleActions.class)
@ThingActionsScope(name = "lcn") @ThingActionsScope(name = "lcn")
@NonNullByDefault @NonNullByDefault
public class LcnModuleActions implements ThingActions { public class LcnModuleActions implements ThingActions {

View File

@ -31,14 +31,13 @@ import org.openhab.binding.lcn.internal.common.LcnAddrMod;
import org.openhab.binding.lcn.internal.connection.Connection; import org.openhab.binding.lcn.internal.connection.Connection;
import org.openhab.binding.lcn.internal.subhandler.LcnModuleMetaAckSubHandler; import org.openhab.binding.lcn.internal.subhandler.LcnModuleMetaAckSubHandler;
import org.openhab.binding.lcn.internal.subhandler.LcnModuleMetaFirmwareSubHandler; 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.DiscoveryResultBuilder;
import org.openhab.core.config.discovery.DiscoveryService;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -55,9 +54,9 @@ import org.slf4j.LoggerFactory;
* *
* @author Fabian Wolter - Initial Contribution * @author Fabian Wolter - Initial Contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = LcnModuleDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class LcnModuleDiscoveryService extends AbstractDiscoveryService public class LcnModuleDiscoveryService extends AbstractThingHandlerDiscoveryService<PckGatewayHandler> {
implements DiscoveryService, ThingHandlerService {
private final Logger logger = LoggerFactory.getLogger(LcnModuleDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(LcnModuleDiscoveryService.class);
private static final Pattern NAME_PATTERN = Pattern private static final Pattern NAME_PATTERN = Pattern
.compile("=M(?<segId>\\d{3})(?<modId>\\d{3}).N(?<part>[1-2]{1})(?<name>.*)"); .compile("=M(?<segId>\\d{3})(?<modId>\\d{3}).N(?<part>[1-2]{1})(?<name>.*)");
@ -67,7 +66,6 @@ public class LcnModuleDiscoveryService extends AbstractDiscoveryService
private static final int DISCOVERY_TIMEOUT_SEC = 90; private static final int DISCOVERY_TIMEOUT_SEC = 90;
private static final int ACK_TIMEOUT_MS = 1000; private static final int ACK_TIMEOUT_MS = 1000;
private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(LcnBindingConstants.THING_TYPE_MODULE); private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(LcnBindingConstants.THING_TYPE_MODULE);
private @Nullable PckGatewayHandler bridgeHandler;
private final Map<LcnAddrMod, @Nullable Map<Integer, String>> moduleNames = new HashMap<>(); private final Map<LcnAddrMod, @Nullable Map<Integer, String>> moduleNames = new HashMap<>();
private final Map<LcnAddrMod, DiscoveryResultBuilder> discoveryResultBuilders = new ConcurrentHashMap<>(); private final Map<LcnAddrMod, DiscoveryResultBuilder> discoveryResultBuilders = new ConcurrentHashMap<>();
private final List<LcnAddrMod> successfullyDiscovered = new LinkedList<>(); private final List<LcnAddrMod> successfullyDiscovered = new LinkedList<>();
@ -77,57 +75,39 @@ public class LcnModuleDiscoveryService extends AbstractDiscoveryService
private @Nullable ScheduledFuture<?> builderTask; private @Nullable ScheduledFuture<?> builderTask;
public LcnModuleDiscoveryService() { public LcnModuleDiscoveryService() {
super(SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIMEOUT_SEC, false); super(PckGatewayHandler.class, SUPPORTED_THING_TYPES_UIDS, DISCOVERY_TIMEOUT_SEC, false);
} }
@Override @Override
public void setThingHandler(@Nullable ThingHandler handler) { public void dispose() {
if (handler instanceof PckGatewayHandler gatewayHandler) { super.dispose();
this.bridgeHandler = gatewayHandler;
}
}
@Override
public @Nullable ThingHandler getThingHandler() {
return bridgeHandler;
}
@Override
public void deactivate() {
stopScan(); stopScan();
super.deactivate();
} }
@Override @Override
@SuppressWarnings("PMD.CompareObjectsWithEquals") @SuppressWarnings("PMD.CompareObjectsWithEquals")
protected void startScan() { protected void startScan() {
synchronized (this) { synchronized (this) {
PckGatewayHandler localBridgeHandler = bridgeHandler;
if (localBridgeHandler == null) {
logger.warn("Bridge handler not set");
return;
}
ScheduledFuture<?> localBuilderTask = builderTask; ScheduledFuture<?> localBuilderTask = builderTask;
if (localBridgeHandler.getConnection() == null && localBuilderTask != null) { if (thingHandler.getConnection() == null && localBuilderTask != null) {
localBuilderTask.cancel(true); localBuilderTask.cancel(true);
} }
localBridgeHandler.registerPckListener(data -> { thingHandler.registerPckListener(data -> {
Matcher matcher; Matcher matcher;
if ((matcher = LcnModuleMetaAckSubHandler.PATTERN_POS.matcher(data)).matches() if ((matcher = LcnModuleMetaAckSubHandler.PATTERN_POS.matcher(data)).matches()
|| (matcher = LcnModuleMetaFirmwareSubHandler.PATTERN.matcher(data)).matches() || (matcher = LcnModuleMetaFirmwareSubHandler.PATTERN.matcher(data)).matches()
|| (matcher = NAME_PATTERN.matcher(data)).matches()) { || (matcher = NAME_PATTERN.matcher(data)).matches()) {
synchronized (LcnModuleDiscoveryService.this) { synchronized (LcnModuleDiscoveryService.this) {
Connection connection = localBridgeHandler.getConnection(); Connection connection = thingHandler.getConnection();
if (connection == null) { if (connection == null) {
return; return;
} }
LcnAddrMod addr = new LcnAddrMod( LcnAddrMod addr = new LcnAddrMod(
localBridgeHandler.toLogicalSegmentId(Integer.parseInt(matcher.group("segId"))), thingHandler.toLogicalSegmentId(Integer.parseInt(matcher.group("segId"))),
Integer.parseInt(matcher.group("modId"))); Integer.parseInt(matcher.group("modId")));
if (matcher.pattern() == LcnModuleMetaAckSubHandler.PATTERN_POS) { if (matcher.pattern() == LcnModuleMetaAckSubHandler.PATTERN_POS) {
@ -148,7 +128,7 @@ public class LcnModuleDiscoveryService extends AbstractDiscoveryService
} else if (matcher.pattern() == LcnModuleMetaFirmwareSubHandler.PATTERN) { } else if (matcher.pattern() == LcnModuleMetaFirmwareSubHandler.PATTERN) {
// Received a firmware version info frame // Received a firmware version info frame
ThingUID bridgeUid = localBridgeHandler.getThing().getUID(); ThingUID bridgeUid = thingHandler.getThing().getUID();
String serialNumber = matcher.group("sn"); String serialNumber = matcher.group("sn");
String thingID = String.format("S%03dM%03d", addr.getSegmentId(), addr.getModuleId()); String thingID = String.format("S%03dM%03d", addr.getSegmentId(), addr.getModuleId());
@ -210,7 +190,7 @@ public class LcnModuleDiscoveryService extends AbstractDiscoveryService
} }
}, 500, 500, TimeUnit.MILLISECONDS); }, 500, 500, TimeUnit.MILLISECONDS);
localBridgeHandler.sendModuleDiscoveryCommand(); thingHandler.sendModuleDiscoveryCommand();
} }
} }
@ -221,22 +201,19 @@ public class LcnModuleDiscoveryService extends AbstractDiscoveryService
localQueueProcessor.cancel(true); localQueueProcessor.cancel(true);
} }
queueProcessor = scheduler.scheduleWithFixedDelay(() -> { queueProcessor = scheduler.scheduleWithFixedDelay(() -> {
PckGatewayHandler localBridgeHandler = bridgeHandler; LcnAddrMod serial = serialNumberRequestQueue.poll();
if (localBridgeHandler != null) { if (serial != null) {
LcnAddrMod serial = serialNumberRequestQueue.poll(); thingHandler.sendSerialNumberRequest(serial);
if (serial != null) { }
localBridgeHandler.sendSerialNumberRequest(serial);
}
LcnAddrMod name = moduleNameRequestQueue.poll(); LcnAddrMod name = moduleNameRequestQueue.poll();
if (name != null) { if (name != null) {
localBridgeHandler.sendModuleNameRequest(name); thingHandler.sendModuleNameRequest(name);
} }
// stop scan when all LCN modules have been requested // stop scan when all LCN modules have been requested
if (serial == null && name == null) { if (serial == null && name == null) {
scheduler.schedule(this::stopScan, ACK_TIMEOUT_MS, TimeUnit.MILLISECONDS); scheduler.schedule(this::stopScan, ACK_TIMEOUT_MS, TimeUnit.MILLISECONDS);
}
} }
}, ACK_TIMEOUT_MS, ACK_TIMEOUT_MS, TimeUnit.MILLISECONDS); }, ACK_TIMEOUT_MS, ACK_TIMEOUT_MS, TimeUnit.MILLISECONDS);
} }
@ -251,10 +228,7 @@ public class LcnModuleDiscoveryService extends AbstractDiscoveryService
if (localQueueProcessor != null) { if (localQueueProcessor != null) {
localQueueProcessor.cancel(true); localQueueProcessor.cancel(true);
} }
PckGatewayHandler localBridgeHandler = bridgeHandler; thingHandler.removeAllPckListeners();
if (localBridgeHandler != null) {
localBridgeHandler.removeAllPckListeners();
}
successfullyDiscovered.clear(); successfullyDiscovered.clear();
moduleNames.clear(); moduleNames.clear();

View File

@ -41,6 +41,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -54,6 +56,7 @@ import com.google.gson.JsonParser;
* @author Sebastian Prehn - Initial contribution * @author Sebastian Prehn - Initial contribution
* @author Laurent Garnier - new method invokeMethodOf + interface ILGWebOSActions * @author Laurent Garnier - new method invokeMethodOf + interface ILGWebOSActions
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = LGWebOSActions.class)
@ThingActionsScope(name = "lgwebos") @ThingActionsScope(name = "lgwebos")
@NonNullByDefault @NonNullByDefault
public class LGWebOSActions implements ThingActions { public class LGWebOSActions implements ThingActions {

View File

@ -21,18 +21,16 @@ import java.util.Optional;
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; 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.LivisiBindingConstants;
import org.openhab.binding.livisismarthome.internal.client.api.entity.device.DeviceDTO; import org.openhab.binding.livisismarthome.internal.client.api.entity.device.DeviceDTO;
import org.openhab.binding.livisismarthome.internal.handler.LivisiBridgeHandler; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; 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.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -42,21 +40,19 @@ import org.slf4j.LoggerFactory;
* @author Oliver Kuhl - Initial contribution * @author Oliver Kuhl - Initial contribution
* @author Sven Strohschein - Renamed from Innogy to Livisi * @author Sven Strohschein - Renamed from Innogy to Livisi
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = LivisiDeviceDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class LivisiDeviceDiscoveryService extends AbstractDiscoveryService public class LivisiDeviceDiscoveryService extends AbstractThingHandlerDiscoveryService<LivisiBridgeHandler> {
implements DiscoveryService, ThingHandlerService {
private static final int SEARCH_TIME_SECONDS = 60; private static final int SEARCH_TIME_SECONDS = 60;
private final Logger logger = LoggerFactory.getLogger(LivisiDeviceDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(LivisiDeviceDiscoveryService.class);
private @Nullable LivisiBridgeHandler bridgeHandler;
/** /**
* Construct a {@link LivisiDeviceDiscoveryService}. * Construct a {@link LivisiDeviceDiscoveryService}.
*/ */
public LivisiDeviceDiscoveryService() { public LivisiDeviceDiscoveryService() {
super(SEARCH_TIME_SECONDS); super(LivisiBridgeHandler.class, SEARCH_TIME_SECONDS);
} }
/** /**
@ -67,7 +63,8 @@ public class LivisiDeviceDiscoveryService extends AbstractDiscoveryService
* @see org.openhab.core.config.discovery.AbstractDiscoveryService#deactivate() * @see org.openhab.core.config.discovery.AbstractDiscoveryService#deactivate()
*/ */
@Override @Override
public void deactivate() { public void dispose() {
super.dispose();
removeOlderResults(new Date().getTime()); removeOlderResults(new Date().getTime());
} }
@ -79,11 +76,8 @@ public class LivisiDeviceDiscoveryService extends AbstractDiscoveryService
@Override @Override
protected void startScan() { protected void startScan() {
logger.debug("SCAN for new LIVISI SmartHome devices started..."); logger.debug("SCAN for new LIVISI SmartHome devices started...");
final LivisiBridgeHandler bridgeHandlerNonNullable = bridgeHandler; for (final DeviceDTO d : thingHandler.loadDevices()) {
if (bridgeHandlerNonNullable != null) { onDeviceAdded(d);
for (final DeviceDTO d : bridgeHandlerNonNullable.loadDevices()) {
onDeviceAdded(d);
}
} }
} }
@ -94,37 +88,34 @@ public class LivisiDeviceDiscoveryService extends AbstractDiscoveryService
} }
public void onDeviceAdded(DeviceDTO device) { public void onDeviceAdded(DeviceDTO device) {
final LivisiBridgeHandler bridgeHandlerNonNullable = bridgeHandler; final ThingUID bridgeUID = thingHandler.getThing().getUID();
if (bridgeHandlerNonNullable != null) { final Optional<ThingUID> thingUID = getThingUID(bridgeUID, device);
final ThingUID bridgeUID = bridgeHandlerNonNullable.getThing().getUID(); final Optional<ThingTypeUID> thingTypeUID = getThingTypeUID(device);
final Optional<ThingUID> thingUID = getThingUID(bridgeUID, device);
final Optional<ThingTypeUID> thingTypeUID = getThingTypeUID(device);
if (thingUID.isPresent() && thingTypeUID.isPresent()) { if (thingUID.isPresent() && thingTypeUID.isPresent()) {
String name = device.getConfig().getName(); String name = device.getConfig().getName();
if (name.isEmpty()) { if (name.isEmpty()) {
name = device.getSerialNumber(); name = device.getSerialNumber();
}
final Map<String, Object> 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);
} else {
logger.debug("Discovered unsupported device of type '{}' and name '{}' with id {}", device.getType(),
device.getConfig().getName(), device.getId());
} }
final Map<String, Object> 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);
} else {
logger.debug("Discovered unsupported device of type '{}' and name '{}' with id {}", device.getType(),
device.getConfig().getName(), device.getId());
} }
} }
@ -157,16 +148,4 @@ public class LivisiDeviceDiscoveryService extends AbstractDiscoveryService
} }
return Optional.empty(); return Optional.empty();
} }
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
if (handler instanceof LivisiBridgeHandler livisiBridgeHandler) {
bridgeHandler = livisiBridgeHandler;
}
}
@Override
public @Nullable ThingHandler getThingHandler() {
return bridgeHandler;
}
} }

View File

@ -24,6 +24,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -32,6 +34,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Bob Adair - Initial contribution * @author Bob Adair - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = DimmerActions.class)
@ThingActionsScope(name = "lutron") @ThingActionsScope(name = "lutron")
@NonNullByDefault @NonNullByDefault
public class DimmerActions implements ThingActions { public class DimmerActions implements ThingActions {

View File

@ -25,14 +25,13 @@ import org.openhab.binding.lutron.internal.handler.LeapBridgeHandler;
import org.openhab.binding.lutron.internal.protocol.leap.dto.Area; 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.Device;
import org.openhab.binding.lutron.internal.protocol.leap.dto.OccupancyGroup; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; 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.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -41,9 +40,9 @@ import org.slf4j.LoggerFactory;
* *
* @author Bob Adair - Initial contribution * @author Bob Adair - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = LeapDeviceDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class LeapDeviceDiscoveryService extends AbstractDiscoveryService public class LeapDeviceDiscoveryService extends AbstractThingHandlerDiscoveryService<LeapBridgeHandler> {
implements DiscoveryService, ThingHandlerService {
private static final int DISCOVERY_SERVICE_TIMEOUT = 0; // seconds private static final int DISCOVERY_SERVICE_TIMEOUT = 0; // seconds
@ -53,29 +52,20 @@ public class LeapDeviceDiscoveryService extends AbstractDiscoveryService
private @Nullable Map<Integer, String> areaMap; private @Nullable Map<Integer, String> areaMap;
private @Nullable List<OccupancyGroup> oGroupList; private @Nullable List<OccupancyGroup> oGroupList;
private @NonNullByDefault({}) LeapBridgeHandler bridgeHandler;
public LeapDeviceDiscoveryService() { public LeapDeviceDiscoveryService() {
super(LutronHandlerFactory.DISCOVERABLE_DEVICE_TYPES_UIDS, DISCOVERY_SERVICE_TIMEOUT); super(LeapBridgeHandler.class, LutronHandlerFactory.DISCOVERABLE_DEVICE_TYPES_UIDS, DISCOVERY_SERVICE_TIMEOUT);
} }
@Override @Override
public void setThingHandler(ThingHandler handler) { public void initialize() {
if (handler instanceof LeapBridgeHandler leapBridgeHandler) { thingHandler.setDiscoveryService(this);
bridgeHandler = leapBridgeHandler; super.initialize();
bridgeHandler.setDiscoveryService(this);
}
}
@Override
public @Nullable ThingHandler getThingHandler() {
return bridgeHandler;
} }
@Override @Override
protected void startScan() { protected void startScan() {
logger.debug("Active discovery scan started"); logger.debug("Active discovery scan started");
bridgeHandler.queryDiscoveryData(); thingHandler.queryDiscoveryData();
} }
public void processDeviceDefinitions(List<Device> deviceList) { public void processDeviceDefinitions(List<Device> deviceList) {
@ -198,10 +188,10 @@ public class LeapDeviceDiscoveryService extends AbstractDiscoveryService
private void notifyDiscovery(ThingTypeUID thingTypeUID, @Nullable Integer integrationId, String label, private void notifyDiscovery(ThingTypeUID thingTypeUID, @Nullable Integer integrationId, String label,
@Nullable String propName, @Nullable Object propValue) { @Nullable String propName, @Nullable Object propValue) {
if (integrationId == null) { if (integrationId == null) {
logger.debug("Discovered {} with no integration ID", label); logger.debug("Discovered {} with no integration ID or thinghandler", label);
return; return;
} }
ThingUID bridgeUID = this.bridgeHandler.getThing().getUID(); ThingUID bridgeUID = thingHandler.getThing().getUID();
ThingUID uid = new ThingUID(thingTypeUID, bridgeUID, integrationId.toString()); ThingUID uid = new ThingUID(thingTypeUID, bridgeUID, integrationId.toString());
Map<String, Object> properties = new HashMap<>(); Map<String, Object> properties = new HashMap<>();
@ -220,9 +210,4 @@ public class LeapDeviceDiscoveryService extends AbstractDiscoveryService
private void notifyDiscovery(ThingTypeUID thingTypeUID, Integer integrationId, String label) { private void notifyDiscovery(ThingTypeUID thingTypeUID, Integer integrationId, String label) {
notifyDiscovery(thingTypeUID, integrationId, label, null, null); notifyDiscovery(thingTypeUID, integrationId, label, null, null);
} }
@Override
public void deactivate() {
super.deactivate();
}
} }

View File

@ -83,7 +83,6 @@ import org.slf4j.LoggerFactory;
*/ */
@NonNullByDefault @NonNullByDefault
public class LutronDeviceDiscoveryService extends AbstractDiscoveryService { public class LutronDeviceDiscoveryService extends AbstractDiscoveryService {
private static final int DECLARATION_MAX_LEN = 80; private static final int DECLARATION_MAX_LEN = 80;
private static final long HTTP_REQUEST_TIMEOUT = 60; // seconds private static final long HTTP_REQUEST_TIMEOUT = 60; // seconds
private static final int DISCOVERY_SERVICE_TIMEOUT = 90; // seconds private static final int DISCOVERY_SERVICE_TIMEOUT = 90; // seconds

View File

@ -16,16 +16,12 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.lutron.internal.LutronHandlerFactory; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; 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.ThingUID;
import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.thing.binding.ThingHandlerService;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -38,38 +34,19 @@ import org.slf4j.LoggerFactory;
* *
* @author Andrew Shilliday - Initial contribution * @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 Logger logger = LoggerFactory.getLogger(HwDiscoveryService.class);
private final AtomicBoolean isScanning = new AtomicBoolean(false); private final AtomicBoolean isScanning = new AtomicBoolean(false);
private @NonNullByDefault({}) HwSerialBridgeHandler handler;
public HwDiscoveryService() { public HwDiscoveryService() {
super(LutronHandlerFactory.HW_DISCOVERABLE_DEVICE_TYPES_UIDS, 10); super(HwSerialBridgeHandler.class, LutronHandlerFactory.HW_DISCOVERABLE_DEVICE_TYPES_UIDS, 10);
} }
@Override @Override
public void setThingHandler(@Nullable ThingHandler handler) { public void initialize() {
if (handler instanceof HwSerialBridgeHandler bridgeHandler) { thingHandler.setDiscoveryService(this);
this.handler = bridgeHandler; super.initialize();
this.handler.setDiscoveryService(this);
}
}
@Override
public @Nullable ThingHandler getThingHandler() {
return handler;
}
@Override
public void activate() {
super.activate(null);
}
@Override
public void deactivate() {
super.deactivate();
} }
@Override @Override
@ -81,7 +58,7 @@ public class HwDiscoveryService extends AbstractDiscoveryService implements Disc
for (int m = 1; m <= 8; m++) { // Modules for (int m = 1; m <= 8; m++) { // Modules
for (int o = 1; o <= 4; o++) { // Outputs for (int o = 1; o <= 4; o++) { // Outputs
String address = String.format("[01:01:00:%02d:%02d]", m, o); String address = String.format("[01:01:00:%02d:%02d]", m, o);
handler.sendCommand("RDL, " + address); thingHandler.sendCommand("RDL, " + address);
Thread.sleep(5); Thread.sleep(5);
} }
} }
@ -99,11 +76,11 @@ public class HwDiscoveryService extends AbstractDiscoveryService implements Disc
*/ */
public void declareUnknownDimmer(String address) { public void declareUnknownDimmer(String address) {
if (address == null) { if (address == null) {
logger.info("Discovered HomeWorks dimmer with no address"); logger.info("Discovered HomeWorks dimmer with no address or thing handler");
return; return;
} }
String addressUid = address.replaceAll("[\\[\\]]", "").replace(":", "-"); 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); ThingUID uid = new ThingUID(HwConstants.THING_TYPE_HWDIMMER, bridgeUID, addressUid);
Map<String, Object> props = new HashMap<>(); Map<String, Object> props = new HashMap<>();

View File

@ -31,6 +31,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -39,6 +41,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Jan N. Klug - Initial contribution * @author Jan N. Klug - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = SendMailActions.class)
@ThingActionsScope(name = "mail") @ThingActionsScope(name = "mail")
@NonNullByDefault @NonNullByDefault
public class SendMailActions implements ThingActions { public class SendMailActions implements ThingActions {

View File

@ -20,6 +20,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -28,6 +30,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Christoph Weitkamp - Initial contribution * @author Christoph Weitkamp - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = MaxCubeActions.class)
@ThingActionsScope(name = "max-cube") @ThingActionsScope(name = "max-cube")
@NonNullByDefault @NonNullByDefault
public class MaxCubeActions implements ThingActions { public class MaxCubeActions implements ThingActions {

View File

@ -20,6 +20,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -28,6 +30,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Christoph Weitkamp - Initial contribution * @author Christoph Weitkamp - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = MaxDevicesActions.class)
@ThingActionsScope(name = "max-devices") @ThingActionsScope(name = "max-devices")
@NonNullByDefault @NonNullByDefault
public class MaxDevicesActions implements ThingActions { public class MaxDevicesActions implements ThingActions {

View File

@ -16,21 +16,19 @@ import java.util.Date;
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; 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.MaxBindingConstants;
import org.openhab.binding.max.internal.device.Device; import org.openhab.binding.max.internal.device.Device;
import org.openhab.binding.max.internal.handler.DeviceStatusListener; import org.openhab.binding.max.internal.handler.DeviceStatusListener;
import org.openhab.binding.max.internal.handler.MaxCubeBridgeHandler; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; 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.Bridge;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -40,46 +38,29 @@ import org.slf4j.LoggerFactory;
* *
* @author Marcel Verpaalen - Initial contribution * @author Marcel Verpaalen - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = MaxDeviceDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class MaxDeviceDiscoveryService extends AbstractDiscoveryService public class MaxDeviceDiscoveryService extends AbstractThingHandlerDiscoveryService<MaxCubeBridgeHandler>
implements DeviceStatusListener, DiscoveryService, ThingHandlerService { implements DeviceStatusListener {
private static final int SEARCH_TIME = 60; private static final int SEARCH_TIME = 60;
private final Logger logger = LoggerFactory.getLogger(MaxDeviceDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(MaxDeviceDiscoveryService.class);
private @Nullable MaxCubeBridgeHandler maxCubeBridgeHandler;
public MaxDeviceDiscoveryService() { public MaxDeviceDiscoveryService() {
super(MaxBindingConstants.SUPPORTED_DEVICE_THING_TYPES_UIDS, SEARCH_TIME, true); super(MaxCubeBridgeHandler.class, MaxBindingConstants.SUPPORTED_DEVICE_THING_TYPES_UIDS, SEARCH_TIME, true);
} }
@Override @Override
public void setThingHandler(@NonNullByDefault({}) ThingHandler handler) { public void initialize() {
if (handler instanceof MaxCubeBridgeHandler maxCubeBridgeHandler) { thingHandler.registerDeviceStatusListener(this);
this.maxCubeBridgeHandler = maxCubeBridgeHandler; super.initialize();
}
} }
@Override @Override
public @Nullable ThingHandler getThingHandler() { public void dispose() {
return maxCubeBridgeHandler; super.dispose();
} thingHandler.unregisterDeviceStatusListener(this);
removeOlderResults(new Date().getTime(), thingHandler.getThing().getUID());
@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());
}
} }
@Override @Override
@ -133,11 +114,8 @@ public class MaxDeviceDiscoveryService extends AbstractDiscoveryService
@Override @Override
protected void startScan() { protected void startScan() {
MaxCubeBridgeHandler localMaxCubeBridgeHandler = maxCubeBridgeHandler; thingHandler.clearDeviceList();
if (localMaxCubeBridgeHandler != null) { thingHandler.deviceInclusion();
localMaxCubeBridgeHandler.clearDeviceList();
localMaxCubeBridgeHandler.deviceInclusion();
}
} }
@Override @Override

View File

@ -14,17 +14,17 @@ package org.openhab.binding.meater.internal.discovery;
import static org.openhab.binding.meater.internal.MeaterBindingConstants.*; import static org.openhab.binding.meater.internal.MeaterBindingConstants.*;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault; 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.MeaterConfiguration;
import org.openhab.binding.meater.internal.handler.MeaterBridgeHandler; 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.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.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ServiceScope;
/** /**
* The {@link MeaterDiscoveryService} searches for available * The {@link MeaterDiscoveryService} searches for available
@ -32,51 +32,34 @@ import org.openhab.core.thing.binding.ThingHandlerService;
* *
* @author Jan Gustafsson - Initial contribution * @author Jan Gustafsson - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = MeaterDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class MeaterDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService { public class MeaterDiscoveryService extends AbstractThingHandlerDiscoveryService<MeaterBridgeHandler> {
private static final int SEARCH_TIME = 2; private static final int SEARCH_TIME = 2;
private @Nullable MeaterBridgeHandler handler;
public MeaterDiscoveryService() { public MeaterDiscoveryService() {
super(SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME); super(MeaterBridgeHandler.class, SUPPORTED_THING_TYPES_UIDS, SEARCH_TIME);
} }
@Override @Reference(unbind = "-")
public void setThingHandler(@Nullable ThingHandler handler) { public void bindTranslationProvider(TranslationProvider translationProvider) {
if (handler instanceof MeaterBridgeHandler bridgeHandler) { this.i18nProvider = translationProvider;
this.handler = bridgeHandler;
i18nProvider = bridgeHandler.getI18nProvider();
localeProvider = bridgeHandler.getLocaleProvider();
}
} }
@Override @Reference(unbind = "-")
public @Nullable ThingHandler getThingHandler() { public void bindLocaleProvider(LocaleProvider localeProvider) {
return handler; this.localeProvider = localeProvider;
}
@Override
public void activate(@Nullable Map<String, Object> configProperties) {
super.activate(configProperties);
}
@Override
public void deactivate() {
super.deactivate();
} }
@Override @Override
protected void startScan() { protected void startScan() {
MeaterBridgeHandler bridgeHandler = this.handler; ThingUID bridgeUID = thingHandler.getThing().getUID();
if (bridgeHandler != null) { thingHandler.getMeaterThings().entrySet().stream().forEach(thing -> {
ThingUID bridgeUID = bridgeHandler.getThing().getUID(); thingDiscovered(
bridgeHandler.getMeaterThings().entrySet().stream().forEach(thing -> { DiscoveryResultBuilder.create(new ThingUID(THING_TYPE_MEATER_PROBE, bridgeUID, thing.getKey()))
thingDiscovered( .withLabel("@text/discovery.probe.label").withBridge(bridgeUID)
DiscoveryResultBuilder.create(new ThingUID(THING_TYPE_MEATER_PROBE, bridgeUID, thing.getKey())) .withProperty(MeaterConfiguration.DEVICE_ID_LABEL, thing.getKey())
.withLabel("@text/discovery.probe.label").withBridge(bridgeUID) .withRepresentationProperty(MeaterConfiguration.DEVICE_ID_LABEL).build());
.withProperty(MeaterConfiguration.DEVICE_ID_LABEL, thing.getKey()) });
.withRepresentationProperty(MeaterConfiguration.DEVICE_ID_LABEL).build());
});
}
} }
} }

View File

@ -29,7 +29,6 @@ import org.openhab.binding.meater.internal.api.MeaterRestAPI;
import org.openhab.binding.meater.internal.discovery.MeaterDiscoveryService; import org.openhab.binding.meater.internal.discovery.MeaterDiscoveryService;
import org.openhab.binding.meater.internal.dto.MeaterProbeDTO; import org.openhab.binding.meater.internal.dto.MeaterProbeDTO;
import org.openhab.core.i18n.LocaleProvider; import org.openhab.core.i18n.LocaleProvider;
import org.openhab.core.i18n.TranslationProvider;
import org.openhab.core.thing.Bridge; import org.openhab.core.thing.Bridge;
import org.openhab.core.thing.ChannelUID; import org.openhab.core.thing.ChannelUID;
import org.openhab.core.thing.ThingStatus; import org.openhab.core.thing.ThingStatus;
@ -59,7 +58,6 @@ public class MeaterBridgeHandler extends BaseBridgeHandler {
private final Gson gson; private final Gson gson;
private final HttpClient httpClient; private final HttpClient httpClient;
private final TranslationProvider i18nProvider;
private final LocaleProvider localeProvider; private final LocaleProvider localeProvider;
private final Map<String, MeaterProbeDTO.Device> meaterProbeThings = new ConcurrentHashMap<>(); private final Map<String, MeaterProbeDTO.Device> meaterProbeThings = new ConcurrentHashMap<>();
@ -67,12 +65,10 @@ public class MeaterBridgeHandler extends BaseBridgeHandler {
private @Nullable MeaterRestAPI api; private @Nullable MeaterRestAPI api;
private @Nullable ScheduledFuture<?> refreshJob; private @Nullable ScheduledFuture<?> refreshJob;
public MeaterBridgeHandler(Bridge bridge, HttpClient httpClient, Gson gson, TranslationProvider i18nProvider, public MeaterBridgeHandler(Bridge bridge, HttpClient httpClient, Gson gson, LocaleProvider localeProvider) {
LocaleProvider localeProvider) {
super(bridge); super(bridge);
this.httpClient = httpClient; this.httpClient = httpClient;
this.gson = gson; this.gson = gson;
this.i18nProvider = i18nProvider;
this.localeProvider = localeProvider; this.localeProvider = localeProvider;
} }
@ -154,12 +150,4 @@ public class MeaterBridgeHandler extends BaseBridgeHandler {
} }
} }
} }
public TranslationProvider getI18nProvider() {
return i18nProvider;
}
public LocaleProvider getLocaleProvider() {
return localeProvider;
}
} }

View File

@ -21,7 +21,6 @@ import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.HttpClient;
import org.openhab.core.i18n.LocaleProvider; import org.openhab.core.i18n.LocaleProvider;
import org.openhab.core.i18n.TimeZoneProvider; import org.openhab.core.i18n.TimeZoneProvider;
import org.openhab.core.i18n.TranslationProvider;
import org.openhab.core.io.net.http.HttpClientFactory; import org.openhab.core.io.net.http.HttpClientFactory;
import org.openhab.core.thing.Bridge; import org.openhab.core.thing.Bridge;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
@ -51,15 +50,12 @@ public class MeaterHandlerFactory extends BaseThingHandlerFactory {
private final Gson gson; private final Gson gson;
private final HttpClient httpClient; private final HttpClient httpClient;
private final TimeZoneProvider timeZoneProvider; private final TimeZoneProvider timeZoneProvider;
private final TranslationProvider i18nProvider;
private final LocaleProvider localeProvider; private final LocaleProvider localeProvider;
@Activate @Activate
public MeaterHandlerFactory(@Reference TimeZoneProvider timeZoneProvider, public MeaterHandlerFactory(@Reference TimeZoneProvider timeZoneProvider, @Reference LocaleProvider localeProvider,
final @Reference TranslationProvider i18nProvider, @Reference LocaleProvider localeProvider,
@Reference HttpClientFactory httpClientFactory) { @Reference HttpClientFactory httpClientFactory) {
this.timeZoneProvider = timeZoneProvider; this.timeZoneProvider = timeZoneProvider;
this.i18nProvider = i18nProvider;
this.localeProvider = localeProvider; this.localeProvider = localeProvider;
this.httpClient = httpClientFactory.getCommonHttpClient(); this.httpClient = httpClientFactory.getCommonHttpClient();
this.gson = new Gson(); this.gson = new Gson();
@ -77,7 +73,7 @@ public class MeaterHandlerFactory extends BaseThingHandlerFactory {
if (THING_TYPE_MEATER_PROBE.equals(thingTypeUID)) { if (THING_TYPE_MEATER_PROBE.equals(thingTypeUID)) {
return new MeaterHandler(thing, timeZoneProvider); return new MeaterHandler(thing, timeZoneProvider);
} else if (THING_TYPE_BRIDGE.equals(thingTypeUID)) { } 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; return null;

View File

@ -20,21 +20,19 @@ import java.util.Map;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; 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.MelCloudBindingConstants;
import org.openhab.binding.melcloud.internal.api.json.Device; import org.openhab.binding.melcloud.internal.api.json.Device;
import org.openhab.binding.melcloud.internal.exceptions.MelCloudCommException; import org.openhab.binding.melcloud.internal.exceptions.MelCloudCommException;
import org.openhab.binding.melcloud.internal.exceptions.MelCloudLoginException; import org.openhab.binding.melcloud.internal.exceptions.MelCloudLoginException;
import org.openhab.binding.melcloud.internal.handler.MelCloudAccountHandler; 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.DiscoveryResultBuilder;
import org.openhab.core.config.discovery.DiscoveryService;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.osgi.service.component.annotations.Modified;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -45,38 +43,21 @@ import org.slf4j.LoggerFactory;
* @author Pauli Anttila - Refactoring * @author Pauli Anttila - Refactoring
* @author Wietse van Buitenen - Check device type, added heatpump device * @author Wietse van Buitenen - Check device type, added heatpump device
*/ */
public class MelCloudDiscoveryService extends AbstractDiscoveryService @Component(scope = ServiceScope.PROTOTYPE, service = MelCloudDiscoveryService.class)
implements DiscoveryService, ThingHandlerService { public class MelCloudDiscoveryService extends AbstractThingHandlerDiscoveryService<@NonNull MelCloudAccountHandler> {
private final Logger logger = LoggerFactory.getLogger(MelCloudDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(MelCloudDiscoveryService.class);
private static final String PROPERTY_DEVICE_ID = "deviceID"; private static final String PROPERTY_DEVICE_ID = "deviceID";
private static final int DISCOVER_TIMEOUT_SECONDS = 10; private static final int DISCOVER_TIMEOUT_SECONDS = 10;
private MelCloudAccountHandler melCloudHandler;
private ScheduledFuture<?> scanTask; private ScheduledFuture<?> scanTask;
/** /**
* Creates a MelCloudDiscoveryService with enabled autostart. * Creates a MelCloudDiscoveryService with enabled autostart.
*/ */
public MelCloudDiscoveryService() { public MelCloudDiscoveryService() {
super(MelCloudBindingConstants.DISCOVERABLE_THING_TYPE_UIDS, DISCOVER_TIMEOUT_SECONDS, true); super(MelCloudAccountHandler.class, MelCloudBindingConstants.DISCOVERABLE_THING_TYPE_UIDS,
} DISCOVER_TIMEOUT_SECONDS, true);
@Override
protected void activate(Map<String, Object> configProperties) {
super.activate(configProperties);
}
@Override
public void deactivate() {
super.deactivate();
}
@Override
@Modified
protected void modified(Map<String, Object> configProperties) {
super.modified(configProperties);
} }
@Override @Override
@ -104,50 +85,47 @@ public class MelCloudDiscoveryService extends AbstractDiscoveryService
private void discoverDevices() { private void discoverDevices() {
logger.debug("Discover devices"); logger.debug("Discover devices");
try {
List<Device> deviceList = thingHandler.getDeviceList();
if (melCloudHandler != null) { if (deviceList == null) {
try { logger.debug("No devices found");
List<Device> deviceList = melCloudHandler.getDeviceList(); } else {
ThingUID bridgeUID = thingHandler.getThing().getUID();
if (deviceList == null) { deviceList.forEach(device -> {
logger.debug("No devices found"); ThingTypeUID thingTypeUid = null;
} else { if (device.getType() == 0) {
ThingUID bridgeUID = melCloudHandler.getThing().getUID(); 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());
deviceList.forEach(device -> { Map<String, Object> deviceProperties = new HashMap<>();
ThingTypeUID thingTypeUid = null; deviceProperties.put(PROPERTY_DEVICE_ID, device.getDeviceID().toString());
if (device.getType() == 0) { deviceProperties.put(Thing.PROPERTY_SERIAL_NUMBER, device.getSerialNumber());
thingTypeUid = THING_TYPE_ACDEVICE; deviceProperties.put(Thing.PROPERTY_MAC_ADDRESS, device.getMacAddress());
} else if (device.getType() == 1) { deviceProperties.put("deviceName", device.getDeviceName());
thingTypeUid = THING_TYPE_HEATPUMPDEVICE; deviceProperties.put("buildingID", device.getBuildingID().toString());
} 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<String, Object> deviceProperties = new HashMap<>(); String label = createLabel(device);
deviceProperties.put(PROPERTY_DEVICE_ID, device.getDeviceID().toString()); logger.debug("Found device: {} : {}", label, deviceProperties);
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); thingDiscovered(
logger.debug("Found device: {} : {}", label, deviceProperties); DiscoveryResultBuilder.create(deviceThing).withLabel(label).withProperties(deviceProperties)
.withRepresentationProperty(PROPERTY_DEVICE_ID).withBridge(bridgeUID).build());
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);
} }
} 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 @@ public class MelCloudDiscoveryService extends AbstractDiscoveryService
sb.append(device.getDeviceName()); sb.append(device.getDeviceName());
return sb.toString(); return sb.toString();
} }
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
if (handler instanceof MelCloudAccountHandler accountHandler) {
melCloudHandler = accountHandler;
}
}
@Override
public @Nullable ThingHandler getThingHandler() {
return melCloudHandler;
}
} }

View File

@ -15,6 +15,7 @@ package org.openhab.binding.mielecloud.internal.discovery;
import static org.openhab.binding.mielecloud.internal.MieleCloudBindingConstants.*; import static org.openhab.binding.mielecloud.internal.MieleCloudBindingConstants.*;
import static org.openhab.binding.mielecloud.internal.handler.MieleHandlerFactory.SUPPORTED_THING_TYPES; import static org.openhab.binding.mielecloud.internal.handler.MieleHandlerFactory.SUPPORTED_THING_TYPES;
import java.util.Map;
import java.util.Optional; import java.util.Optional;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -22,15 +23,15 @@ import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.mielecloud.internal.handler.MieleBridgeHandler; 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.DeviceState;
import org.openhab.binding.mielecloud.internal.webservice.api.json.DeviceType; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.config.discovery.DiscoveryService; import org.openhab.core.config.discovery.DiscoveryService;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingTypeUID; import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -40,13 +41,11 @@ import org.slf4j.LoggerFactory;
* @author Roland Edelhoff - Initial contribution * @author Roland Edelhoff - Initial contribution
* @author Björn Lange - Do not directly listen to webservice events * @author Björn Lange - Do not directly listen to webservice events
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = ThingDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class ThingDiscoveryService extends AbstractDiscoveryService implements DiscoveryService, ThingHandlerService { public class ThingDiscoveryService extends AbstractThingHandlerDiscoveryService<MieleBridgeHandler> {
private static final int BACKGROUND_DISCOVERY_TIMEOUT_IN_SECONDS = 5; private static final int BACKGROUND_DISCOVERY_TIMEOUT_IN_SECONDS = 5;
@Nullable
private MieleBridgeHandler bridgeHandler;
private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final Logger logger = LoggerFactory.getLogger(this.getClass());
private boolean discoveringDevices = false; private boolean discoveringDevices = false;
@ -55,12 +54,12 @@ public class ThingDiscoveryService extends AbstractDiscoveryService implements D
* Creates a new {@link ThingDiscoveryService}. * Creates a new {@link ThingDiscoveryService}.
*/ */
public ThingDiscoveryService() { public ThingDiscoveryService() {
super(SUPPORTED_THING_TYPES, BACKGROUND_DISCOVERY_TIMEOUT_IN_SECONDS); super(MieleBridgeHandler.class, SUPPORTED_THING_TYPES, BACKGROUND_DISCOVERY_TIMEOUT_IN_SECONDS);
} }
@Nullable @Nullable
private ThingUID getBridgeUid() { private ThingUID getBridgeUid() {
var bridgeHandler = this.bridgeHandler; var bridgeHandler = this.thingHandler;
if (bridgeHandler == null) { if (bridgeHandler == null) {
return null; return null;
} else { } else {
@ -74,12 +73,12 @@ public class ThingDiscoveryService extends AbstractDiscoveryService implements D
@Override @Override
public void activate() { public void activate() {
startBackgroundDiscovery(); super.activate(Map.of(DiscoveryService.CONFIG_PROPERTY_BACKGROUND_DISCOVERY, true));
} }
@Override @Override
public void deactivate() { public void dispose() {
stopBackgroundDiscovery(); super.dispose();
removeOlderResults(System.currentTimeMillis(), getBridgeUid()); removeOlderResults(System.currentTimeMillis(), getBridgeUid());
} }
@ -100,16 +99,11 @@ public class ThingDiscoveryService extends AbstractDiscoveryService implements D
} }
private void createDiscoveryResult(DeviceState deviceState, ThingTypeUID thingTypeUid) { private void createDiscoveryResult(DeviceState deviceState, ThingTypeUID thingTypeUid) {
MieleBridgeHandler bridgeHandler = this.bridgeHandler; ThingUID thingUid = new ThingUID(thingTypeUid, thingHandler.getThing().getUID(),
if (bridgeHandler == null) {
return;
}
ThingUID thingUid = new ThingUID(thingTypeUid, bridgeHandler.getThing().getUID(),
deviceState.getDeviceIdentifier()); deviceState.getDeviceIdentifier());
DiscoveryResultBuilder discoveryResultBuilder = DiscoveryResultBuilder.create(thingUid) 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)); .withLabel(getLabel(deviceState));
ThingInformationExtractor.extractProperties(thingTypeUid, deviceState).entrySet() ThingInformationExtractor.extractProperties(thingTypeUid, deviceState).entrySet()
@ -199,15 +193,8 @@ public class ThingDiscoveryService extends AbstractDiscoveryService implements D
} }
@Override @Override
public void setThingHandler(ThingHandler handler) { public void initialize() {
if (handler instanceof MieleBridgeHandler bridgeHandler) { thingHandler.setDiscoveryService(this);
bridgeHandler.setDiscoveryService(this); super.initialize();
this.bridgeHandler = bridgeHandler;
}
}
@Override
public @Nullable ThingHandler getThingHandler() {
return bridgeHandler;
} }
} }

View File

@ -25,6 +25,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -33,6 +35,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Bernhard Bauer - Initial contribution * @author Bernhard Bauer - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = HeliosEasyControlsActions.class)
@ThingActionsScope(name = "modbus.helioseasycontrols") @ThingActionsScope(name = "modbus.helioseasycontrols")
@NonNullByDefault @NonNullByDefault
public class HeliosEasyControlsActions implements ThingActions { public class HeliosEasyControlsActions implements ThingActions {

View File

@ -22,6 +22,8 @@ import org.openhab.binding.modbus.discovery.ModbusDiscoveryParticipant;
import org.openhab.binding.modbus.handler.ModbusEndpointThingHandler; import org.openhab.binding.modbus.handler.ModbusEndpointThingHandler;
import org.openhab.core.config.discovery.DiscoveryResult; import org.openhab.core.config.discovery.DiscoveryResult;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -35,6 +37,7 @@ import org.slf4j.LoggerFactory;
* @author Nagy Attila Gabor - initial contribution * @author Nagy Attila Gabor - initial contribution
* *
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = ModbusEndpointDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class ModbusEndpointDiscoveryService implements ModbusThingHandlerDiscoveryService { public class ModbusEndpointDiscoveryService implements ModbusThingHandlerDiscoveryService {

View File

@ -20,6 +20,8 @@ import org.openhab.core.automation.annotation.RuleAction;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -28,6 +30,7 @@ import org.slf4j.LoggerFactory;
* *
* @author Stefan Röllin - Initial contribution * @author Stefan Röllin - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = MPDActions.class)
@ThingActionsScope(name = "mpd") @ThingActionsScope(name = "mpd")
@NonNullByDefault @NonNullByDefault
public class MPDActions implements ThingActions { public class MPDActions implements ThingActions {

View File

@ -21,6 +21,8 @@ import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
import org.openhab.core.thing.binding.ThingActions; import org.openhab.core.thing.binding.ThingActions;
import org.openhab.core.thing.binding.ThingActionsScope; import org.openhab.core.thing.binding.ThingActionsScope;
import org.openhab.core.thing.binding.ThingHandler; 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.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -29,6 +31,7 @@ import org.slf4j.LoggerFactory;
* *
* @author David Graeff - Initial contribution * @author David Graeff - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = MQTTActions.class)
@ThingActionsScope(name = "mqtt") @ThingActionsScope(name = "mqtt")
@NonNullByDefault @NonNullByDefault
public class MQTTActions implements ThingActions { public class MQTTActions implements ThingActions {

View File

@ -19,7 +19,6 @@ import java.util.Optional;
import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.NonNullByDefault; 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.MyBMWConstants;
import org.openhab.binding.mybmw.internal.dto.vehicle.Vehicle; import org.openhab.binding.mybmw.internal.dto.vehicle.Vehicle;
import org.openhab.binding.mybmw.internal.dto.vehicle.VehicleAttributes; import org.openhab.binding.mybmw.internal.dto.vehicle.VehicleAttributes;
@ -31,12 +30,12 @@ import org.openhab.binding.mybmw.internal.handler.enums.RemoteService;
import org.openhab.binding.mybmw.internal.utils.Constants; import org.openhab.binding.mybmw.internal.utils.Constants;
import org.openhab.binding.mybmw.internal.utils.VehicleStatusUtils; import org.openhab.binding.mybmw.internal.utils.VehicleStatusUtils;
import org.openhab.core.config.core.Configuration; 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.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.thing.Thing; import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -47,34 +46,26 @@ import org.slf4j.LoggerFactory;
* @author Bernd Weymann - Initial contribution * @author Bernd Weymann - Initial contribution
* @author Martin Grassl - refactoring * @author Martin Grassl - refactoring
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = VehicleDiscovery.class)
@NonNullByDefault @NonNullByDefault
public class VehicleDiscovery extends AbstractDiscoveryService implements ThingHandlerService { public class VehicleDiscovery extends AbstractThingHandlerDiscoveryService<MyBMWBridgeHandler> {
private final Logger logger = LoggerFactory.getLogger(VehicleDiscovery.class); private final Logger logger = LoggerFactory.getLogger(VehicleDiscovery.class);
private static final int DISCOVERY_TIMEOUT = 10; private static final int DISCOVERY_TIMEOUT = 10;
private Optional<MyBMWBridgeHandler> bridgeHandler = Optional.empty();
private Optional<MyBMWProxy> myBMWProxy = Optional.empty(); private Optional<MyBMWProxy> myBMWProxy = Optional.empty();
private Optional<ThingUID> bridgeUid = Optional.empty(); private @NonNullByDefault({}) ThingUID bridgeUid;
public VehicleDiscovery() { public VehicleDiscovery() {
super(MyBMWConstants.SUPPORTED_THING_SET, DISCOVERY_TIMEOUT, false); super(MyBMWBridgeHandler.class, MyBMWConstants.SUPPORTED_THING_SET, DISCOVERY_TIMEOUT, false);
} }
@Override @Override
public void setThingHandler(ThingHandler handler) { public void initialize() {
if (handler instanceof MyBMWBridgeHandler bmwBridgeHandler) { thingHandler.setVehicleDiscovery(this);
logger.trace("VehicleDiscovery.setThingHandler for MybmwBridge"); bridgeUid = thingHandler.getThing().getUID();
bridgeHandler = Optional.of(bmwBridgeHandler); super.initialize();
bridgeHandler.get().setVehicleDiscovery(this);
bridgeUid = Optional.of(bridgeHandler.get().getThing().getUID());
}
}
@Override
public @Nullable ThingHandler getThingHandler() {
return bridgeHandler.orElse(null);
} }
@Override @Override
@ -83,17 +74,10 @@ public class VehicleDiscovery extends AbstractDiscoveryService implements ThingH
discoverVehicles(); discoverVehicles();
} }
@Override
public void deactivate() {
logger.trace("VehicleDiscovery.deactivate");
super.deactivate();
}
public void discoverVehicles() { public void discoverVehicles() {
logger.trace("VehicleDiscovery.discoverVehicles"); logger.trace("VehicleDiscovery.discoverVehicles");
myBMWProxy = bridgeHandler.get().getMyBmwProxy(); myBMWProxy = thingHandler.getMyBmwProxy();
try { try {
Optional<List<@NonNull Vehicle>> vehicleList = myBMWProxy.map(prox -> { Optional<List<@NonNull Vehicle>> vehicleList = myBMWProxy.map(prox -> {
@ -104,11 +88,11 @@ public class VehicleDiscovery extends AbstractDiscoveryService implements ThingH
} }
}); });
vehicleList.ifPresentOrElse(vehicles -> { vehicleList.ifPresentOrElse(vehicles -> {
bridgeHandler.ifPresent(bridge -> bridge.vehicleDiscoverySuccess()); thingHandler.vehicleDiscoverySuccess();
processVehicles(vehicles); processVehicles(vehicles);
}, () -> bridgeHandler.ifPresent(bridge -> bridge.vehicleDiscoveryError())); }, () -> thingHandler.vehicleDiscoveryError());
} catch (IllegalStateException ex) { } catch (IllegalStateException ex) {
bridgeHandler.ifPresent(bridge -> bridge.vehicleDiscoveryError()); thingHandler.vehicleDiscoveryError();
} }
} }
@ -131,13 +115,13 @@ public class VehicleDiscovery extends AbstractDiscoveryService implements ThingH
.toString(); .toString();
MyBMWConstants.SUPPORTED_THING_SET.forEach(entry -> { MyBMWConstants.SUPPORTED_THING_SET.forEach(entry -> {
if (entry.getId().equals(vehicleType)) { 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<String, String> properties = generateProperties(vehicle); Map<String, String> properties = generateProperties(vehicle);
boolean thingFound = false; boolean thingFound = false;
// Update Properties for already created Things // Update Properties for already created Things
List<Thing> vehicleThings = bridgeHandler.get().getThing().getThings(); List<Thing> vehicleThings = thingHandler.getThing().getThings();
for (Thing vehicleThing : vehicleThings) { for (Thing vehicleThing : vehicleThings) {
Configuration configuration = vehicleThing.getConfiguration(); Configuration configuration = vehicleThing.getConfiguration();
@ -161,7 +145,7 @@ public class VehicleDiscovery extends AbstractDiscoveryService implements ThingH
Integer.toString(MyBMWConstants.DEFAULT_REFRESH_INTERVAL_MINUTES)); Integer.toString(MyBMWConstants.DEFAULT_REFRESH_INTERVAL_MINUTES));
String vehicleLabel = vehicleAttributes.getBrand() + " " + vehicleAttributes.getModel(); String vehicleLabel = vehicleAttributes.getBrand() + " " + vehicleAttributes.getModel();
thingDiscovered(DiscoveryResultBuilder.create(uid).withBridge(bridgeUid.get()) thingDiscovered(DiscoveryResultBuilder.create(uid).withBridge(bridgeUid)
.withRepresentationProperty(MyBMWConstants.VIN).withLabel(vehicleLabel) .withRepresentationProperty(MyBMWConstants.VIN).withLabel(vehicleLabel)
.withProperties(convertedProperties).build()); .withProperties(convertedProperties).build());
} }

View File

@ -83,6 +83,7 @@ public class VehicleDiscoveryTest {
when(bridgeHandler.getMyBmwProxy()).thenReturn(Optional.of(myBMWProxy)); when(bridgeHandler.getMyBmwProxy()).thenReturn(Optional.of(myBMWProxy));
vehicleDiscovery.setThingHandler(bridgeHandler); vehicleDiscovery.setThingHandler(bridgeHandler);
vehicleDiscovery.initialize();
assertNotNull(vehicleDiscovery.getThingHandler()); assertNotNull(vehicleDiscovery.getThingHandler());
DiscoveryListener listener = mock(DiscoveryListener.class); DiscoveryListener listener = mock(DiscoveryListener.class);

View File

@ -15,21 +15,19 @@ package org.openhab.binding.mynice.internal.discovery;
import static org.openhab.binding.mynice.internal.MyNiceBindingConstants.*; import static org.openhab.binding.mynice.internal.MyNiceBindingConstants.*;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; 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.It4WifiHandler;
import org.openhab.binding.mynice.internal.handler.MyNiceDataListener; 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.CommandType;
import org.openhab.binding.mynice.internal.xml.dto.Device; 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.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder; import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.thing.ThingUID; import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler; import org.osgi.service.component.annotations.Component;
import org.openhab.core.thing.binding.ThingHandlerService; import org.osgi.service.component.annotations.ServiceScope;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -39,72 +37,56 @@ import org.slf4j.LoggerFactory;
* *
* @author Gaël L'hopital - Initial contribution * @author Gaël L'hopital - Initial contribution
*/ */
@Component(scope = ServiceScope.PROTOTYPE, service = MyNiceDiscoveryService.class)
@NonNullByDefault @NonNullByDefault
public class MyNiceDiscoveryService extends AbstractDiscoveryService public class MyNiceDiscoveryService extends AbstractThingHandlerDiscoveryService<It4WifiHandler>
implements MyNiceDataListener, ThingHandlerService { implements MyNiceDataListener {
private static final int SEARCH_TIME = 5; private static final int SEARCH_TIME = 5;
private final Logger logger = LoggerFactory.getLogger(MyNiceDiscoveryService.class); private final Logger logger = LoggerFactory.getLogger(MyNiceDiscoveryService.class);
private Optional<It4WifiHandler> bridgeHandler = Optional.empty();
/** /**
* Creates a MyNiceDiscoveryService with background discovery disabled. * Creates a MyNiceDiscoveryService with background discovery disabled.
*/ */
public MyNiceDiscoveryService() { public MyNiceDiscoveryService() {
super(Set.of(THING_TYPE_SWING, THING_TYPE_SLIDING), SEARCH_TIME, false); super(It4WifiHandler.class, Set.of(THING_TYPE_SWING, THING_TYPE_SLIDING), SEARCH_TIME, false);
} }
@Override @Override
public void setThingHandler(ThingHandler handler) { public void initialize() {
if (handler instanceof It4WifiHandler it4Handler) { thingHandler.registerDataListener(this);
bridgeHandler = Optional.of(it4Handler); super.initialize();
}
} }
@Override @Override
public @Nullable ThingHandler getThingHandler() { public void dispose() {
return bridgeHandler.orElse(null); super.dispose();
} thingHandler.unregisterDataListener(this);
@Override
public void activate() {
super.activate(null);
bridgeHandler.ifPresent(h -> h.registerDataListener(this));
}
@Override
public void deactivate() {
bridgeHandler.ifPresent(h -> h.unregisterDataListener(this));
bridgeHandler = Optional.empty();
super.deactivate();
} }
@Override @Override
public void onDataFetched(List<Device> devices) { public void onDataFetched(List<Device> devices) {
bridgeHandler.ifPresent(handler -> { ThingUID bridgeUID = thingHandler.getThing().getUID();
ThingUID bridgeUID = handler.getThing().getUID(); devices.stream().filter(device -> device.type != null).forEach(device -> {
devices.stream().filter(device -> device.type != null).forEach(device -> { ThingUID thingUID = switch (device.type) {
ThingUID thingUID = switch (device.type) { case SWING -> new ThingUID(THING_TYPE_SWING, bridgeUID, device.id);
case SWING -> new ThingUID(THING_TYPE_SWING, bridgeUID, device.id); case SLIDING -> new ThingUID(THING_TYPE_SLIDING, bridgeUID, device.id);
case SLIDING -> new ThingUID(THING_TYPE_SLIDING, bridgeUID, device.id); default -> null;
default -> null; };
};
if (thingUID != null) { if (thingUID != null) {
DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withBridge(bridgeUID) DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withBridge(bridgeUID)
.withLabel(String.format("%s %s", device.manuf, device.prod)) .withLabel(String.format("%s %s", device.manuf, device.prod))
.withRepresentationProperty(DEVICE_ID).withProperty(DEVICE_ID, device.id).build(); .withRepresentationProperty(DEVICE_ID).withProperty(DEVICE_ID, device.id).build();
thingDiscovered(discoveryResult); thingDiscovered(discoveryResult);
} else { } else {
logger.info("`{}` type of device is not yet supported", device.type); logger.info("`{}` type of device is not yet supported", device.type);
} }
});
}); });
} }
@Override @Override
protected void startScan() { protected void startScan() {
bridgeHandler.ifPresent(h -> h.sendCommand(CommandType.INFO)); thingHandler.sendCommand(CommandType.INFO);
} }
} }

Some files were not shown because too many files have changed in this diff Show More