From 5ea0dcbda94ee3312bd515f16c76fbe319480555 Mon Sep 17 00:00:00 2001 From: J-N-K Date: Thu, 16 Feb 2023 18:49:00 +0100 Subject: [PATCH] [onewire] Code improvements and bug fixes (#14400) Signed-off-by: Jan N. Klug --- CODEOWNERS | 2 +- .../onewire/internal/DS2438Configuration.java | 32 +++---- .../onewire/internal/DigitalIoConfig.java | 4 +- .../onewire/internal/OwBindingConstants.java | 14 ++- .../onewire/internal/OwHandlerFactory.java | 61 ++----------- .../binding/onewire/internal/Util.java | 30 ++++--- .../internal/device/AbstractOwDevice.java | 29 ++---- .../onewire/internal/device/BAE0910.java | 89 +++++++++---------- .../internal/discovery/OwDiscoveryItem.java | 30 +++---- .../discovery/OwDiscoveryService.java | 48 +++++++--- .../AdvancedMultisensorThingHandler.java | 58 ++++-------- .../handler/BAE091xSensorThingHandler.java | 14 ++- .../handler/BasicMultisensorThingHandler.java | 29 ++---- .../internal/handler/BasicThingHandler.java | 49 +++------- .../handler/EDSSensorThingHandler.java | 15 ++-- .../internal/handler/OwBaseThingHandler.java | 50 +++++------ .../handler/OwserverBridgeHandler.java | 28 +++--- .../internal/owserver/OwserverConnection.java | 21 +++-- .../owserver/OwserverDeviceParameter.java | 3 + .../internal/owserver/OwserverPacket.java | 12 ++- .../resources/OH-INF/i18n/onewire.properties | 4 +- .../main/resources/OH-INF/thing/common.xml | 8 +- .../resources/accepted_itemtypes.properties | 29 ------ .../binding/onewire/CompletenessTest.java | 29 +----- .../onewire/OwserverDeviceParameterTest.java | 11 +-- .../openhab/binding/onewire/SensorIdTest.java | 4 +- .../binding/onewire/device/BAE0910Test.java | 2 +- .../test/AbstractThingHandlerTest.java | 10 +++ 28 files changed, 279 insertions(+), 436 deletions(-) delete mode 100644 bundles/org.openhab.binding.onewire/src/main/resources/accepted_itemtypes.properties diff --git a/CODEOWNERS b/CODEOWNERS index e1fe2044e90..0a9c9c64bae 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -242,7 +242,7 @@ /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 diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/DS2438Configuration.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/DS2438Configuration.java index 008905e0687..f879eb00013 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/DS2438Configuration.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/DS2438Configuration.java @@ -87,19 +87,16 @@ public class DS2438Configuration { 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 -> { + } } } } @@ -129,7 +126,7 @@ public class DS2438Configuration { * @return a list of OwDiscoveryItems */ public List 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()); } @@ -198,18 +195,16 @@ public class DS2438Configuration { List 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)) { @@ -221,8 +216,9 @@ public class DS2438Configuration { // two DS2438 (first TH, second TV), DS18B20, DS2413 multisensorType = OwSensorType.AMS; } - break; - default: + } + default -> { + } } return multisensorType; diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/DigitalIoConfig.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/DigitalIoConfig.java index 9ca9a34711f..cbedac14937 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/DigitalIoConfig.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/DigitalIoConfig.java @@ -14,8 +14,6 @@ package org.openhab.binding.onewire.internal; 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; @@ -100,6 +98,6 @@ public class DigitalIoConfig { @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); } } diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/OwBindingConstants.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/OwBindingConstants.java index 1d5fccff495..02cc8f8cae1 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/OwBindingConstants.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/OwBindingConstants.java @@ -26,7 +26,7 @@ import org.openhab.core.thing.ThingTypeUID; 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 @@ -143,19 +143,17 @@ public class OwBindingConstants { public static final Map THING_LABEL_MAP; public static final Map> SENSOR_TYPE_CHANNEL_MAP; - public static final Map ACCEPTED_ITEM_TYPES_MAP = Util - .readPropertiesFile("accepted_itemtypes.properties"); - static { Map 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())); } diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/OwHandlerFactory.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/OwHandlerFactory.java index b0f2216e74b..55876daae30 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/OwHandlerFactory.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/OwHandlerFactory.java @@ -14,32 +14,23 @@ package org.openhab.binding.onewire.internal; 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 @@ -50,11 +41,12 @@ import org.slf4j.LoggerFactory; @NonNullByDefault @Component(service = ThingHandlerFactory.class, configurationPid = "binding.onewire") public class OwHandlerFactory extends BaseThingHandlerFactory { - Logger logger = LoggerFactory.getLogger(OwHandlerFactory.class); - private final Map> 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) { @@ -66,9 +58,7 @@ public class OwHandlerFactory extends BaseThingHandlerFactory { 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)) { @@ -83,41 +73,4 @@ public class OwHandlerFactory extends BaseThingHandlerFactory { 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; - } } diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/Util.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/Util.java index 6957cfa7f28..5e4be4fbfa5 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/Util.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/Util.java @@ -13,7 +13,7 @@ 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; @@ -52,9 +52,9 @@ public class Util { 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³"); @@ -78,24 +78,32 @@ public class Util { 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 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<>(); } } diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/device/AbstractOwDevice.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/device/AbstractOwDevice.java index 97f0696cee9..29db6ffc7dc 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/device/AbstractOwDevice.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/device/AbstractOwDevice.java @@ -26,7 +26,7 @@ import org.slf4j.Logger; 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 */ @@ -68,7 +68,7 @@ public abstract class AbstractOwDevice { /** * 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 */ @@ -80,9 +80,7 @@ public abstract class AbstractOwDevice { * @param channelID the channels channelID */ public void enableChannel(String channelID) { - if (!enabledChannels.contains(channelID)) { - enabledChannels.add(channelID); - } + enabledChannels.add(channelID); } /** @@ -91,9 +89,7 @@ public abstract class AbstractOwDevice { * @param channelID the channels channelID */ public void disableChannel(String channelID) { - if (enabledChannels.contains(channelID)) { - enabledChannels.remove(channelID); - } + enabledChannels.remove(channelID); } /** @@ -108,10 +104,9 @@ public abstract class AbstractOwDevice { /** * 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); @@ -123,18 +118,4 @@ public abstract class AbstractOwDevice { 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; - } } diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/device/BAE0910.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/device/BAE0910.java index 1fca433692c..e846c58e605 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/device/BAE0910.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/device/BAE0910.java @@ -88,11 +88,11 @@ public class BAE0910 extends AbstractOwDevice { 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 @@ -155,15 +155,16 @@ public class BAE0910 extends AbstractOwDevice { 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"); @@ -284,81 +285,78 @@ public class BAE0910 extends AbstractOwDevice { 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; } @@ -369,14 +367,11 @@ public class BAE0910 extends AbstractOwDevice { 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 { diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/discovery/OwDiscoveryItem.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/discovery/OwDiscoveryItem.java index d87192c7fb5..bb2c8196e89 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/discovery/OwDiscoveryItem.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/discovery/OwDiscoveryItem.java @@ -44,35 +44,31 @@ public class OwDiscoveryItem { 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 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 -> { + } } } @@ -142,12 +138,10 @@ public class OwDiscoveryItem { 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 -> { + } } } diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/discovery/OwDiscoveryService.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/discovery/OwDiscoveryService.java index 90b6a202689..0f6cac6670f 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/discovery/OwDiscoveryService.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/discovery/OwDiscoveryService.java @@ -22,6 +22,7 @@ import java.util.Map; 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; @@ -31,6 +32,8 @@ 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; @@ -40,28 +43,27 @@ 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 owDiscoveryItems = new HashMap<>(); Set 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 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; @@ -70,13 +72,13 @@ public class OwDiscoveryService extends AbstractDiscoveryService { // 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()); @@ -93,7 +95,15 @@ public class OwDiscoveryService extends AbstractDiscoveryService { @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())); @@ -130,6 +140,18 @@ public class OwDiscoveryService extends AbstractDiscoveryService { 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()); diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/AdvancedMultisensorThingHandler.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/AdvancedMultisensorThingHandler.java index 6ce53c586c0..f6b571a74c2 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/AdvancedMultisensorThingHandler.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/AdvancedMultisensorThingHandler.java @@ -14,10 +14,7 @@ package org.openhab.binding.onewire.internal.handler; 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; @@ -52,11 +49,9 @@ import org.slf4j.LoggerFactory; */ @NonNullByDefault public class AdvancedMultisensorThingHandler extends OwBaseThingHandler { - public static final Set SUPPORTED_THING_TYPES = new HashSet<>( - Arrays.asList(THING_TYPE_AMS, THING_TYPE_BMS)); - public static final Set SUPPORTED_SENSOR_TYPES = Collections - .unmodifiableSet(Stream.of(OwSensorType.AMS, OwSensorType.AMS_S, OwSensorType.BMS, OwSensorType.BMS_S) - .collect(Collectors.toSet())); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_AMS, THING_TYPE_BMS); + public static final Set 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"; @@ -90,7 +85,7 @@ public class AdvancedMultisensorThingHandler extends OwBaseThingHandler { 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)); @@ -104,9 +99,7 @@ public class AdvancedMultisensorThingHandler extends OwBaseThingHandler { } catch (IllegalArgumentException e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "properties invalid"); } - scheduler.execute(() -> { - configureThingChannels(); - }); + scheduler.execute(this::configureThingChannels); } @Override @@ -140,8 +133,8 @@ public class AdvancedMultisensorThingHandler extends OwBaseThingHandler { 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); } } } @@ -159,7 +152,7 @@ public class AdvancedMultisensorThingHandler extends OwBaseThingHandler { // delete unwanted channels Set existingChannelIds = thing.getChannels().stream().map(channel -> channel.getUID().getId()) .collect(Collectors.toSet()); - Set wantedChannelIds = SENSOR_TYPE_CHANNEL_MAP.get(sensorType).stream() + Set 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); @@ -167,9 +160,8 @@ public class AdvancedMultisensorThingHandler extends OwBaseThingHandler { .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) @@ -184,12 +176,7 @@ public class AdvancedMultisensorThingHandler extends OwBaseThingHandler { // humidity channel addChannelIfMissingAndEnable(thingBuilder, new OwChannelConfig(CHANNEL_HUMIDITY, CHANNEL_TYPE_UID_HUMIDITY), - new Configuration(new HashMap() { - 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) { @@ -230,23 +217,18 @@ public class AdvancedMultisensorThingHandler extends OwBaseThingHandler { 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); @@ -259,10 +241,6 @@ public class AdvancedMultisensorThingHandler extends OwBaseThingHandler { * @return */ private static Set 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; } } diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/BAE091xSensorThingHandler.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/BAE091xSensorThingHandler.java index 7ab53f936de..bc39038ed4c 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/BAE091xSensorThingHandler.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/BAE091xSensorThingHandler.java @@ -14,7 +14,6 @@ package org.openhab.binding.onewire.internal.handler; import static org.openhab.binding.onewire.internal.OwBindingConstants.*; -import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Set; @@ -47,11 +46,11 @@ import org.slf4j.LoggerFactory; */ @NonNullByDefault public class BAE091xSensorThingHandler extends OwBaseThingHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_BAE091X); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BAE091X); private final Logger logger = LoggerFactory.getLogger(BAE091xSensorThingHandler.class); - public static final Set SUPPORTED_SENSOR_TYPES = Collections.singleton(OwSensorType.BAE0910); + public static final Set SUPPORTED_SENSOR_TYPES = Set.of(OwSensorType.BAE0910); public BAE091xSensorThingHandler(Thing thing, OwDynamicStateDescriptionProvider dynamicStateDescriptionProvider) { super(thing, dynamicStateDescriptionProvider, SUPPORTED_SENSOR_TYPES); @@ -89,9 +88,7 @@ public class BAE091xSensorThingHandler extends OwBaseThingHandler { sensors.add(new BAE0910(sensorId, this)); - scheduler.execute(() -> { - configureThingChannels(); - }); + scheduler.execute(this::configureThingChannels); } @Override @@ -101,8 +98,7 @@ public class BAE091xSensorThingHandler extends OwBaseThingHandler { BAE091xHandlerConfiguration configuration = getConfig().as(BAE091xHandlerConfiguration.class); - Set wantedChannel = new HashSet<>(); - wantedChannel.addAll(SENSOR_TYPE_CHANNEL_MAP.getOrDefault(sensorType, Set.of())); + Set wantedChannel = new HashSet<>(SENSOR_TYPE_CHANNEL_MAP.getOrDefault(sensorType, Set.of())); // Pin1: switch (configuration.pin1) { @@ -214,7 +210,7 @@ public class BAE091xSensorThingHandler extends OwBaseThingHandler { .forEach(channelId -> removeChannelIfExisting(thingBuilder, channelId)); // add or update wanted channels - wantedChannel.stream().forEach(channelConfig -> { + wantedChannel.forEach(channelConfig -> { addChannelIfMissingAndEnable(thingBuilder, channelConfig); }); diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/BasicMultisensorThingHandler.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/BasicMultisensorThingHandler.java index 21fc44a37bc..f3699e0b8d3 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/BasicMultisensorThingHandler.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/BasicMultisensorThingHandler.java @@ -14,11 +14,8 @@ package org.openhab.binding.onewire.internal.handler; 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; @@ -44,10 +41,9 @@ import org.slf4j.LoggerFactory; @NonNullByDefault public class BasicMultisensorThingHandler extends OwBaseThingHandler { public Logger logger = LoggerFactory.getLogger(BasicMultisensorThingHandler.class); - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_MS_TX); - public static final Set 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 SUPPORTED_THING_TYPES = Set.of(THING_TYPE_MS_TX); + public static final Set 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) { @@ -74,24 +70,17 @@ public class BasicMultisensorThingHandler extends OwBaseThingHandler { 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(); diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/BasicThingHandler.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/BasicThingHandler.java index 618751f41f7..1ee3d3cef39 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/BasicThingHandler.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/BasicThingHandler.java @@ -14,10 +14,7 @@ package org.openhab.binding.onewire.internal.handler; 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; @@ -45,11 +42,10 @@ import org.slf4j.LoggerFactory; */ @NonNullByDefault public class BasicThingHandler extends OwBaseThingHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_BASIC); - public static final Set 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 SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BASIC); + public static final Set 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); @@ -65,36 +61,17 @@ public class BasicThingHandler extends OwBaseThingHandler { // 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 diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/EDSSensorThingHandler.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/EDSSensorThingHandler.java index 7f6e6a9ca39..122c2942303 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/EDSSensorThingHandler.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/EDSSensorThingHandler.java @@ -18,8 +18,6 @@ import java.nio.charset.StandardCharsets; 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; @@ -37,10 +35,9 @@ import org.openhab.core.thing.ThingTypeUID; */ @NonNullByDefault public class EDSSensorThingHandler extends OwBaseThingHandler { - public static final Set SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_EDS_ENV); - public static final Set SUPPORTED_SENSOR_TYPES = Collections - .unmodifiableSet(Stream.of(OwSensorType.EDS0064, OwSensorType.EDS0065, OwSensorType.EDS0066, - OwSensorType.EDS0067, OwSensorType.EDS0068).collect(Collectors.toSet())); + public static final Set SUPPORTED_THING_TYPES = Set.of(THING_TYPE_EDS_ENV); + public static final Set SUPPORTED_SENSOR_TYPES = Set.of(OwSensorType.EDS0064, OwSensorType.EDS0065, + OwSensorType.EDS0066, OwSensorType.EDS0067, OwSensorType.EDS0068); private static final Set REQUIRED_PROPERTIES = Collections.singleton(PROPERTY_HW_REVISION); public EDSSensorThingHandler(Thing thing, OwDynamicStateDescriptionProvider dynamicStateDescriptionProvider) { @@ -56,9 +53,7 @@ public class EDSSensorThingHandler extends OwBaseThingHandler { // add sensors sensors.add(new EDS006x(sensorId, sensorType, this)); - scheduler.execute(() -> { - configureThingChannels(); - }); + scheduler.execute(this::configureThingChannels); } @Override @@ -70,7 +65,7 @@ public class EDSSensorThingHandler extends OwBaseThingHandler { 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)) { diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/OwBaseThingHandler.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/OwBaseThingHandler.java index c1a13d80b98..f26b4722be5 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/OwBaseThingHandler.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/OwBaseThingHandler.java @@ -15,14 +15,12 @@ package org.openhab.binding.onewire.internal.handler; 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; @@ -43,6 +41,7 @@ import org.openhab.core.thing.ThingStatus; 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; @@ -64,8 +63,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 REQUIRED_PROPERTIES = Collections - .unmodifiableSet(Stream.of(PROPERTY_MODELID, PROPERTY_VENDOR).collect(Collectors.toSet())); + private static final Set REQUIRED_PROPERTIES = Set.of(PROPERTY_MODELID, PROPERTY_VENDOR); protected List requiredProperties = new ArrayList<>(REQUIRED_PROPERTIES); protected Set supportedSensorTypes; @@ -137,7 +135,7 @@ public abstract class OwBaseThingHandler extends BaseThingHandler { return false; } - refreshInterval = configuration.refresh * 1000; + refreshInterval = configuration.refresh * 1000L; // check if all required properties are present. update if not for (String property : requiredProperties) { @@ -166,13 +164,13 @@ public abstract class OwBaseThingHandler extends BaseThingHandler { // remove unwanted channels Set existingChannelIds = thing.getChannels().stream().map(channel -> channel.getUID().getId()) .collect(Collectors.toSet()); - Set wantedChannelIds = SENSOR_TYPE_CHANNEL_MAP.get(sensorType).stream() + Set 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); }); @@ -325,8 +323,7 @@ public abstract class OwBaseThingHandler extends BaseThingHandler { * 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 properties = editProperties(); @@ -365,10 +362,9 @@ public abstract class OwBaseThingHandler extends BaseThingHandler { * * @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); } /** @@ -377,11 +373,10 @@ public abstract class OwBaseThingHandler extends BaseThingHandler { * @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); } /** @@ -390,11 +385,10 @@ public abstract class OwBaseThingHandler extends BaseThingHandler { * @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); } /** @@ -404,9 +398,8 @@ public abstract class OwBaseThingHandler extends BaseThingHandler { * @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; @@ -423,23 +416,28 @@ public abstract class OwBaseThingHandler extends BaseThingHandler { // 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; } } diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/OwserverBridgeHandler.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/OwserverBridgeHandler.java index 1e8e88a7ad6..882760b7c94 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/OwserverBridgeHandler.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/handler/OwserverBridgeHandler.java @@ -17,6 +17,7 @@ import static org.openhab.binding.onewire.internal.OwBindingConstants.*; 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; @@ -32,6 +33,7 @@ import org.openhab.binding.onewire.internal.OwException; 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; @@ -47,6 +49,7 @@ import org.openhab.core.thing.ThingStatus; 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; @@ -236,7 +239,7 @@ public class OwserverBridgeHandler extends BaseBridgeHandler { * * @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) { @@ -249,14 +252,14 @@ public class OwserverBridgeHandler extends BaseBridgeHandler { * * @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; @@ -267,7 +270,7 @@ public class OwserverBridgeHandler extends BaseBridgeHandler { * * @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) { @@ -281,7 +284,7 @@ public class OwserverBridgeHandler extends BaseBridgeHandler { * @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) { @@ -295,7 +298,7 @@ public class OwserverBridgeHandler extends BaseBridgeHandler { * @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() }); @@ -307,7 +310,7 @@ public class OwserverBridgeHandler extends BaseBridgeHandler { * @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 readDecimalTypeArray(SensorId sensorId, OwserverDeviceParameter parameter) throws OwException { synchronized (owserverConnection) { @@ -321,7 +324,7 @@ public class OwserverBridgeHandler extends BaseBridgeHandler { * @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) { @@ -334,7 +337,7 @@ public class OwserverBridgeHandler extends BaseBridgeHandler { * * @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 { @@ -348,7 +351,7 @@ public class OwserverBridgeHandler extends BaseBridgeHandler { * * @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])); @@ -427,4 +430,9 @@ public class OwserverBridgeHandler extends BaseBridgeHandler { } } } + + @Override + public Collection> getServices() { + return Set.of(OwDiscoveryService.class); + } } diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/owserver/OwserverConnection.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/owserver/OwserverConnection.java index f5ee5e02306..ed4326a175d 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/owserver/OwserverConnection.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/owserver/OwserverConnection.java @@ -174,8 +174,7 @@ public class OwserverConnection { returnValue = OnOffType.ON; } - } catch (OwException e) { - returnValue = OnOffType.OFF; + } catch (OwException ignored) { } logger.trace("presence {} : {}", path, returnValue); return returnValue; @@ -186,7 +185,7 @@ public class OwserverConnection { * * @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; @@ -211,7 +210,7 @@ public class OwserverConnection { * * @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 readDecimalTypeArray(String path) throws OwException { List returnList = new ArrayList<>(); @@ -232,7 +231,7 @@ public class OwserverConnection { * * @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); @@ -250,7 +249,7 @@ public class OwserverConnection { * * @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"); @@ -267,7 +266,7 @@ public class OwserverConnection { * * @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); @@ -284,7 +283,7 @@ public class OwserverConnection { * * @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); @@ -441,7 +440,7 @@ public class OwserverConnection { * {@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 { @@ -475,7 +474,7 @@ public class OwserverConnection { * * @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); @@ -495,7 +494,7 @@ public class OwserverConnection { 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"); diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/owserver/OwserverDeviceParameter.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/owserver/OwserverDeviceParameter.java index d583f73d2e1..1a4cefc51be 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/owserver/OwserverDeviceParameter.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/owserver/OwserverDeviceParameter.java @@ -39,6 +39,9 @@ public class OwserverDeviceParameter { } else { this.prefix = prefix; } + if (this.prefix.startsWith("/")) { + this.prefix = this.prefix.substring(1); + } if (path.startsWith("/")) { this.path = path; } else { diff --git a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/owserver/OwserverPacket.java b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/owserver/OwserverPacket.java index 83e1530b7c1..c4a2495b397 100644 --- a/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/owserver/OwserverPacket.java +++ b/bundles/org.openhab.binding.onewire/src/main/java/org/openhab/binding/onewire/internal/owserver/OwserverPacket.java @@ -13,7 +13,6 @@ package org.openhab.binding.onewire.internal.owserver; import java.io.DataInputStream; -import java.io.EOFException; import java.io.IOException; import java.nio.ByteBuffer; @@ -60,10 +59,10 @@ public class OwserverPacket { * * @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 @@ -148,7 +147,7 @@ public class OwserverPacket { /** * set this packet's temperature scale * - * @param pressureScale + * @param temperatureScale */ public void setTemperatureScale(OwserverTemperatureScale temperatureScale) { controlFlags = temperatureScale.setFlag(controlFlags); @@ -181,7 +180,7 @@ public class OwserverPacket { * @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); @@ -298,8 +297,7 @@ public class OwserverPacket { * @return OwPageBuffer with this packet's payload */ public OwPageBuffer getPayload() { - OwPageBuffer byteBuffer = new OwPageBuffer(payload); - return byteBuffer; + return new OwPageBuffer(payload); } /** diff --git a/bundles/org.openhab.binding.onewire/src/main/resources/OH-INF/i18n/onewire.properties b/bundles/org.openhab.binding.onewire/src/main/resources/OH-INF/i18n/onewire.properties index f82cbbeeea3..57e83d0dd36 100644 --- a/bundles/org.openhab.binding.onewire/src/main/resources/OH-INF/i18n/onewire.properties +++ b/bundles/org.openhab.binding.onewire/src/main/resources/OH-INF/i18n/onewire.properties @@ -109,9 +109,9 @@ channel-type.onewire.dewpoint.label = Dewpoint 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) diff --git a/bundles/org.openhab.binding.onewire/src/main/resources/OH-INF/thing/common.xml b/bundles/org.openhab.binding.onewire/src/main/resources/OH-INF/thing/common.xml index 762237d3599..4a048968957 100644 --- a/bundles/org.openhab.binding.onewire/src/main/resources/OH-INF/thing/common.xml +++ b/bundles/org.openhab.binding.onewire/src/main/resources/OH-INF/thing/common.xml @@ -65,14 +65,14 @@ Number:Dimensionless - relative humidity (0-100%) - + Relative humidity (0-100%) + Number:Dimensionless - relative humidity (0-100%) - + Relative humidity (0-100%) + diff --git a/bundles/org.openhab.binding.onewire/src/main/resources/accepted_itemtypes.properties b/bundles/org.openhab.binding.onewire/src/main/resources/accepted_itemtypes.properties deleted file mode 100644 index e4f8dfd8f25..00000000000 --- a/bundles/org.openhab.binding.onewire/src/main/resources/accepted_itemtypes.properties +++ /dev/null @@ -1,29 +0,0 @@ -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 diff --git a/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/CompletenessTest.java b/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/CompletenessTest.java index 3f91eda05d5..622583da995 100644 --- a/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/CompletenessTest.java +++ b/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/CompletenessTest.java @@ -14,11 +14,8 @@ package org.openhab.binding.onewire; 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; @@ -26,7 +23,6 @@ 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; @@ -42,9 +38,8 @@ import org.openhab.binding.onewire.internal.handler.EDSSensorThingHandler; @NonNullByDefault public class CompletenessTest { // internal/temporary types, DS2409 (MicroLAN Coupler), DS2431 (EEPROM) - private static final Set 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 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 THINGHANDLER_SENSOR_TYPES = Collections.unmodifiableSet(Stream .of(AdvancedMultisensorThingHandler.SUPPORTED_SENSOR_TYPES, @@ -90,24 +85,4 @@ public class CompletenessTest { } } } - - @Test - public void acceptedItemTypeMapCompleteness() throws OwException { - List 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); - } - } - } } diff --git a/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/OwserverDeviceParameterTest.java b/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/OwserverDeviceParameterTest.java index 83208b8038d..7a0330d5b48 100644 --- a/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/OwserverDeviceParameterTest.java +++ b/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/OwserverDeviceParameterTest.java @@ -37,25 +37,26 @@ public class OwserverDeviceParameterTest { 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)); } } diff --git a/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/SensorIdTest.java b/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/SensorIdTest.java index b292494b03d..ff42c8c38ed 100644 --- a/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/SensorIdTest.java +++ b/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/SensorIdTest.java @@ -71,7 +71,7 @@ public class SensorIdTest { 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); } } diff --git a/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/device/BAE0910Test.java b/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/device/BAE0910Test.java index ee0a0a3c35b..0e889799835 100644 --- a/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/device/BAE0910Test.java +++ b/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/device/BAE0910Test.java @@ -287,7 +287,7 @@ public class BAE0910Test extends DeviceTestParent { * * @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 configArgumentCaptor = ArgumentCaptor.forClass(BitSet.class); diff --git a/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/test/AbstractThingHandlerTest.java b/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/test/AbstractThingHandlerTest.java index b0a3cfadccc..a84bd3adee4 100644 --- a/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/test/AbstractThingHandlerTest.java +++ b/bundles/org.openhab.binding.onewire/src/test/java/org/openhab/binding/onewire/test/AbstractThingHandlerTest.java @@ -42,10 +42,13 @@ import org.openhab.core.library.types.OnOffType; 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. @@ -99,6 +102,13 @@ public abstract class AbstractThingHandlerTest extends JavaTest { 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); }