/bundles/org.openhab.binding.omnikinverter/ @hansbogert
/bundles/org.openhab.binding.omnilink/ @ecdye
/bundles/org.openhab.binding.onebusaway/ @sdwilsh
-/bundles/org.openhab.binding.onewire/ @openhab/add-ons-maintainers
+/bundles/org.openhab.binding.onewire/ @J-N-K
/bundles/org.openhab.binding.onewiregpio/ @aogorek
/bundles/org.openhab.binding.onkyo/ @pail23 @paulianttila
/bundles/org.openhab.binding.opengarage/ @psmedley
SensorId associatedSensorId = new SensorId(sensorId.getPath() + matcher.group(2));
switch (matcher.group(2).substring(0, 2)) {
- case "26":
+ case "26" -> {
DS2438Configuration associatedDs2438Config = new DS2438Configuration(bridgeHandler,
associatedSensorId);
associatedSensors.put(associatedSensorId, associatedDs2438Config.getSensorSubType());
associatedSensors.putAll(associatedDs2438Config.getAssociatedSensors());
- break;
- case "28":
- associatedSensors.put(associatedSensorId, OwSensorType.DS18B20);
- break;
- case "3A":
- associatedSensors.put(associatedSensorId, OwSensorType.DS2413);
- break;
- default:
+ }
+ case "28" -> associatedSensors.put(associatedSensorId, OwSensorType.DS18B20);
+ case "3A" -> associatedSensors.put(associatedSensorId, OwSensorType.DS2413);
+ default -> {
+ }
}
}
}
* @return a list of OwDiscoveryItems
*/
public List<SensorId> getAssociatedSensorIds(OwSensorType sensorType) {
- return associatedSensors.entrySet().stream().filter(s -> s.getValue() == sensorType).map(s -> s.getKey())
+ return associatedSensors.entrySet().stream().filter(s -> s.getValue() == sensorType).map(Map.Entry::getKey)
.collect(Collectors.toList());
}
List<OwSensorType> associatedSensorTypes) {
OwSensorType multisensorType = OwSensorType.UNKNOWN;
switch (associatedSensorTypes.size()) {
- case 0:
- multisensorType = mainsensorType;
- break;
- case 1:
+ case 0 -> multisensorType = mainsensorType;
+ case 1 -> {
if (mainsensorType == OwSensorType.MS_TH_S && associatedSensorTypes.contains(OwSensorType.DS18B20)) {
multisensorType = OwSensorType.BMS_S;
} else if (mainsensorType == OwSensorType.MS_TH
&& associatedSensorTypes.contains(OwSensorType.DS18B20)) {
multisensorType = OwSensorType.BMS;
}
- break;
- case 3:
+ }
+ case 3 -> {
if (mainsensorType == OwSensorType.MS_TH_S && associatedSensorTypes.contains(OwSensorType.MS_TV)
&& associatedSensorTypes.contains(OwSensorType.DS18B20)
&& associatedSensorTypes.contains(OwSensorType.DS2413)) {
// two DS2438 (first TH, second TV), DS18B20, DS2413
multisensorType = OwSensorType.AMS;
}
- break;
- default:
+ }
+ default -> {
+ }
}
return multisensorType;
import static org.openhab.binding.onewire.internal.OwBindingConstants.CHANNEL_DIGITAL;
-import java.util.Arrays;
-
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.onewire.internal.owserver.OwserverDeviceParameter;
import org.openhab.core.library.types.DecimalType;
@Override
public String toString() {
- return String.format("path=%s, mode=%s, logic=%s", Arrays.asList(getParameter()), ioMode, ioLogic);
+ return String.format("path=%s, mode=%s, logic=%s", getParameter(), ioMode, ioLogic);
}
}
import org.openhab.core.thing.type.ChannelTypeUID;
/**
- * The {@link OneWireBinding} class defines common constants, which are
+ * The {@link OwBindingConstants} class defines common constants, which are
* used across the whole binding.
*
* @author Jan N. Klug - Initial contribution
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"))
.collect(Collectors.toConcurrentMap(e -> OwSensorType.valueOf(e.getKey().split("\\.")[0]),
e -> new ThingTypeUID(BINDING_ID, e.getValue())));
SENSOR_TYPE_CHANNEL_MAP = properties.entrySet().stream().filter(e -> e.getKey().endsWith(".channels"))
- .collect(Collectors.toConcurrentMap(e -> OwSensorType.valueOf(e.getKey().split("\\.")[0]),
- e -> !e.getValue().isEmpty() ? Stream.of(e.getValue().split(","))
- .map(c -> OwChannelConfig.fromString(c)).collect(Collectors.toSet())
- : new HashSet<>()));
+ .collect(
+ Collectors.toConcurrentMap(e -> OwSensorType.valueOf(e.getKey().split("\\.")[0]),
+ e -> !e.getValue().isEmpty() ? Stream.of(e.getValue().split(","))
+ .map(OwChannelConfig::fromString).collect(Collectors.toSet())
+ : new HashSet<>()));
THING_LABEL_MAP = properties.entrySet().stream().filter(e -> e.getKey().endsWith(".label")).collect(
Collectors.toConcurrentMap(e -> OwSensorType.valueOf(e.getKey().split("\\.")[0]), e -> e.getValue()));
}
import static org.openhab.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.binding.onewire.internal.discovery.OwDiscoveryService;
import org.openhab.binding.onewire.internal.handler.AdvancedMultisensorThingHandler;
import org.openhab.binding.onewire.internal.handler.BAE091xSensorThingHandler;
import org.openhab.binding.onewire.internal.handler.BasicMultisensorThingHandler;
import org.openhab.binding.onewire.internal.handler.BasicThingHandler;
import org.openhab.binding.onewire.internal.handler.EDSSensorThingHandler;
import org.openhab.binding.onewire.internal.handler.OwserverBridgeHandler;
-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;
/**
* The {@link OwHandlerFactory} is responsible for creating things and thing
@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 dynamicStateDescriptionProvider) {
+ this.dynamicStateDescriptionProvider = dynamicStateDescriptionProvider;
+ }
@Override
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)) {
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;
- }
}
package org.openhab.binding.onewire.internal;
import java.io.IOException;
-import java.net.URL;
+import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
if (temperatureDegC == null) {
throw new IllegalArgumentException("could not change unit");
}
- Double theta = temperatureDegC.doubleValue();
+ double theta = temperatureDegC.doubleValue();
// saturation vapor pressure in kg/(m s^2)
- Double saturationVaporPressure = 611.2 * Math.exp(17.62 * theta / (243.12 + theta));
+ double saturationVaporPressure = 611.2 * Math.exp(17.62 * theta / (243.12 + theta));
// absolute humidity in kg/m^3
Double aH = relativeHumidity.doubleValue() / 100 * saturationVaporPressure / (461.52 * (273.15 + theta));
State absoluteHumidity = new QuantityType<>(aH, Units.KILOGRAM_PER_CUBICMETRE).toUnit("g/m³");
if (temperatureDegC == null) {
throw new IllegalArgumentException("could not change unit");
}
- Double theta = temperatureDegC.doubleValue();
- Double rH = relativeHumidity.doubleValue() / 100;
+ double theta = temperatureDegC.doubleValue();
+ double rH = relativeHumidity.doubleValue() / 100;
// dewpoint in °C
Double dP = 243.12 * (((17.62 * theta) / (243.12 + theta) + Math.log(rH))
/ (((17.62 * 243.12) / (243.12 + theta) - Math.log(rH))));
- State dewPoint = new QuantityType<>(dP, SIUnits.CELSIUS);
- return dewPoint;
+ return new QuantityType<>(dP, SIUnits.CELSIUS);
}
public static Map<String, String> readPropertiesFile(String filename) {
- URL resource = Thread.currentThread().getContextClassLoader().getResource(filename);
+ ClassLoader classLoader = OwBindingConstants.class.getClassLoader();
+ if (classLoader == null) {
+ LOGGER.warn("Could not get classloader, binding will fail.");
+ return Map.of();
+ }
Properties properties = new Properties();
- try {
- properties.load(resource.openStream());
+
+ try (InputStream inputStream = classLoader.getResourceAsStream(filename)) {
+ if (inputStream == null) {
+ LOGGER.warn("Could not get input stream for resource file '{}', binding will fail.", filename);
+ return Map.of();
+ }
+ properties.load(inputStream);
return properties.entrySet().stream()
.collect(Collectors.toMap(e -> (String) e.getKey(), e -> (String) e.getValue()));
} catch (IOException e) {
- LOGGER.warn("Could not read resource file {}, binding will probably fail: {}", filename, e.getMessage());
+ LOGGER.warn("Could not read resource file {}, binding will fail: {}", filename, e.getMessage());
return new HashMap<>();
}
}
import org.slf4j.LoggerFactory;
/**
- * The {@link AbstractOwClass} class defines an abstract onewire device
+ * The {@link AbstractOwDevice} class defines an abstract onewire device
*
* @author Jan N. Klug - Initial contribution
*/
/**
* refresh this sensor
*
- * @param bridgeHandler for sending requests
+ * @param owBridgeHandler for sending requests
* @param forcedRefresh post update even if state did not change
* @throws OwException in case of communication error
*/
* @param channelID the channels channelID
*/
public void enableChannel(String channelID) {
- if (!enabledChannels.contains(channelID)) {
- enabledChannels.add(channelID);
- }
+ enabledChannels.add(channelID);
}
/**
* @param channelID the channels channelID
*/
public void disableChannel(String channelID) {
- if (enabledChannels.contains(channelID)) {
- enabledChannels.remove(channelID);
- }
+ enabledChannels.remove(channelID);
}
/**
/**
* check sensor presence and update thing state
*
- * @param owServerConnection
+ * @param bridgeHandler
* @return sensors presence state
*/
-
public Boolean checkPresence(OwserverBridgeHandler bridgeHandler) {
try {
State present = bridgeHandler.checkPresence(sensorId);
return false;
}
}
-
- /**
- * get this sensors type
- *
- * @param bridgeHandler bridge handler to request from if type formerly unknown
- * @return this sensors type
- * @throws OwException
- */
- public OwSensorType getSensorType(OwserverBridgeHandler bridgeHandler) throws OwException {
- if (sensorType == OwSensorType.UNKNOWN) {
- sensorType = bridgeHandler.getType(sensorId);
- }
- return sensorType;
- }
}
private final OwserverDeviceParameter duty3Parameter = new OwserverDeviceParameter("/duty3");
private final OwserverDeviceParameter duty4Parameter = new OwserverDeviceParameter("/duty4");
- private BitSet outcRegister = new BitSet(8);
- private BitSet piocRegister = new BitSet(8);
- private BitSet adccRegister = new BitSet(8);
- private BitSet tpm1cRegister = new BitSet(8);
- private BitSet tpm2cRegister = new BitSet(8);
+ private final BitSet outcRegister = new BitSet(8);
+ private final BitSet piocRegister = new BitSet(8);
+ private final BitSet adccRegister = new BitSet(8);
+ private final BitSet tpm1cRegister = new BitSet(8);
+ private final BitSet tpm2cRegister = new BitSet(8);
private double resolution1 = 8; // in µs
private double resolution2 = 8; // in µs
BAE091xPIOConfiguration channelConfig = channel.getConfiguration().as(BAE091xPIOConfiguration.class);
piocRegister.set(PIOC_DD, channelConfig.mode.equals("output"));
switch (channelConfig.pulldevice) {
- case "pullup":
+ case "pullup" -> {
piocRegister.set(PIOC_PE);
piocRegister.clear(PIOC_PD);
- break;
- case "pulldown":
+ }
+ case "pulldown" -> {
piocRegister.set(PIOC_PE);
piocRegister.set(PIOC_PD);
- break;
- default:
+ }
+ default -> {
+ }
}
} else {
throw new OwException("trying to configure pin 6 but channel is missing");
try {
BitSet value = new BitSet(8);
switch (channelId) {
- case CHANNEL_DIGITAL2:
+ case CHANNEL_DIGITAL2 -> {
// output
if (!outcRegister.get(OUTC_OUTEN)) {
return false;
}
- value.set(0, ((OnOffType) command).equals(OnOffType.ON));
+ value.set(0, command.equals(OnOffType.ON));
bridgeHandler.writeBitSet(sensorId, pin2OutParameter, value);
- break;
- case CHANNEL_DIGITAL6:
+ }
+ case CHANNEL_DIGITAL6 -> {
// not input, pio
if (!piocRegister.get(PIOC_DD) || !piocRegister.get(PIOC_PIOEN)) {
return false;
}
- value.set(0, ((OnOffType) command).equals(OnOffType.ON));
+ value.set(0, command.equals(OnOffType.ON));
bridgeHandler.writeBitSet(sensorId, pin6PIOParameter, value);
- break;
- case CHANNEL_DIGITAL7:
+ }
+ case CHANNEL_DIGITAL7 -> {
// not pwm, not analog
if (!tpm2cRegister.get(TPMC_PWMDIS) || adccRegister.get(ADCC_ADCEN)) {
return false;
}
- tpm2cRegister.set(TPMC_POL, ((OnOffType) command).equals(OnOffType.ON));
+ tpm2cRegister.set(TPMC_POL, command.equals(OnOffType.ON));
bridgeHandler.writeBitSet(sensorId, tpm2cParameter, tpm2cRegister);
- break;
- case CHANNEL_DIGITAL8:
+ }
+ case CHANNEL_DIGITAL8 -> {
// not input, not pwm
if (tpm1cRegister.get(TPMC_INENA) || !tpm1cRegister.get(TPMC_PWMDIS)) {
return false;
}
- tpm1cRegister.set(TPMC_POL, ((OnOffType) command).equals(OnOffType.ON));
+ tpm1cRegister.set(TPMC_POL, command.equals(OnOffType.ON));
bridgeHandler.writeBitSet(sensorId, tpm1cParameter, tpm1cRegister);
- break;
- case CHANNEL_PWM_FREQ1:
+ }
+ case CHANNEL_PWM_FREQ1 -> {
if (command instanceof QuantityType<?>) {
bridgeHandler.writeDecimalType(sensorId, period1Parameter,
convertFrequencyToPeriod(command, resolution1));
}
- break;
- case CHANNEL_PWM_FREQ2:
+ }
+ case CHANNEL_PWM_FREQ2 -> {
if (command instanceof QuantityType<?>) {
bridgeHandler.writeDecimalType(sensorId, period2Parameter,
convertFrequencyToPeriod(command, resolution2));
}
- break;
- case CHANNEL_PWM_DUTY1:
+ }
+ case CHANNEL_PWM_DUTY1 -> {
if (command instanceof QuantityType<?>) {
bridgeHandler.writeDecimalType(sensorId, duty1Parameter, calculateDutyCycle(command,
(DecimalType) bridgeHandler.readDecimalType(sensorId, period1Parameter)));
}
- break;
- case CHANNEL_PWM_DUTY2:
+ }
+ case CHANNEL_PWM_DUTY2 -> {
if (command instanceof QuantityType<?>) {
bridgeHandler.writeDecimalType(sensorId, duty2Parameter, calculateDutyCycle(command,
(DecimalType) bridgeHandler.readDecimalType(sensorId, period2Parameter)));
}
- break;
- case CHANNEL_PWM_DUTY3:
+ }
+ case CHANNEL_PWM_DUTY3 -> {
if (command instanceof QuantityType<?>) {
bridgeHandler.writeDecimalType(sensorId, duty3Parameter, calculateDutyCycle(command,
(DecimalType) bridgeHandler.readDecimalType(sensorId, period1Parameter)));
}
- break;
- case CHANNEL_PWM_DUTY4:
+ }
+ case CHANNEL_PWM_DUTY4 -> {
if (command instanceof QuantityType<?>) {
bridgeHandler.writeDecimalType(sensorId, duty4Parameter, calculateDutyCycle(command,
(DecimalType) bridgeHandler.readDecimalType(sensorId, period2Parameter)));
}
- break;
- default:
- throw new OwException("unknown or invalid channel");
+ }
+ default -> throw new OwException("unknown or invalid channel");
}
return true;
- } catch (
-
- OwException e) {
+ } catch (OwException e) {
logger.info("could not write {} to {}: {}", command, channelId, e.getMessage());
return false;
}
OwserverDeviceParameter deviceTypeParameter = new OwserverDeviceParameter("/device_type");
String subDeviceType = bridgeHandler.readString(sensorId, deviceTypeParameter);
- switch (subDeviceType) {
- case "2":
- return OwSensorType.BAE0910;
- case "3":
- return OwSensorType.BAE0911;
- default:
- return OwSensorType.UNKNOWN;
- }
+ return switch (subDeviceType) {
+ case "2" -> OwSensorType.BAE0910;
+ case "3" -> OwSensorType.BAE0911;
+ default -> OwSensorType.UNKNOWN;
+ };
}
private DecimalType convertFrequencyToPeriod(Command command, double resolution) throws OwException {
private OwSensorType sensorType = OwSensorType.UNKNOWN;
private String vendor = "Dallas/Maxim";
- private OwPageBuffer pages = new OwPageBuffer();
-
- private ThingTypeUID thingTypeUID = new ThingTypeUID(BINDING_ID, "");
-
private final Map<SensorId, OwSensorType> associatedSensors = new HashMap<>();
public OwDiscoveryItem(OwserverBridgeHandler bridgeHandler, SensorId sensorId) throws OwException {
this.sensorId = sensorId;
sensorType = bridgeHandler.getType(sensorId);
switch (sensorType) {
- case DS2438:
- pages = bridgeHandler.readPages(sensorId);
+ case DS2438 -> {
+ bridgeHandler.readPages(sensorId);
DS2438Configuration config = new DS2438Configuration(bridgeHandler, sensorId);
associatedSensors.putAll(config.getAssociatedSensors());
logger.trace("found associated sensors: {}", associatedSensors);
vendor = config.getVendor();
sensorType = config.getSensorSubType();
- break;
- case EDS:
+ }
+ case EDS -> {
vendor = "Embedded Data Systems";
- pages = bridgeHandler.readPages(sensorId);
-
+ OwPageBuffer pages = bridgeHandler.readPages(sensorId);
try { // determine subsensorType
sensorType = OwSensorType.valueOf(new String(pages.getPage(0), 0, 7, StandardCharsets.US_ASCII));
} catch (IllegalArgumentException e) {
sensorType = OwSensorType.UNKNOWN;
}
- break;
- default:
+ }
+ default -> {
+ }
}
}
logger.debug("checkSensorType: {} with {}", this, associatedSensors);
switch (sensorType) {
- case MS_TH:
- case MS_TH_S:
- sensorType = DS2438Configuration.getMultisensorType(sensorType,
- new ArrayList<>(associatedSensors.values()));
- break;
- default:
+ case MS_TH, MS_TH_S -> sensorType = DS2438Configuration.getMultisensorType(sensorType,
+ new ArrayList<>(associatedSensors.values()));
+ default -> {
+ }
}
}
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.onewire.internal.OwException;
import org.openhab.binding.onewire.internal.SensorId;
import org.openhab.binding.onewire.internal.device.OwSensorType;
import org.openhab.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;
* @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;
// 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());
@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()));
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());
import static org.openhab.binding.onewire.internal.OwBindingConstants.*;
-import java.util.Arrays;
import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
*/
@NonNullByDefault
public class AdvancedMultisensorThingHandler extends OwBaseThingHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = new HashSet<>(
- Arrays.asList(THING_TYPE_AMS, THING_TYPE_BMS));
- public static final Set<OwSensorType> SUPPORTED_SENSOR_TYPES = Collections
- .unmodifiableSet(Stream.of(OwSensorType.AMS, OwSensorType.AMS_S, OwSensorType.BMS, OwSensorType.BMS_S)
- .collect(Collectors.toSet()));
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_AMS, THING_TYPE_BMS);
+ public static final Set<OwSensorType> SUPPORTED_SENSOR_TYPES = Set.of(OwSensorType.AMS, OwSensorType.AMS_S,
+ OwSensorType.BMS, OwSensorType.BMS_S);
private static final String PROPERTY_DS18B20 = "ds18b20";
private static final String PROPERTY_DS2413 = "ds2413";
return;
}
- hwRevision = Integer.valueOf(properties.getOrDefault(PROPERTY_HW_REVISION, "0"));
+ hwRevision = Integer.parseInt(properties.getOrDefault(PROPERTY_HW_REVISION, "0"));
try {
sensors.add(new DS2438(sensorId, this));
} catch (IllegalArgumentException e) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "properties invalid");
}
- scheduler.execute(() -> {
- configureThingChannels();
- });
+ scheduler.execute(this::configureThingChannels);
}
@Override
sensors.get(i).refresh(bridgeHandler, forcedRefresh);
}
} else {
- for (int i = 0; i < sensors.size(); i++) {
- sensors.get(i).refresh(bridgeHandler, forcedRefresh);
+ for (AbstractOwDevice sensor : sensors) {
+ sensor.refresh(bridgeHandler, forcedRefresh);
}
}
}
// delete unwanted channels
Set<String> existingChannelIds = thing.getChannels().stream().map(channel -> channel.getUID().getId())
.collect(Collectors.toSet());
- Set<String> wantedChannelIds = SENSOR_TYPE_CHANNEL_MAP.get(sensorType).stream()
+ Set<String> wantedChannelIds = SENSOR_TYPE_CHANNEL_MAP.getOrDefault(sensorType, Set.of()).stream()
.map(channelConfig -> channelConfig.channelId).collect(Collectors.toSet());
wantedChannelIds.add(CHANNEL_TEMPERATURE);
wantedChannelIds.add(CHANNEL_HUMIDITY);
.forEach(channelId -> removeChannelIfExisting(thingBuilder, channelId));
// add or update wanted channels
- SENSOR_TYPE_CHANNEL_MAP.get(sensorType).stream().forEach(channelConfig -> {
- addChannelIfMissingAndEnable(thingBuilder, channelConfig);
- });
+ SENSOR_TYPE_CHANNEL_MAP.getOrDefault(sensorType, Set.of()).stream()
+ .forEach(channelConfig -> addChannelIfMissingAndEnable(thingBuilder, channelConfig));
// temperature channel
if (configuration.containsKey(CONFIG_TEMPERATURESENSOR)
// humidity channel
addChannelIfMissingAndEnable(thingBuilder, new OwChannelConfig(CHANNEL_HUMIDITY, CHANNEL_TYPE_UID_HUMIDITY),
- new Configuration(new HashMap<String, Object>() {
- private static final long serialVersionUID = 1L;
- {
- put(CONFIG_HUMIDITY, "/HIH4000/humidity");
- }
- }));
+ new Configuration(Map.of(CONFIG_HUMIDITY, "/HIH4000/humidity")));
// configure light channel
if (sensorType == OwSensorType.AMS_S || sensorType == OwSensorType.BMS_S) {
properties.put(PROPERTY_HW_REVISION, ds2438configuration.getHardwareRevision());
switch (sensorType) {
- case BMS:
- case BMS_S:
- properties.put(PROPERTY_DS18B20,
- ds2438configuration.getAssociatedSensorIds(OwSensorType.DS18B20).get(0).getFullPath());
- break;
- case AMS:
- case AMS_S:
+ case BMS, BMS_S -> properties.put(PROPERTY_DS18B20,
+ ds2438configuration.getAssociatedSensorIds(OwSensorType.DS18B20).get(0).getFullPath());
+ case AMS, AMS_S -> {
properties.put(PROPERTY_DS18B20,
ds2438configuration.getAssociatedSensorIds(OwSensorType.DS18B20).get(0).getFullPath());
properties.put(PROPERTY_DS2413,
ds2438configuration.getAssociatedSensorIds(OwSensorType.DS2413).get(0).getFullPath());
properties.put(PROPERTY_DS2438,
ds2438configuration.getAssociatedSensorIds(OwSensorType.MS_TV).get(0).getFullPath());
-
- break;
- default:
- throw new OwException("sensorType " + sensorType.toString() + " not supported by this thing handler");
+ }
+ default -> throw new OwException(
+ "sensorType " + sensorType.toString() + " not supported by this thing handler");
}
updateProperties(properties);
* @return
*/
private static Set<String> getRequiredProperties(ThingTypeUID thingType) {
- if (THING_TYPE_AMS.equals(thingType)) {
- return REQUIRED_PROPERTIES_AMS;
- } else {
- return REQUIRED_PROPERTIES_BMS;
- }
+ return THING_TYPE_AMS.equals(thingType) ? REQUIRED_PROPERTIES_AMS : REQUIRED_PROPERTIES_BMS;
}
}
import static org.openhab.binding.onewire.internal.OwBindingConstants.*;
-import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
*/
@NonNullByDefault
public class BAE091xSensorThingHandler extends OwBaseThingHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_BAE091X);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BAE091X);
private final Logger logger = LoggerFactory.getLogger(BAE091xSensorThingHandler.class);
- public static final Set<OwSensorType> SUPPORTED_SENSOR_TYPES = Collections.singleton(OwSensorType.BAE0910);
+ public static final Set<OwSensorType> SUPPORTED_SENSOR_TYPES = Set.of(OwSensorType.BAE0910);
public BAE091xSensorThingHandler(Thing thing, OwDynamicStateDescriptionProvider dynamicStateDescriptionProvider) {
super(thing, dynamicStateDescriptionProvider, SUPPORTED_SENSOR_TYPES);
sensors.add(new BAE0910(sensorId, this));
- scheduler.execute(() -> {
- configureThingChannels();
- });
+ scheduler.execute(this::configureThingChannels);
}
@Override
BAE091xHandlerConfiguration configuration = getConfig().as(BAE091xHandlerConfiguration.class);
- Set<OwChannelConfig> wantedChannel = new HashSet<>();
- wantedChannel.addAll(SENSOR_TYPE_CHANNEL_MAP.getOrDefault(sensorType, Set.of()));
+ Set<OwChannelConfig> wantedChannel = new HashSet<>(SENSOR_TYPE_CHANNEL_MAP.getOrDefault(sensorType, Set.of()));
// Pin1:
switch (configuration.pin1) {
.forEach(channelId -> removeChannelIfExisting(thingBuilder, channelId));
// add or update wanted channels
- wantedChannel.stream().forEach(channelConfig -> {
+ wantedChannel.forEach(channelConfig -> {
addChannelIfMissingAndEnable(thingBuilder, channelConfig);
});
import static org.openhab.binding.onewire.internal.OwBindingConstants.*;
-import java.util.Collections;
import java.util.Map;
import java.util.Set;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.onewire.internal.DS2438Configuration;
@NonNullByDefault
public class BasicMultisensorThingHandler extends OwBaseThingHandler {
public Logger logger = LoggerFactory.getLogger(BasicMultisensorThingHandler.class);
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_MS_TX);
- public static final Set<OwSensorType> SUPPORTED_SENSOR_TYPES = Collections
- .unmodifiableSet(Stream.of(OwSensorType.MS_TH, OwSensorType.MS_TC, OwSensorType.MS_TL, OwSensorType.MS_TV,
- OwSensorType.DS1923, OwSensorType.DS2438).collect(Collectors.toSet()));
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_MS_TX);
+ public static final Set<OwSensorType> SUPPORTED_SENSOR_TYPES = Set.of(OwSensorType.MS_TH, OwSensorType.MS_TC,
+ OwSensorType.MS_TL, OwSensorType.MS_TV, OwSensorType.DS1923, OwSensorType.DS2438);
public BasicMultisensorThingHandler(Thing thing,
OwDynamicStateDescriptionProvider dynamicStateDescriptionProvider) {
sensors.add(new DS2438(sensorId, this));
}
- scheduler.execute(() -> {
- configureThingChannels();
- });
+ scheduler.execute(this::configureThingChannels);
}
@Override
protected void configureThingChannels() {
switch (sensorType) {
- case DS2438:
- ((DS2438) sensors.get(0)).setCurrentSensorType(CurrentSensorType.INTERNAL);
- break;
- case MS_TC:
- ((DS2438) sensors.get(0)).setCurrentSensorType(CurrentSensorType.IBUTTONLINK);
- break;
- case MS_TL:
- ((DS2438) sensors.get(0)).setLightSensorType(LightSensorType.IBUTTONLINK);
- break;
- default:
+ case DS2438 -> ((DS2438) sensors.get(0)).setCurrentSensorType(CurrentSensorType.INTERNAL);
+ case MS_TC -> ((DS2438) sensors.get(0)).setCurrentSensorType(CurrentSensorType.IBUTTONLINK);
+ case MS_TL -> ((DS2438) sensors.get(0)).setLightSensorType(LightSensorType.IBUTTONLINK);
+ default -> {
+ }
}
super.configureThingChannels();
import static org.openhab.binding.onewire.internal.OwBindingConstants.*;
-import java.util.Collections;
import java.util.Set;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.onewire.internal.OwDynamicStateDescriptionProvider;
*/
@NonNullByDefault
public class BasicThingHandler extends OwBaseThingHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_BASIC);
- public static final Set<OwSensorType> SUPPORTED_SENSOR_TYPES = Collections
- .unmodifiableSet(Stream.of(OwSensorType.DS1420, OwSensorType.DS18B20, OwSensorType.DS18S20,
- OwSensorType.DS1822, OwSensorType.DS2401, OwSensorType.DS2405, OwSensorType.DS2406,
- OwSensorType.DS2408, OwSensorType.DS2413, OwSensorType.DS2423).collect(Collectors.toSet()));
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BASIC);
+ public static final Set<OwSensorType> SUPPORTED_SENSOR_TYPES = Set.of(OwSensorType.DS1420, OwSensorType.DS18B20,
+ OwSensorType.DS18S20, OwSensorType.DS1822, OwSensorType.DS2401, OwSensorType.DS2405, OwSensorType.DS2406,
+ OwSensorType.DS2408, OwSensorType.DS2413, OwSensorType.DS2423);
private final Logger logger = LoggerFactory.getLogger(BasicThingHandler.class);
// add sensor
switch (sensorType) {
- case DS18B20:
- case DS18S20:
- case DS1822:
- sensors.add(new DS18x20(sensorId, this));
- break;
- case DS1420:
- case DS2401:
- sensors.add(new DS2401(sensorId, this));
- break;
- case DS2405:
- sensors.add(new DS2405(sensorId, this));
- break;
- case DS2406:
- case DS2413:
- sensors.add(new DS2406_DS2413(sensorId, this));
- break;
- case DS2408:
- sensors.add(new DS2408(sensorId, this));
- break;
- case DS2423:
- sensors.add(new DS2423(sensorId, this));
- break;
- default:
- throw new IllegalArgumentException(
- "unsupported sensorType " + sensorType.name() + ", this should have been checked before!");
+ case DS18B20, DS18S20, DS1822 -> sensors.add(new DS18x20(sensorId, this));
+ case DS1420, DS2401 -> sensors.add(new DS2401(sensorId, this));
+ case DS2405 -> sensors.add(new DS2405(sensorId, this));
+ case DS2406, DS2413 -> sensors.add(new DS2406_DS2413(sensorId, this));
+ case DS2408 -> sensors.add(new DS2408(sensorId, this));
+ case DS2423 -> sensors.add(new DS2423(sensorId, this));
+ default -> throw new IllegalArgumentException(
+ "unsupported sensorType " + sensorType.name() + ", this should have been checked before!");
}
- scheduler.execute(() -> {
- configureThingChannels();
- });
+ scheduler.execute(this::configureThingChannels);
}
@Override
import java.util.Collections;
import java.util.Map;
import java.util.Set;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.onewire.internal.OwDynamicStateDescriptionProvider;
*/
@NonNullByDefault
public class EDSSensorThingHandler extends OwBaseThingHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_EDS_ENV);
- public static final Set<OwSensorType> SUPPORTED_SENSOR_TYPES = Collections
- .unmodifiableSet(Stream.of(OwSensorType.EDS0064, OwSensorType.EDS0065, OwSensorType.EDS0066,
- OwSensorType.EDS0067, OwSensorType.EDS0068).collect(Collectors.toSet()));
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_EDS_ENV);
+ public static final Set<OwSensorType> SUPPORTED_SENSOR_TYPES = Set.of(OwSensorType.EDS0064, OwSensorType.EDS0065,
+ OwSensorType.EDS0066, OwSensorType.EDS0067, OwSensorType.EDS0068);
private static final Set<String> REQUIRED_PROPERTIES = Collections.singleton(PROPERTY_HW_REVISION);
public EDSSensorThingHandler(Thing thing, OwDynamicStateDescriptionProvider dynamicStateDescriptionProvider) {
// add sensors
sensors.add(new EDS006x(sensorId, sensorType, this));
- scheduler.execute(() -> {
- configureThingChannels();
- });
+ scheduler.execute(this::configureThingChannels);
}
@Override
OwSensorType sensorType = OwSensorType.UNKNOWN;
try {
sensorType = OwSensorType.valueOf(new String(pages.getPage(0), 0, 7, StandardCharsets.US_ASCII));
- } catch (IllegalArgumentException e) {
+ } catch (IllegalArgumentException ignored) {
}
if (!SUPPORTED_SENSOR_TYPES.contains(sensorType)) {
import static org.openhab.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;
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;
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;
return false;
}
- refreshInterval = configuration.refresh * 1000;
+ refreshInterval = configuration.refresh * 1000L;
// check if all required properties are present. update if not
for (String property : requiredProperties) {
// remove unwanted channels
Set<String> existingChannelIds = thing.getChannels().stream().map(channel -> channel.getUID().getId())
.collect(Collectors.toSet());
- Set<String> wantedChannelIds = SENSOR_TYPE_CHANNEL_MAP.get(sensorType).stream()
+ Set<String> wantedChannelIds = SENSOR_TYPE_CHANNEL_MAP.getOrDefault(sensorType, Set.of()).stream()
.map(channelConfig -> channelConfig.channelId).collect(Collectors.toSet());
existingChannelIds.stream().filter(channelId -> !wantedChannelIds.contains(channelId))
.forEach(channelId -> removeChannelIfExisting(thingBuilder, channelId));
// add or update wanted channels
- SENSOR_TYPE_CHANNEL_MAP.get(sensorType).stream().forEach(channelConfig -> {
+ SENSOR_TYPE_CHANNEL_MAP.getOrDefault(sensorType, Set.of()).stream().forEach(channelConfig -> {
addChannelIfMissingAndEnable(thingBuilder, channelConfig);
});
* called by the bridge handler
*
* @param bridgeHandler the bridge handler to be used
- * @return properties to be added to the properties map
- * @throws OwException
+ * @throws OwException in case an error occurs
*/
public void updateSensorProperties(OwserverBridgeHandler bridgeHandler) throws OwException {
Map<String, String> properties = editProperties();
*
* @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);
}
/**
* @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);
}
/**
* @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);
}
/**
* @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;
// 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;
}
}
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;
import org.openhab.binding.onewire.internal.OwPageBuffer;
import org.openhab.binding.onewire.internal.SensorId;
import org.openhab.binding.onewire.internal.device.OwSensorType;
+import org.openhab.binding.onewire.internal.discovery.OwDiscoveryService;
import org.openhab.binding.onewire.internal.owserver.OwfsDirectChannelConfig;
import org.openhab.binding.onewire.internal.owserver.OwserverConnection;
import org.openhab.binding.onewire.internal.owserver.OwserverConnectionState;
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;
*
* @param sensorId the sensor's full ID
* @return ON if present, OFF if missing
- * @throws OwException
+ * @throws OwException in case an error occurs
*/
public State checkPresence(SensorId sensorId) throws OwException {
synchronized (owserverConnection) {
*
* @param sensorId the sensor's full ID
* @return a String containing the sensor type
- * @throws OwException
+ * @throws OwException in case an error occurs
*/
public OwSensorType getType(SensorId sensorId) throws OwException {
OwSensorType sensorType = OwSensorType.UNKNOWN;
synchronized (owserverConnection) {
try {
sensorType = OwSensorType.valueOf(owserverConnection.readString(sensorId + "/type"));
- } catch (IllegalArgumentException e) {
+ } catch (IllegalArgumentException ignored) {
}
}
return sensorType;
*
* @param sensorId the sensor's full ID
* @return a OwPageBuffer object containing the requested information
- * @throws OwException
+ * @throws OwException in case an error occurs
*/
public OwPageBuffer readPages(SensorId sensorId) throws OwException {
synchronized (owserverConnection) {
* @param sensorId the sensor's full ID
* @param parameter device parameters needed for this request
* @return a DecimalType
- * @throws OwException
+ * @throws OwException in case an error occurs
*/
public State readDecimalType(SensorId sensorId, OwserverDeviceParameter parameter) throws OwException {
synchronized (owserverConnection) {
* @param sensorId the sensor's full ID
* @param parameter device parameters needed for this request
* @return a BitSet
- * @throws OwException
+ * @throws OwException in case an error occurs
*/
public BitSet readBitSet(SensorId sensorId, OwserverDeviceParameter parameter) throws OwException {
return BitSet.valueOf(new long[] { ((DecimalType) readDecimalType(sensorId, parameter)).longValue() });
* @param sensorId the sensor's full ID
* @param parameter device parameters needed for this request
* @return a list of DecimalType values
- * @throws OwException
+ * @throws OwException in case an error occurs
*/
public List<State> readDecimalTypeArray(SensorId sensorId, OwserverDeviceParameter parameter) throws OwException {
synchronized (owserverConnection) {
* @param sensorId the sensor's full ID
* @param parameter device parameters needed for this request
* @return a String
- * @throws OwException
+ * @throws OwException in case an error occurs
*/
public String readString(SensorId sensorId, OwserverDeviceParameter parameter) throws OwException {
synchronized (owserverConnection) {
*
* @param sensorId the sensor's full ID
* @param parameter device parameters needed for this request
- * @throws OwException
+ * @throws OwException in case an error occurs
*/
public void writeDecimalType(SensorId sensorId, OwserverDeviceParameter parameter, DecimalType value)
throws OwException {
*
* @param sensorId the sensor's full ID
* @param parameter device parameters needed for this request
- * @throws OwException
+ * @throws OwException in case an error occurs
*/
public void writeBitSet(SensorId sensorId, OwserverDeviceParameter parameter, BitSet value) throws OwException {
writeDecimalType(sensorId, parameter, new DecimalType(value.toLongArray()[0]));
}
}
}
+
+ @Override
+ public Collection<Class<? extends ThingHandlerService>> getServices() {
+ return Set.of(OwDiscoveryService.class);
+ }
}
returnValue = OnOffType.ON;
}
- } catch (OwException e) {
- returnValue = OnOffType.OFF;
+ } catch (OwException ignored) {
}
logger.trace("presence {} : {}", path, returnValue);
return returnValue;
*
* @param path full owfs path to sensor
* @return DecimalType if successful
- * @throws OwException
+ * @throws OwException in case an error occurs
*/
public State readDecimalType(String path) throws OwException {
State returnState = UnDefType.UNDEF;
*
* @param path full owfs path to sensor
* @return a List of DecimalType values if successful
- * @throws OwException
+ * @throws OwException in case an error occurs
*/
public List<State> readDecimalTypeArray(String path) throws OwException {
List<State> returnList = new ArrayList<>();
*
* @param path full owfs path to sensor
* @return requested String
- * @throws OwException
+ * @throws OwException in case an error occurs
*/
public String readString(String path) throws OwException {
OwserverPacket requestPacket = new OwserverPacket(OwserverMessageType.READ, path);
*
* @param path full owfs path to sensor
* @return page buffer
- * @throws OwException
+ * @throws OwException in case an error occurs
*/
public OwPageBuffer readPages(String path) throws OwException {
OwserverPacket requestPacket = new OwserverPacket(OwserverMessageType.READ, path + "/pages/page.ALL");
*
* @param path full owfs path to the sensor
* @param value the value to write
- * @throws OwException
+ * @throws OwException in case an error occurs
*/
public void writeDecimalType(String path, DecimalType value) throws OwException {
OwserverPacket requestPacket = new OwserverPacket(OwserverMessageType.WRITE, path);
*
* @param requestPacket the request to be send
* @return the raw owserver answer
- * @throws OwException
+ * @throws OwException in case an error occurs
*/
private OwserverPacket request(OwserverPacket requestPacket) throws OwException {
OwserverPacket returnPacket = new OwserverPacket(OwserverPacketType.RETURN);
* {@link OwException} is thrown.
*
* @param requestPacket data to write
- * @throws OwException
+ * @throws OwException in case an error occurs
*/
private void write(OwserverPacket requestPacket) throws OwException {
try {
*
* @param noTimeoutException retry in case of read time outs instead of exiting with an {@link OwException}.
* @return the read packet
- * @throws OwException
+ * @throws OwException in case an error occurs
*/
private OwserverPacket read(boolean noTimeoutException) throws OwException {
OwserverPacket returnPacket = new OwserverPacket(OwserverPacketType.RETURN);
throw e;
} catch (IOException e) {
// Read time out
- if (e.getMessage().equals("Read timed out") && noTimeoutException) {
+ if ("Read timed out".equals(e.getMessage()) && noTimeoutException) {
logger.trace("timeout - setting error code to -1");
// will lead to re-try reading in request method!!!
returnPacket.setPayload("timeout");
} else {
this.prefix = prefix;
}
+ if (this.prefix.startsWith("/")) {
+ this.prefix = this.prefix.substring(1);
+ }
if (path.startsWith("/")) {
this.path = path;
} else {
package org.openhab.binding.onewire.internal.owserver;
import java.io.DataInputStream;
-import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
*
* @param owInputStream input stream to read from
* @throws IOException
- * @throws OwExeption
+ * @throws OwException in case an error occurs
*/
public OwserverPacket(DataInputStream owInputStream, OwserverPacketType packetType)
- throws IOException, OwException, EOFException {
+ throws IOException, OwException {
this.packetType = packetType;
// header
/**
* set this packet's temperature scale
*
- * @param pressureScale
+ * @param temperatureScale
*/
public void setTemperatureScale(OwserverTemperatureScale temperatureScale) {
controlFlags = temperatureScale.setFlag(controlFlags);
* @param payload string representation of the payload to append
*/
public void appendPayload(String payload) {
- byte appendBytes[] = payload.getBytes();
+ byte[] appendBytes = payload.getBytes();
byte[] fullPayload = new byte[this.payload.length + appendBytes.length];
System.arraycopy(this.payload, 0, fullPayload, 0, this.payload.length);
* @return OwPageBuffer with this packet's payload
*/
public OwPageBuffer getPayload() {
- OwPageBuffer byteBuffer = new OwPageBuffer(payload);
- return byteBuffer;
+ return new OwPageBuffer(payload);
}
/**
channel-type.onewire.dewpoint.description = dewpoint (calculated from temperature and relative humidity)
channel-type.onewire.dio.label = Digital I/O
channel-type.onewire.humidity.label = Humidity
-channel-type.onewire.humidity.description = relative humidity (0-100%)
+channel-type.onewire.humidity.description = Relative humidity (0-100%)
channel-type.onewire.humidityconf.label = Humidity
-channel-type.onewire.humidityconf.description = relative humidity (0-100%)
+channel-type.onewire.humidityconf.description = Relative humidity (0-100%)
channel-type.onewire.light.label = Illuminance
channel-type.onewire.light.description = Ambient light
channel-type.onewire.owfs-number.label = Direct Access to OWFS-Path (Number)
<channel-type id="humidity">
<item-type>Number:Dimensionless</item-type>
<label>Humidity</label>
- <description>relative humidity (0-100%)</description>
- <state readOnly="true" pattern="%d %%"/>
+ <description>Relative humidity (0-100%)</description>
+ <state readOnly="true" pattern="%.0f %%"/>
</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 %%"/>
+ <description>Relative humidity (0-100%)</description>
+ <state readOnly="true" pattern="%.0f %%"/>
<config-description>
<parameter name="humiditytype" type="text" required="false">
<label>Humidity Sensor-Type</label>
+++ /dev/null
-humidity = Number:Dimensionless
-absolutehumidity = Number:Density
-dewpoint = Number:Temperature
-temperature = Number:Temperature
-light = Number:Illuminance
-pressure = Number:Pressure
-voltage = Number:ElectricPotential
-supplyvoltage = Number:ElectricPotential
-current = Number:ElectricCurrent
-counter = Number
-counter0 = Number
-counter1 = Number
-digital = Switch
-digital0 = Switch
-digital1 = Switch
-digital2 = Switch
-digital3 = Switch
-digital4 = Switch
-digital5 = Switch
-digital6 = Switch
-digital7 = Switch
-digital8 = Switch
-present = Switch
-pwmduty1 = Number:Dimensionsless
-pwmduty2 = Number:Dimensionsless
-pwmduty3 = Number:Dimensionsless
-pwmduty4 = Number:Dimensionsless
-pwmfreq1 = Number:Frequency
-pwmfreq2 = Number:Frequency
import static org.junit.jupiter.api.Assertions.fail;
-import java.lang.reflect.Modifier;
-import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
-import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.binding.onewire.internal.OwBindingConstants;
-import org.openhab.binding.onewire.internal.OwException;
import org.openhab.binding.onewire.internal.device.OwSensorType;
import org.openhab.binding.onewire.internal.handler.AdvancedMultisensorThingHandler;
import org.openhab.binding.onewire.internal.handler.BAE091xSensorThingHandler;
@NonNullByDefault
public class CompletenessTest {
// internal/temporary types, DS2409 (MicroLAN Coupler), DS2431 (EEPROM)
- private static final Set<OwSensorType> IGNORED_SENSOR_TYPES = Collections
- .unmodifiableSet(Stream.of(OwSensorType.DS2409, OwSensorType.DS2431, OwSensorType.EDS, OwSensorType.MS_TH_S,
- OwSensorType.BAE, OwSensorType.BAE0911, OwSensorType.UNKNOWN).collect(Collectors.toSet()));
+ private static final Set<OwSensorType> IGNORED_SENSOR_TYPES = Set.of(OwSensorType.DS2409, OwSensorType.DS2431,
+ OwSensorType.EDS, OwSensorType.MS_TH_S, OwSensorType.BAE, OwSensorType.BAE0911, OwSensorType.UNKNOWN);
private static final Set<OwSensorType> THINGHANDLER_SENSOR_TYPES = Collections.unmodifiableSet(Stream
.of(AdvancedMultisensorThingHandler.SUPPORTED_SENSOR_TYPES,
}
}
}
-
- @Test
- public void acceptedItemTypeMapCompleteness() throws OwException {
- List<String> channels = Arrays.stream(OwBindingConstants.class.getDeclaredFields())
- .filter(f -> Modifier.isStatic(f.getModifiers()))
- .filter(f -> f.getName().startsWith("CHANNEL") && !f.getName().startsWith("CHANNEL_TYPE")).map(f -> {
- try {
- return (String) f.get(null);
- } catch (IllegalAccessException e) {
- fail("unexpected");
- return null;
- }
- }).collect(Collectors.toList());
-
- for (String channel : channels) {
- if (!OwBindingConstants.ACCEPTED_ITEM_TYPES_MAP.containsKey(channel)) {
- fail("missing accepted item type for channel " + channel);
- }
- }
- }
}
assertEquals("/1F.0123456789ab/main/00.1234567890ab/humidity", owserverDeviceParameter.getPath(sensorId));
}
+ @Test
public void withPrefixTest() {
OwserverDeviceParameter owserverDeviceParameter = new OwserverDeviceParameter("uncached", "/humidity");
- assertEquals("/uncached/1F.0123456789ab/main/00.1234567890ab/humidity",
+ assertEquals("uncached/1F.0123456789ab/main/00.1234567890ab/humidity",
owserverDeviceParameter.getPath(sensorId));
owserverDeviceParameter = new OwserverDeviceParameter("uncached", "/humidity");
- assertEquals("/uncached/1F.0123456789ab/main/00.1234567890ab/humidity",
+ assertEquals("uncached/1F.0123456789ab/main/00.1234567890ab/humidity",
owserverDeviceParameter.getPath(sensorId));
owserverDeviceParameter = new OwserverDeviceParameter("/uncached", "/humidity");
- assertEquals("/uncached/1F.0123456789ab/main/00.1234567890ab/humidity",
+ assertEquals("uncached/1F.0123456789ab/main/00.1234567890ab/humidity",
owserverDeviceParameter.getPath(sensorId));
owserverDeviceParameter = new OwserverDeviceParameter("/uncached/", "/humidity");
- assertEquals("/uncached/1F.0123456789ab/main/00.1234567890ab/humidity",
+ assertEquals("uncached/1F.0123456789ab/main/00.1234567890ab/humidity",
owserverDeviceParameter.getPath(sensorId));
owserverDeviceParameter = new OwserverDeviceParameter("uncached/", "/humidity");
- assertEquals("/uncached/1F.0123456789ab/main/00.1234567890ab/humidity",
+ assertEquals("uncached/1F.0123456789ab/main/00.1234567890ab/humidity",
owserverDeviceParameter.getPath(sensorId));
}
}
SensorId sensorId2 = new SensorId("1F.0123456789ab/aux/28.0123456789ab");
SensorId sensorId3 = new SensorId("1F.0123456789ab/aux/28.0123456789ac");
- assertTrue(sensorId1.equals(sensorId2));
- assertFalse(sensorId1.equals(sensorId3));
+ assertEquals(sensorId1, sensorId2);
+ assertNotEquals(sensorId1, sensorId3);
}
}
*
* @param registerIndex number of register to return
* @return this register's BitSet
- * @throws OwException
+ * @throws OwException in case an error occurs
*/
private BitSet checkConfiguration(int registerIndex) throws OwException {
ArgumentCaptor<BitSet> configArgumentCaptor = ArgumentCaptor.forClass(BitSet.class);
import org.openhab.core.test.java.JavaTest;
import org.openhab.core.thing.Bridge;
import org.openhab.core.thing.Channel;
+import org.openhab.core.thing.ChannelUID;
import org.openhab.core.thing.Thing;
import org.openhab.core.thing.binding.ThingHandler;
import org.openhab.core.thing.binding.ThingHandlerCallback;
import org.openhab.core.thing.binding.builder.BridgeBuilder;
+import org.openhab.core.thing.binding.builder.ChannelBuilder;
+import org.openhab.core.thing.type.ChannelTypeUID;
/**
* Base class for thing handler tests.
return null;
}).when(thingHandlerCallback).statusUpdated(any(), any());
+ Mockito.when(thingHandlerCallback.createChannelBuilder(any(), any())).thenAnswer(invocation -> {
+ ChannelUID channelUID = (ChannelUID) invocation.getArguments()[0];
+ ChannelTypeUID channelTypeUID = (ChannelTypeUID) invocation.getArguments()[1];
+
+ return ChannelBuilder.create(channelUID).withType(channelTypeUID);
+ });
+
inOrder = Mockito.inOrder(bridgeHandler);
}