Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[onewire] use ChannelBuilder from ThingHandlerCallback #146

Merged
merged 3 commits into from
Jun 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -144,9 +144,6 @@ public class OwBindingConstants {
public static final Map<OwSensorType, String> THING_LABEL_MAP;
public static final Map<OwSensorType, Set<OwChannelConfig>> SENSOR_TYPE_CHANNEL_MAP;

public static final Map<String, String> ACCEPTED_ITEM_TYPES_MAP = Util
.readPropertiesFile("accepted_itemtypes.properties");

static {
Map<String, String> properties = Util.readPropertiesFile("sensor.properties");
THING_TYPE_MAP = properties.entrySet().stream().filter(e -> e.getKey().endsWith(".thingtype"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,26 +15,17 @@

import static org.smarthomej.binding.onewire.internal.OwBindingConstants.SUPPORTED_THING_TYPES;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.config.discovery.DiscoveryService;
import org.openhab.core.thing.Bridge;
import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.BaseThingHandlerFactory;
import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.thing.binding.ThingHandlerFactory;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smarthomej.binding.onewire.internal.discovery.OwDiscoveryService;
import org.smarthomej.binding.onewire.internal.handler.AdvancedMultisensorThingHandler;
import org.smarthomej.binding.onewire.internal.handler.BAE091xSensorThingHandler;
import org.smarthomej.binding.onewire.internal.handler.BasicMultisensorThingHandler;
Expand All @@ -51,11 +42,12 @@
@NonNullByDefault
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.onewire")
public class OwHandlerFactory extends BaseThingHandlerFactory {
Logger logger = LoggerFactory.getLogger(OwHandlerFactory.class);
private final Map<ThingUID, ServiceRegistration<?>> discoveryServiceRegs = new HashMap<>();
private final OwDynamicStateDescriptionProvider dynamicStateDescriptionProvider;

@NonNullByDefault({})
private OwDynamicStateDescriptionProvider dynamicStateDescriptionProvider;
@Activate
public OwHandlerFactory(@Reference OwDynamicStateDescriptionProvider owDynamicStateDescriptionProvider) {
this.dynamicStateDescriptionProvider = owDynamicStateDescriptionProvider;
}

@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
Expand All @@ -67,9 +59,7 @@ public boolean supportsThingType(ThingTypeUID thingTypeUID) {
ThingTypeUID thingTypeUID = thing.getThingTypeUID();

if (OwserverBridgeHandler.SUPPORTED_THING_TYPES.contains(thingTypeUID)) {
OwserverBridgeHandler owserverBridgeHandler = new OwserverBridgeHandler((Bridge) thing);
registerDiscoveryService(owserverBridgeHandler);
return owserverBridgeHandler;
return new OwserverBridgeHandler((Bridge) thing);
} else if (BasicMultisensorThingHandler.SUPPORTED_THING_TYPES.contains(thingTypeUID)) {
return new BasicMultisensorThingHandler(thing, dynamicStateDescriptionProvider);
} else if (AdvancedMultisensorThingHandler.SUPPORTED_THING_TYPES.contains(thingTypeUID)) {
Expand All @@ -84,41 +74,4 @@ public boolean supportsThingType(ThingTypeUID thingTypeUID) {

return null;
}

@Override
public void unregisterHandler(Thing thing) {
super.unregisterHandler(thing);
logger.error("factory {} deleting thing {}", this, thing);
}

private synchronized void registerDiscoveryService(OwserverBridgeHandler owserverBridgeHandler) {
OwDiscoveryService owDiscoveryService = new OwDiscoveryService(owserverBridgeHandler);

this.discoveryServiceRegs.put(owserverBridgeHandler.getThing().getUID(),
bundleContext.registerService(DiscoveryService.class.getName(), owDiscoveryService, new Hashtable<>()));
}

@Override
protected synchronized void removeHandler(ThingHandler thingHandler) {
if (thingHandler instanceof OwserverBridgeHandler) {
// remove discovery service, if bridge handler is removed
ServiceRegistration<?> serviceReg = this.discoveryServiceRegs.remove(thingHandler.getThing().getUID());
if (serviceReg != null) {
OwDiscoveryService service = (OwDiscoveryService) bundleContext.getService(serviceReg.getReference());
serviceReg.unregister();
if (service != null) {
service.deactivate();
}
}
}
}

@Reference
protected void setDynamicStateDescriptionProvider(OwDynamicStateDescriptionProvider provider) {
this.dynamicStateDescriptionProvider = provider;
}

protected void unsetDynamicStateDescriptionProvider(OwDynamicStateDescriptionProvider provider) {
this.dynamicStateDescriptionProvider = null;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,14 @@
import java.util.Set;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.config.discovery.AbstractDiscoveryService;
import org.openhab.core.config.discovery.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder;
import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.ThingUID;
import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.thing.binding.ThingHandlerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smarthomej.binding.onewire.internal.OwException;
Expand All @@ -41,28 +44,27 @@
* @author Jan N. Klug - Initial contribution
*/
@NonNullByDefault
public class OwDiscoveryService extends AbstractDiscoveryService {
public class OwDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService {
private final Logger logger = LoggerFactory.getLogger(OwDiscoveryService.class);

private final OwserverBridgeHandler owBridgeHandler;
private final ThingUID bridgeUID;
private @Nullable OwserverBridgeHandler bridgeHandler;

Map<SensorId, OwDiscoveryItem> owDiscoveryItems = new HashMap<>();
Set<SensorId> associatedSensors = new HashSet<>();

public OwDiscoveryService(OwserverBridgeHandler owBridgeHandler) {
public OwDiscoveryService() {
super(SUPPORTED_THING_TYPES, 60, false);
this.owBridgeHandler = owBridgeHandler;
this.bridgeUID = owBridgeHandler.getThing().getUID();
logger.debug("registering discovery service for {}", owBridgeHandler);
logger.debug("registering discovery service for {}", bridgeHandler);
}

private void scanDirectory(String baseDirectory) {
private void scanDirectory(OwserverBridgeHandler bridgeHandler, String baseDirectory) {
ThingUID bridgeUID = bridgeHandler.getThing().getUID();

List<SensorId> directoryList;

logger.trace("scanning {} on bridge {}", baseDirectory, bridgeUID);
try {
directoryList = owBridgeHandler.getDirectory(baseDirectory);
directoryList = bridgeHandler.getDirectory(baseDirectory);
} catch (OwException e) {
logger.info("empty directory '{}' for {}", baseDirectory, bridgeUID);
return;
Expand All @@ -71,13 +73,13 @@ private void scanDirectory(String baseDirectory) {
// find all valid sensors
for (SensorId directoryEntry : directoryList) {
try {
OwDiscoveryItem owDiscoveryItem = new OwDiscoveryItem(owBridgeHandler, directoryEntry);
OwDiscoveryItem owDiscoveryItem = new OwDiscoveryItem(bridgeHandler, directoryEntry);
if (owDiscoveryItem.getSensorType() == OwSensorType.DS2409) {
// scan hub sub-directories
logger.trace("found hub {}, scanning sub-directories", directoryEntry);

scanDirectory(owDiscoveryItem.getSensorId().getFullPath() + "/main/");
scanDirectory(owDiscoveryItem.getSensorId().getFullPath() + "/aux/");
scanDirectory(bridgeHandler, owDiscoveryItem.getSensorId().getFullPath() + "/main/");
scanDirectory(bridgeHandler, owDiscoveryItem.getSensorId().getFullPath() + "/aux/");
} else {
// add found sensor to list
logger.trace("found sensor {} (type: {})", directoryEntry, owDiscoveryItem.getSensorType());
Expand All @@ -94,7 +96,15 @@ private void scanDirectory(String baseDirectory) {

@Override
public void startScan() {
scanDirectory("/");
OwserverBridgeHandler bridgeHandler = this.bridgeHandler;
if (bridgeHandler == null) {
logger.warn("bridgeHandler not found");
return;
}

ThingUID bridgeUID = bridgeHandler.getThing().getUID();

scanDirectory(bridgeHandler, "/");

// remove duplicates
owDiscoveryItems.entrySet().removeIf(s -> associatedSensors.contains(s.getKey()));
Expand Down Expand Up @@ -131,6 +141,18 @@ protected synchronized void stopScan() {
super.stopScan();
}

@Override
public void setThingHandler(ThingHandler thingHandler) {
if (thingHandler instanceof OwserverBridgeHandler) {
this.bridgeHandler = (OwserverBridgeHandler) thingHandler;
}
}

@Override
public @Nullable ThingHandler getThingHandler() {
return bridgeHandler;
}

@Override
public void deactivate() {
removeOlderResults(new Date().getTime());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,9 +215,7 @@ protected void configureThingChannels() {
.forEach(channelId -> removeChannelIfExisting(thingBuilder, channelId));

// add or update wanted channels
wantedChannel.stream().forEach(channelConfig -> {
addChannelIfMissingAndEnable(thingBuilder, channelConfig);
});
wantedChannel.forEach(channelConfig -> addChannelIfMissingAndEnable(thingBuilder, channelConfig));

updateThing(thingBuilder.build());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,12 @@
import static org.smarthomej.binding.onewire.internal.OwBindingConstants.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
Expand All @@ -37,6 +35,7 @@
import org.openhab.core.thing.ThingStatusDetail;
import org.openhab.core.thing.ThingStatusInfo;
import org.openhab.core.thing.binding.BaseThingHandler;
import org.openhab.core.thing.binding.ThingHandlerCallback;
import org.openhab.core.thing.binding.builder.ChannelBuilder;
import org.openhab.core.thing.binding.builder.ThingBuilder;
import org.openhab.core.types.Command;
Expand Down Expand Up @@ -65,8 +64,7 @@ public abstract class OwBaseThingHandler extends BaseThingHandler {
protected static final int PROPERTY_UPDATE_INTERVAL = 5000; // in ms
protected static final int PROPERTY_UPDATE_MAX_RETRY = 5;

private static final Set<String> REQUIRED_PROPERTIES = Collections
.unmodifiableSet(Stream.of(PROPERTY_MODELID, PROPERTY_VENDOR).collect(Collectors.toSet()));
private static final Set<String> REQUIRED_PROPERTIES = Set.of(PROPERTY_MODELID, PROPERTY_VENDOR);

protected List<String> requiredProperties = new ArrayList<>(REQUIRED_PROPERTIES);
protected Set<OwSensorType> supportedSensorTypes;
Expand Down Expand Up @@ -366,10 +364,9 @@ protected void removeChannelIfExisting(ThingBuilder thingBuilder, String channel
*
* @param thingBuilder ThingBuilder of the edited thing
* @param channelConfig a OwChannelConfig for the new channel
* @return the newly created channel
*/
protected Channel addChannelIfMissingAndEnable(ThingBuilder thingBuilder, OwChannelConfig channelConfig) {
return addChannelIfMissingAndEnable(thingBuilder, channelConfig, null, 0);
protected void addChannelIfMissingAndEnable(ThingBuilder thingBuilder, OwChannelConfig channelConfig) {
addChannelIfMissingAndEnable(thingBuilder, channelConfig, null, 0);
}

/**
Expand All @@ -378,11 +375,10 @@ protected Channel addChannelIfMissingAndEnable(ThingBuilder thingBuilder, OwChan
* @param thingBuilder ThingBuilder of the edited thing
* @param channelConfig a OwChannelConfig for the new channel
* @param configuration the new Configuration for this channel
* @return the newly created channel
*/
protected Channel addChannelIfMissingAndEnable(ThingBuilder thingBuilder, OwChannelConfig channelConfig,
protected void addChannelIfMissingAndEnable(ThingBuilder thingBuilder, OwChannelConfig channelConfig,
Configuration configuration) {
return addChannelIfMissingAndEnable(thingBuilder, channelConfig, configuration, 0);
addChannelIfMissingAndEnable(thingBuilder, channelConfig, configuration, 0);
}

/**
Expand All @@ -391,11 +387,10 @@ protected Channel addChannelIfMissingAndEnable(ThingBuilder thingBuilder, OwChan
* @param thingBuilder ThingBuilder of the edited thing
* @param channelConfig a OwChannelConfig for the new channel
* @param sensorNo number of sensor that provides this channel
* @return the newly created channel
*/
protected Channel addChannelIfMissingAndEnable(ThingBuilder thingBuilder, OwChannelConfig channelConfig,
protected void addChannelIfMissingAndEnable(ThingBuilder thingBuilder, OwChannelConfig channelConfig,
int sensorNo) {
return addChannelIfMissingAndEnable(thingBuilder, channelConfig, null, sensorNo);
addChannelIfMissingAndEnable(thingBuilder, channelConfig, null, sensorNo);
}

/**
Expand All @@ -405,9 +400,8 @@ protected Channel addChannelIfMissingAndEnable(ThingBuilder thingBuilder, OwChan
* @param channelConfig a OwChannelConfig for the new channel
* @param configuration the new Configuration for this channel
* @param sensorNo number of sensor that provides this channel
* @return the newly created channel
*/
protected Channel addChannelIfMissingAndEnable(ThingBuilder thingBuilder, OwChannelConfig channelConfig,
protected void addChannelIfMissingAndEnable(ThingBuilder thingBuilder, OwChannelConfig channelConfig,
@Nullable Configuration configuration, int sensorNo) {
Channel channel = thing.getChannel(channelConfig.channelId);
Configuration config = configuration;
Expand All @@ -424,23 +418,28 @@ protected Channel addChannelIfMissingAndEnable(ThingBuilder thingBuilder, OwChan

// create channel if missing
if (channel == null) {
ChannelBuilder channelBuilder = ChannelBuilder
.create(new ChannelUID(thing.getUID(), channelConfig.channelId),
ACCEPTED_ITEM_TYPES_MAP.get(channelConfig.channelId))
.withType(channelConfig.channelTypeUID);
ChannelUID channelUID = new ChannelUID(thing.getUID(), channelConfig.channelId);

ThingHandlerCallback callback = getCallback();
if (callback == null) {
logger.warn("Could not get callback, adding '{}' failed.", channelUID);
return;
}

ChannelBuilder channelBuilder = callback.createChannelBuilder(channelUID, channelConfig.channelTypeUID);

if (label != null) {
channelBuilder.withLabel(label);
}
if (config != null) {
channelBuilder.withConfiguration(config);
}

channel = channelBuilder.build();
thingBuilder.withChannel(channel);
}

// enable channel in sensor
sensors.get(sensorNo).enableChannel(channelConfig.channelId);

return channel;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
Expand All @@ -40,6 +41,7 @@
import org.openhab.core.thing.ThingStatusDetail;
import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.binding.BaseBridgeHandler;
import org.openhab.core.thing.binding.ThingHandlerService;
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
import org.slf4j.Logger;
Expand All @@ -48,6 +50,7 @@
import org.smarthomej.binding.onewire.internal.OwPageBuffer;
import org.smarthomej.binding.onewire.internal.SensorId;
import org.smarthomej.binding.onewire.internal.device.OwSensorType;
import org.smarthomej.binding.onewire.internal.discovery.OwDiscoveryService;
import org.smarthomej.binding.onewire.internal.owserver.OwfsDirectChannelConfig;
import org.smarthomej.binding.onewire.internal.owserver.OwserverConnection;
import org.smarthomej.binding.onewire.internal.owserver.OwserverConnectionState;
Expand Down Expand Up @@ -428,4 +431,9 @@ public void refreshBridgeChannels(long now) {
}
}
}

@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
return Set.of(OwDiscoveryService.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,13 @@
<item-type>Number:Dimensionless</item-type>
<label>Humidity</label>
<description>relative humidity (0-100%)</description>
<state readOnly="true" pattern="%d %%"/>
<state readOnly="true" pattern="%.0f %unit%"/>
</channel-type>
<channel-type id="humidityconf">
<item-type>Number:Dimensionless</item-type>
<label>Humidity</label>
<description>relative humidity (0-100%)</description>
<state readOnly="true" pattern="%d %%"/>
<state readOnly="true" pattern="%.0f %unit%"/>
<config-description>
<parameter name="humiditytype" type="text">
<label>Humidity Sensor-Type</label>
Expand Down
Loading