import static org.openhab.binding.adorne.internal.AdorneBindingConstants.*;
-import java.util.Collections;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
*/
public AdorneDiscoveryService() {
// Passing false as last argument to super constructor turns off background discovery
- super(Collections.singleton(new ThingTypeUID(BINDING_ID, "-")), DISCOVERY_TIMEOUT_SECONDS, false);
+ super(Set.of(new ThingTypeUID(BINDING_ID, "-")), DISCOVERY_TIMEOUT_SECONDS, false);
// We create the hub controller with default host and port. In the future we could let users create hubs
// manually with custom host and port settings and then perform discovery here for those hubs.
// Future enhancement: Need a timeout for each future execution to recover from bugs in the hub controller, but
// Java8 doesn't yet offer that
- adorneHubController.start().thenCompose(Void -> {
- // We use the hub's MAC address as its unique identifier
- return adorneHubController.getMACAddress();
- }).thenCompose(macAddress -> {
+ adorneHubController.start().thenCompose(Void ->
+ // We use the hub's MAC address as its unique identifier
+ adorneHubController.getMACAddress()).thenCompose(macAddress -> {
String macAddressNoColon = macAddress.replace(':', '-'); // Colons are not allowed in ThingUIDs
bridgeUID[0] = new ThingUID(THING_TYPE_HUB, macAddressNoColon);
// We have fully discovered the hub
if (channelUID.getId().equals(CHANNEL_BRIGHTNESS)) {
if (command instanceof RefreshType) {
refreshBrightness();
- } else if (command instanceof PercentType) {
+ } else if (command instanceof PercentType percentCommand) {
// Change the brightness through the hub controller
AdorneHubController adorneHubController = getAdorneHubController();
- int level = ((PercentType) command).intValue();
+ int level = percentCommand.intValue();
if (level >= 1 && level <= 100) { // Ignore commands outside of the supported 1-100 range
adorneHubController.setBrightness(zoneId, level);
} else {
return null; // Eat empty messages
}
logger.debug("Received message {}", msg);
- if (msg instanceof JsonObject) {
- msgJsonObject = (JsonObject) msg;
+ if (msg instanceof JsonObject object) {
+ msgJsonObject = object;
}
return msgJsonObject;
}
final Elements table = doc.select("table");
- if (table.size() == 0) {
+ if (table.isEmpty()) {
logger.warn("No result table found.");
return Collections.emptyMap();
}
while (rowIt.hasNext()) {
final Element currentRow = rowIt.next();
- if (!currentRow.tagName().equals("tr")) {
+ if (!"tr".equals(currentRow.tagName())) {
continue;
}
// Skip header, empty and download button rows.
import static org.openhab.binding.airq.internal.AirqBindingConstants.THING_TYPE_AIRQ;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.airq", service = ThingHandlerFactory.class)
public class AirqHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_AIRQ);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_AIRQ);
private final HttpClientFactory httpClientFactory;
@Activate
new ConcentrationRange(205, 404, TWO_HUNDRED), new ConcentrationRange(405, 504, THREE_HUNDRED),
new ConcentrationRange(505, 604, FOUR_HUNDRED));
- public static enum SensitiveGroup {
+ public enum SensitiveGroup {
RESPIRATORY,
HEART,
ELDERLY,
CHILDREN,
- ASTHMA;
+ ASTHMA
}
public final Set<SensitiveGroup> sensitiveGroups;
* @author Gaël L'hopital - Initial contribution
*/
public class ResponseRoot {
- public static enum ResponseStatus {
+ public enum ResponseStatus {
@SerializedName("error")
ERROR,
@SerializedName("ok")
- OK;
+ OK
}
protected ResponseStatus status = ResponseStatus.OK;
public @Nullable SensitiveGroup asSensitiveGroup() {
try {
- SensitiveGroup value = SensitiveGroup.valueOf(group);
- return value;
+ return SensitiveGroup.valueOf(group);
} catch (IllegalArgumentException e) {
return null;
}
import static org.openhab.binding.airquality.internal.AirQualityBindingConstants.*;
import static org.openhab.binding.airquality.internal.config.AirQualityConfiguration.LOCATION;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@NonNullByDefault
public class AirQualityDiscoveryService extends AbstractDiscoveryService implements ThingHandlerService {
private static final int DISCOVER_TIMEOUT_SECONDS = 2;
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_STATION);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_STATION);
private final Logger logger = LoggerFactory.getLogger(AirQualityDiscoveryService.class);
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof AirQualityBridgeHandler) {
- final AirQualityBridgeHandler bridgeHandler = (AirQualityBridgeHandler) handler;
- this.bridgeHandler = bridgeHandler;
+ if (handler instanceof AirQualityBridgeHandler bridgeHandlerInstance) {
+ this.bridgeHandler = bridgeHandlerInstance;
this.locationProvider = bridgeHandler.getLocationProvider();
}
}
*/
package org.openhab.binding.airvisualnode.internal;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
.getUID().getId();
// List of all supported Thing UIDs
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .unmodifiableSet(new HashSet<>(Arrays.asList(THING_TYPE_AVNODE)));
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_AVNODE);
// List of all supported Channel ids
- public static final Set<String> SUPPORTED_CHANNEL_IDS = Collections
- .unmodifiableSet(new HashSet<>(Arrays.asList(CHANNEL_CO2, CHANNEL_HUMIDITY, CHANNEL_AQI_US, CHANNEL_PM_25,
- CHANNEL_PM_10, CHANNEL_PM_01, CHANNEL_TEMP_CELSIUS, CHANNEL_BATTERY_LEVEL, CHANNEL_WIFI_STRENGTH,
- CHANNEL_TIMESTAMP, CHANNEL_USED_MEMORY)));
+ public static final Set<String> SUPPORTED_CHANNEL_IDS = Set.of(CHANNEL_CO2, CHANNEL_HUMIDITY, CHANNEL_AQI_US,
+ CHANNEL_PM_25, CHANNEL_PM_10, CHANNEL_PM_01, CHANNEL_TEMP_CELSIUS, CHANNEL_BATTERY_LEVEL,
+ CHANNEL_WIFI_STRENGTH, CHANNEL_TIMESTAMP, CHANNEL_USED_MEMORY);
}
import java.io.IOException;
import java.net.UnknownHostException;
-import java.util.Collections;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
private @Nullable ScheduledFuture<?> backgroundDiscoveryFuture;
public AirVisualNodeDiscoveryService() {
- super(Collections.singleton(AirVisualNodeBindingConstants.THING_TYPE_AVNODE), 600, true);
+ super(Set.of(AirVisualNodeBindingConstants.THING_TYPE_AVNODE), 600, true);
}
@Override
this.vocPpb = vocPpb;
}
+ @Override
public int getCo2Ppm() {
return co2Ppm;
}
this.co2Ppm = co2Ppm;
}
+ @Override
public int getHumidityRH() {
return humidityRH;
}
this.humidityRH = humidityRH;
}
+ @Override
public int getPm25AQICN() {
return pm25AQICN;
}
this.pm25AQICN = pm25AQICN;
}
+ @Override
public int getPm25AQIUS() {
return pm25AQIUS;
}
return 0;
}
+ @Override
public float getPm25Ugm3() {
return pm25Ugm3;
}
this.pm25Ugm3 = pm25Ugm3;
}
+ @Override
public float getTemperatureC() {
return temperatureC;
}
this.temperatureC = temperatureC;
}
+ @Override
public float getTemperatureF() {
return temperatureF;
}
this.temperatureF = temperatureF;
}
+ @Override
public int getVocPpb() {
return vocPpb;
}
this.status = status;
}
+ @Override
public DateAndTime getDateAndTime() {
return dateAndTime;
}
this.dateAndTime = dateAndTime;
}
+ @Override
public MeasurementsInterface getMeasurements() {
return measurements;
}
this.measurements = measurements;
}
+ @Override
public String getSerialNumber() {
return serialNumber;
}
this.serialNumber = serialNumber;
}
+ @Override
public Settings getSettings() {
return settings;
}
this.settings = settings;
}
+ @Override
public Status getStatus() {
return status;
}
this.vocPpb = vocPpb;
}
+ @Override
public int getCo2Ppm() {
return co2Ppm;
}
this.co2Ppm = co2Ppm;
}
+ @Override
public int getHumidityRH() {
return humidityRH;
}
this.humidityRH = humidityRH;
}
+ @Override
public int getPm25AQICN() {
return pm25AQICN;
}
this.pm25AQICN = pm25AQICN;
}
+ @Override
public int getPm25AQIUS() {
return pm25AQIUS;
}
this.pm25AQIUS = pm25AQIUS;
}
+ @Override
public float getPm01Ugm3() {
return pm01Ugm3;
}
this.pm01Ugm3 = pm01Ugm3;
}
+ @Override
public float getPm10Ugm3() {
return pm10Ugm3;
}
this.pm10Ugm3 = pm10Ugm3;
}
+ @Override
public float getPm25Ugm3() {
return pm25Ugm3;
}
this.pm25Ugm3 = pm25Ugm3;
}
+ @Override
public float getTemperatureC() {
return temperatureC;
}
this.temperatureC = temperatureC;
}
+ @Override
public float getTemperatureF() {
return temperatureF;
}
this.temperatureF = temperatureF;
}
+ @Override
public int getVocPpb() {
return vocPpb;
}
this.status = status;
}
+ @Override
public DateAndTime getDateAndTime() {
return dateAndTime;
}
this.dateAndTime = dateAndTime;
}
+ @Override
public MeasurementsInterface getMeasurements() {
return measurements.get(0);
}
this.measurements = measurements;
}
+ @Override
public String getSerialNumber() {
return serialNumber;
}
this.serialNumber = serialNumber;
}
+ @Override
public Settings getSettings() {
return settings;
}
this.settings = settings;
}
+ @Override
public Status getStatus() {
return status;
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof ADBridgeHandler) {
- this.bridge = (ADBridgeHandler) handler;
+ if (handler instanceof ADBridgeHandler bridgeHandler) {
+ this.bridge = bridgeHandler;
}
}
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
-import java.util.Collections;
import java.util.Date;
+import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singletonList(BridgeActions.class);
+ return List.of(BridgeActions.class);
}
public void setDiscoveryService(AlarmDecoderDiscoveryService discoveryService) {
IntCommandMap intCommandMap = this.intCommandMap;
if (channelUID.getId().equals(CHANNEL_KP_COMMAND)) {
- if (command instanceof StringType) {
- String cmd = ((StringType) command).toString();
+ if (command instanceof StringType commandString) {
+ String cmd = commandString.toString();
handleKeypadCommand(cmd);
}
} else if (channelUID.getId().equals(CHANNEL_KP_INTCOMMAND)) {
- if (command instanceof Number) {
- int icmd = ((Number) command).intValue();
+ if (command instanceof Number numberCommand) {
+ int icmd = numberCommand.intValue();
if (intCommandMap != null) {
String cmd = intCommandMap.getCommand(icmd);
if (cmd != null) {
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
if (channelUID.getId().equals(CHANNEL_COMMAND)) {
- if (command instanceof StringType) {
- String cmd = ((StringType) command).toString();
+ if (command instanceof StringType stringCommand) {
+ String cmd = stringCommand.toString();
if (CMD_OPEN.equalsIgnoreCase(cmd)) {
sendCommand(ADCommand.setZone(config.address, ADCommand.ZONE_OPEN));
setChannelState(OnOffType.OFF);
}
/** Construct zone id from address and channel */
- public static final String zoneID(int address, int channel) {
+ public static String zoneID(int address, int channel) {
return String.format("%d-%d", address, channel);
}
public EXPMessage(String message) throws IllegalArgumentException {
super(message);
- String topLevel[] = message.split(":");
+ String[] topLevel = message.split(":");
if (topLevel.length != 2) {
throw new IllegalArgumentException("Multiple colons found in EXP message");
}
return false;
} else if (this == obj) {
return true;
- } else if (obj instanceof KeypadMessage) {
- KeypadMessage other = (KeypadMessage) obj;
+ } else if (obj instanceof KeypadMessage other) {
return this.message.equals(other.message);
} else {
return false;
public LRRMessage(String message) throws IllegalArgumentException {
super(message);
- String topLevel[] = message.split(":");
+ String[] topLevel = message.split(":");
if (topLevel.length != 2) {
throw new IllegalArgumentException("multiple colons in LRR message");
}
public RFXMessage(String message) throws IllegalArgumentException {
super(message);
- String topLevel[] = message.split(":");
+ String[] topLevel = message.split(":");
if (topLevel.length != 2) {
throw new IllegalArgumentException("Multiple colons found in RFX message");
}
public VersionMessage(String message) throws IllegalArgumentException {
super(message);
- String topLevel[] = message.split(":");
+ String[] topLevel = message.split(":");
if (topLevel.length != 2) {
throw new IllegalArgumentException("Multiple colons found in VER message");
}
private int getIntegerProperty(Dictionary<String, Object> properties, String propertyKey, int defaultValue) {
Object configValue = properties.get(propertyKey);
int value = defaultValue;
- if (configValue instanceof String) {
+ if (configValue instanceof String stringValue) {
try {
- value = Integer.parseInt((String) configValue);
+ value = Integer.parseInt(stringValue);
} catch (NumberFormatException e) {
logger.warn("Unable to convert value {} for config property {} to integer. Using default value.",
configValue, propertyKey);
import static org.openhab.binding.allplay.internal.AllPlayBindingConstants.SPEAKER_THING_TYPE;
-import java.util.Collections;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Map;
private final Logger logger = LoggerFactory.getLogger(AllPlayHandlerFactory.class);
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(SPEAKER_THING_TYPE);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(SPEAKER_THING_TYPE);
private final Map<String, ServiceRegistration<AudioSink>> audioSinkRegistrations = new ConcurrentHashMap<>();
private AllPlay allPlay;
import static org.openhab.binding.allplay.internal.AllPlayBindingConstants.SPEAKER_THING_TYPE;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
private final Logger logger = LoggerFactory.getLogger(AllPlaySpeakerDiscoveryService.class);
private static final int DISCOVERY_TIMEOUT = 30;
- private static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPES_UIDS = Collections.singleton(SPEAKER_THING_TYPE);
+ private static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPES_UIDS = Set.of(SPEAKER_THING_TYPE);
private AllPlay allPlay;
public AllPlaySpeakerDiscoveryService() {
* @throws SpeakerException Exception if the volume change failed
*/
public void handleVolumeCommand(Command command) throws SpeakerException {
- if (command instanceof PercentType) {
- speaker.volume().setVolume(convertPercentToAbsoluteVolume((PercentType) command));
+ if (command instanceof PercentType percentCommand) {
+ speaker.volume().setVolume(convertPercentToAbsoluteVolume(percentCommand));
} else if (command instanceof IncreaseDecreaseType) {
int stepSize = (command == IncreaseDecreaseType.DECREASE ? -getVolumeStepSize() : getVolumeStepSize());
speaker.volume().adjustVolume(stepSize);
import static org.openhab.binding.amazondashbutton.internal.AmazonDashButtonBindingConstants.DASH_BUTTON_THING_TYPE;
-import java.util.Collections;
import java.util.Set;
import org.openhab.binding.amazondashbutton.internal.handler.AmazonDashButtonHandler;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.amazondashbutton")
public class AmazonDashButtonHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(DASH_BUTTON_THING_TYPE);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(DASH_BUTTON_THING_TYPE);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
import static org.openhab.binding.amazondashbutton.internal.AmazonDashButtonBindingConstants.*;
import java.math.BigDecimal;
-import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
private boolean backgroundScanning = false;
public AmazonDashButtonDiscoveryService() {
- super(Collections.singleton(DASH_BUTTON_THING_TYPE), DISCOVER_TIMEOUT_SECONDS, false);
+ super(Set.of(DASH_BUTTON_THING_TYPE), DISCOVER_TIMEOUT_SECONDS, false);
}
@Override
*/
public static Set<PcapNetworkInterfaceWrapper> getAllNetworkInterfaces() {
try {
- final Set<PcapNetworkInterfaceWrapper> allNetworkInterfaces = Collections.unmodifiableSet(Pcaps
- .findAllDevs().stream().map(PcapNetworkInterfaceWrapper.TRANSFORMER).collect(Collectors.toSet()));
- return allNetworkInterfaces;
+ return Collections.unmodifiableSet(Pcaps.findAllDevs().stream().map(PcapNetworkInterfaceWrapper.TRANSFORMER)
+ .collect(Collectors.toSet()));
} catch (PcapNativeException e) {
throw new RuntimeException(e);
}
.getService(serviceReg.getReference());
serviceReg.unregister();
if (service != null) {
- if (service instanceof AmazonEchoDiscovery) {
- ((AmazonEchoDiscovery) service).deactivate();
- } else if (service instanceof SmartHomeDevicesDiscovery) {
- ((SmartHomeDevicesDiscovery) service).deactivate();
+ if (service instanceof AmazonEchoDiscovery discovery) {
+ discovery.deactivate();
+ } else if (service instanceof SmartHomeDevicesDiscovery discovery) {
+ discovery.deactivate();
} else {
logger.warn("Found unknown discovery-service instance: {}", service);
}
public boolean tryHandleCommand(Device device, Connection connection, String channelId, Command command)
throws IOException, URISyntaxException {
if (channelId.equals(CHANNEL_NAME)) {
- if (command instanceof StringType) {
- String commandValue = ((StringType) command).toFullString();
+ if (command instanceof StringType stringCommand) {
+ String commandValue = stringCommand.toFullString();
String body = commandValue;
String title = null;
String speak = commandValue;
*/
@NonNullByDefault
public interface IEchoThingHandler extends IAmazonThingHandler {
+ @Override
void startAnnouncement(Device device, String speak, String bodyText, @Nullable String title,
@Nullable Integer volume) throws IOException, URISyntaxException;
}
String deviceName = null;
Map<String, Object> props = new HashMap<>();
- if (smartHomeDevice instanceof SmartHomeDevice) {
- SmartHomeDevice shd = (SmartHomeDevice) smartHomeDevice;
+ if (smartHomeDevice instanceof SmartHomeDevice shd) {
logger.trace("Found SmartHome device: {}", shd);
String entityId = shd.entityId;
// Connected through skill
continue;
}
- if (!(smartHomeDeviceDiscoveryMode == 2) && "openHAB".equalsIgnoreCase(shd.manufacturerName)) {
+ if (smartHomeDeviceDiscoveryMode != 2 && "openHAB".equalsIgnoreCase(shd.manufacturerName)) {
// OpenHAB device
continue;
}
deviceName = shd.friendlyName;
}
props.put(DEVICE_PROPERTY_ID, id);
- } else if (smartHomeDevice instanceof SmartHomeGroup) {
- SmartHomeGroup shg = (SmartHomeGroup) smartHomeDevice;
+ } else if (smartHomeDevice instanceof SmartHomeGroup shg) {
logger.trace("Found SmartHome device: {}", shg);
String id = shg.findId();
// create new id map
Map<String, SmartHomeBaseDevice> newJsonIdSmartHomeDeviceMapping = new HashMap<>();
for (Object smartHomeDevice : smartHomeDevices) {
- if (smartHomeDevice instanceof SmartHomeBaseDevice) {
- SmartHomeBaseDevice smartHomeBaseDevice = (SmartHomeBaseDevice) smartHomeDevice;
+ if (smartHomeDevice instanceof SmartHomeBaseDevice smartHomeBaseDevice) {
String id = smartHomeBaseDevice.findId();
if (id != null) {
newJsonIdSmartHomeDeviceMapping.put(id, smartHomeBaseDevice);
}
// Notification commands
if (channelId.equals(CHANNEL_NOTIFICATION_VOLUME)) {
- if (command instanceof PercentType) {
- int volume = ((PercentType) command).intValue();
+ if (command instanceof PercentType percentCommand) {
+ int volume = percentCommand.intValue();
connection.notificationVolume(device, volume);
this.notificationVolumeLevel = volume;
waitForUpdate = -1;
// Media progress commands
Long mediaPosition = null;
if (channelId.equals(CHANNEL_MEDIA_PROGRESS)) {
- if (command instanceof PercentType) {
- PercentType value = (PercentType) command;
- int percent = value.intValue();
+ if (command instanceof PercentType percentCommand) {
+ int percent = percentCommand.intValue();
mediaPosition = Math.round((mediaLengthMs / 1000d) * (percent / 100d));
}
}
if (channelId.equals(CHANNEL_MEDIA_PROGRESS_TIME)) {
- if (command instanceof DecimalType) {
- DecimalType value = (DecimalType) command;
- mediaPosition = value.longValue();
+ if (command instanceof DecimalType decimalCommand) {
+ mediaPosition = decimalCommand.longValue();
}
- if (command instanceof QuantityType<?>) {
- QuantityType<?> value = (QuantityType<?>) command;
+ if (command instanceof QuantityType<?> quantityCommand) {
@Nullable
- QuantityType<?> seconds = value.toUnit(Units.SECOND);
+ QuantityType<?> seconds = quantityCommand.toUnit(Units.SECOND);
if (seconds != null) {
mediaPosition = seconds.longValue();
}
// Volume commands
if (channelId.equals(CHANNEL_VOLUME)) {
Integer volume = null;
- if (command instanceof PercentType) {
- PercentType value = (PercentType) command;
- volume = value.intValue();
+ if (command instanceof PercentType percentCommand) {
+ volume = percentCommand.intValue();
} else if (command == OnOffType.OFF) {
volume = 0;
} else if (command == OnOffType.ON) {
// shuffle command
if (channelId.equals(CHANNEL_SHUFFLE)) {
- if (command instanceof OnOffType) {
- OnOffType value = (OnOffType) command;
+ if (command instanceof OnOffType value) {
connection.command(device, "{\"type\":\"ShuffleCommand\",\"shuffle\":\""
+ (value == OnOffType.ON ? "true" : "false") + "\"}");
// bluetooth commands
if (channelId.equals(CHANNEL_BLUETOOTH_MAC)) {
needBluetoothRefresh = true;
- if (command instanceof StringType) {
- String address = ((StringType) command).toFullString();
+ if (command instanceof StringType stringCommand) {
+ String address = stringCommand.toFullString();
if (!address.isEmpty()) {
waitForUpdate = 4000;
}
}
}
if (channelId.equals(CHANNEL_TEXT_TO_SPEECH_VOLUME)) {
- if (command instanceof PercentType) {
- PercentType value = (PercentType) command;
- textToSpeechVolume = value.intValue();
+ if (command instanceof PercentType percentCommand) {
+ textToSpeechVolume = percentCommand.intValue();
} else if (command == OnOffType.OFF) {
textToSpeechVolume = 0;
} else if (command == OnOffType.ON) {
if (command instanceof RefreshType) {
this.lastKnownEqualizer = null;
}
- if (command instanceof DecimalType) {
- DecimalType value = (DecimalType) command;
+ if (command instanceof DecimalType decimalCommand) {
if (this.lastKnownEqualizer == null) {
updateEqualizerState();
}
if (lastKnownEqualizer != null) {
JsonEqualizer newEqualizerSetting = lastKnownEqualizer.createClone();
if (channelId.equals(CHANNEL_EQUALIZER_BASS)) {
- newEqualizerSetting.bass = value.intValue();
+ newEqualizerSetting.bass = decimalCommand.intValue();
}
if (channelId.equals(CHANNEL_EQUALIZER_MIDRANGE)) {
- newEqualizerSetting.mid = value.intValue();
+ newEqualizerSetting.mid = decimalCommand.intValue();
}
if (channelId.equals(CHANNEL_EQUALIZER_TREBLE)) {
- newEqualizerSetting.treble = value.intValue();
+ newEqualizerSetting.treble = decimalCommand.intValue();
}
try {
connection.setEqualizer(device, newEqualizerSetting);
boolean stateFound = false;
Map<String, List<JsonObject>> mapInterfaceToStates = new HashMap<>();
SmartHomeDevice firstDevice = null;
- for (SmartHomeDevice shd : getSupportedSmartHomeDevices(smartHomeBaseDevice, allDevices)) {
- String applianceId = shd.applianceId;
+ for (SmartHomeDevice smartHomeDevice : getSupportedSmartHomeDevices(smartHomeBaseDevice, allDevices)) {
+ String applianceId = smartHomeDevice.applianceId;
if (applianceId == null) {
continue;
}
}
}
if (firstDevice == null) {
- firstDevice = shd;
+ firstDevice = smartHomeDevice;
}
for (JsonElement stateElement : states) {
String stateJson = stateElement.getAsString();
}
}
- if (result.needSingleUpdate && smartHomeBaseDevice instanceof SmartHomeDevice && accountHandler != null) {
- SmartHomeDevice shd = (SmartHomeDevice) smartHomeBaseDevice;
- accountHandler.forceDelayedSmartHomeStateUpdate(shd.findId());
+ if (result.needSingleUpdate && smartHomeBaseDevice instanceof SmartHomeDevice smartHomeDevice
+ && accountHandler != null) {
+ accountHandler.forceDelayedSmartHomeStateUpdate(smartHomeDevice.findId());
}
}
Bridge bridge = getBridge();
if (bridge != null) {
BridgeHandler bridgeHandler = bridge.getHandler();
- if (bridgeHandler instanceof AccountHandler) {
- return (AccountHandler) bridgeHandler;
+ if (bridgeHandler instanceof AccountHandler accountHandler) {
+ return accountHandler;
}
}
if (handlerBase == null || !handlerBase.hasChannel(channelId)) {
continue;
}
- for (SmartHomeDevice shd : devices) {
- String entityId = shd.entityId;
+ for (SmartHomeDevice smartHomeDevice : devices) {
+ String entityId = smartHomeDevice.entityId;
if (entityId == null) {
continue;
}
accountHandler.forceDelayedSmartHomeStateUpdate(getId()); // block updates
- if (handlerBase.handleCommand(connection, shd, entityId, shd.getCapabilities(), channelUID.getId(),
- command)) {
+ if (handlerBase.handleCommand(connection, smartHomeDevice, entityId,
+ smartHomeDevice.getCapabilities(), channelUID.getId(), command)) {
accountHandler.forceDelayedSmartHomeStateUpdate(getId()); // force update again to restart
// update timer
- logger.debug("Command {} sent to {}", command, shd.findId());
+ logger.debug("Command {} sent to {}", command, smartHomeDevice.findId());
}
}
}
private static void getCapabilities(Map<String, List<SmartHomeCapability>> result, AccountHandler accountHandler,
SmartHomeBaseDevice device) {
- if (device instanceof SmartHomeDevice) {
- SmartHomeDevice shd = (SmartHomeDevice) device;
- for (SmartHomeCapability capability : shd.getCapabilities()) {
+ if (device instanceof SmartHomeDevice smartHomeDevice) {
+ for (SmartHomeCapability capability : smartHomeDevice.getCapabilities()) {
String interfaceName = capability.interfaceName;
if (interfaceName != null) {
Objects.requireNonNull(result.computeIfAbsent(interfaceName, name -> new ArrayList<>()))
}
}
if (device instanceof SmartHomeGroup) {
- for (SmartHomeDevice shd : getSupportedSmartHomeDevices(device,
+ for (SmartHomeDevice smartHomeDevice : getSupportedSmartHomeDevices(device,
accountHandler.getLastKnownSmartHomeDevices())) {
- getCapabilities(result, accountHandler, shd);
+ getCapabilities(result, accountHandler, smartHomeDevice);
}
}
}
return Collections.emptySet();
}
Set<SmartHomeDevice> result = new HashSet<>();
- if (baseDevice instanceof SmartHomeDevice) {
- SmartHomeDevice shd = (SmartHomeDevice) baseDevice;
- if (shd.getCapabilities().stream().map(capability -> capability.interfaceName)
+ if (baseDevice instanceof SmartHomeDevice smartHomeDevice) {
+ if (smartHomeDevice.getCapabilities().stream().map(capability -> capability.interfaceName)
.anyMatch(SUPPORTED_INTERFACES::contains)) {
- result.add(shd);
+ result.add(smartHomeDevice);
}
} else {
- SmartHomeGroup shg = (SmartHomeGroup) baseDevice;
+ SmartHomeGroup smartHomeGroup = (SmartHomeGroup) baseDevice;
for (SmartHomeBaseDevice device : allDevices) {
- if (device instanceof SmartHomeDevice) {
- SmartHomeDevice shd = (SmartHomeDevice) device;
- JsonSmartHomeTags.JsonSmartHomeTag tags = shd.tags;
+ if (device instanceof SmartHomeDevice smartHomeDevice) {
+ JsonSmartHomeTags.JsonSmartHomeTag tags = smartHomeDevice.tags;
if (tags != null) {
JsonSmartHomeGroupIdentity.SmartHomeGroupIdentity tagNameToValueSetMap = tags.tagNameToValueSetMap;
- JsonSmartHomeGroupIdentifiers.SmartHomeGroupIdentifier applianceGroupIdentifier = shg.applianceGroupIdentifier;
+ JsonSmartHomeGroupIdentifiers.SmartHomeGroupIdentifier applianceGroupIdentifier = smartHomeGroup.applianceGroupIdentifier;
if (tagNameToValueSetMap != null) {
List<String> groupIdentity = Objects.requireNonNullElse(tagNameToValueSetMap.groupIdentity,
List.of());
if (applianceGroupIdentifier != null && applianceGroupIdentifier.value != null
&& groupIdentity.contains(applianceGroupIdentifier.value)) {
- if (shd.getCapabilities().stream().map(capability -> capability.interfaceName)
+ if (smartHomeDevice.getCapabilities().stream()
+ .map(capability -> capability.interfaceName)
.anyMatch(SUPPORTED_INTERFACES::contains)) {
- result.add(shd);
+ result.add(smartHomeDevice);
}
}
}
return null;
}
ThingHandler handler = thing.getHandler();
- if (!(handler instanceof SmartHomeDeviceHandler)) {
- return null;
+ if (handler instanceof SmartHomeDeviceHandler smartHomeHandler) {
+ return smartHomeHandler;
}
- SmartHomeDeviceHandler smartHomeHandler = (SmartHomeDeviceHandler) handler;
- return smartHomeHandler;
+ return null;
}
@Override
private void handleError(String event, Object... args) {
String reason = "Unknown";
if (args.length > 0) {
- if (args[0] instanceof String) {
- reason = (String) args[0];
- } else if (args[0] instanceof Exception) {
- reason = String.format("Exception=%s Message=%s", args[0].getClass(),
- ((Exception) args[0]).getMessage());
+ if (args[0] instanceof String stringArg) {
+ reason = stringArg;
+ } else if (args[0] instanceof Exception exception) {
+ reason = String.format("Exception=%s Message=%s", args[0].getClass(), exception.getMessage());
}
}
logger.debug("Listener: Received socket event: {}, Reason: {}", event, reason);
@Override
public String toString() {
- return String.valueOf(value);
+ return value;
}
public static StreamCommand fromValue(String value) {
}
break;
case AmpliPiBindingConstants.CHANNEL_VOLUME:
- if (command instanceof PercentType) {
- update.setVolDelta(AmpliPiUtils.percentTypeToVolume((PercentType) command));
+ if (command instanceof PercentType percentCommand) {
+ update.setVolDelta(AmpliPiUtils.percentTypeToVolume(percentCommand));
} else if (command instanceof IncreaseDecreaseType) {
if (groupState != null) {
if (IncreaseDecreaseType.INCREASE.equals(command)) {
}
break;
case AmpliPiBindingConstants.CHANNEL_SOURCE:
- if (command instanceof DecimalType) {
- update.setSourceId(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ update.setSourceId(decimalCommand.intValue());
}
break;
}
if (bridgeHandler != null) {
String url = bridgeHandler.getUrl() + "/api/groups/" + getId(thing);
- ;
StringContentProvider contentProvider = new StringContentProvider(gson.toJson(update));
try {
ContentResponse response = httpClient.newRequest(url).method(HttpMethod.PATCH)
if (CHANNEL_PRESET.equals(channelUID.getId())) {
if (command instanceof RefreshType) {
updateState(channelUID, UnDefType.NULL);
- } else if (command instanceof DecimalType) {
- DecimalType preset = (DecimalType) command;
+ } else if (command instanceof DecimalType decimalCommand) {
try {
ContentResponse response = this.httpClient
- .newRequest(url + "/api/presets/" + preset.intValue() + "/load").method(HttpMethod.POST)
- .timeout(REQUEST_TIMEOUT, TimeUnit.MILLISECONDS).send();
+ .newRequest(url + "/api/presets/" + decimalCommand.intValue() + "/load")
+ .method(HttpMethod.POST).timeout(REQUEST_TIMEOUT, TimeUnit.MILLISECONDS).send();
if (response.getStatus() != HttpStatus.OK_200) {
logger.error("AmpliPi API returned HTTP status {}.", response.getStatus());
logger.debug("Content: {}", response.getContentAsString());
}
}
} else if (channelUID.getId().startsWith(CHANNEL_INPUT)) {
- if (command instanceof StringType) {
- StringType input = (StringType) command;
+ if (command instanceof StringType stringCommand) {
int source = Integer.valueOf(channelUID.getId().substring(CHANNEL_INPUT.length())) - 1;
SourceUpdate update = new SourceUpdate();
- update.setInput(input.toString());
+ update.setInput(stringCommand.toString());
try {
StringContentProvider contentProvider = new StringContentProvider(gson.toJson(update));
ContentResponse response = this.httpClient.newRequest(url + "/api/sources/" + source)
}
break;
case AmpliPiBindingConstants.CHANNEL_VOLUME:
- if (command instanceof PercentType) {
- update.setVol(AmpliPiUtils.percentTypeToVolume((PercentType) command));
+ if (command instanceof PercentType percentCommand) {
+ update.setVol(AmpliPiUtils.percentTypeToVolume(percentCommand));
} else if (command instanceof IncreaseDecreaseType) {
if (zoneState != null) {
if (IncreaseDecreaseType.INCREASE.equals(command)) {
}
break;
case AmpliPiBindingConstants.CHANNEL_SOURCE:
- if (command instanceof DecimalType) {
- update.setSourceId(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ update.setSourceId(decimalCommand.intValue());
}
break;
}
}
private @Nullable String getLabel(Stream stream) {
- if (stream.getType().equals("internetradio")) {
+ if ("internetradio".equals(stream.getType())) {
return stream.getName();
} else {
return stream.getType().substring(0, 1).toUpperCase() + stream.getType().substring(1);
public @Nullable DiscoveryResult createResult(ServiceInfo service) {
ThingUID uid = getThingUID(service);
if (uid != null) {
- DiscoveryResult result = DiscoveryResultBuilder.create(uid).withLabel("AmpliPi Controller")
+ return DiscoveryResultBuilder.create(uid).withLabel("AmpliPi Controller")
.withProperty(AmpliPiBindingConstants.CFG_PARAM_HOSTNAME, getIpAddress(service).getHostAddress())
.withRepresentationProperty(AmpliPiBindingConstants.CFG_PARAM_HOSTNAME).build();
- return result;
} else {
return null;
}
if (service.getName().equals(AMPLIPI_API)) {
InetAddress ip = getIpAddress(service);
if (ip != null) {
- String id = ip.toString().substring(1).replaceAll("\\.", "");
+ String id = ip.toString().substring(1).replace(".", "");
return new ThingUID(AmpliPiBindingConstants.THING_TYPE_CONTROLLER, id);
}
}
AndroidDebugBridgeDeviceReadException, TimeoutException, ExecutionException {
if (isAtLeastVersion(12)) {
String devicesResp = runAdbShell("getprop", "debug.tracing.screen_state");
- return devicesResp.replace("\n", "").equals("2");
+ return "2".equals(devicesResp.replace("\n", ""));
}
String devicesResp = runAdbShell("dumpsys", "power", "|", "grep", "'Display Power'");
if (devicesResp.contains("=")) {
try {
var state = devicesResp.split("=")[1].trim();
- return state.equals("ON");
+ return "ON".equals(state);
} catch (NumberFormatException e) {
logger.debug("Unable to parse device screen state: {}", e.getMessage());
}
String brand, String macAddress) {
String friendlyName = String.format("%s (%s)", model, ip);
thingDiscovered(
- DiscoveryResultBuilder.create(new ThingUID(THING_TYPE_ANDROID_DEVICE, macAddress.replaceAll(":", ""))) //
+ DiscoveryResultBuilder.create(new ThingUID(THING_TYPE_ANDROID_DEVICE, macAddress.replace(":", ""))) //
.withProperties(Map.of( //
PARAMETER_IP, ip, //
PARAMETER_PORT, port, //
public @Nullable ThingUID getThingUID(ServiceInfo service) {
String macAddress = service.getPropertyString(MDNS_PROPERTY_MAC_ADDRESS);
if (macAddress != null && !macAddress.isBlank()) {
- return new ThingUID(THING_TYPE_ANDROID_DEVICE, macAddress.replaceAll(":", "").toLowerCase());
+ return new ThingUID(THING_TYPE_ANDROID_DEVICE, macAddress.replace(":", "").toLowerCase());
}
return null;
}
public @Nullable ThingUID getThingUID(ServiceInfo service) {
String macAddress = service.getPropertyString(MDNS_PROPERTY_MAC_ADDRESS);
if (macAddress != null && !macAddress.isBlank()) {
- return new ThingUID(THING_TYPE_ANDROID_DEVICE, macAddress.replaceAll(":", "").toLowerCase());
+ return new ThingUID(THING_TYPE_ANDROID_DEVICE, macAddress.replace(":", "").toLowerCase());
}
return null;
}
private void assertTemperature(@Nullable State state, double value) {
assertThat(state, isA(QuantityType.class));
- if (state instanceof QuantityType<?>) {
- assertThat(((QuantityType<?>) state).doubleValue(), closeTo(value, 0.0001d));
+ if (state instanceof QuantityType<?> temperature) {
+ assertThat(temperature.doubleValue(), closeTo(value, 0.0001d));
}
}
}
// toggle state of switch 1
final String auth = AnelAuthentication.getUserPasswordString(USER, PASSWORD, AuthMethod.of(status));
- final String command = "Sw_" + (switch1state ? "off" : "on") + String.valueOf(switchNr) + auth;
+ final String command = "Sw_" + (switch1state ? "off" : "on") + switchNr + auth;
final String status2 = sendAndReceiveSingle(command);
// assert new state of switch 1
@NonNullByDefault
public interface IAnelTestStatus {
- String STATUS_INVALID_NAME = "NET-PwrCtrl:NET-CONTROL :192.168.6.63:255.255.255.0:192.168.6.1:0.4.163.21.4.71:"
- + "Nr. 1,0:Nr. 2,1:Nr: 3,1:Nr. 4,0:Nr. 5,0:Nr. 6,0:Nr. 7,0:Nr. 8,0:248:80:NET-PWRCTRL_04.6:H:xor:";
- String STATUS_HUT_V61_POW = "NET-PwrCtrl:NET-CONTROL :192.168.178.148:255.255.255.0:192.168.178.1:0.4.163.10.9.107:"
- + "Nr. 1,1:Nr. 2,1:Nr. 3,1:Nr. 4,0:Nr. 5,0:Nr. 6,0:Nr. 7,1:Nr. 8,1:0:80:"
- + "IO-1,0,0:IO-2,0,0:IO-3,0,0:IO-4,0,0:IO-5,0,0:IO-6,0,0:IO-7,0,0:IO-8,0,0:27.7°C:NET-PWRCTRL_06.1:h:"
- + "p:225.9:0.0004:50.056:0.04:0.00:0.0:1.0000:xor:";
- String STATUS_HUT_V61_SENSOR = "NET-PwrCtrl:NET-CONTROL :192.168.178.148:255.255.255.0:192.168.178.1:0.4.163.10.9.107:"
- + "Nr. 1,1:Nr. 2,1:Nr. 3,1:Nr. 4,0:Nr. 5,0:Nr. 6,0:Nr. 7,1:Nr. 8,1:0:80:"
- + "IO-1,0,0:IO-2,0,0:IO-3,0,0:IO-4,0,0:IO-5,0,0:IO-6,0,0:IO-7,0,0:IO-8,0,0:27.7°C:NET-PWRCTRL_06.1:h:"
- + "n:s:20.61:40.7:7.0:xor:";
- String STATUS_HUT_V61_POW_SENSOR = "NET-PwrCtrl:NET-CONTROL :192.168.178.148:255.255.255.0:192.168.178.1:0.4.163.10.9.107:"
- + "Nr. 1,1:Nr. 2,1:Nr. 3,1:Nr. 4,0:Nr. 5,0:Nr. 6,0:Nr. 7,1:Nr. 8,1:0:80:"
- + "IO-1,0,0:IO-2,0,0:IO-3,0,0:IO-4,0,0:IO-5,0,0:IO-6,0,0:IO-7,0,0:IO-8,0,0:27.7°C:NET-PWRCTRL_06.1:h:"
- + "p:225.9:0.0004:50.056:0.04:0.00:0.0:1.0000:s:20.61:40.7:7.0:xor";
- String STATUS_HUT_V5 = "NET-PwrCtrl:ANEL1 :192.168.0.244:255.255.255.0:192.168.0.1:0.5.163.14.7.91:"
- + "hoch,0:links hoch,0:runter,0:rechts run,0:runter,0:hoch,0:links runt,0:rechts hoc,0:0:80:"
- + "WHN_UP,1,1:LI_DOWN,1,1:RE_DOWN,1,1:LI_UP,1,1:RE_UP,1,1:DOWN,1,1:DOWN,1,1:UP,1,1:27.3°C:NET-PWRCTRL_05.0";
- String STATUS_HUT_V65 = "NET-PwrCtrl:NET-CONTROL :192.168.0.64:255.255.255.0:192.168.6.1:0.5.163.17.9.116:"
- + "Nr.1,0:Nr.2,1:Nr.3,0:Nr.4,1:Nr.5,0:Nr.6,1:Nr.7,0:Nr.8,1:248:80:"
- + "IO-1,0,0:IO-2,0,0:IO-3,0,0:IO-4,0,0:IO-5,1,0:IO-6,1,0:IO-7,1,0:IO-8,1,0:27.0�C:NET-PWRCTRL_06.5:h:n:xor:";
- String STATUS_HOME_V46 = "NET-PwrCtrl:NET-CONTROL :192.168.0.63:255.255.255.0:192.168.6.1:0.5.163.21.4.71:"
- + "Nr. 1,1:Nr. 2,0:Nr. 3,1:Nr. 4,0:Nr. 5,1:Nr. 6,0:Nr. 7,1:Nr. 8,0:248:80:NET-PWRCTRL_04.6:H:xor:";
+ String STATUS_INVALID_NAME = """
+ NET-PwrCtrl:NET-CONTROL :192.168.6.63:255.255.255.0:192.168.6.1:0.4.163.21.4.71:\
+ Nr. 1,0:Nr. 2,1:Nr: 3,1:Nr. 4,0:Nr. 5,0:Nr. 6,0:Nr. 7,0:Nr. 8,0:248:80:NET-PWRCTRL_04.6:H:xor:\
+ """;
+ String STATUS_HUT_V61_POW = """
+ NET-PwrCtrl:NET-CONTROL :192.168.178.148:255.255.255.0:192.168.178.1:0.4.163.10.9.107:\
+ Nr. 1,1:Nr. 2,1:Nr. 3,1:Nr. 4,0:Nr. 5,0:Nr. 6,0:Nr. 7,1:Nr. 8,1:0:80:\
+ IO-1,0,0:IO-2,0,0:IO-3,0,0:IO-4,0,0:IO-5,0,0:IO-6,0,0:IO-7,0,0:IO-8,0,0:27.7°C:NET-PWRCTRL_06.1:h:\
+ p:225.9:0.0004:50.056:0.04:0.00:0.0:1.0000:xor:\
+ """;
+ String STATUS_HUT_V61_SENSOR = """
+ NET-PwrCtrl:NET-CONTROL :192.168.178.148:255.255.255.0:192.168.178.1:0.4.163.10.9.107:\
+ Nr. 1,1:Nr. 2,1:Nr. 3,1:Nr. 4,0:Nr. 5,0:Nr. 6,0:Nr. 7,1:Nr. 8,1:0:80:\
+ IO-1,0,0:IO-2,0,0:IO-3,0,0:IO-4,0,0:IO-5,0,0:IO-6,0,0:IO-7,0,0:IO-8,0,0:27.7°C:NET-PWRCTRL_06.1:h:\
+ n:s:20.61:40.7:7.0:xor:\
+ """;
+ String STATUS_HUT_V61_POW_SENSOR = """
+ NET-PwrCtrl:NET-CONTROL :192.168.178.148:255.255.255.0:192.168.178.1:0.4.163.10.9.107:\
+ Nr. 1,1:Nr. 2,1:Nr. 3,1:Nr. 4,0:Nr. 5,0:Nr. 6,0:Nr. 7,1:Nr. 8,1:0:80:\
+ IO-1,0,0:IO-2,0,0:IO-3,0,0:IO-4,0,0:IO-5,0,0:IO-6,0,0:IO-7,0,0:IO-8,0,0:27.7°C:NET-PWRCTRL_06.1:h:\
+ p:225.9:0.0004:50.056:0.04:0.00:0.0:1.0000:s:20.61:40.7:7.0:xor\
+ """;
+ String STATUS_HUT_V5 = """
+ NET-PwrCtrl:ANEL1 :192.168.0.244:255.255.255.0:192.168.0.1:0.5.163.14.7.91:\
+ hoch,0:links hoch,0:runter,0:rechts run,0:runter,0:hoch,0:links runt,0:rechts hoc,0:0:80:\
+ WHN_UP,1,1:LI_DOWN,1,1:RE_DOWN,1,1:LI_UP,1,1:RE_UP,1,1:DOWN,1,1:DOWN,1,1:UP,1,1:27.3°C:NET-PWRCTRL_05.0\
+ """;
+ String STATUS_HUT_V65 = """
+ NET-PwrCtrl:NET-CONTROL :192.168.0.64:255.255.255.0:192.168.6.1:0.5.163.17.9.116:\
+ Nr.1,0:Nr.2,1:Nr.3,0:Nr.4,1:Nr.5,0:Nr.6,1:Nr.7,0:Nr.8,1:248:80:\
+ IO-1,0,0:IO-2,0,0:IO-3,0,0:IO-4,0,0:IO-5,1,0:IO-6,1,0:IO-7,1,0:IO-8,1,0:27.0�C:NET-PWRCTRL_06.5:h:n:xor:\
+ """;
+ String STATUS_HOME_V46 = """
+ NET-PwrCtrl:NET-CONTROL :192.168.0.63:255.255.255.0:192.168.6.1:0.5.163.21.4.71:\
+ Nr. 1,1:Nr. 2,0:Nr. 3,1:Nr. 4,0:Nr. 5,1:Nr. 6,0:Nr. 7,1:Nr. 8,0:248:80:NET-PWRCTRL_04.6:H:xor:\
+ """;
}
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
- logger.trace("Command {} received for channel {}", command, channelUID.getId().toString());
+ logger.trace("Command {} received for channel {}", command, channelUID.getId());
String groupId = channelUID.getGroupId();
if (groupId == null) {
return;
}
break;
case CHANNEL_VOLUME_DB:
- if (command instanceof DecimalType) {
- sendCommand(AnthemCommand.volume(zone, ((DecimalType) command).intValue()));
+ if (command instanceof DecimalType decimalCommand) {
+ sendCommand(AnthemCommand.volume(zone, decimalCommand.intValue()));
}
break;
case CHANNEL_MUTE:
}
break;
case CHANNEL_ACTIVE_INPUT:
- if (command instanceof DecimalType) {
- sendCommand(AnthemCommand.activeInput(zone, ((DecimalType) command).intValue()));
+ if (command instanceof DecimalType decimalCommand) {
+ sendCommand(AnthemCommand.activeInput(zone, decimalCommand.intValue()));
}
break;
default:
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof AstroThingHandler) {
- this.handler = (AstroThingHandler) handler;
+ if (handler instanceof AstroThingHandler thingHandler) {
+ this.handler = thingHandler;
}
}
try {
AstroThingHandler theHandler = this.handler;
if (theHandler != null) {
- if (theHandler instanceof SunHandler) {
- SunHandler handler = (SunHandler) theHandler;
+ if (theHandler instanceof SunHandler sunHandler) {
SunPhaseName phase = SunPhaseName.valueOf(phaseName.toUpperCase());
- return handler.getEventTime(phase, date != null ? date : ZonedDateTime.now(),
+ return sunHandler.getEventTime(phase, date != null ? date : ZonedDateTime.now(),
moment == null || AstroBindingConstants.EVENT_START.equalsIgnoreCase(moment));
} else {
logger.info("Astro Action service ThingHandler is not a SunHandler!");
double m1 = 134.9634114 + 477198.8676313 * t + .008997 * t * t + t * t * t / 69699 - t * t * t * t / 14712000;
double f = 93.27209929999999 + 483202.0175273 * t - .0034029 * t * t - t * t * t / 3526000
+ t * t * t * t / 863310000;
- double sr = 385000.56 + getCoefficient(d, m, m1, f) / 1000;
- return sr;
+ return 385000.56 + getCoefficient(d, m, m1, f) / 1000;
}
private double[] calcMoon(double t) {
private double SINALT(double moonJd, int hour, double lambda, double cphi, double sphi) {
double jdo = moonJd + hour / 24.0;
double t = (jdo - 51544.5) / 36525.0;
- double decra[] = calcMoon(t);
+ double[] decra = calcMoon(t);
double tau = 15.0 * (LMST(jdo, lambda) - decra[1]);
return sphi * SN(decra[0]) + cphi * CS(decra[0]) * CS(tau);
}
double moonLon = mod2Pi(n2 + Math.atan2(Math.sin(l3 - n2) * Math.cos(i), Math.cos(l3 - n2)));
double moonLat = Math.asin(Math.sin(l3 - n2) * Math.sin(i));
- double raDec[] = ecl2Equ(moonLat, moonLon, julianDate);
+ double[] raDec = ecl2Equ(moonLat, moonLon, julianDate);
double distance = (1 - 0.00301401) / (1 + 0.054900 * Math.cos(mMoon2 + ec)) * 384401;
- double raDecTopo[] = geoEqu2TopoEqu(raDec, distance, lat, lmst);
- double azAlt[] = equ2AzAlt(raDecTopo[0], raDecTopo[1], lat, lmst);
+ double[] raDecTopo = geoEqu2TopoEqu(raDec, distance, lat, lmst);
+ double[] azAlt = equ2AzAlt(raDecTopo[0], raDecTopo[1], lat, lmst);
Position position = moon.getPosition();
position.setAzimuth(azAlt[0] * SunCalc.RAD2DEG);
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
-import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singletonList(AstroActions.class);
+ return List.of(AstroActions.class);
}
}
*/
package org.openhab.binding.astro.internal.job;
-import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toList;
import static org.openhab.binding.astro.internal.AstroBindingConstants.*;
import static org.openhab.binding.astro.internal.util.DateTimeUtils.*;
*/
static void scheduleEvent(String thingUID, AstroThingHandler astroHandler, Calendar eventAt, String event,
String channelId, boolean configAlreadyApplied) {
- scheduleEvent(thingUID, astroHandler, eventAt, singletonList(event), channelId, configAlreadyApplied);
+ scheduleEvent(thingUID, astroHandler, eventAt, List.of(event), channelId, configAlreadyApplied);
}
/**
Channel phaseNameChannel = astroHandler.getThing().getChannel(CHANNEL_ID_SUN_PHASE_NAME);
if (phaseNameChannel != null) {
Planet planet = astroHandler.getPlanet();
- if (planet != null && planet instanceof Sun) {
- final Sun typedSun = (Sun) planet;
- typedSun.getPhase().setName(sunPhaseName);
+ if (planet instanceof Sun theSun) {
+ theSun.getPhase().setName(sunPhaseName);
astroHandler.publishChannelIfLinked(phaseNameChannel.getUID());
}
} else {
public enum EclipseKind {
PARTIAL,
TOTAL,
- RING;
+ RING
}
@NonNullByDefault
public enum EclipseType {
SUN,
- MOON;
+ MOON
}
Object value = getPropertyValue(channelUID, instance);
if (value == null) {
return UnDefType.UNDEF;
- } else if (value instanceof State) {
- return (State) value;
- } else if (value instanceof Calendar) {
- Calendar cal = (Calendar) value;
+ } else if (value instanceof State state) {
+ return state;
+ } else if (value instanceof Calendar cal) {
GregorianCalendar gregorianCal = (GregorianCalendar) DateTimeUtils.applyConfig(cal, config);
cal.setTimeZone(TimeZone.getTimeZone(zoneId));
ZonedDateTime zoned = gregorianCal.toZonedDateTime().withFixedOffsetZone();
import static org.openhab.binding.atlona.internal.AtlonaBindingConstants.*;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
ThingTypeUID thingTypeUID = thing.getThingTypeUID();
if (thingTypeUID.equals(THING_TYPE_PRO3_44M)) {
- return new AtlonaPro3Handler(thing, new AtlonaPro3Capabilities(5, 3, Collections.singleton(5), true));
+ return new AtlonaPro3Handler(thing, new AtlonaPro3Capabilities(5, 3, Set.of(5), true));
}
if (thingTypeUID.equals(THING_TYPE_PRO3_66M)) {
String name = msg.substring(0, idx);
if ("Host".equalsIgnoreCase(name)) {
- host = msg.substring(idx + 1).trim().replaceAll("\"", "");
+ host = msg.substring(idx + 1).trim().replace("\"", "");
int sep = host.indexOf('_');
if (sep >= 0) {
host = host.substring(sep + 1);
}
} else if ("Model".equalsIgnoreCase(name)) {
- model = msg.substring(idx + 1).trim().replaceAll("\"", "");
+ model = msg.substring(idx + 1).trim().replace("\"", "");
} else if ("Manufacturer".equalsIgnoreCase(name)) {
- manufacturer = msg.substring(idx + 1).trim().replaceAll("\"", "");
+ manufacturer = msg.substring(idx + 1).trim().replace("\"", "");
} else if ("From".equalsIgnoreCase(name)) {
- from = msg.substring(idx + 1).trim().replaceAll("\"", "");
+ from = msg.substring(idx + 1).trim().replace("\"", "");
int sep = from.indexOf(':');
if (sep >= 0) {
from = from.substring(0, sep);
final Object response = responses.poll(1, TimeUnit.SECONDS);
if (response != null) {
- if (response instanceof String) {
+ if (response instanceof String stringResponse) {
try {
logger.debug("Dispatching response: {}", response);
final SocketSessionListener[] listeners = SocketChannelSession.this.listeners
.toArray(new SocketSessionListener[0]);
for (SocketSessionListener listener : listeners) {
- listener.responseReceived((String) response);
+ listener.responseReceived(stringResponse);
}
} catch (Exception e) {
logger.warn("Exception occurred processing the response '{}': ", response, e);
}
- } else if (response instanceof Exception) {
+ } else if (response instanceof Exception exceptionResponse) {
logger.debug("Dispatching exception: {}", response);
final SocketSessionListener[] listeners = SocketChannelSession.this.listeners
.toArray(new SocketSessionListener[0]);
for (SocketSessionListener listener : listeners) {
- listener.responseException((Exception) response);
+ listener.responseException(exceptionResponse);
}
} else {
logger.warn("Unknown response class: {}", response);
if ((m = GROUP_PRIMARY_PATTERN.matcher(group)).matches()) {
switch (id) {
case AtlonaPro3Constants.CHANNEL_POWER:
- if (command instanceof OnOffType) {
- final boolean makeOn = ((OnOffType) command) == OnOffType.ON;
+ if (command instanceof OnOffType onOffCommand) {
+ final boolean makeOn = onOffCommand == OnOffType.ON;
atlonaHandler.setPower(makeOn);
} else {
logger.debug("Received a POWER channel command with a non OnOffType: {}", command);
break;
case AtlonaPro3Constants.CHANNEL_PANELLOCK:
- if (command instanceof OnOffType) {
- final boolean makeOn = ((OnOffType) command) == OnOffType.ON;
+ if (command instanceof OnOffType onOffCommand) {
+ final boolean makeOn = onOffCommand == OnOffType.ON;
atlonaHandler.setPanelLock(makeOn);
} else {
logger.debug("Received a PANELLOCK channel command with a non OnOffType: {}", command);
break;
case AtlonaPro3Constants.CHANNEL_IRENABLE:
- if (command instanceof OnOffType) {
- final boolean makeOn = ((OnOffType) command) == OnOffType.ON;
+ if (command instanceof OnOffType onOffCommand) {
+ final boolean makeOn = onOffCommand == OnOffType.ON;
atlonaHandler.setIrOn(makeOn);
} else {
logger.debug("Received an IRLOCK channel command with a non OnOffType: {}", command);
switch (id) {
case AtlonaPro3Constants.CHANNEL_PORTOUTPUT:
- if (command instanceof DecimalType) {
- final int inpNbr = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ final int inpNbr = decimalCommand.intValue();
atlonaHandler.setPortSwitch(inpNbr, portNbr);
} else {
logger.debug("Received a PORTOUTPUT channel command with a non DecimalType: {}",
break;
case AtlonaPro3Constants.CHANNEL_PORTPOWER:
- if (command instanceof OnOffType) {
- final boolean makeOn = ((OnOffType) command) == OnOffType.ON;
+ if (command instanceof OnOffType onOffCommand) {
+ final boolean makeOn = onOffCommand == OnOffType.ON;
atlonaHandler.setPortPower(portNbr, makeOn);
} else {
logger.debug("Received a PORTPOWER channel command with a non OnOffType: {}", command);
switch (id) {
case AtlonaPro3Constants.CHANNEL_PORTMIRROR:
- if (command instanceof DecimalType) {
- final int outPortNbr = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ final int outPortNbr = decimalCommand.intValue();
if (outPortNbr <= 0) {
atlonaHandler.removePortMirror(hdmiPortNbr);
} else {
.getCallback();
final State state = callback.getState(AtlonaPro3Constants.CHANNEL_PORTMIRROR);
int outPortNbr = 1;
- if (state != null && state instanceof DecimalType) {
- outPortNbr = ((DecimalType) state).intValue();
+ if (state instanceof DecimalType decimalCommand) {
+ outPortNbr = decimalCommand.intValue();
}
atlonaHandler.setPortMirror(hdmiPortNbr, outPortNbr);
} else {
switch (id) {
case AtlonaPro3Constants.CHANNEL_VOLUME_MUTE:
- if (command instanceof OnOffType) {
- atlonaHandler.setVolumeMute(portNbr, ((OnOffType) command) == OnOffType.ON);
+ if (command instanceof OnOffType onOffCommand) {
+ atlonaHandler.setVolumeMute(portNbr, onOffCommand == OnOffType.ON);
} else {
logger.debug("Received a VOLUME MUTE channel command with a non OnOffType: {}",
command);
break;
case AtlonaPro3Constants.CHANNEL_VOLUME:
- if (command instanceof DecimalType) {
- final int level = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ final int level = decimalCommand.intValue();
atlonaHandler.setVolume(portNbr, level);
} else {
logger.debug("Received a VOLUME channel command with a non DecimalType: {}", command);
*/
String getResponse() throws Exception {
final Object lastResponse = responses.poll(5, TimeUnit.SECONDS);
- if (lastResponse instanceof String) {
- return (String) lastResponse;
- } else if (lastResponse instanceof Exception) {
- throw (Exception) lastResponse;
+ if (lastResponse instanceof String stringResponse) {
+ return stringResponse;
+ } else if (lastResponse instanceof Exception exceptionResponse) {
+ throw exceptionResponse;
} else if (lastResponse == null) {
throw new Exception("Didn't receive response in time");
} else {
device.getDetails().getModelDetails().getModelNumber());
if (device.getDetails().getManufacturerDetails().getManufacturer().toLowerCase().startsWith(MANUFACTURER)) {
logger.debug("Autelis Pool Control Found at {}", device.getDetails().getBaseURL());
- String id = device.getIdentity().getUdn().getIdentifierString().replaceAll(":", "").toUpperCase();
+ String id = device.getIdentity().getUdn().getIdentifierString().replace(":", "").toUpperCase();
if (device.getDetails().getModelDetails().getModelNumber().toLowerCase().startsWith(MODEL_PENTAIR)) {
return new ThingUID(AutelisBindingConstants.PENTAIR_THING_TYPE_UID, id);
}
import static org.openhab.binding.automower.internal.AutomowerBindingConstants.THING_TYPE_BRIDGE;
-import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
private static final String HUSQVARNA_API_TOKEN_URL = "https://api.authentication.husqvarnagroup.dev/v1/oauth2/token";
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_BRIDGE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BRIDGE);
private static final long DEFAULT_POLLING_INTERVAL_S = TimeUnit.HOURS.toSeconds(1);
private final OAuthFactory oAuthFactory;
import static org.openhab.binding.automower.internal.AutomowerBindingConstants.THING_TYPE_AUTOMOWER;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.automower.internal.AutomowerBindingConstants;
private final AutomowerBridgeHandler bridgeHandler;
public AutomowerDiscoveryService(AutomowerBridgeHandler bridgeHandler) {
- super(Collections.singleton(THING_TYPE_AUTOMOWER), 10, false);
+ super(Set.of(THING_TYPE_AUTOMOWER), 10, false);
this.bridgeHandler = bridgeHandler;
}
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
*/
@NonNullByDefault
public class AutomowerHandler extends BaseThingHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_AUTOMOWER);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_AUTOMOWER);
private static final String NO_ID = "NO_ID";
private static final long DEFAULT_COMMAND_DURATION_MIN = 60;
private static final long DEFAULT_POLLING_INTERVAL_S = TimeUnit.MINUTES.toSeconds(10);
}
private Optional<Integer> getCommandValue(Type type) {
- if (type instanceof DecimalType) {
- return Optional.of(((DecimalType) type).intValue());
+ if (type instanceof DecimalType command) {
+ return Optional.of(command.intValue());
}
return Optional.empty();
}
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(AutomowerActions.class);
+ return Set.of(AutomowerActions.class);
}
@Override
Bridge bridge = getBridge();
if (bridge != null) {
ThingHandler handler = bridge.getHandler();
- if (handler instanceof AutomowerBridgeHandler) {
- AutomowerBridgeHandler bridgeHandler = (AutomowerBridgeHandler) handler;
+ if (handler instanceof AutomowerBridgeHandler bridgeHandler) {
return bridgeHandler.getAutomowerBridge();
}
}
@Override
public void setThingHandler(@NonNullByDefault({}) ThingHandler handler) {
- if (handler instanceof AVMFritzBaseBridgeHandler) {
- bridgeHandler = (AVMFritzBaseBridgeHandler) handler;
+ if (handler instanceof AVMFritzBaseBridgeHandler baseBridgeHandler) {
+ bridgeHandler = baseBridgeHandler;
}
}
properties.put(PRODUCT_NAME, device.getProductName());
properties.put(PROPERTY_SERIAL_NUMBER, device.getIdentifier());
properties.put(PROPERTY_FIRMWARE_VERSION, device.getFirmwareVersion());
- if (device instanceof GroupModel && ((GroupModel) device).getGroupinfo() != null) {
- properties.put(PROPERTY_MASTER, ((GroupModel) device).getGroupinfo().getMasterdeviceid());
- properties.put(PROPERTY_MEMBERS, ((GroupModel) device).getGroupinfo().getMembers());
+ if (device instanceof GroupModel model && model.getGroupinfo() != null) {
+ properties.put(PROPERTY_MASTER, model.getGroupinfo().getMasterdeviceid());
+ properties.put(PROPERTY_MEMBERS, model.getGroupinfo().getMembers());
}
DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID).withProperties(properties)
import java.util.Arrays;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
- if (childHandler instanceof FritzAhaStatusListener) {
- registerStatusListener((FritzAhaStatusListener) childHandler);
+ if (childHandler instanceof FritzAhaStatusListener listener) {
+ registerStatusListener(listener);
}
}
@Override
public void childHandlerDisposed(ThingHandler childHandler, Thing childThing) {
- if (childHandler instanceof FritzAhaStatusListener) {
- unregisterStatusListener((FritzAhaStatusListener) childHandler);
+ if (childHandler instanceof FritzAhaStatusListener listener) {
+ unregisterStatusListener(listener);
}
}
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(AVMFritzDiscoveryService.class);
+ return Set.of(AVMFritzDiscoveryService.class);
}
public boolean registerStatusListener(FritzAhaStatusListener listener) {
} else if (device.isSwitchableOutlet()) {
return GROUP_SWITCH;
}
- } else if (device instanceof DeviceModel && device.isHANFUNUnit()) {
+ } else if (device instanceof DeviceModel deviceModel && device.isHANFUNUnit()) {
if (device.isHANFUNBlinds()) {
return DEVICE_HAN_FUN_BLINDS;
} else if (device.isColorLight()) {
} else if (device.isDimmableLight()) {
return DEVICE_HAN_FUN_DIMMABLE_BULB;
}
- List<String> interfaces = Arrays
- .asList(((DeviceModel) device).getEtsiunitinfo().getInterfaces().split(","));
+ List<String> interfaces = Arrays.asList(deviceModel.getEtsiunitinfo().getInterfaces().split(","));
if (interfaces.contains(HAN_FUN_INTERFACE_ALERT)) {
return DEVICE_HAN_FUN_CONTACT;
} else if (interfaces.contains(HAN_FUN_INTERFACE_SIMPLE_BUTTON)) {
if (device.isHeatingThermostat()) {
updateHeatingThermostat(device.getHkr());
}
- if (device instanceof DeviceModel) {
- DeviceModel deviceModel = (DeviceModel) device;
+ if (device instanceof DeviceModel deviceModel) {
if (deviceModel.isTemperatureSensor()) {
updateTemperatureSensor(deviceModel.getTemperature());
}
case CHANNEL_COLOR:
case CHANNEL_BRIGHTNESS:
BigDecimal brightness = null;
- if (command instanceof HSBType) {
- HSBType hsbType = (HSBType) command;
- brightness = hsbType.getBrightness().toBigDecimal();
- fritzBox.setUnmappedHueAndSaturation(ain, hsbType.getHue().intValue(),
- ColorControlModel.fromPercent(hsbType.getSaturation()), 0);
- } else if (command instanceof PercentType) {
- brightness = ((PercentType) command).toBigDecimal();
+ if (command instanceof HSBType hsbCommand) {
+ brightness = hsbCommand.getBrightness().toBigDecimal();
+ fritzBox.setUnmappedHueAndSaturation(ain, hsbCommand.getHue().intValue(),
+ ColorControlModel.fromPercent(hsbCommand.getSaturation()), 0);
+ } else if (command instanceof PercentType brightnessPercent) {
+ brightness = brightnessPercent.toBigDecimal();
} else if (command instanceof OnOffType) {
fritzBox.setSwitch(ain, OnOffType.ON.equals(command));
} else if (command instanceof IncreaseDecreaseType) {
break;
case CHANNEL_COLORTEMPERATURE:
BigDecimal colorTemperaturePct = null;
- if (command instanceof PercentType) {
- colorTemperaturePct = ((PercentType) command).toBigDecimal();
+ if (command instanceof PercentType percentCommand) {
+ colorTemperaturePct = percentCommand.toBigDecimal();
}
if (colorTemperaturePct != null) {
int pct = colorTemperaturePct.intValue();
break;
case CHANNEL_COLORTEMPERATURE_ABS:
BigDecimal colorTemperature = null;
- if (command instanceof QuantityType) {
- QuantityType<?> convertedCommand = ((QuantityType<?>) command).toInvertibleUnit(Units.KELVIN);
+ if (command instanceof QuantityType quantityCommand) {
+ QuantityType<?> convertedCommand = quantityCommand.toInvertibleUnit(Units.KELVIN);
if (convertedCommand != null) {
colorTemperature = convertedCommand.toBigDecimal();
}
- } else if (command instanceof DecimalType) {
- colorTemperature = ((DecimalType) command).toBigDecimal();
+ } else if (command instanceof DecimalType decimalCommand) {
+ colorTemperature = decimalCommand.toBigDecimal();
}
if (colorTemperature != null) {
fritzBox.setColorTemperature(ain, colorTemperature.intValue(), 0);
break;
case CHANNEL_SETTEMP:
BigDecimal temperature = null;
- if (command instanceof DecimalType) {
- temperature = normalizeCelsius(((DecimalType) command).toBigDecimal());
- } else if (command instanceof QuantityType) {
+ if (command instanceof DecimalType decimalCommand) {
+ temperature = normalizeCelsius(decimalCommand.toBigDecimal());
+ } else if (command instanceof QuantityType quantityCommand) {
@SuppressWarnings("unchecked")
QuantityType<Temperature> convertedCommand = ((QuantityType<Temperature>) command)
.toUnit(SIUnits.CELSIUS);
temperature = normalizeCelsius(convertedCommand.toBigDecimal());
} else {
logger.warn("Unable to convert unit from '{}' to '{}'. Skipping command.",
- ((QuantityType<?>) command).getUnit(), SIUnits.CELSIUS);
+ quantityCommand.getUnit(), SIUnits.CELSIUS);
}
} else if (command instanceof IncreaseDecreaseType) {
temperature = currentDevice.getHkr().getTsoll();
}
break;
case CHANNEL_ROLLERSHUTTER:
- if (command instanceof StopMoveType) {
- StopMoveType rollershutterCommand = (StopMoveType) command;
+ if (command instanceof StopMoveType rollershutterCommand) {
if (StopMoveType.STOP.equals(rollershutterCommand)) {
fritzBox.setBlind(ain, BlindCommand.STOP);
} else {
logger.debug("Received unknown rollershutter StopMove command MOVE");
}
- } else if (command instanceof UpDownType) {
- UpDownType rollershutterCommand = (UpDownType) command;
+ } else if (command instanceof UpDownType rollershutterCommand) {
if (UpDownType.UP.equals(rollershutterCommand)) {
fritzBox.setBlind(ain, BlindCommand.OPEN);
} else {
fritzBox.setBlind(ain, BlindCommand.CLOSE);
}
- } else if (command instanceof PercentType) {
- BigDecimal levelPercentage = ((PercentType) command).toBigDecimal();
+ } else if (command instanceof PercentType percentCommand) {
+ BigDecimal levelPercentage = percentCommand.toBigDecimal();
fritzBox.setLevelPercentage(ain, levelPercentage);
} else {
logger.debug("Received unknown rollershutter command type '{}'", command.toString());
Bridge bridge = getBridge();
if (bridge != null) {
BridgeHandler handler = bridge.getHandler();
- if (handler instanceof AVMFritzBaseBridgeHandler) {
- return ((AVMFritzBaseBridgeHandler) handler).getWebInterface();
+ if (handler instanceof AVMFritzBaseBridgeHandler bridgeHandler) {
+ return bridgeHandler.getWebInterface();
}
}
return null;
Bridge bridge = getBridge();
if (bridge != null) {
BridgeHandler handler = bridge.getHandler();
- if (handler instanceof AVMFritzBaseBridgeHandler) {
- ((AVMFritzBaseBridgeHandler) handler).handleRefreshCommand();
+ if (handler instanceof AVMFritzBaseBridgeHandler bridgeHandler) {
+ bridgeHandler.handleRefreshCommand();
}
}
}
if (thing.getUID().equals(thingUID)) {
super.onDeviceUpdated(thingUID, device);
- if (device instanceof DeviceModel) {
- DeviceModel deviceModel = (DeviceModel) device;
+ if (device instanceof DeviceModel deviceModel) {
if (deviceModel.isHANFUNButton()) {
updateHANFUNButton(deviceModel.getButtons());
}
package org.openhab.binding.avmfritz.internal.handler;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.avmfritz.internal.actions.AVMFritzHeatingActions;
@Override
default Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(AVMFritzHeatingActions.class);
+ return Set.of(AVMFritzHeatingActions.class);
}
/**
@Override
protected void updateProperties(AVMFritzBaseModel device, Map<String, String> editProperties) {
- if (device instanceof GroupModel) {
- GroupModel groupModel = (GroupModel) device;
+ if (device instanceof GroupModel groupModel) {
if (groupModel.getGroupinfo() != null) {
editProperties.put(PROPERTY_MASTER, groupModel.getGroupinfo().getMasterdeviceid());
editProperties.put(PROPERTY_MEMBERS, groupModel.getGroupinfo().getMembers());
public void setUp() throws JAXBException, XMLStreamException {
//@formatter:off
final String xml =
- "<devicelist version=\"1\">"
- + "<group identifier=\"F0:A3:7F-900\" id=\"20000\" functionbitmask=\"6784\" fwversion=\"1.0\" manufacturer=\"AVM\" productname=\"\"><present>1</present><name>Schlafzimmer</name><switch><state>1</state><mode>manuell</mode><lock>0</lock><devicelock>0</devicelock></switch><powermeter><voltage>230051</voltage><power>0</power><energy>2087</energy></powermeter><groupinfo><masterdeviceid>17</masterdeviceid><members>17,18</members></groupinfo></group>"
- + "<group identifier=\"F0:A3:7F-901\" id=\"20001\" functionbitmask=\"4160\" fwversion=\"1.0\" manufacturer=\"AVM\" productname=\"\"><present>1</present><name>Schlafzimmer</name><temperature><celsius>220</celsius><offset>-10</offset></temperature><hkr><tist>44</tist><tsoll>42</tsoll><absenk>28</absenk><komfort>42</komfort><lock>1</lock><devicelock>1</devicelock><errorcode>0</errorcode><windowopenactiv>0</windowopenactiv><windowopenactiveendtime>0</windowopenactiveendtime><boostactive>0</boostactive><boostactiveendtime>0</boostactiveendtime><batterylow>0</batterylow><battery>100</battery><nextchange><endperiod>1484341200</endperiod><tchange>28</tchange></nextchange></hkr><groupinfo><masterdeviceid>0</masterdeviceid><members>20,21,22</members></groupinfo></group>"
- + "<device identifier=\"08761 0000434\" id=\"17\" functionbitmask=\"35712\" fwversion=\"03.83\" manufacturer=\"AVM\" productname=\"FRITZ!DECT 200\"><present>1</present><name>FRITZ!DECT 200 #1</name><switch><state>1</state><mode>manuell</mode><lock>0</lock><devicelock>0</devicelock></switch><powermeter><voltage>230051</voltage><power>0</power><energy>2087</energy></powermeter><temperature><celsius>255</celsius><offset>0</offset></temperature></device>"
- + "<device identifier=\"08761 0000438\" id=\"18\" functionbitmask=\"35712\" fwversion=\"03.83\" manufacturer=\"AVM\" productname=\"FRITZ!DECT 210\"><present>1</present><name>FRITZ!DECT 210 #8</name><switch><state>1</state><mode>manuell</mode><lock>0</lock><devicelock>0</devicelock></switch><powermeter><voltage>230051</voltage><power>0</power><energy>2087</energy></powermeter><temperature><celsius>255</celsius><offset>0</offset></temperature></device>"
- + "<device identifier=\"08761 0000437\" id=\"20\" functionbitmask=\"320\" fwversion=\"03.50\" manufacturer=\"AVM\" productname=\"FRITZ!DECT 300\"><present>0</present><name>FRITZ!DECT 300 #1</name><temperature><celsius>220</celsius><offset>-10</offset></temperature><hkr><tist>44</tist><tsoll>42</tsoll><absenk>28</absenk><komfort>42</komfort><lock>1</lock><devicelock>1</devicelock><errorcode>0</errorcode><windowopenactiv>0</windowopenactiv><windowopenactiveendtime>0</windowopenactiveendtime><boostactive>0</boostactive><boostactiveendtime>0</boostactiveendtime><batterylow>0</batterylow><battery>100</battery><nextchange><endperiod>1484341200</endperiod><tchange>28</tchange></nextchange></hkr></device>"
- + "<device identifier=\"08761 0000436\" id=\"21\" functionbitmask=\"320\" fwversion=\"03.50\" manufacturer=\"AVM\" productname=\"FRITZ!DECT 301\"><present>0</present><name>FRITZ!DECT 301 #1</name><temperature><celsius>220</celsius><offset>-10</offset></temperature><hkr><tist>44</tist><tsoll>42</tsoll><absenk>28</absenk><komfort>42</komfort><lock>1</lock><devicelock>1</devicelock><errorcode>0</errorcode><windowopenactiv>0</windowopenactiv><windowopenactiveendtime>0</windowopenactiveendtime><boostactive>0</boostactive><boostactiveendtime>0</boostactiveendtime><batterylow>0</batterylow><battery>100</battery><nextchange><endperiod>1484341200</endperiod><tchange>28</tchange></nextchange></hkr></device>"
- + "<device identifier=\"08761 0000435\" id=\"22\" functionbitmask=\"320\" fwversion=\"03.50\" manufacturer=\"AVM\" productname=\"Comet DECT\"><present>0</present><name>Comet DECT #1</name><temperature><celsius>220</celsius><offset>-10</offset></temperature><hkr><tist>44</tist><tsoll>42</tsoll><absenk>28</absenk><komfort>42</komfort><lock>1</lock><devicelock>1</devicelock><errorcode>0</errorcode><windowopenactiv>0</windowopenactiv><windowopenactiveendtime>0</windowopenactiveendtime><boostactive>0</boostactive><boostactiveendtime>0</boostactiveendtime><batterylow>0</batterylow><battery>100</battery><nextchange><endperiod>1484341200</endperiod><tchange>28</tchange></nextchange></hkr></device>"
- + "<device identifier=\"5C:49:79:F0:A3:84\" id=\"30\" functionbitmask=\"640\" fwversion=\"06.92\" manufacturer=\"AVM\" productname=\"FRITZ!Powerline 546E\"><present>1</present><name>FRITZ!Powerline 546E #1</name><switch><state>0</state><mode>manuell</mode><lock>0</lock><devicelock>1</devicelock></switch><powermeter><voltage>230051</voltage><power>0</power><energy>2087</energy></powermeter></device>"
- + "<device identifier=\"08761 0000439\" id=\"40\" functionbitmask=\"1280\" fwversion=\"03.86\" manufacturer=\"AVM\" productname=\"FRITZ!DECT Repeater 100\"><present>1</present><name>FRITZ!DECT Repeater 100 #5</name><temperature><celsius>230</celsius><offset>0</offset></temperature></device>"
- + "<device identifier=\"11934 0059978-1\" id=\"2000\" functionbitmask=\"8208\" fwversion=\"0.0\" manufacturer=\"0x0feb\" productname=\"HAN-FUN\"><present>0</present><name>HAN-FUN #2: Unit #2</name><etsiunitinfo><etsideviceid>406</etsideviceid><unittype>514</unittype><interfaces>256</interfaces></etsiunitinfo><alert><state>1</state></alert></device>"
- + "<device identifier=\"11934 0059979-1\" id=\"2001\" functionbitmask=\"8200\" fwversion=\"0.0\" manufacturer=\"0x0feb\" productname=\"HAN-FUN\"><present>0</present><name>HAN-FUN #2: Unit #2</name><etsiunitinfo><etsideviceid>412</etsideviceid><unittype>273</unittype><interfaces>772</interfaces></etsiunitinfo><button><lastpressedtimestamp>1529590797</lastpressedtimestamp></button></device>"
- + "<device identifier=\"13096 0007307\" id=\"29\" functionbitmask=\"32\" fwversion=\"04.90\" manufacturer=\"AVM\" productname=\"FRITZ!DECT 400\"><present>1</present><name>FRITZ!DECT 400 #14</name><battery>100</battery><batterylow>0</batterylow><button identifier=\"13096 0007307-0\" id=\"5000\"><name>FRITZ!DECT 400 #14: kurz</name><lastpressedtimestamp>1549195586</lastpressedtimestamp></button><button identifier=\"13096 0007307-9\" id=\"5001\"><name>FRITZ!DECT 400 #14: lang</name><lastpressedtimestamp>1549195595</lastpressedtimestamp></button></device>"
- + "<device identifier=\"13096 0007308\" id=\"30\" functionbitmask=\"1048864\" fwversion=\"05.10\" manufacturer=\"AVM\" productname=\"FRITZ!DECT 440\"><present>1</present><name>FRITZ!DECT 440 #15</name><temperature><celsius>230</celsius><offset>0</offset></temperature><humidity><rel_humidity>43</rel_humidity></humidity><battery>100</battery><batterylow>0</batterylow><button identifier=\"13096 0007308-1\" id=\"5000\"><name>FRITZ!DECT 440 #15: Oben rechts</name><lastpressedtimestamp>1549195586</lastpressedtimestamp></button><button identifier=\"13096 0007308-3\" id=\"5001\"><name>FRITZ!DECT 440 #15: Unten rechts</name><lastpressedtimestamp>1549195595</lastpressedtimestamp></button><button identifier=\"13096 0007308-5\" id=\"5002\"><name>FRITZ!DECT 440 #15: Unten links</name><lastpressedtimestamp>1549195586</lastpressedtimestamp></button><button identifier=\"13096 0007308-7\" id=\"5003\"><name>FRITZ!DECT 440 #15: Oben links</name><lastpressedtimestamp>1549195595</lastpressedtimestamp></button></device>"
- + "<device identifier=\"14276 0503450-1\" id=\"2000\" functionbitmask=\"335888\" fwversion=\"0.0\" manufacturer=\"0x37c4\" productname=\"Rollotron 1213\"><present>1</present><txbusy>0</txbusy><name>Rollotron 1213 #1</name><blind><endpositionsset>1</endpositionsset><mode>manuell</mode></blind><levelcontrol><level>26</level><levelpercentage>10</levelpercentage></levelcontrol><etsiunitinfo><etsideviceid>406</etsideviceid><unittype>281</unittype><interfaces>256,513,516,517</interfaces></etsiunitinfo><alert><state>0</state><lastalertchgtimestamp></lastalertchgtimestamp></alert></device>"
- + "<device identifier=\"11324 0824499-1\" id=\"2002\" functionbitmask=\"40960\" fwversion=\"0.0\" manufacturer=\"0x2c3c\" productname=\"HAN-FUN\">\n"
- + " <present>1</present>\n"
- + " <txbusy>0</txbusy>\n"
- + " <name>Steckdose innen</name>\n"
- + " <simpleonoff>\n"
- + " <state>0</state>\n"
- + " </simpleonoff>\n"
- + " <etsiunitinfo>\n"
- + " <etsideviceid>408</etsideviceid>\n"
- + " <unittype>263</unittype>\n"
- + " <interfaces>512,768</interfaces>\n"
- + " </etsiunitinfo>\n"
- + "</device>"
- + "<device identifier=\"11324 0584796-1\" id=\"2001\" functionbitmask=\"40960\" fwversion=\"0.0\" manufacturer=\"0x2c3c\" productname=\"HAN-FUN\">\n"
- + " <present>1</present>\n"
- + " <txbusy>0</txbusy>\n"
- + " <name>Steckdose außen</name>\n"
- + " <simpleonoff>\n"
- + " <state>0</state>\n"
- + " </simpleonoff>\n"
- + " <etsiunitinfo>\n"
- + " <etsideviceid>407</etsideviceid>\n"
- + " <unittype>262</unittype>\n"
- + " <interfaces>512</interfaces>\n"
- + " </etsiunitinfo>\n"
- + "</device>"
- + "<device identifier=\"12701 0027533-1\" id=\"2002\" functionbitmask=\"237572\" fwversion=\"0.0\" manufacturer=\"0x319d\" productname=\"HAN-FUN\">\n"
- + " <present>0</present>\n"
- + " <txbusy>0</txbusy>\n"
- + " <name>SmartHome LED-Lampe #1</name>\n"
- + " <simpleonoff>\n"
- + " <state>0</state>\n"
- + " </simpleonoff>\n"
- + " <levelcontrol>\n"
- + " <level>26</level>\n"
- + " <levelpercentage>10</levelpercentage>\n"
- + " </levelcontrol>\n"
- + " <colorcontrol supported_modes=\"0\" current_mode=\"\" fullcolorsupport=\"0\" mapped=\"0\">\n"
- + " <hue>254</hue>\n"
- + " <saturation>100</saturation>\n"
- + " <unmapped_hue></unmapped_hue>\n"
- + " <unmapped_saturation></unmapped_saturation>\n"
- + " <temperature>2700</temperature>\n"
- + " </colorcontrol>\n"
- + " <etsiunitinfo>\n"
- + " <etsideviceid>407</etsideviceid>\n"
- + " <unittype>278</unittype>\n"
- + " <interfaces>512,514,513</interfaces>\n"
- + " </etsiunitinfo>\n"
- + "</device>" +
- "</devicelist>";
+ """
+ <devicelist version="1">\
+ <group identifier="F0:A3:7F-900" id="20000" functionbitmask="6784" fwversion="1.0" manufacturer="AVM" productname=""><present>1</present><name>Schlafzimmer</name><switch><state>1</state><mode>manuell</mode><lock>0</lock><devicelock>0</devicelock></switch><powermeter><voltage>230051</voltage><power>0</power><energy>2087</energy></powermeter><groupinfo><masterdeviceid>17</masterdeviceid><members>17,18</members></groupinfo></group>\
+ <group identifier="F0:A3:7F-901" id="20001" functionbitmask="4160" fwversion="1.0" manufacturer="AVM" productname=""><present>1</present><name>Schlafzimmer</name><temperature><celsius>220</celsius><offset>-10</offset></temperature><hkr><tist>44</tist><tsoll>42</tsoll><absenk>28</absenk><komfort>42</komfort><lock>1</lock><devicelock>1</devicelock><errorcode>0</errorcode><windowopenactiv>0</windowopenactiv><windowopenactiveendtime>0</windowopenactiveendtime><boostactive>0</boostactive><boostactiveendtime>0</boostactiveendtime><batterylow>0</batterylow><battery>100</battery><nextchange><endperiod>1484341200</endperiod><tchange>28</tchange></nextchange></hkr><groupinfo><masterdeviceid>0</masterdeviceid><members>20,21,22</members></groupinfo></group>\
+ <device identifier="08761 0000434" id="17" functionbitmask="35712" fwversion="03.83" manufacturer="AVM" productname="FRITZ!DECT 200"><present>1</present><name>FRITZ!DECT 200 #1</name><switch><state>1</state><mode>manuell</mode><lock>0</lock><devicelock>0</devicelock></switch><powermeter><voltage>230051</voltage><power>0</power><energy>2087</energy></powermeter><temperature><celsius>255</celsius><offset>0</offset></temperature></device>\
+ <device identifier="08761 0000438" id="18" functionbitmask="35712" fwversion="03.83" manufacturer="AVM" productname="FRITZ!DECT 210"><present>1</present><name>FRITZ!DECT 210 #8</name><switch><state>1</state><mode>manuell</mode><lock>0</lock><devicelock>0</devicelock></switch><powermeter><voltage>230051</voltage><power>0</power><energy>2087</energy></powermeter><temperature><celsius>255</celsius><offset>0</offset></temperature></device>\
+ <device identifier="08761 0000437" id="20" functionbitmask="320" fwversion="03.50" manufacturer="AVM" productname="FRITZ!DECT 300"><present>0</present><name>FRITZ!DECT 300 #1</name><temperature><celsius>220</celsius><offset>-10</offset></temperature><hkr><tist>44</tist><tsoll>42</tsoll><absenk>28</absenk><komfort>42</komfort><lock>1</lock><devicelock>1</devicelock><errorcode>0</errorcode><windowopenactiv>0</windowopenactiv><windowopenactiveendtime>0</windowopenactiveendtime><boostactive>0</boostactive><boostactiveendtime>0</boostactiveendtime><batterylow>0</batterylow><battery>100</battery><nextchange><endperiod>1484341200</endperiod><tchange>28</tchange></nextchange></hkr></device>\
+ <device identifier="08761 0000436" id="21" functionbitmask="320" fwversion="03.50" manufacturer="AVM" productname="FRITZ!DECT 301"><present>0</present><name>FRITZ!DECT 301 #1</name><temperature><celsius>220</celsius><offset>-10</offset></temperature><hkr><tist>44</tist><tsoll>42</tsoll><absenk>28</absenk><komfort>42</komfort><lock>1</lock><devicelock>1</devicelock><errorcode>0</errorcode><windowopenactiv>0</windowopenactiv><windowopenactiveendtime>0</windowopenactiveendtime><boostactive>0</boostactive><boostactiveendtime>0</boostactiveendtime><batterylow>0</batterylow><battery>100</battery><nextchange><endperiod>1484341200</endperiod><tchange>28</tchange></nextchange></hkr></device>\
+ <device identifier="08761 0000435" id="22" functionbitmask="320" fwversion="03.50" manufacturer="AVM" productname="Comet DECT"><present>0</present><name>Comet DECT #1</name><temperature><celsius>220</celsius><offset>-10</offset></temperature><hkr><tist>44</tist><tsoll>42</tsoll><absenk>28</absenk><komfort>42</komfort><lock>1</lock><devicelock>1</devicelock><errorcode>0</errorcode><windowopenactiv>0</windowopenactiv><windowopenactiveendtime>0</windowopenactiveendtime><boostactive>0</boostactive><boostactiveendtime>0</boostactiveendtime><batterylow>0</batterylow><battery>100</battery><nextchange><endperiod>1484341200</endperiod><tchange>28</tchange></nextchange></hkr></device>\
+ <device identifier="5C:49:79:F0:A3:84" id="30" functionbitmask="640" fwversion="06.92" manufacturer="AVM" productname="FRITZ!Powerline 546E"><present>1</present><name>FRITZ!Powerline 546E #1</name><switch><state>0</state><mode>manuell</mode><lock>0</lock><devicelock>1</devicelock></switch><powermeter><voltage>230051</voltage><power>0</power><energy>2087</energy></powermeter></device>\
+ <device identifier="08761 0000439" id="40" functionbitmask="1280" fwversion="03.86" manufacturer="AVM" productname="FRITZ!DECT Repeater 100"><present>1</present><name>FRITZ!DECT Repeater 100 #5</name><temperature><celsius>230</celsius><offset>0</offset></temperature></device>\
+ <device identifier="11934 0059978-1" id="2000" functionbitmask="8208" fwversion="0.0" manufacturer="0x0feb" productname="HAN-FUN"><present>0</present><name>HAN-FUN #2: Unit #2</name><etsiunitinfo><etsideviceid>406</etsideviceid><unittype>514</unittype><interfaces>256</interfaces></etsiunitinfo><alert><state>1</state></alert></device>\
+ <device identifier="11934 0059979-1" id="2001" functionbitmask="8200" fwversion="0.0" manufacturer="0x0feb" productname="HAN-FUN"><present>0</present><name>HAN-FUN #2: Unit #2</name><etsiunitinfo><etsideviceid>412</etsideviceid><unittype>273</unittype><interfaces>772</interfaces></etsiunitinfo><button><lastpressedtimestamp>1529590797</lastpressedtimestamp></button></device>\
+ <device identifier="13096 0007307" id="29" functionbitmask="32" fwversion="04.90" manufacturer="AVM" productname="FRITZ!DECT 400"><present>1</present><name>FRITZ!DECT 400 #14</name><battery>100</battery><batterylow>0</batterylow><button identifier="13096 0007307-0" id="5000"><name>FRITZ!DECT 400 #14: kurz</name><lastpressedtimestamp>1549195586</lastpressedtimestamp></button><button identifier="13096 0007307-9" id="5001"><name>FRITZ!DECT 400 #14: lang</name><lastpressedtimestamp>1549195595</lastpressedtimestamp></button></device>\
+ <device identifier="13096 0007308" id="30" functionbitmask="1048864" fwversion="05.10" manufacturer="AVM" productname="FRITZ!DECT 440"><present>1</present><name>FRITZ!DECT 440 #15</name><temperature><celsius>230</celsius><offset>0</offset></temperature><humidity><rel_humidity>43</rel_humidity></humidity><battery>100</battery><batterylow>0</batterylow><button identifier="13096 0007308-1" id="5000"><name>FRITZ!DECT 440 #15: Oben rechts</name><lastpressedtimestamp>1549195586</lastpressedtimestamp></button><button identifier="13096 0007308-3" id="5001"><name>FRITZ!DECT 440 #15: Unten rechts</name><lastpressedtimestamp>1549195595</lastpressedtimestamp></button><button identifier="13096 0007308-5" id="5002"><name>FRITZ!DECT 440 #15: Unten links</name><lastpressedtimestamp>1549195586</lastpressedtimestamp></button><button identifier="13096 0007308-7" id="5003"><name>FRITZ!DECT 440 #15: Oben links</name><lastpressedtimestamp>1549195595</lastpressedtimestamp></button></device>\
+ <device identifier="14276 0503450-1" id="2000" functionbitmask="335888" fwversion="0.0" manufacturer="0x37c4" productname="Rollotron 1213"><present>1</present><txbusy>0</txbusy><name>Rollotron 1213 #1</name><blind><endpositionsset>1</endpositionsset><mode>manuell</mode></blind><levelcontrol><level>26</level><levelpercentage>10</levelpercentage></levelcontrol><etsiunitinfo><etsideviceid>406</etsideviceid><unittype>281</unittype><interfaces>256,513,516,517</interfaces></etsiunitinfo><alert><state>0</state><lastalertchgtimestamp></lastalertchgtimestamp></alert></device>\
+ <device identifier="11324 0824499-1" id="2002" functionbitmask="40960" fwversion="0.0" manufacturer="0x2c3c" productname="HAN-FUN">
+ <present>1</present>
+ <txbusy>0</txbusy>
+ <name>Steckdose innen</name>
+ <simpleonoff>
+ <state>0</state>
+ </simpleonoff>
+ <etsiunitinfo>
+ <etsideviceid>408</etsideviceid>
+ <unittype>263</unittype>
+ <interfaces>512,768</interfaces>
+ </etsiunitinfo>
+ </device>\
+ <device identifier="11324 0584796-1" id="2001" functionbitmask="40960" fwversion="0.0" manufacturer="0x2c3c" productname="HAN-FUN">
+ <present>1</present>
+ <txbusy>0</txbusy>
+ <name>Steckdose außen</name>
+ <simpleonoff>
+ <state>0</state>
+ </simpleonoff>
+ <etsiunitinfo>
+ <etsideviceid>407</etsideviceid>
+ <unittype>262</unittype>
+ <interfaces>512</interfaces>
+ </etsiunitinfo>
+ </device>\
+ <device identifier="12701 0027533-1" id="2002" functionbitmask="237572" fwversion="0.0" manufacturer="0x319d" productname="HAN-FUN">
+ <present>0</present>
+ <txbusy>0</txbusy>
+ <name>SmartHome LED-Lampe #1</name>
+ <simpleonoff>
+ <state>0</state>
+ </simpleonoff>
+ <levelcontrol>
+ <level>26</level>
+ <levelpercentage>10</levelpercentage>
+ </levelcontrol>
+ <colorcontrol supported_modes="0" current_mode="" fullcolorsupport="0" mapped="0">
+ <hue>254</hue>
+ <saturation>100</saturation>
+ <unmapped_hue></unmapped_hue>
+ <unmapped_saturation></unmapped_saturation>
+ <temperature>2700</temperature>
+ </colorcontrol>
+ <etsiunitinfo>
+ <etsideviceid>407</etsideviceid>
+ <unittype>278</unittype>
+ <interfaces>512,514,513</interfaces>
+ </etsiunitinfo>
+ </device>\
+ </devicelist>\
+ """;
//@formatter:on
XMLStreamReader xsr = JAXBUtils.XMLINPUTFACTORY.createXMLStreamReader(new StringReader(xml));
Unmarshaller u = JAXBUtils.JAXBCONTEXT_DEVICES.createUnmarshaller();
public void setUp() throws JAXBException, XMLStreamException {
//@formatter:off
String xml =
- "<templatelist version=\"1\">" +
- "<template identifier=\"tmpXXXXX-39DC738C5\" id=\"30103\" functionbitmask=\"6784\" applymask=\"64\"><name>Test template #1</name><devices><device identifier=\"YY:5D:AA-900\" /><device identifier=\"XX:5D:AA-900\" /></devices><applymask><relay_automatic /></applymask></template>" +
- "<template identifier=\"tmpXXXXX-39722FC0F\" id=\"30003\" functionbitmask=\"6784\" applymask=\"64\"><name>Test template #2</name><devices><device identifier=\"YY:5D:AA-900\" /></devices><applymask><relay_automatic /></applymask></template>" +
- "</templatelist>";
+ """
+ <templatelist version="1">\
+ <template identifier="tmpXXXXX-39DC738C5" id="30103" functionbitmask="6784" applymask="64"><name>Test template #1</name><devices><device identifier="YY:5D:AA-900" /><device identifier="XX:5D:AA-900" /></devices><applymask><relay_automatic /></applymask></template>\
+ <template identifier="tmpXXXXX-39722FC0F" id="30003" functionbitmask="6784" applymask="64"><name>Test template #2</name><devices><device identifier="YY:5D:AA-900" /></devices><applymask><relay_automatic /></applymask></template>\
+ </templatelist>\
+ """;
//@formatter:on
XMLStreamReader xsr = JAXBUtils.XMLINPUTFACTORY.createXMLStreamReader(new StringReader(xml));
Unmarshaller u = JAXBUtils.JAXBCONTEXT_TEMPLATES.createUnmarshaller();
public int length;
public boolean consecutive;
+ @Override
public String toString() {
return String.format("{ s: %d, d: %d, l: %d, c: %b )", rangeStart, rangeDuration, length, consecutive);
}
return priceSum;
}
+ @Override
public String toString() {
return String.format("{%s, %s, %.2f}", formatDate(getStart(), zoneId), formatDate(getEnd(), zoneId),
priceSum / length);
}
+ @Override
public String getHours() {
return hours;
}
return members.stream().anyMatch(x -> x.contains(Instant.now().toEpochMilli()));
}
+ @Override
public String toString() {
return String.format("NonConsecutiveBestpriceResult with %s", members.toString());
}
}
}
+ @Override
public String getHours() {
boolean second = false;
sort();
return price;
}
+ @Override
public String toString() {
return String.format("(%1$tF %1$tR - %2$tR: %3$.3f)", startTimestamp, endTimestamp, getPrice());
}
int offset = min % mod;
offset = offset == 0 ? mod : offset;
dt = dt.plusMinutes(offset);
- long result = dt.toInstant().toEpochMilli() - now;
-
- return result;
+ return dt.toInstant().toEpochMilli() - now;
}
public static ZonedDateTime getCalendarForHour(int hour, ZoneId zone) {
updateStatus(ThingStatus.UNKNOWN);
}
+ @Override
public void dispose() {
ScheduledFuture<?> localRefresher = thingRefresher;
if (localRefresher != null) {
@NonNullByDefault
public enum Switch {
ON,
- OFF;
+ OFF
}
logger.debug("Handling fan speed command for {}: {}", thing.getUID(), command);
// <mac;FAN;SPD;SET;0..7>
- if (command instanceof PercentType) {
- sendCommand(macAddress, ";FAN;SPD;SET;".concat(BigAssFanConverter.percentToSpeed((PercentType) command)));
+ if (command instanceof PercentType percentCommand) {
+ sendCommand(macAddress, ";FAN;SPD;SET;".concat(BigAssFanConverter.percentToSpeed(percentCommand)));
}
}
private void handleFanLearnSpeedMin(Command command) {
logger.debug("Handling fan learn speed minimum command {}", command);
// <mac;FAN;SPD;SET;MIN;0..7>
- if (command instanceof PercentType) {
+ if (command instanceof PercentType percentCommand) {
// Send min speed set command
- sendCommand(macAddress,
- ";LEARN;MINSPEED;SET;".concat(BigAssFanConverter.percentToSpeed((PercentType) command)));
- fanStateMap.put(CHANNEL_FAN_LEARN_MINSPEED, (PercentType) command);
+ sendCommand(macAddress, ";LEARN;MINSPEED;SET;".concat(BigAssFanConverter.percentToSpeed(percentCommand)));
+ fanStateMap.put(CHANNEL_FAN_LEARN_MINSPEED, percentCommand);
// Don't let max be less than min
- adjustMaxSpeed((PercentType) command, CHANNEL_FAN_LEARN_MAXSPEED, ";LEARN;MAXSPEED;");
+ adjustMaxSpeed(percentCommand, CHANNEL_FAN_LEARN_MAXSPEED, ";LEARN;MAXSPEED;");
}
}
private void handleFanLearnSpeedMax(Command command) {
logger.debug("Handling fan learn speed maximum command {}", command);
// <mac;FAN;SPD;SET;MAX;0..7>
- if (command instanceof PercentType) {
+ if (command instanceof PercentType percentCommand) {
// Send max speed set command
- sendCommand(macAddress,
- ";LEARN;MAXSPEED;SET;;".concat(BigAssFanConverter.percentToSpeed((PercentType) command)));
- fanStateMap.put(CHANNEL_FAN_LEARN_MAXSPEED, (PercentType) command);
+ sendCommand(macAddress, ";LEARN;MAXSPEED;SET;;".concat(BigAssFanConverter.percentToSpeed(percentCommand)));
+ fanStateMap.put(CHANNEL_FAN_LEARN_MAXSPEED, percentCommand);
// Don't let min be greater than max
- adjustMinSpeed((PercentType) command, CHANNEL_FAN_LEARN_MINSPEED, ";LEARN;MINSPEED;");
+ adjustMinSpeed(percentCommand, CHANNEL_FAN_LEARN_MINSPEED, ";LEARN;MINSPEED;");
}
}
private void handleFanSpeedMin(Command command) {
logger.debug("Handling fan speed minimum command {}", command);
// <mac;FAN;SPD;SET;MIN;0..7>
- if (command instanceof PercentType) {
+ if (command instanceof PercentType percentCommand) {
// Send min speed set command
- sendCommand(macAddress,
- ";FAN;SPD;SET;MIN;".concat(BigAssFanConverter.percentToSpeed((PercentType) command)));
- fanStateMap.put(CHANNEL_FAN_SPEED_MIN, (PercentType) command);
+ sendCommand(macAddress, ";FAN;SPD;SET;MIN;".concat(BigAssFanConverter.percentToSpeed(percentCommand)));
+ fanStateMap.put(CHANNEL_FAN_SPEED_MIN, percentCommand);
// Don't let max be less than min
- adjustMaxSpeed((PercentType) command, CHANNEL_FAN_SPEED_MAX, ";FAN;SPD;SET;MAX;");
+ adjustMaxSpeed(percentCommand, CHANNEL_FAN_SPEED_MAX, ";FAN;SPD;SET;MAX;");
}
}
private void handleFanSpeedMax(Command command) {
logger.debug("Handling fan speed maximum command {}", command);
// <mac;FAN;SPD;SET;MAX;0..7>
- if (command instanceof PercentType) {
+ if (command instanceof PercentType percentCommand) {
// Send max speed set command
- sendCommand(macAddress,
- ";FAN;SPD;SET;MAX;".concat(BigAssFanConverter.percentToSpeed((PercentType) command)));
- fanStateMap.put(CHANNEL_FAN_SPEED_MAX, (PercentType) command);
+ sendCommand(macAddress, ";FAN;SPD;SET;MAX;".concat(BigAssFanConverter.percentToSpeed(percentCommand)));
+ fanStateMap.put(CHANNEL_FAN_SPEED_MAX, percentCommand);
// Don't let min be greater than max
- adjustMinSpeed((PercentType) command, CHANNEL_FAN_SPEED_MIN, ";FAN;SPD;SET;MIN;");
+ adjustMinSpeed(percentCommand, CHANNEL_FAN_SPEED_MIN, ";FAN;SPD;SET;MIN;");
}
}
logger.debug("Handling light level command {}", command);
// <mac;LIGHT;LEVEL;SET;0..16>
- if (command instanceof PercentType) {
- sendCommand(macAddress,
- ";LIGHT;LEVEL;SET;".concat(BigAssFanConverter.percentToLevel((PercentType) command)));
+ if (command instanceof PercentType percentCommand) {
+ sendCommand(macAddress, ";LIGHT;LEVEL;SET;".concat(BigAssFanConverter.percentToLevel(percentCommand)));
}
}
logger.debug("Handling light hue command {}", command);
// <mac;LIGHT;COLOR;TEMP;SET;2200..5000>
- if (command instanceof PercentType) {
+ if (command instanceof PercentType percentCommand) {
sendCommand(macAddress,
- ";LIGHT;COLOR;TEMP;VALUE;SET;".concat(BigAssFanConverter.percentToHue((PercentType) command)));
+ ";LIGHT;COLOR;TEMP;VALUE;SET;".concat(BigAssFanConverter.percentToHue(percentCommand)));
}
}
logger.debug("Handling light level minimum command {}", command);
// <mac;LIGHT;LEVEL;MIN;0-16>
- if (command instanceof PercentType) {
+ if (command instanceof PercentType percentCommand) {
// Send min light level set command
- sendCommand(macAddress,
- ";LIGHT;LEVEL;MIN;".concat(BigAssFanConverter.percentToLevel((PercentType) command)));
+ sendCommand(macAddress, ";LIGHT;LEVEL;MIN;".concat(BigAssFanConverter.percentToLevel(percentCommand)));
// Don't let max be less than min
- adjustMaxLevel((PercentType) command);
+ adjustMaxLevel(percentCommand);
}
}
logger.debug("Handling light level maximum command {}", command);
// <mac;LIGHT;LEVEL;MAX;0-16>
- if (command instanceof PercentType) {
+ if (command instanceof PercentType percentCommand) {
// Send max light level set command
- sendCommand(macAddress,
- ";LIGHT;LEVEL;MAX;".concat(BigAssFanConverter.percentToLevel((PercentType) command)));
+ sendCommand(macAddress, ";LIGHT;LEVEL;MAX;".concat(BigAssFanConverter.percentToLevel(percentCommand)));
// Don't let min be greater than max
- adjustMinLevel((PercentType) command);
+ adjustMinLevel(percentCommand);
}
}
*/
package org.openhab.binding.bluetooth.am43.internal;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(AM43BindingConstants.THING_TYPE_AM43);
+ return Set.of(AM43BindingConstants.THING_TYPE_AM43);
}
@Override
}
switch (channelUID.getId()) {
case AM43BindingConstants.CHANNEL_ID_POSITION:
- if (command instanceof PercentType) {
+ if (command instanceof PercentType percentCommand) {
MotorSettings settings = motorSettings;
if (settings == null) {
logger.warn("Cannot set position before settings have been received.");
return;
}
if (!settings.isTopLimitSet() || !settings.isBottomLimitSet()) {
- logger.warn("Cannot set position of blinds. Top or bottom limits have not been set. "
- + "Please configure manually.");
+ logger.warn("""
+ Cannot set position of blinds. Top or bottom limits have not been set. \
+ Please configure manually.\
+ """);
return;
}
- PercentType percent = (PercentType) command;
- int value = percent.intValue();
+ int value = percentCommand.intValue();
if (getAM43Config().invertPosition) {
value = 100 - value;
}
submitCommand(new SetPositionCommand(value));
return;
}
- if (command instanceof StopMoveType) {
- switch ((StopMoveType) command) {
+ if (command instanceof StopMoveType stopMoveCommand) {
+ switch (stopMoveCommand) {
case STOP:
submitCommand(new ControlCommand(ControlAction.STOP));
return;
return;
}
}
- if (command instanceof UpDownType) {
- switch ((UpDownType) command) {
+ if (command instanceof UpDownType upDownCommand) {
+ switch (upDownCommand) {
case UP:
submitCommand(new ControlCommand(ControlAction.OPEN));
return;
}
return;
case AM43BindingConstants.CHANNEL_ID_SPEED:
- if (command instanceof DecimalType) {
+ if (command instanceof DecimalType decimalCommand) {
MotorSettings settings = motorSettings;
if (settings != null) {
- DecimalType speedType = (DecimalType) command;
- settings.setSpeed(speedType.intValue());
+ settings.setSpeed(decimalCommand.intValue());
submitCommand(new SetSettingsCommand(settings));
} else {
logger.warn("Cannot set Speed before setting have been received");
*/
package org.openhab.binding.bluetooth.am43.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.am43")
public class AM43HandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .singleton(AM43BindingConstants.THING_TYPE_AM43);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(AM43BindingConstants.THING_TYPE_AM43);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
super(null, handle);
}
+ @Override
public void setProperties(int properties) {
this.properties = properties;
}
@Override
public void bluegigaEventReceived(BlueGigaResponse event) {
- if (event instanceof BlueGigaScanResponseEvent) {
- handleScanEvent((BlueGigaScanResponseEvent) event);
+ if (event instanceof BlueGigaScanResponseEvent responseEvent) {
+ handleScanEvent(responseEvent);
}
- else if (event instanceof BlueGigaGroupFoundEvent) {
- handleGroupFoundEvent((BlueGigaGroupFoundEvent) event);
+ else if (event instanceof BlueGigaGroupFoundEvent foundEvent) {
+ handleGroupFoundEvent(foundEvent);
}
- else if (event instanceof BlueGigaFindInformationFoundEvent) {
+ else if (event instanceof BlueGigaFindInformationFoundEvent foundEvent) {
// A Characteristic has been discovered
- handleFindInformationFoundEvent((BlueGigaFindInformationFoundEvent) event);
+ handleFindInformationFoundEvent(foundEvent);
}
- else if (event instanceof BlueGigaProcedureCompletedEvent) {
- handleProcedureCompletedEvent((BlueGigaProcedureCompletedEvent) event);
+ else if (event instanceof BlueGigaProcedureCompletedEvent completedEvent) {
+ handleProcedureCompletedEvent(completedEvent);
}
- else if (event instanceof BlueGigaConnectionStatusEvent) {
- handleConnectionStatusEvent((BlueGigaConnectionStatusEvent) event);
+ else if (event instanceof BlueGigaConnectionStatusEvent statusEvent) {
+ handleConnectionStatusEvent(statusEvent);
}
- else if (event instanceof BlueGigaDisconnectedEvent) {
- handleDisconnectedEvent((BlueGigaDisconnectedEvent) event);
+ else if (event instanceof BlueGigaDisconnectedEvent disconnectedEvent) {
+ handleDisconnectedEvent(disconnectedEvent);
}
- else if (event instanceof BlueGigaAttributeValueEvent) {
- handleAttributeValueEvent((BlueGigaAttributeValueEvent) event);
+ else if (event instanceof BlueGigaAttributeValueEvent valueEvent) {
+ handleAttributeValueEvent(valueEvent);
}
}
@Override
public void bluegigaEventReceived(@Nullable BlueGigaResponse event) {
- if (event instanceof BlueGigaScanResponseEvent) {
+ if (event instanceof BlueGigaScanResponseEvent scanEvent) {
if (initComplete) {
- BlueGigaScanResponseEvent scanEvent = (BlueGigaScanResponseEvent) event;
// We use the scan event to add any devices we hear to the devices list
// The device gets created, and then manages itself for discovery etc.
return;
}
- if (event instanceof BlueGigaConnectionStatusEvent) {
- BlueGigaConnectionStatusEvent connectionEvent = (BlueGigaConnectionStatusEvent) event;
+ if (event instanceof BlueGigaConnectionStatusEvent connectionEvent) {
connections.put(connectionEvent.getConnection(), new BluetoothAddress(connectionEvent.getAddress()));
}
- if (event instanceof BlueGigaDisconnectedEvent) {
- BlueGigaDisconnectedEvent disconnectedEvent = (BlueGigaDisconnectedEvent) event;
+ if (event instanceof BlueGigaDisconnectedEvent disconnectedEvent) {
connections.remove(disconnectedEvent.getConnection());
}
}
@Override
public String toString() {
- return String.format(
- "[discovery=%b, port=%s, passiveScanIdleTime=%d, passiveScanInterval=%d, passiveScanWindow=%d"
- + ", activeScanInterval=%d, activeScanWindow=%d, connIntervalMin=%d, connIntervalMax=%d"
- + ", connLatency=%d, connTimeout=%d]",
- backgroundDiscovery, port, passiveScanIdleTime, passiveScanInterval, passiveScanWindow,
+ return String.format("""
+ [discovery=%b, port=%s, passiveScanIdleTime=%d, passiveScanInterval=%d, passiveScanWindow=%d\
+ , activeScanInterval=%d, activeScanWindow=%d, connIntervalMin=%d, connIntervalMax=%d\
+ , connLatency=%d, connTimeout=%d]\
+ """, backgroundDiscovery, port, passiveScanIdleTime, passiveScanInterval, passiveScanWindow,
activeScanInterval, activeScanWindow, connIntervalMin, connIntervalMax, connLatency, connTimeout);
}
}
try {
ctor = bleClass.getConstructor(int[].class);
- BlueGigaResponse bleFrame = (BlueGigaResponse) ctor.newInstance(data);
- return bleFrame;
+ return (BlueGigaResponse) ctor.newInstance(data);
} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException e) {
logger.debug("Error instantiating BLE class", e);
private void checkIfAlive() {
if (!isAlive()) {
- throw new IllegalStateException("Bluegiga handler is dead. Most likely because of IO errors. "
- + "Re-initialization of the BlueGigaSerialHandler is required.");
+ throw new IllegalStateException("""
+ Bluegiga handler is dead. Most likely because of IO errors. \
+ Re-initialization of the BlueGigaSerialHandler is required.\
+ """);
}
}
private void sendNextTransactionIfNoOngoing() {
synchronized (this) {
logger.trace("Send next transaction if no ongoing");
- if (!ongoingTransactionId.isPresent()) {
+ if (ongoingTransactionId.isEmpty()) {
sendNextFrame();
}
}
logger.trace("Expected frame: {}, received frame: {}", expected.getSimpleName(), bleResponse);
- if (bleCommand instanceof BlueGigaDeviceCommand && bleResponse instanceof BlueGigaDeviceResponse) {
- BlueGigaDeviceCommand devCommand = (BlueGigaDeviceCommand) bleCommand;
- BlueGigaDeviceResponse devResponse = (BlueGigaDeviceResponse) bleResponse;
+ if (bleCommand instanceof BlueGigaDeviceCommand devCommand
+ && bleResponse instanceof BlueGigaDeviceResponse devResponse) {
logger.trace("Expected connection id: {}, received connection id: {}", devCommand.getConnection(),
devResponse.getConnection());
*/
package org.openhab.binding.bluetooth.bluegiga.internal.factory;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.bluegiga")
public class BlueGigaHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .singleton(BlueGigaAdapterConstants.THING_TYPE_BLUEGIGA);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set
+ .of(BlueGigaAdapterConstants.THING_TYPE_BLUEGIGA);
private final Map<ThingUID, ServiceRegistration<?>> serviceRegs = new HashMap<>();
@Override
protected synchronized void removeHandler(ThingHandler thingHandler) {
- if (thingHandler instanceof BluetoothAdapter) {
- UID uid = ((BluetoothAdapter) thingHandler).getUID();
+ if (thingHandler instanceof BluetoothAdapter bluetoothAdapter) {
+ UID uid = bluetoothAdapter.getUID();
ServiceRegistration<?> serviceReg = this.serviceRegs.remove(uid);
if (serviceReg != null) {
serviceReg.unregister();
@Override
protected BlueZBluetoothDevice createDevice(BluetoothAddress address) {
logger.debug("createDevice {}", address);
- BlueZBluetoothDevice device = new BlueZBluetoothDevice(this, address);
- return device;
+ return new BlueZBluetoothDevice(this, address);
}
@Override
*/
package org.openhab.binding.bluetooth.bluez.internal;
-import java.util.Collections;
+import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
@Activate
public BlueZDiscoveryService(@Reference DeviceManagerFactory deviceManagerFactory) {
- super(Collections.singleton(BlueZAdapterConstants.THING_TYPE_BLUEZ), 1, true);
+ super(Set.of(BlueZAdapterConstants.THING_TYPE_BLUEZ), 1, true);
this.deviceManagerFactory = deviceManagerFactory;
}
*/
package org.openhab.binding.bluetooth.bluez.internal;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.bluetooth.bluez")
public class BlueZHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .singleton(BlueZAdapterConstants.THING_TYPE_BLUEZ);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(BlueZAdapterConstants.THING_TYPE_BLUEZ);
private final Map<ThingUID, ServiceRegistration<?>> serviceRegs = new HashMap<>();
@Override
protected synchronized void removeHandler(ThingHandler thingHandler) {
- if (thingHandler instanceof BluetoothAdapter) {
- UID uid = ((BluetoothAdapter) thingHandler).getUID();
+ if (thingHandler instanceof BluetoothAdapter bluetoothAdapter) {
+ UID uid = bluetoothAdapter.getUID();
ServiceRegistration<?> serviceReg = this.serviceRegs.remove(uid);
if (serviceReg != null) {
serviceReg.unregister();
*/
package org.openhab.binding.bluetooth.blukii.internal;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(BlukiiBindingConstants.THING_TYPE_BEACON);
+ return Set.of(BlukiiBindingConstants.THING_TYPE_BEACON);
}
@Override
*/
package org.openhab.binding.bluetooth.blukii.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.blukii")
public class BlukiiHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .singleton(BlukiiBindingConstants.THING_TYPE_BEACON);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set
+ .of(BlukiiBindingConstants.THING_TYPE_BEACON);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
import static org.openhab.binding.bluetooth.daikinmadoka.DaikinMadokaBindingConstants.THING_TYPE_BRC1H;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.bluetooth.daikinmadoka", service = ThingHandlerFactory.class)
public class DaikinMadokaHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_BRC1H);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_BRC1H);
private final Logger logger = LoggerFactory.getLogger(DaikinMadokaHandlerFactory.class);
*/
package org.openhab.binding.bluetooth.enoceanble.internal;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(EnoceanBleBindingConstants.THING_TYPE_PTM215B);
+ return Set.of(EnoceanBleBindingConstants.THING_TYPE_PTM215B);
}
@Override
*/
package org.openhab.binding.bluetooth.enoceanble.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.enoceanble")
public class EnoceanBleHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .singleton(EnoceanBleBindingConstants.THING_TYPE_PTM215B);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set
+ .of(EnoceanBleBindingConstants.THING_TYPE_PTM215B);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
if (channelID.charAt(30) != '-') {
return false;
}
- return !(channelID.charAt(67) != '-');
+ return channelID.charAt(67) == '-';
}
public ChannelTypeUID registerChannelType(String characteristicUUID, boolean advanced, boolean readOnly,
*/
package org.openhab.binding.bluetooth.roaming.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
public static final ThingTypeUID THING_TYPE_ROAMING = new ThingTypeUID(BluetoothBindingConstants.BINDING_ID,
"roaming");
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_ROAMING);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_ROAMING);
public static final String CONFIGURATION_GROUP_ADAPTER_UIDS = "groupUIDs";
}
return false;
}
Object discovery = getConfig().get(BluetoothBindingConstants.CONFIGURATION_DISCOVERY);
- return !(discovery != null && discovery.toString().equalsIgnoreCase("false"));
+ return !(discovery != null && "false".equalsIgnoreCase(discovery.toString()));
}
@Override
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
-import org.openhab.binding.bluetooth.BluetoothAdapter;
import org.openhab.core.thing.Bridge;
import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingTypeUID;
@Override
protected synchronized void removeHandler(ThingHandler thingHandler) {
- if (thingHandler instanceof RoamingBluetoothAdapter) {
- UID uid = ((BluetoothAdapter) thingHandler).getUID();
+ if (thingHandler instanceof RoamingBluetoothAdapter bluetoothAdapter) {
+ UID uid = bluetoothAdapter.getUID();
ServiceRegistration<?> serviceReg = this.serviceRegs.remove(uid);
if (serviceReg != null) {
serviceReg.unregister();
*/
package org.openhab.binding.bluetooth.ruuvitag.internal;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(RuuviTagBindingConstants.THING_TYPE_BEACON);
+ return Set.of(RuuviTagBindingConstants.THING_TYPE_BEACON);
}
@Override
*/
package org.openhab.binding.bluetooth.ruuvitag.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.ruuvitag")
public class RuuviTagHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .singleton(RuuviTagBindingConstants.THING_TYPE_BEACON);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set
+ .of(RuuviTagBindingConstants.THING_TYPE_BEACON);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
Object idleDisconnectDelayRaw = getConfig().get(BluetoothBindingConstants.CONFIGURATION_IDLE_DISCONNECT_DELAY);
idleDisconnectDelay = 1000;
- if (idleDisconnectDelayRaw instanceof Number) {
- idleDisconnectDelay = ((Number) idleDisconnectDelayRaw).intValue();
+ if (idleDisconnectDelayRaw instanceof Number numberCommand) {
+ idleDisconnectDelay = numberCommand.intValue();
}
// Start the recurrent job if the device is always connected
return CompletableFuture.failedFuture(new IllegalStateException("connectionTaskExecutor is shut down"));
}
// we use a RetryFuture because it supports running Callable instances
- return RetryFuture.callWithRetry(() -> {
- // we block for completion here so that we keep the lock on the connectionTaskExecutor active.
- return callable.apply(connectAndGetCharacteristic(serviceUUID, characteristicUUID)).get();
- }, connectionTaskExecutor)// we make this completion async so that operations chained off the returned future
- // will not run on the connectionTaskExecutor
+ return RetryFuture.callWithRetry(() ->
+ // we block for completion here so that we keep the lock on the connectionTaskExecutor active.
+ callable.apply(connectAndGetCharacteristic(serviceUUID, characteristicUUID)).get(), connectionTaskExecutor)
+ // we make this completion async so that operations chained off the returned future
+ // will not run on the connectionTaskExecutor
.whenCompleteAsync((r, th) -> {
// we us a while loop here in case the exceptions get nested
while (th instanceof CompletionException || th instanceof ExecutionException) {
if (th instanceof CompletionException) {
th = th.getCause();
}
- if (th instanceof RetryException) {
- RetryException e = (RetryException) th;
+ if (th instanceof RetryException e) {
setParentFuture(() -> {
if (!isDone()) {
return scheduler.schedule(this, e.delay, e.unit);
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(typeUID);
+ return Set.of(typeUID);
}
@Override
ThingTypeUID thingTypeUID = thing.getThingTypeUID();
if (THING_TYPE_BOND_BRIDGE.equals(thingTypeUID)) {
- final BondBridgeHandler handler = new BondBridgeHandler((Bridge) thing, httpClientFactory);
- return handler;
+ return new BondBridgeHandler((Bridge) thing, httpClientFactory);
} else if (SUPPORTED_THING_TYPES.contains(thingTypeUID)) {
return new BondDeviceHandler(thing);
}
bridgeHandler.getBridgeToken());
ContentResponse response;
response = request.send();
- String encoding = response.getEncoding() != null ? response.getEncoding().replaceAll("\"", "").trim()
+ String encoding = response.getEncoding() != null ? response.getEncoding().replace("\"", "").trim()
: StandardCharsets.UTF_8.name();
try {
httpResponse = new String(response.getContent(), encoding);
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof BondBridgeHandler) {
- @Nullable
- BondBridgeHandler localHandler = (BondBridgeHandler) handler;
+ if (handler instanceof BondBridgeHandler localHandler) {
bridgeHandler = localHandler;
localHandler.setDiscoveryService(this);
api = localHandler.getBridgeAPI();
@Override
public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
super.childHandlerInitialized(childHandler, childThing);
- if (childHandler instanceof BondDeviceHandler) {
- BondDeviceHandler handler = (BondDeviceHandler) childHandler;
+ if (childHandler instanceof BondDeviceHandler handler) {
synchronized (handlers) {
// Start the BPUP update service after the first child device is added
startUDPListenerJob();
@Override
public void childHandlerDisposed(ThingHandler childHandler, Thing childThing) {
- if (childHandler instanceof BondDeviceHandler) {
- BondDeviceHandler handler = (BondDeviceHandler) childHandler;
+ if (childHandler instanceof BondDeviceHandler handler) {
synchronized (handlers) {
handlers.remove(handler);
if (handlers.isEmpty()) {
String deviceId = null;
String topicType = null;
if (topic != null) {
- String parts[] = topic.split("/");
+ String[] parts = topic.split("/");
deviceId = parts[1];
topicType = parts[2];
}
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(BondDiscoveryService.class);
+ return Set.of(BondDiscoveryService.class);
}
public void setDiscoveryService(BondDiscoveryService discoveryService) {
case CHANNEL_FAN_SPEED:
logger.trace("Fan speed command");
- if (command instanceof PercentType) {
+ if (command instanceof PercentType percentCommand) {
if (devInfo.actions.contains(BondDeviceAction.SET_FP_FAN)) {
- value = ((PercentType) command).intValue();
+ value = percentCommand.intValue();
if (value == 0) {
action = BondDeviceAction.TURN_FP_FAN_OFF;
value = null;
BondDeviceProperties devProperties = this.deviceProperties;
if (devProperties != null) {
int maxSpeed = devProperties.maxSpeed;
- value = (int) Math.ceil(((PercentType) command).intValue() * maxSpeed / 100);
+ value = (int) Math.ceil(percentCommand.intValue() * maxSpeed / 100);
} else {
value = 1;
}
}
logger.trace("Fan speed command with speed set as {}", value);
api.executeDeviceAction(deviceId, action, value);
- } else if (command instanceof IncreaseDecreaseType) {
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
logger.trace("Fan increase/decrease speed command");
api.executeDeviceAction(deviceId,
- ((IncreaseDecreaseType) command == IncreaseDecreaseType.INCREASE
- ? BondDeviceAction.INCREASE_SPEED
+ (increaseDecreaseCommand == IncreaseDecreaseType.INCREASE ? BondDeviceAction.INCREASE_SPEED
: BondDeviceAction.DECREASE_SPEED),
null);
} else if (command instanceof OnOffType) {
break;
case CHANNEL_RAW_FAN_SPEED:
- if (command instanceof DecimalType) {
- value = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ value = decimalCommand.intValue();
BondDeviceProperties devProperties = this.deviceProperties;
if (devProperties != null) {
if (value < 1) {
logger.trace("Fan direction command {}", command.toString());
if (command instanceof StringType) {
api.executeDeviceAction(deviceId, BondDeviceAction.SET_DIRECTION,
- command.toString().equals("winter") ? -1 : 1);
+ "winter".equals(command.toString()) ? -1 : 1);
}
break;
break;
case CHANNEL_LIGHT_BRIGHTNESS:
- if (command instanceof PercentType) {
- PercentType pctCommand = (PercentType) command;
- value = pctCommand.intValue();
+ if (command instanceof PercentType percentCommand) {
+ value = percentCommand.intValue();
if (value == 0) {
action = BondDeviceAction.TURN_LIGHT_OFF;
value = null;
}
logger.trace("Fan light brightness command with value of {}", value);
api.executeDeviceAction(deviceId, action, value);
- } else if (command instanceof IncreaseDecreaseType) {
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
logger.trace("Fan light brightness increase/decrease command {}", command);
api.executeDeviceAction(deviceId,
- ((IncreaseDecreaseType) command == IncreaseDecreaseType.INCREASE
+ (increaseDecreaseCommand == IncreaseDecreaseType.INCREASE
? BondDeviceAction.INCREASE_BRIGHTNESS
: BondDeviceAction.DECREASE_BRIGHTNESS),
null);
case CHANNEL_UP_LIGHT_BRIGHTNESS:
enableUpLight();
- if (command instanceof PercentType) {
- PercentType pctCommand = (PercentType) command;
- value = pctCommand.intValue();
+ if (command instanceof PercentType percentCommand) {
+ value = percentCommand.intValue();
if (value == 0) {
action = BondDeviceAction.TURN_LIGHT_OFF;
value = null;
}
logger.trace("Fan up light brightness command with value of {}", value);
api.executeDeviceAction(deviceId, action, value);
- } else if (command instanceof IncreaseDecreaseType) {
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
logger.trace("Fan uplight brightness increase/decrease command {}", command);
api.executeDeviceAction(deviceId,
- ((IncreaseDecreaseType) command == IncreaseDecreaseType.INCREASE
+ (increaseDecreaseCommand == IncreaseDecreaseType.INCREASE
? BondDeviceAction.INCREASE_UP_LIGHT_BRIGHTNESS
: BondDeviceAction.DECREASE_UP_LIGHT_BRIGHTNESS),
null);
case CHANNEL_DOWN_LIGHT_BRIGHTNESS:
enableDownLight();
- if (command instanceof PercentType) {
- PercentType pctCommand = (PercentType) command;
- value = pctCommand.intValue();
+ if (command instanceof PercentType percentCommand) {
+ value = percentCommand.intValue();
if (value == 0) {
action = BondDeviceAction.TURN_LIGHT_OFF;
value = null;
}
logger.trace("Fan down light brightness command with value of {}", value);
api.executeDeviceAction(deviceId, action, value);
- } else if (command instanceof IncreaseDecreaseType) {
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
logger.trace("Fan down light brightness increase/decrease command");
api.executeDeviceAction(deviceId,
- ((IncreaseDecreaseType) command == IncreaseDecreaseType.INCREASE
+ (increaseDecreaseCommand == IncreaseDecreaseType.INCREASE
? BondDeviceAction.INCREASE_DOWN_LIGHT_BRIGHTNESS
: BondDeviceAction.DECREASE_DOWN_LIGHT_BRIGHTNESS),
null);
break;
case CHANNEL_FLAME:
- if (command instanceof PercentType) {
- PercentType pctCommand = (PercentType) command;
- value = pctCommand.intValue();
+ if (command instanceof PercentType percentCommand) {
+ value = percentCommand.intValue();
if (value == 0) {
action = BondDeviceAction.TURN_OFF;
value = null;
}
logger.trace("Fireplace flame command with value of {}", value);
api.executeDeviceAction(deviceId, action, value);
- } else if (command instanceof IncreaseDecreaseType) {
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
logger.trace("Fireplace flame increase/decrease command");
api.executeDeviceAction(deviceId,
- ((IncreaseDecreaseType) command == IncreaseDecreaseType.INCREASE
- ? BondDeviceAction.INCREASE_FLAME
+ (increaseDecreaseCommand == IncreaseDecreaseType.INCREASE ? BondDeviceAction.INCREASE_FLAME
: BondDeviceAction.DECREASE_FLAME),
null);
} else if (command instanceof OnOffType) {
updateProperty(thingProperties, PROPERTIES_TEMPLATE_NAME, devInfo.template);
thingProperties.put(PROPERTIES_MAX_SPEED, String.valueOf(devProperties.maxSpeed));
thingProperties.put(PROPERTIES_TRUST_STATE, String.valueOf(devProperties.trustState));
- thingProperties.put(PROPERTIES_ADDRESS, String.valueOf(devProperties.addr));
+ thingProperties.put(PROPERTIES_ADDRESS, devProperties.addr);
thingProperties.put(PROPERTIES_RF_FREQUENCY, String.valueOf(devProperties.freq));
logger.trace("Saving properties for {} ({})", config.deviceId, this.getThing().getLabel());
updateProperties(thingProperties);
this.oAuthClientService = oAuthClientService;
}
+ @Override
public String getAuthorizationHeader() throws IndegoAuthenticationException {
final AccessTokenResponse accessTokenResponse;
try {
throw new IndegoException(e);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
- if (cause != null && cause instanceof HttpResponseException) {
- Response response = ((HttpResponseException) cause).getResponse();
+ if (cause != null && cause instanceof HttpResponseException httpResponseException) {
+ Response response = httpResponseException.getResponse();
if (response.getStatus() == HttpStatus.UNAUTHORIZED_401) {
/*
* The service may respond with HTTP code 401 without any "WWW-Authenticate"
throw new IndegoException(e);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
- if (cause != null && cause instanceof HttpResponseException) {
- Response response = ((HttpResponseException) cause).getResponse();
+ if (cause != null && cause instanceof HttpResponseException httpResponseException) {
+ Response response = httpResponseException.getResponse();
if (response.getStatus() == HttpStatus.UNAUTHORIZED_401) {
/*
* When contextId is not valid, the service will respond with HTTP code 401 without
throw new IndegoException(e);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
- if (cause != null && cause instanceof HttpResponseException) {
- Response response = ((HttpResponseException) cause).getResponse();
+ if (cause != null && cause instanceof HttpResponseException httpResponseException) {
+ Response response = httpResponseException.getResponse();
if (response.getStatus() == HttpStatus.UNAUTHORIZED_401) {
/*
* When contextId is not valid, the service will respond with HTTP code 401 without
* @throws IndegoException if any communication or parsing error occurred
*/
public DeviceCalendarResponse getCalendar() throws IndegoAuthenticationException, IndegoException {
- DeviceCalendarResponse calendar = getRequest(SERIAL_NUMBER_SUBPATH + serialNumber + "/calendar",
- DeviceCalendarResponse.class);
- return calendar;
+ return getRequest(SERIAL_NUMBER_SUBPATH + serialNumber + "/calendar", DeviceCalendarResponse.class);
}
/**
}
}
+ @Override
public void onSuccessfulAuthorization() {
updateStatus(ThingStatus.ONLINE);
}
+ @Override
public void onFailedAuthorization(Throwable throwable) {
logger.debug("Authorization failure", throwable);
if (throwable instanceof IndegoAuthenticationException) {
}
}
+ @Override
public void onAuthorizationFlowCompleted() {
// Ignore
}
}
}
+ @Override
public void onSuccessfulAuthorization() {
// Ignore
}
+ @Override
public void onFailedAuthorization(Throwable throwable) {
// Ignore
}
+ @Override
public void onAuthorizationFlowCompleted() {
// Trigger immediate state refresh upon authorization success.
rescheduleStatePoll(0, stateInactiveRefreshIntervalSeconds, true);
handleRefreshCommand(channelUID.getId());
return;
}
- if (command instanceof DecimalType && channelUID.getId().equals(STATE)) {
- sendCommand(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand && channelUID.getId().equals(STATE)) {
+ sendCommand(decimalCommand.intValue());
}
} catch (IndegoAuthenticationException e) {
// Ignore, will be handled by bridge
import java.util.List;
import java.util.Objects;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(ThingDiscoveryService.class);
+ return Set.of(ThingDiscoveryService.class);
}
@Override
super.handleCommand(channelUID, command);
switch (channelUID.getId()) {
case CHANNEL_SETPOINT_TEMPERATURE:
- if (command instanceof QuantityType<?>) {
- updateSetpointTemperature((QuantityType<?>) command);
+ if (command instanceof QuantityType<?> temperature) {
+ updateSetpointTemperature(temperature);
}
break;
}
switch (channelUID.getId()) {
case CHANNEL_ARM_ACTION:
- if (command instanceof StringType) {
- armIntrusionDetectionSystem((StringType) command);
+ if (command instanceof StringType stringCommand) {
+ armIntrusionDetectionSystem(stringCommand);
}
break;
case CHANNEL_DISARM_ACTION:
- if (command instanceof OnOffType) {
- disarmIntrusionDetectionSystem((OnOffType) command);
+ if (command instanceof OnOffType onOffCommand) {
+ disarmIntrusionDetectionSystem(onOffCommand);
}
break;
case CHANNEL_MUTE_ACTION:
- if (command instanceof OnOffType) {
- muteIntrusionDetectionSystem((OnOffType) command);
+ if (command instanceof OnOffType onOffCommand) {
+ muteIntrusionDetectionSystem(onOffCommand);
}
break;
}
PRE_ALARM,
ALARM_ON,
ALARM_MUTED,
- UNKNOWN;
+ UNKNOWN
}
public enum ArmingState {
SYSTEM_ARMED,
SYSTEM_ARMING,
- SYSTEM_DISARMED;
+ SYSTEM_DISARMED
}
@NonNullByDefault
public enum ShutterContactState {
OPEN,
- CLOSED;
+ CLOSED
}
@NonNullByDefault
public enum OperationState {
MOVING,
- STOPPED;
+ STOPPED
}
@Override
public SmokeDetectorCheckServiceState handleCommand(Command command) throws BoschSHCException {
- if (command instanceof StringType) {
- var stringCommand = (StringType) command;
+ if (command instanceof StringType stringCommand) {
var state = new SmokeDetectorCheckServiceState();
state.value = SmokeDetectorCheckState.from(stringCommand.toString());
return state;
}
- if (command instanceof PlayPauseType) {
- var playPauseCommand = (PlayPauseType) command;
+ if (command instanceof PlayPauseType playPauseCommand) {
if (playPauseCommand.equals(PlayPauseType.PLAY)) {
var state = new SmokeDetectorCheckServiceState();
state.value = SmokeDetectorCheckState.SMOKE_TEST_REQUESTED;
@Test
public void testProcessUpdateBatteryLevelLowBattery() {
- JsonElement deviceServiceData = JsonParser.parseString("{ \n" + " \"@type\":\"DeviceServiceData\",\n"
- + " \"path\":\"/devices/hdm:ZigBee:000d6f0004b93361/services/BatteryLevel\",\n"
- + " \"id\":\"BatteryLevel\",\n" + " \"deviceId\":\"hdm:ZigBee:000d6f0004b93361\",\n"
- + " \"faults\":{ \n" + " \"entries\":[\n" + " {\n"
- + " \"type\":\"LOW_BATTERY\",\n" + " \"category\":\"WARNING\"\n" + " }\n"
- + " ]\n" + " }\n" + "}");
+ JsonElement deviceServiceData = JsonParser.parseString("""
+ {
+ "@type":"DeviceServiceData",
+ "path":"/devices/hdm:ZigBee:000d6f0004b93361/services/BatteryLevel",
+ "id":"BatteryLevel",
+ "deviceId":"hdm:ZigBee:000d6f0004b93361",
+ "faults":{
+ "entries":[
+ {
+ "type":"LOW_BATTERY",
+ "category":"WARNING"
+ }
+ ]
+ }
+ }\
+ """);
getFixture().processUpdate("BatteryLevel", deviceServiceData);
verify(getCallback()).stateUpdated(getChannelUID(BoschSHCBindingConstants.CHANNEL_BATTERY_LEVEL),
new DecimalType(10));
@Test
public void testProcessUpdateBatteryLevelCriticalLow() {
- JsonElement deviceServiceData = JsonParser.parseString("{ \n" + " \"@type\":\"DeviceServiceData\",\n"
- + " \"path\":\"/devices/hdm:ZigBee:000d6f0004b93361/services/BatteryLevel\",\n"
- + " \"id\":\"BatteryLevel\",\n" + " \"deviceId\":\"hdm:ZigBee:000d6f0004b93361\",\n"
- + " \"faults\":{ \n" + " \"entries\":[\n" + " {\n"
- + " \"type\":\"CRITICAL_LOW\",\n" + " \"category\":\"WARNING\"\n"
- + " }\n" + " ]\n" + " }\n" + "}");
+ JsonElement deviceServiceData = JsonParser.parseString("""
+ {
+ "@type":"DeviceServiceData",
+ "path":"/devices/hdm:ZigBee:000d6f0004b93361/services/BatteryLevel",
+ "id":"BatteryLevel",
+ "deviceId":"hdm:ZigBee:000d6f0004b93361",
+ "faults":{
+ "entries":[
+ {
+ "type":"CRITICAL_LOW",
+ "category":"WARNING"
+ }
+ ]
+ }
+ }\
+ """);
getFixture().processUpdate("BatteryLevel", deviceServiceData);
verify(getCallback()).stateUpdated(getChannelUID(BoschSHCBindingConstants.CHANNEL_BATTERY_LEVEL),
new DecimalType(1));
@Test
public void testProcessUpdateBatteryLevelCriticallyLowBattery() {
- JsonElement deviceServiceData = JsonParser.parseString("{ \n" + " \"@type\":\"DeviceServiceData\",\n"
- + " \"path\":\"/devices/hdm:ZigBee:000d6f0004b93361/services/BatteryLevel\",\n"
- + " \"id\":\"BatteryLevel\",\n" + " \"deviceId\":\"hdm:ZigBee:000d6f0004b93361\",\n"
- + " \"faults\":{ \n" + " \"entries\":[\n" + " {\n"
- + " \"type\":\"CRITICALLY_LOW_BATTERY\",\n" + " \"category\":\"WARNING\"\n"
- + " }\n" + " ]\n" + " }\n" + "}");
+ JsonElement deviceServiceData = JsonParser.parseString("""
+ {
+ "@type":"DeviceServiceData",
+ "path":"/devices/hdm:ZigBee:000d6f0004b93361/services/BatteryLevel",
+ "id":"BatteryLevel",
+ "deviceId":"hdm:ZigBee:000d6f0004b93361",
+ "faults":{
+ "entries":[
+ {
+ "type":"CRITICALLY_LOW_BATTERY",
+ "category":"WARNING"
+ }
+ ]
+ }
+ }\
+ """);
getFixture().processUpdate("BatteryLevel", deviceServiceData);
verify(getCallback()).stateUpdated(getChannelUID(BoschSHCBindingConstants.CHANNEL_BATTERY_LEVEL),
new DecimalType(1));
@Test
public void testProcessUpdateBatteryLevelOK() {
- JsonElement deviceServiceData = JsonParser.parseString("{ \n" + " \"@type\":\"DeviceServiceData\",\n"
- + " \"path\":\"/devices/hdm:ZigBee:000d6f0004b93361/services/BatteryLevel\",\n"
- + " \"id\":\"BatteryLevel\",\n" + " \"deviceId\":\"hdm:ZigBee:000d6f0004b93361\" }");
+ JsonElement deviceServiceData = JsonParser.parseString("""
+ {
+ "@type":"DeviceServiceData",
+ "path":"/devices/hdm:ZigBee:000d6f0004b93361/services/BatteryLevel",
+ "id":"BatteryLevel",
+ "deviceId":"hdm:ZigBee:000d6f0004b93361" }\
+ """);
getFixture().processUpdate("BatteryLevel", deviceServiceData);
verify(getCallback()).stateUpdated(
new ChannelUID(getThing().getUID(), BoschSHCBindingConstants.CHANNEL_BATTERY_LEVEL),
@Test
public void testProcessUpdateBatteryLevelNotAvailable() {
- JsonElement deviceServiceData = JsonParser.parseString("{ \n" + " \"@type\":\"DeviceServiceData\",\n"
- + " \"path\":\"/devices/hdm:ZigBee:000d6f0004b93361/services/BatteryLevel\",\n"
- + " \"id\":\"BatteryLevel\",\n" + " \"deviceId\":\"hdm:ZigBee:000d6f0004b93361\",\n"
- + " \"faults\":{ \n" + " \"entries\":[\n" + " {\n"
- + " \"type\":\"NOT_AVAILABLE\",\n" + " \"category\":\"WARNING\"\n"
- + " }\n" + " ]\n" + " }\n" + "}");
+ JsonElement deviceServiceData = JsonParser.parseString("""
+ {
+ "@type":"DeviceServiceData",
+ "path":"/devices/hdm:ZigBee:000d6f0004b93361/services/BatteryLevel",
+ "id":"BatteryLevel",
+ "deviceId":"hdm:ZigBee:000d6f0004b93361",
+ "faults":{
+ "entries":[
+ {
+ "type":"NOT_AVAILABLE",
+ "category":"WARNING"
+ }
+ ]
+ }
+ }\
+ """);
getFixture().processUpdate("BatteryLevel", deviceServiceData);
verify(getCallback()).stateUpdated(getChannelUID(BoschSHCBindingConstants.CHANNEL_BATTERY_LEVEL),
UnDefType.UNDEF);
@Test
public void testUpdateChannelPowerMeterServiceState() {
- JsonElement jsonObject = JsonParser.parseString("{\n" + " \"@type\": \"powerMeterState\",\n"
- + " \"powerConsumption\": \"23\",\n" + " \"energyConsumption\": 42\n" + "}");
+ JsonElement jsonObject = JsonParser.parseString("""
+ {
+ "@type": "powerMeterState",
+ "powerConsumption": "23",
+ "energyConsumption": 42
+ }\
+ """);
getFixture().processUpdate("PowerMeter", jsonObject);
verify(getCallback()).stateUpdated(eq(getChannelUID(BoschSHCBindingConstants.CHANNEL_POWER_CONSUMPTION)),
// mock a logger using reflection to avoid NPEs during logger calls
Logger mockedLogger = mock(Logger.class);
List<Field> fields = ReflectionSupport.findFields(BoschHttpClient.class,
- f -> f.getName().equalsIgnoreCase("logger"), HierarchyTraversalMode.TOP_DOWN);
+ f -> "logger".equalsIgnoreCase(f.getName()), HierarchyTraversalMode.TOP_DOWN);
Field field = fields.iterator().next();
field.setAccessible(true);
field.set(mockedHttpClient, mockedLogger);
// mock a logger using reflection to avoid NPEs during logger calls
Logger mockedLogger = mock(Logger.class);
List<Field> fields = ReflectionSupport.findFields(BoschHttpClient.class,
- f -> f.getName().equalsIgnoreCase("logger"), HierarchyTraversalMode.TOP_DOWN);
+ f -> "logger".equalsIgnoreCase(f.getName()), HierarchyTraversalMode.TOP_DOWN);
Field field = fields.iterator().next();
field.setAccessible(true);
field.set(mockedHttpClient, mockedLogger);
"{\"@type\": \"JsonRestExceptionResponseEntity\", \"errorCode\": \"500\", \"statusCode\": \"500\"}");
BoschSHCException e = assertThrows(BoschSHCException.class, () -> httpClient.sendRequest(request, Device.class,
- Device::isValid, (Integer statusCode, String content) -> {
- return new BoschSHCException("test exception");
- }));
+ Device::isValid, (Integer statusCode, String content) -> new BoschSHCException("test exception")));
assertEquals("test exception", e.getMessage());
}
when(response.getContentAsString()).thenReturn(
"{\"@type\": \"JsonRestExceptionResponseEntity\", \"errorCode\": \"500\", \"statusCode\": \"500\"}");
ExecutionException e = assertThrows(ExecutionException.class,
- () -> httpClient.sendRequest(request, SubscribeResult.class, sr -> {
- return false;
- }, null));
+ () -> httpClient.sendRequest(request, SubscribeResult.class, sr -> false, null));
String actualMessage = e.getMessage();
assertTrue(actualMessage.contains(
"Received invalid content for type org.openhab.binding.boschshc.internal.devices.bridge.dto.SubscribeResult:"));
when(response.getStatus()).thenReturn(200);
when(response.getContentAsString()).thenReturn("{\"@type\": \"JsonRestExceptionResponseEntity}");
ExecutionException e = assertThrows(ExecutionException.class,
- () -> httpClient.sendRequest(request, SubscribeResult.class, sr -> {
- return false;
- }, null));
+ () -> httpClient.sendRequest(request, SubscribeResult.class, sr -> false, null));
assertEquals(
"Received invalid content in response, expected type org.openhab.binding.boschshc.internal.devices.bridge.dto.SubscribeResult: com.google.gson.stream.MalformedJsonException: Unterminated string at line 1 column 44 path $.@type",
e.getMessage());
Request devicesRequest = mock(Request.class);
ContentResponse devicesResponse = mock(ContentResponse.class);
when(devicesResponse.getStatus()).thenReturn(200);
- when(devicesResponse.getContentAsString()).thenReturn("[{\"@type\":\"device\",\r\n"
- + " \"rootDeviceId\":\"64-da-a0-02-14-9b\",\r\n"
- + " \"id\":\"hdm:HomeMaticIP:3014F711A00004953859F31B\",\r\n"
- + " \"deviceServiceIds\":[\"PowerMeter\",\"PowerSwitch\",\"PowerSwitchProgram\",\"Routing\"],\r\n"
- + " \"manufacturer\":\"BOSCH\",\r\n" + " \"roomId\":\"hz_3\",\r\n" + " \"deviceModel\":\"PSM\",\r\n"
- + " \"serial\":\"3014F711A00004953859F31B\",\r\n" + " \"profile\":\"GENERIC\",\r\n"
- + " \"name\":\"Coffee Machine\",\r\n" + " \"status\":\"AVAILABLE\",\r\n" + " \"childDeviceIds\":[]\r\n"
- + " }]");
+ when(devicesResponse.getContentAsString()).thenReturn("""
+ [{"@type":"device",
+ "rootDeviceId":"64-da-a0-02-14-9b",
+ "id":"hdm:HomeMaticIP:3014F711A00004953859F31B",
+ "deviceServiceIds":["PowerMeter","PowerSwitch","PowerSwitchProgram","Routing"],
+ "manufacturer":"BOSCH",
+ "roomId":"hz_3",
+ "deviceModel":"PSM",
+ "serial":"3014F711A00004953859F31B",
+ "profile":"GENERIC",
+ "name":"Coffee Machine",
+ "status":"AVAILABLE",
+ "childDeviceIds":[]
+ }]\
+ """);
when(devicesRequest.send()).thenReturn(devicesResponse);
when(httpClient.createRequest(contains("/devices"), same(HttpMethod.GET))).thenReturn(devicesRequest);
Request longPollRequest = mock(Request.class);
when(httpClient.createRequest(anyString(), same(HttpMethod.POST),
- argThat((JsonRpcRequest r) -> r.method.equals("RE/longPoll")))).thenReturn(longPollRequest);
+ argThat((JsonRpcRequest r) -> "RE/longPoll".equals(r.method)))).thenReturn(longPollRequest);
fixture.initialAccess(httpClient);
verify(thingHandlerCallback).statusUpdated(any(),
when(request.header(anyString(), anyString())).thenReturn(request);
ContentResponse response = mock(ContentResponse.class);
when(response.getStatus()).thenReturn(200);
- when(response.getContentAsString()).thenReturn("{\r\n" + " \"@type\": \"systemState\",\r\n"
- + " \"systemAvailability\": {\r\n" + " \"@type\": \"systemAvailabilityState\",\r\n"
- + " \"available\": true,\r\n" + " \"deleted\": false\r\n" + " },\r\n"
- + " \"armingState\": {\r\n" + " \"@type\": \"armingState\",\r\n"
- + " \"state\": \"SYSTEM_DISARMED\",\r\n" + " \"deleted\": false\r\n" + " },\r\n"
- + " \"alarmState\": {\r\n" + " \"@type\": \"alarmState\",\r\n"
- + " \"value\": \"ALARM_OFF\",\r\n" + " \"incidents\": [],\r\n"
- + " \"deleted\": false\r\n" + " },\r\n" + " \"activeConfigurationProfile\": {\r\n"
- + " \"@type\": \"activeConfigurationProfile\",\r\n" + " \"deleted\": false\r\n"
- + " },\r\n" + " \"securityGapState\": {\r\n" + " \"@type\": \"securityGapState\",\r\n"
- + " \"securityGaps\": [],\r\n" + " \"deleted\": false\r\n" + " },\r\n"
- + " \"deleted\": false\r\n" + " }");
+ when(response.getContentAsString()).thenReturn("""
+ {
+ "@type": "systemState",
+ "systemAvailability": {
+ "@type": "systemAvailabilityState",
+ "available": true,
+ "deleted": false
+ },
+ "armingState": {
+ "@type": "armingState",
+ "state": "SYSTEM_DISARMED",
+ "deleted": false
+ },
+ "alarmState": {
+ "@type": "alarmState",
+ "value": "ALARM_OFF",
+ "incidents": [],
+ "deleted": false
+ },
+ "activeConfigurationProfile": {
+ "@type": "activeConfigurationProfile",
+ "deleted": false
+ },
+ "securityGapState": {
+ "@type": "securityGapState",
+ "securityGaps": [],
+ "deleted": false
+ },
+ "deleted": false
+ }\
+ """);
when(request.send()).thenReturn(response);
when(httpClient.createRequest(anyString(), same(HttpMethod.GET))).thenReturn(request);
when(request.header(anyString(), anyString())).thenReturn(request);
ContentResponse response = mock(ContentResponse.class);
when(response.getStatus()).thenReturn(200);
- when(response.getContentAsString()).thenReturn("{ \n" + " \"@type\":\"DeviceServiceData\",\n"
- + " \"path\":\"/devices/hdm:ZigBee:000d6f0004b93361/services/BatteryLevel\",\n"
- + " \"id\":\"BatteryLevel\",\n" + " \"deviceId\":\"hdm:ZigBee:000d6f0004b93361\",\n"
- + " \"faults\":{ \n" + " \"entries\":[\n" + " {\n"
- + " \"type\":\"LOW_BATTERY\",\n" + " \"category\":\"WARNING\"\n" + " }\n"
- + " ]\n" + " }\n" + "}");
+ when(response.getContentAsString()).thenReturn("""
+ {
+ "@type":"DeviceServiceData",
+ "path":"/devices/hdm:ZigBee:000d6f0004b93361/services/BatteryLevel",
+ "id":"BatteryLevel",
+ "deviceId":"hdm:ZigBee:000d6f0004b93361",
+ "faults":{\s
+ "entries":[
+ {
+ "type":"LOW_BATTERY",
+ "category":"WARNING"
+ }
+ ]
+ }
+ }\
+ """);
when(request.send()).thenReturn(response);
when(httpClient.createRequest(anyString(), same(HttpMethod.GET))).thenReturn(request);
Request subscribeRequest = mock(Request.class);
when(httpClient.createRequest(anyString(), same(HttpMethod.POST),
- argThat((JsonRpcRequest r) -> r.method.equals("RE/subscribe")))).thenReturn(subscribeRequest);
+ argThat((JsonRpcRequest r) -> "RE/subscribe".equals(r.method)))).thenReturn(subscribeRequest);
SubscribeResult subscribeResult = new SubscribeResult();
when(httpClient.sendRequest(any(), same(SubscribeResult.class), any(), any())).thenReturn(subscribeResult);
Request longPollRequest = mock(Request.class);
when(httpClient.createRequest(anyString(), same(HttpMethod.POST),
- argThat((JsonRpcRequest r) -> r.method.equals("RE/longPoll")))).thenReturn(longPollRequest);
+ argThat((JsonRpcRequest r) -> "RE/longPoll".equals(r.method)))).thenReturn(longPollRequest);
fixture.start(httpClient);
Request longPollRequest = mock(Request.class);
when(httpClient.createRequest(anyString(), same(HttpMethod.POST),
- argThat((JsonRpcRequest r) -> r.method.equals("RE/longPoll")))).thenReturn(longPollRequest);
+ argThat((JsonRpcRequest r) -> "RE/longPoll".equals(r.method)))).thenReturn(longPollRequest);
fixture.start(httpClient);
Request subscribeRequest = mock(Request.class);
when(httpClient.createRequest(anyString(), same(HttpMethod.POST),
- argThat((JsonRpcRequest r) -> r.method.equals("RE/subscribe")))).thenReturn(subscribeRequest);
+ argThat((JsonRpcRequest r) -> "RE/subscribe".equals(r.method)))).thenReturn(subscribeRequest);
SubscribeResult subscribeResult = new SubscribeResult();
when(httpClient.sendRequest(any(), same(SubscribeResult.class), any(), any())).thenReturn(subscribeResult);
Request longPollRequest = mock(Request.class);
when(httpClient.createRequest(anyString(), same(HttpMethod.POST),
- argThat((JsonRpcRequest r) -> r.method.equals("RE/longPoll")))).thenReturn(longPollRequest);
+ argThat((JsonRpcRequest r) -> "RE/longPoll".equals(r.method)))).thenReturn(longPollRequest);
fixture.start(httpClient);
@Test
void testUpdateChannelsTemperatureLevelService() {
- JsonElement jsonObject = JsonParser.parseString(
- "{\n" + " \"@type\": \"temperatureLevelState\",\n" + " \"temperature\": 21.5\n" + " }");
+ JsonElement jsonObject = JsonParser.parseString("""
+ {
+ "@type": "temperatureLevelState",
+ "temperature": 21.5
+ }\
+ """);
getFixture().processUpdate("TemperatureLevel", jsonObject);
verify(getCallback()).stateUpdated(
new ChannelUID(getThing().getUID(), BoschSHCBindingConstants.CHANNEL_TEMPERATURE),
@Test
void testUpdateChannelsRoomClimateControlService() {
- JsonElement jsonObject = JsonParser.parseString(
- "{\n" + " \"@type\": \"climateControlState\",\n" + " \"setpointTemperature\": 21.5\n" + " }");
+ JsonElement jsonObject = JsonParser.parseString("""
+ {
+ "@type": "climateControlState",
+ "setpointTemperature": 21.5
+ }\
+ """);
getFixture().processUpdate("RoomClimateControl", jsonObject);
verify(getCallback()).stateUpdated(
new ChannelUID(getThing().getUID(), BoschSHCBindingConstants.CHANNEL_SETPOINT_TEMPERATURE),
@Test
void testUpdateChannelsIntrusionDetectionSystemState() {
- JsonElement jsonObject = JsonParser.parseString("{\n" + " \"@type\": \"systemState\",\n"
- + " \"systemAvailability\": {\n" + " \"@type\": \"systemAvailabilityState\",\n"
- + " \"available\": true,\n" + " \"deleted\": false\n" + " },\n"
- + " \"armingState\": {\n" + " \"@type\": \"armingState\",\n"
- + " \"state\": \"SYSTEM_DISARMED\",\n" + " \"deleted\": false\n" + " },\n"
- + " \"alarmState\": {\n" + " \"@type\": \"alarmState\",\n"
- + " \"value\": \"ALARM_OFF\",\n" + " \"incidents\": [],\n"
- + " \"deleted\": false\n" + " },\n" + " \"activeConfigurationProfile\": {\n"
- + " \"@type\": \"activeConfigurationProfile\",\n" + " \"deleted\": false\n"
- + " },\n" + " \"securityGapState\": {\n" + " \"@type\": \"securityGapState\",\n"
- + " \"securityGaps\": [],\n" + " \"deleted\": false\n" + " },\n"
- + " \"deleted\": false\n" + " }\n");
+ JsonElement jsonObject = JsonParser.parseString("""
+ {
+ "@type": "systemState",
+ "systemAvailability": {
+ "@type": "systemAvailabilityState",
+ "available": true,
+ "deleted": false
+ },
+ "armingState": {
+ "@type": "armingState",
+ "state": "SYSTEM_DISARMED",
+ "deleted": false
+ },
+ "alarmState": {
+ "@type": "alarmState",
+ "value": "ALARM_OFF",
+ "incidents": [],
+ "deleted": false
+ },
+ "activeConfigurationProfile": {
+ "@type": "activeConfigurationProfile",
+ "deleted": false
+ },
+ "securityGapState": {
+ "@type": "securityGapState",
+ "securityGaps": [],
+ "deleted": false
+ },
+ "deleted": false
+ }
+ """);
getFixture().processUpdate(BoschSHCBindingConstants.SERVICE_INTRUSION_DETECTION, jsonObject);
verify(getCallback()).stateUpdated(
new ChannelUID(getThing().getUID(), BoschSHCBindingConstants.CHANNEL_SYSTEM_AVAILABILITY),
@Test
void testUpdateChannelsIntrusionDetectionControlState() {
- JsonElement jsonObject = JsonParser.parseString("{\n" + " \"@type\": \"intrusionDetectionControlState\",\n"
- + " \"activeProfile\": \"0\",\n" + " \"alarmActivationDelayTime\": 30,\n" + " \"actuators\": [\n"
- + " {\n" + " \"readonly\": false,\n" + " \"active\": true,\n"
- + " \"id\": \"intrusion:video\"\n" + " },\n" + " {\n" + " \"readonly\": false,\n"
- + " \"active\": false,\n" + " \"id\": \"intrusion:siren\"\n" + " }\n" + " ],\n"
- + " \"remainingTimeUntilArmed\": 29559,\n" + " \"armActivationDelayTime\": 30,\n"
- + " \"triggers\": [\n" + " {\n" + " \"readonly\": false,\n" + " \"active\": true,\n"
- + " \"id\": \"hdm:ZigBee:000d6f0012f02378\"\n" + " }\n" + " ],\n"
- + " \"value\": \"SYSTEM_ARMING\"\n" + " }");
+ JsonElement jsonObject = JsonParser.parseString("""
+ {
+ "@type": "intrusionDetectionControlState",
+ "activeProfile": "0",
+ "alarmActivationDelayTime": 30,
+ "actuators": [
+ {
+ "readonly": false,
+ "active": true,
+ "id": "intrusion:video"
+ },
+ {
+ "readonly": false,
+ "active": false,
+ "id": "intrusion:siren"
+ }
+ ],
+ "remainingTimeUntilArmed": 29559,
+ "armActivationDelayTime": 30,
+ "triggers": [
+ {
+ "readonly": false,
+ "active": true,
+ "id": "hdm:ZigBee:000d6f0012f02378"
+ }
+ ],
+ "value": "SYSTEM_ARMING"
+ }\
+ """);
getFixture().processUpdate("IntrusionDetectionControl", jsonObject);
verify(getCallback()).stateUpdated(
new ChannelUID(getThing().getUID(), BoschSHCBindingConstants.CHANNEL_ARMING_STATE),
@Test
void testUpdateChannelsSurveillanceAlarmState() {
- JsonElement jsonObject = JsonParser.parseString("{\n" + " \"@type\": \"surveillanceAlarmState\",\n"
- + " \"incidents\": [\n" + " {\n" + " \"triggerName\": \"Motion Detector\",\n"
- + " \"locationId\": \"hz_5\",\n" + " \"location\": \"Living Room\",\n"
- + " \"id\": \"hdm:ZigBee:000d6f0012f02342\",\n" + " \"time\": 1652615755336,\n"
- + " \"type\": \"INTRUSION\"\n" + " }\n" + " ],\n" + " \"value\": \"ALARM_ON\"\n" + " }");
+ JsonElement jsonObject = JsonParser.parseString("""
+ {
+ "@type": "surveillanceAlarmState",
+ "incidents": [
+ {
+ "triggerName": "Motion Detector",
+ "locationId": "hz_5",
+ "location": "Living Room",
+ "id": "hdm:ZigBee:000d6f0012f02342",
+ "time": 1652615755336,
+ "type": "INTRUSION"
+ }
+ ],
+ "value": "ALARM_ON"
+ }\
+ """);
getFixture().processUpdate("SurveillanceAlarm", jsonObject);
verify(getCallback()).stateUpdated(
new ChannelUID(getThing().getUID(), BoschSHCBindingConstants.CHANNEL_ALARM_STATE),
@Test
void testUpdateChannelsLatestMotionService() {
- JsonElement jsonObject = JsonParser.parseString("{\n" + " \"@type\": \"latestMotionState\",\n"
- + " \"latestMotionDetected\": \"2020-04-03T19:02:19.054Z\"\n" + " }");
+ JsonElement jsonObject = JsonParser.parseString("""
+ {
+ "@type": "latestMotionState",
+ "latestMotionDetected": "2020-04-03T19:02:19.054Z"
+ }\
+ """);
getFixture().processUpdate("LatestMotion", jsonObject);
verify(getCallback()).stateUpdated(
new ChannelUID(getThing().getUID(), BoschSHCBindingConstants.CHANNEL_LATEST_MOTION),
@Test
void testUpdateChannelHSBColorActuatorState() {
- JsonElement jsonObject = JsonParser.parseString("{\"colorTemperatureRange\": {\n" + " \"minCt\": 153,\n"
- + " \"maxCt\": 526\n" + " },\n" + " \"@type\": \"colorState\",\n"
- + " \"gamut\": \"LEDVANCE_GAMUT_A\",\n" + " \"rgb\": -12427}");
+ JsonElement jsonObject = JsonParser.parseString("""
+ {"colorTemperatureRange": {
+ "minCt": 153,
+ "maxCt": 526
+ },
+ "@type": "colorState",
+ "gamut": "LEDVANCE_GAMUT_A",
+ "rgb": -12427}\
+ """);
getFixture().processUpdate("HSBColorActuator", jsonObject);
verify(getCallback()).stateUpdated(new ChannelUID(getThing().getUID(), BoschSHCBindingConstants.CHANNEL_COLOR),
HSBType.fromRGB(255, 207, 117));
@Test
void testUpdateChannelsTemperatureLevelService() {
- JsonElement jsonObject = JsonParser.parseString(
- "{\n" + " \"@type\": \"temperatureLevelState\",\n" + " \"temperature\": 21.5\n" + " }");
+ JsonElement jsonObject = JsonParser.parseString("""
+ {
+ "@type": "temperatureLevelState",
+ "temperature": 21.5
+ }\
+ """);
getFixture().processUpdate("TemperatureLevel", jsonObject);
verify(getCallback()).stateUpdated(
new ChannelUID(getThing().getUID(), BoschSHCBindingConstants.CHANNEL_TEMPERATURE),
@Test
void testUpdateChannelsAirQualityLevelService() {
JsonElement jsonObject = JsonParser.parseString(
- "{\"temperatureRating\":\"GOOD\",\"humidityRating\":\"MEDIUM\",\"purity\":620,\"@type\":\"airQualityLevelState\",\n"
- + " \"purityRating\":\"GOOD\",\"temperature\":23.77,\"description\":\"LITTLE_DRY\",\"humidity\":32.69,\"combinedRating\":\"MEDIUM\"}");
+ """
+ {"temperatureRating":"GOOD","humidityRating":"MEDIUM","purity":620,"@type":"airQualityLevelState",
+ "purityRating":"GOOD","temperature":23.77,"description":"LITTLE_DRY","humidity":32.69,"combinedRating":"MEDIUM"}\
+ """);
getFixture().processUpdate("AirQualityLevel", jsonObject);
verify(getCallback()).stateUpdated(
@Test
void testUpdateChannelsTemperatureLevelService() {
- JsonElement jsonObject = JsonParser.parseString(
- "{\n" + " \"@type\": \"temperatureLevelState\",\n" + " \"temperature\": 21.5\n" + " }");
+ JsonElement jsonObject = JsonParser.parseString("""
+ {
+ "@type": "temperatureLevelState",
+ "temperature": 21.5
+ }\
+ """);
getFixture().processUpdate("TemperatureLevel", jsonObject);
verify(getCallback()).stateUpdated(
new ChannelUID(getThing().getUID(), BoschSHCBindingConstants.CHANNEL_TEMPERATURE),
@Test
void onStateUpdate() {
- final String json = "{\n" + "\"@type\": \"intrusionDetectionControlState\",\n" + "\"activeProfile\": \"0\",\n"
- + "\"alarmActivationDelayTime\": 30,\n" + "\"actuators\": [\n" + "{\n" + "\"readonly\": false,\n"
- + "\"active\": true,\n" + "\"id\": \"intrusion:video\"\n" + "},\n" + "{\n" + "\"readonly\": false,\n"
- + "\"active\": false,\n" + "\"id\": \"intrusion:siren\"\n" + "}\n" + "],\n"
- + "\"remainingTimeUntilArmed\": 28959,\n" + "\"armActivationDelayTime\": 30,\n" + "\"triggers\": [\n"
- + "{\n" + "\"readonly\": false,\n" + "\"active\": true,\n" + "\"id\": \"hdm:ZigBee:000d6f0422f42378\"\n"
- + "}\n" + "],\n" + "\"value\": \"SYSTEM_ARMING\"\n" + "}";
+ final String json = """
+ {
+ "@type":"intrusionDetectionControlState",
+ "activeProfile":"0",
+ "alarmActivationDelayTime":30,
+ "actuators":[
+ {
+ "readonly":false,
+ "active":true,
+ "id":"intrusion:video"
+ },
+ {
+ "readonly":false,
+ "active":false,
+ "id":"intrusion:siren"
+ }
+ ],
+ "remainingTimeUntilArmed":28959,
+ "armActivationDelayTime":30,
+ "triggers":[
+ {
+ "readonly":false,
+ "active":true,
+ "id":"hdm:ZigBee:000d6f0422f42378"
+ }
+ ],
+ "value":"SYSTEM_ARMING"
+ }\
+ """;
JsonElement jsonElement = JsonParser.parseString(json);
fixture.onStateUpdate(jsonElement);
verify(consumer).accept(any());
ContentItem.class.getClassLoader());
BoseStateDescriptionOptionProvider localDescriptionOptionProvider = stateOptionProvider;
if (localDescriptionOptionProvider != null) {
- BoseSoundTouchHandler handler = new BoseSoundTouchHandler(thing, new PresetContainer(storage),
- localDescriptionOptionProvider);
- return handler;
+ return new BoseSoundTouchHandler(thing, new PresetContainer(storage), localDescriptionOptionProvider);
}
}
return null;
*/
@Override
public boolean equals(@Nullable Object obj) {
- if (obj instanceof ContentItem) {
- ContentItem other = (ContentItem) obj;
+ if (obj instanceof ContentItem other) {
return Objects.equals(other.source, this.source) || Objects.equals(other.sourceAccount, this.sourceAccount)
|| other.presetable == this.presetable || Objects.equals(other.location, this.location)
|| Objects.equals(other.itemName, this.itemName);
* ' - '
*/
private String escapeXml(String xml) {
- xml = xml.replaceAll("&", "&");
- xml = xml.replaceAll("<", "<");
- xml = xml.replaceAll(">", ">");
- xml = xml.replaceAll("\"", """);
- xml = xml.replaceAll("'", "'");
+ xml = xml.replace("&", "&");
+ xml = xml.replace("<", "<");
+ xml = xml.replace(">", ">");
+ xml = xml.replace("\"", """);
+ xml = xml.replace("'", "'");
return xml;
}
}
public StateOption toStateOption() {
- String stateOptionLabel = String.valueOf(presetID) + ": " + itemName;
+ String stateOptionLabel = presetID + ": " + itemName;
return new StateOption(String.valueOf(presetID), stateOptionLabel);
}
Integer.toHexString(dev.getDeviceType()), dev.getHost(), dev.getMac());
ThingUID thingUID;
- String id = dev.getHost().replaceAll("\\.", "-");
+ String id = dev.getHost().replace(".", "-");
logger.debug("Device ID with IP address replacement: {}", id);
try {
id = getHostnameWithoutDomain(InetAddress.getByName(dev.getHost()).getHostName());
if (hostname.matches(broadlinkRegex)) {
String[] dotSeparatedString = hostname.split("\\.");
logger.debug("Found original broadlink DNS name {}, removing domain", hostname);
- return dotSeparatedString[0].replaceAll("\\.", "-");
+ return dotSeparatedString[0].replace(".", "-");
} else {
logger.debug("DNS name does not match original broadlink name: {}, using it without modification. ",
hostname);
- return hostname.replaceAll("\\.", "-");
+ return hostname.replace(".", "-");
}
}
}
private void handleSetpointCommand(ChannelUID channelUID, Command command) {
FloureonDevice floureonDevice = this.floureonDevice;
- if (command instanceof QuantityType && floureonDevice != null) {
+ if (command instanceof QuantityType quantityCommand && floureonDevice != null) {
try {
- QuantityType<?> temperatureQuantityType = ((QuantityType<?>) command).toUnit(SIUnits.CELSIUS);
+ QuantityType<?> temperatureQuantityType = quantityCommand.toUnit(SIUnits.CELSIUS);
if (temperatureQuantityType != null) {
floureonDevice.setThermostatTemp(temperatureQuantityType.doubleValue());
} else {
}
private void handleSetTimeCommand(ChannelUID channelUID, Command command) {
- if (command instanceof DateTimeType) {
- ZonedDateTime zonedDateTime = ((DateTimeType) command).getZonedDateTime();
+ if (command instanceof DateTimeType dateTimeCommand) {
+ ZonedDateTime zonedDateTime = dateTimeCommand.getZonedDateTime();
try {
new SetTimeCommand(tob(zonedDateTime.getHour()), tob(zonedDateTime.getMinute()),
tob(zonedDateTime.getSecond()), tob(zonedDateTime.getDayOfWeek().getValue()))
return null;
}
ThingHandler handler = bridge.getHandler();
- if (handler instanceof BsbLanBridgeHandler) {
- this.bridgeHandler = (BsbLanBridgeHandler) handler;
+ if (handler instanceof BsbLanBridgeHandler lanBridgeHandler) {
+ this.bridgeHandler = lanBridgeHandler;
}
}
return this.bridgeHandler;
private static State getStateForSwitchValueChannel(BsbLanApiParameterDTO parameter) {
// treat "0" as OFF and everything else as ON
- return parameter.value.equals("0") ? OnOffType.OFF : OnOffType.ON;
+ return "0".equals(parameter.value) ? OnOffType.OFF : OnOffType.ON;
}
/**
}
private static @Nullable String getValueForNumberValueChannel(Command command) {
- if (command instanceof QuantityType<?>) {
- // the target unit is yet unknown, so just use the value as is (without converting based on the unit)
- QuantityType<?> quantity = (QuantityType<?>) command;
+ if (command instanceof QuantityType<?> quantity) {
return String.valueOf(quantity.doubleValue());
}
// check if numeric
@Test
public void parseBsbLanApiParameterQueryResponse() {
- String content = "{\r\n" + "\"700\": {\r\n" + "\"name\": \"Betriebsart\",\r\n" + "\"value\": \"0\",\r\n"
- + "\"unit\": \"\",\r\n" + "\"desc\": \"Schutzbetrieb\",\r\n" + "\"dataType\": 1\r\n" + "}\r\n" + "}";
+ String content = """
+ {
+ "700": {
+ "name": "Betriebsart",
+ "value": "0",
+ "unit": "",
+ "desc": "Schutzbetrieb",
+ "dataType": 1
+ }
+ }\
+ """;
BsbLanApiParameterQueryResponseDTO r = BsbLanApiContentConverter.fromJson(content,
BsbLanApiParameterQueryResponseDTO.class);
} catch (ExecutionException e) {
final Throwable cause = e.getCause();
- if (cause instanceof SmartherGatewayException) {
- throw (SmartherGatewayException) cause;
+ if (cause instanceof SmartherGatewayException gatewayException) {
+ throw gatewayException;
} else {
throw new SmartherGatewayException(e.getMessage(), e);
}
if (locations == null || locations.isEmpty()) {
return null;
}
- return locations.stream().map(a -> String.valueOf(a.getName())).collect(Collectors.joining(NAME_SEPARATOR));
+ return locations.stream().map(a -> a.getName()).collect(Collectors.joining(NAME_SEPARATOR));
}
@Override
if (modules == null || modules.isEmpty()) {
return null;
}
- return modules.stream().map(a -> String.valueOf(a.getName())).collect(Collectors.joining(NAME_SEPARATOR));
+ return modules.stream().map(a -> a.getName()).collect(Collectors.joining(NAME_SEPARATOR));
}
}
import static org.openhab.binding.bticinosmarther.internal.SmartherBindingConstants.*;
-import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
implements DiscoveryService, ThingHandlerService {
// Only modules can be discovered. A bridge must be manually added.
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_MODULE);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_MODULE);
private static final int DISCOVERY_TIME_SECONDS = 30;
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof SmartherAccountHandler) {
- final SmartherAccountHandler localBridgeHandler = (SmartherAccountHandler) handler;
+ if (handler instanceof SmartherAccountHandler localBridgeHandler) {
this.bridgeHandler = localBridgeHandler;
this.bridgeUID = localBridgeHandler.getUID();
}
@Override
protected synchronized void removeHandler(ThingHandler thingHandler) {
- if (thingHandler instanceof SmartherBridgeHandler) {
- authService.removeSmartherAccountHandler((SmartherBridgeHandler) thingHandler);
+ if (thingHandler instanceof SmartherBridgeHandler bridgeHandler) {
+ authService.removeSmartherAccountHandler(bridgeHandler);
}
}
}
import java.util.Collections;
import java.util.List;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(SmartherModuleDiscoveryService.class);
+ return Set.of(SmartherModuleDiscoveryService.class);
}
// ===========================================================================
}
break;
case CHANNEL_SETTINGS_PROGRAM:
- if (command instanceof DecimalType) {
- localModuleSettings.setProgram(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ localModuleSettings.setProgram(decimalCommand.intValue());
return;
}
break;
case CHANNEL_SETTINGS_BOOSTTIME:
- if (command instanceof DecimalType) {
- localModuleSettings.setBoostTime(BoostTime.fromValue(((DecimalType) command).intValue()));
+ if (command instanceof DecimalType decimalCommand) {
+ localModuleSettings.setBoostTime(BoostTime.fromValue(decimalCommand.intValue()));
return;
}
break;
* @return {@code true} if the change succeeded, {@code false} otherwise
*/
private boolean changeTimeHour(Command command, final ModuleSettings settings) {
- if (command instanceof DecimalType) {
- int endHour = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ int endHour = decimalCommand.intValue();
if (endHour >= 0 && endHour <= 23) {
settings.setEndHour(endHour);
return true;
* @return {@code true} if the change succeeded, {@code false} otherwise
*/
private boolean changeTimeMinute(Command command, final ModuleSettings settings) {
- if (command instanceof DecimalType) {
- int endMinute = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ int endMinute = decimalCommand.intValue();
if (endMinute >= 0 && endMinute <= 59) {
// Only 15 min increments are allowed
endMinute = Math.round(endMinute / 15) * 15;
* @return the passed in string, or the empty string if it was {@code null}
*
*/
- public static final String defaultString(@Nullable String str) {
+ public static String defaultString(@Nullable String str) {
return (str == null) ? "" : str;
}
}
try {
final Optional<List<Prediction>> predictionsOpt = client.getPredictions(location);
- if (!predictionsOpt.isPresent()) {
+ if (predictionsOpt.isEmpty()) {
// Did not get a result, retry the retrieval.
// Buienradar is not a very stable source and returns nothing quite regular
if (tries <= 2) {
import static org.openhab.binding.buienradar.internal.BuienradarBindingConstants.THING_TYPE_RAIN_FORECAST;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.buienradar", service = ThingHandlerFactory.class)
public class BuienradarHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_RAIN_FORECAST);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_RAIN_FORECAST);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
public enum CaddxMessageContext {
NONE,
DISCOVERY,
- COMMAND;
+ COMMAND
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof CaddxBridgeHandler) {
- this.handler = (CaddxBridgeHandler) handler;
+ if (handler instanceof CaddxBridgeHandler bridgeHandler) {
+ this.handler = bridgeHandler;
}
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof ThingHandlerKeypad) {
- this.handler = (ThingHandlerKeypad) handler;
+ if (handler instanceof ThingHandlerKeypad keypadHandler) {
+ this.handler = keypadHandler;
}
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof ThingHandlerPanel) {
- this.handler = (ThingHandlerPanel) handler;
+ if (handler instanceof ThingHandlerPanel panelHandler) {
+ this.handler = panelHandler;
}
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof ThingHandlerPartition) {
- this.handler = (ThingHandlerPartition) handler;
+ if (handler instanceof ThingHandlerPartition partitionHandler) {
+ this.handler = partitionHandler;
}
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof ThingHandlerZone) {
- this.handler = (ThingHandlerZone) handler;
+ if (handler instanceof ThingHandlerZone zoneHandler) {
+ this.handler = zoneHandler;
}
}
*/
package org.openhab.binding.caddx.internal.discovery;
-import java.util.Collections;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
thingUID = new ThingUID(CaddxBindingConstants.PARTITION_THING_TYPE, bridge.getUID(), thingID);
if (partition != null) {
- properties = Collections.singletonMap(CaddxPartitionConfiguration.PARTITION_NUMBER, partition);
+ properties = Map.of(CaddxPartitionConfiguration.PARTITION_NUMBER, partition);
representationProperty = CaddxPartitionConfiguration.PARTITION_NUMBER;
}
thingUID = new ThingUID(CaddxBindingConstants.ZONE_THING_TYPE, bridge.getUID(), thingID);
if (zone != null) {
- properties = Collections.singletonMap(CaddxZoneConfiguration.ZONE_NUMBER, zone);
+ properties = Map.of(CaddxZoneConfiguration.ZONE_NUMBER, zone);
representationProperty = CaddxZoneConfiguration.ZONE_NUMBER;
}
break;
thingUID = new ThingUID(CaddxBindingConstants.KEYPAD_THING_TYPE, bridge.getUID(), thingID);
if (keypad != null) {
- properties = Collections.singletonMap(CaddxKeypadConfiguration.KEYPAD_ADDRESS, keypad);
+ properties = Map.of(CaddxKeypadConfiguration.KEYPAD_ADDRESS, keypad);
representationProperty = CaddxKeypadConfiguration.KEYPAD_ADDRESS;
}
break;
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof CaddxBridgeHandler) {
- caddxBridgeHandler = (CaddxBridgeHandler) handler;
+ if (handler instanceof CaddxBridgeHandler bridgeHandler) {
+ caddxBridgeHandler = bridgeHandler;
}
}
ThingHandler handler = bridge.getHandler();
- if (handler instanceof CaddxBridgeHandler) {
- this.caddxBridgeHandler = (CaddxBridgeHandler) handler;
+ if (handler instanceof CaddxBridgeHandler bridgeHandler) {
+ this.caddxBridgeHandler = bridgeHandler;
} else {
logger.debug("getCaddxBridgeHandler(): Unable to get bridge handler!");
}
switch (caddxMessage.getCaddxMessageType()) {
case PARTITIONS_SNAPSHOT_MESSAGE:
for (int i = 1; i <= 8; i++) {
- if (caddxMessage.getPropertyById("partition_" + i + "_valid").equals("true")) {
+ if ("true".equals(caddxMessage.getPropertyById("partition_" + i + "_valid"))) {
thing = findThing(CaddxThingType.PARTITION, i, null, null);
if (thing != null) {
continue;
PANEL,
PARTITION,
ZONE,
- KEYPAD;
+ KEYPAD
}
package org.openhab.binding.caddx.internal.handler;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.caddx.internal.CaddxBindingConstants;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(CaddxKeypadActions.class);
+ return Set.of(CaddxKeypadActions.class);
}
public void enterTerminalMode() {
package org.openhab.binding.caddx.internal.handler;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(CaddxPanelActions.class);
+ return Set.of(CaddxPanelActions.class);
}
private void sendPrimaryCommand(String pin, String function) {
package org.openhab.binding.caddx.internal.handler;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.caddx.internal.CaddxBindingConstants;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(CaddxPartitionActions.class);
+ return Set.of(CaddxPartitionActions.class);
}
private void sendPrimaryCommand(String pin, String function) {
package org.openhab.binding.caddx.internal.handler;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.caddx.internal.CaddxBindingConstants;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(CaddxZoneActions.class);
+ return Set.of(CaddxZoneActions.class);
}
public void bypass() {
public class CaddxMessageParseTest {
// @formatter:off
- public static final List<Object[]> data() {
+ public static List<Object[]> data() {
return Arrays.asList(new Object[][] {
{ "interface_configuration_message", "panel_firmware_version", "5.37", },
{ "interface_configuration_message", "panel_interface_configuration_message", "true", },
// now also re-initialize all network handlers
for (Thing thing : getThing().getThings()) {
ThingHandler handler = thing.getHandler();
- if (handler instanceof CBusNetworkHandler) {
- ((CBusNetworkHandler) handler).cgateStateChanged(isOnline);
+ if (handler instanceof CBusNetworkHandler networkHandler) {
+ networkHandler.cgateStateChanged(isOnline);
}
}
});
continue;
}
- if (thingThingHandler instanceof CBusGroupHandler) {
- ((CBusGroupHandler) thingThingHandler).updateGroup(application, group, value);
+ if (thingThingHandler instanceof CBusGroupHandler groupHandler) {
+ groupHandler.updateGroup(application, group, value);
}
}
}
} else if (command == OnOffType.OFF) {
group.off();
}
- } else if (command instanceof PercentType) {
- PercentType value = (PercentType) command;
- group.ramp((int) Math.round(value.doubleValue() / 100 * 255), 0);
+ } else if (command instanceof PercentType percentCommand) {
+ group.ramp((int) Math.round(percentCommand.doubleValue() / 100 * 255), 0);
} else if (command instanceof IncreaseDecreaseType) {
int level = group.getLevel();
if (command == IncreaseDecreaseType.DECREASE) {
}
}
+ @Override
public void updateGroup(int updateApplicationId, int updateGroupId, String value) {
if (updateGroupId == groupId && updateApplicationId == applicationId) {
Thing thing = getThing();
return null;
}
ThingHandler handler = bridge.getHandler();
- if (handler instanceof CBusNetworkHandler) {
- return (CBusNetworkHandler) handler;
+ if (handler instanceof CBusNetworkHandler networkHandler) {
+ return networkHandler;
}
logger.debug("No available bridge handler found for bridge: {}", bridge.getUID());
return null;
} else if (command == OnOffType.OFF) {
group.off();
}
- } else if (command instanceof PercentType) {
- PercentType value = (PercentType) command;
- group.ramp((int) Math.round(value.doubleValue() / 100 * 255), 0);
+ } else if (command instanceof PercentType percentCommand) {
+ group.ramp((int) Math.round(percentCommand.doubleValue() / 100 * 255), 0);
} else if (command instanceof IncreaseDecreaseType) {
int level = group.getLevel();
if (command == IncreaseDecreaseType.DECREASE) {
}
}
+ @Override
public void updateGroup(int updateApplicationId, int updateGroupId, String value) {
if (updateGroupId == groupId && updateApplicationId == applicationId) {
Thing thing = getThing();
}
for (Thing thing : getThing().getThings()) {
ThingHandler handler = thing.getHandler();
- if (handler instanceof CBusGroupHandler) {
- ((CBusGroupHandler) handler).updateStatus();
+ if (handler instanceof CBusGroupHandler groupHandler) {
+ groupHandler.updateStatus();
}
}
}
return null;
}
ThingHandler handler = bridge.getHandler();
- if (handler instanceof CBusCGateHandler) {
- return (CBusCGateHandler) handler;
+ if (handler instanceof CBusCGateHandler gateHandler) {
+ return gateHandler;
} else {
logger.debug("No available bridge handler found for bridge: {}.", bridge.getUID());
return null;
}
}
+ @Override
public void updateGroup(int updateApplicationId, int updateGroupId, String value) {
if (updateGroupId == groupId && updateApplicationId == applicationId) {
Thing thing = getThing();
if (channelUID.getId().equals(CBusBindingConstants.CHANNEL_VALUE)) {
logger.debug("Channel Value command for {}: {}", channelUID, command);
try {
- if (command instanceof DecimalType) {
- group.TriggerEvent(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ group.TriggerEvent(decimalCommand.intValue());
}
} catch (CGateException e) {
logger.debug("Failed to send trigger command {} to {}", command, group, e);
}
}
+ @Override
public void updateGroup(int updateApplicationId, int updateGroupId, String value) {
if (updateGroupId == groupId && updateApplicationId == applicationId) {
Thing thing = getThing();
handler.stop();
} else {
final String url;
- if (audioStream instanceof URLAudioStream) {
- // it is an external URL, the speaker can access it itself and play it.
- URLAudioStream urlAudioStream = (URLAudioStream) audioStream;
+ if (audioStream instanceof URLAudioStream urlAudioStream) {
+ // it is an external URL, the speaker can access it itself and play it
url = urlAudioStream.getURL();
tryClose(audioStream);
} else {
return;
}
- if (command instanceof PlayPauseType) {
+ if (command instanceof PlayPauseType playPauseCommand) {
MediaStatus mediaStatus = chromeCast.getMediaStatus();
logger.debug("mediaStatus {}", mediaStatus);
if (mediaStatus == null || mediaStatus.playerState == MediaStatus.PlayerState.IDLE) {
logger.debug("{} command ignored because media is not loaded", command);
return;
}
-
- final PlayPauseType playPause = (PlayPauseType) command;
- if (playPause == PlayPauseType.PLAY) {
+ if (playPauseCommand == PlayPauseType.PLAY) {
chromeCast.play();
- } else if (playPause == PlayPauseType.PAUSE
+ } else if (playPauseCommand == PlayPauseType.PAUSE
&& ((mediaStatus.supportedMediaCommands & 0x00000001) == 0x1)) {
chromeCast.pause();
} else {
}
public void handleVolume(final Command command) {
- if (command instanceof PercentType) {
- setVolumeInternal((PercentType) command);
+ if (command instanceof PercentType percentCommand) {
+ setVolumeInternal(percentCommand);
} else if (command == IncreaseDecreaseType.INCREASE) {
setVolumeInternal(new PercentType(
Math.min(statusUpdater.getVolume().intValue() + VOLUMESTEP, PercentType.HUNDRED.intValue())));
state = new DecimalType(((Integer) value).longValue());
} else if (value instanceof String) {
state = new StringType(value.toString());
- } else if (value instanceof ZonedDateTime) {
- state = new DateTimeType((ZonedDateTime) value);
+ } else if (value instanceof ZonedDateTime datetime) {
+ state = new DateTimeType(datetime);
} else {
state = UnDefType.UNDEF;
logger.warn("Update channel {}: Unsupported value type {}", channelUID, value.getClass().getSimpleName());
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof ChromecastHandler) {
- this.handler = (ChromecastHandler) handler;
+ if (handler instanceof ChromecastHandler chromecastHandler) {
+ this.handler = chromecastHandler;
}
}
import static org.openhab.binding.cm11a.internal.CM11ABindingConstants.*;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
import java.util.Set;
import org.openhab.binding.cm11a.internal.handler.Cm11aApplianceHandler;
private final Logger logger = LoggerFactory.getLogger(Cm11aHandlerFactory.class);
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .unmodifiableSet(new HashSet<>(Arrays.asList(THING_TYPE_SWITCH, THING_TYPE_DIMMER)));
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_SWITCH, THING_TYPE_DIMMER);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
/**
* Lookup table to convert House code received from the cm11a into an X10 house code
*/
- public static final char HOUSE_CODE[] = new char[] { 'M', 'E', 'C', 'K', 'O', 'G', 'A', 'I', 'N', 'F', 'D', 'L',
+ public static final char[] HOUSE_CODE = new char[] { 'M', 'E', 'C', 'K', 'O', 'G', 'A', 'I', 'N', 'F', 'D', 'L',
'P', 'H', 'B', 'J' };
/**
* Lookup table to convert Unit code received from the cm11a into an X10 unit code
*/
- public static final byte UNIT_CODE[] = new byte[] { 13, 5, 3, 11, 15, 7, 1, 9, 14, 6, 4, 12, 16, 8, 2, 10 };
+ public static final byte[] UNIT_CODE = new byte[] { 13, 5, 3, 11, 15, 7, 1, 9, 14, 6, 4, 12, 16, 8, 2, 10 };
private String[] addr;
private X10COMMAND cmd;
desiredState = OnOffType.ON;
} else if (OnOffType.OFF.equals(command)) {
desiredState = OnOffType.OFF;
- } else if (command instanceof PercentType) {
- desiredState = (PercentType) command;
+ } else if (command instanceof PercentType percentCommand) {
+ desiredState = percentCommand;
} else if (command instanceof RefreshType) {
// Refresh is triggered by framework during startup.
// Force the lamp off by indicating it is currently on and we want it off
x10Status = x10Interface.sendFunction(houseUnitCode, X10Interface.FUNC_ON);
} else if (desiredState.equals(OnOffType.OFF)) {
x10Status = x10Interface.sendFunction(houseUnitCode, X10Interface.FUNC_OFF);
- } else if (desiredState instanceof PercentType) {
+ } else if (desiredState instanceof PercentType desiredStatePercent) {
// desiredState must be a PercentType if we got here.
// Calc how many bright increments we need to send (0 to 22)
- int desiredPercentFullBright = ((PercentType) desiredState).intValue();
+ int desiredPercentFullBright = desiredStatePercent.intValue();
int dims = (desiredPercentFullBright * X10_DIM_INCREMENTS) / 100;
if (currentState.equals(OnOffType.ON)) {
// The current level isn't known because it would have gone to
// desiredState must be a PercentType if we got here. And, the light should be off
// We should just be able to send the appropriate number if dims
x10Status = x10Interface.sendFunction(houseUnitCode, X10Interface.FUNC_BRIGHT, dims);
- } else if (currentState instanceof PercentType) {
+ } else if (currentState instanceof PercentType currentStatePercent) {
// This is the expected case
// Now currentState and desiredState are both PercentType's
// Need to calc how much to dim or brighten
- int currentPercentFullBright = ((PercentType) currentState).intValue();
+ int currentPercentFullBright = currentStatePercent.intValue();
int percentToBrighten = desiredPercentFullBright - currentPercentFullBright;
int brightens = (percentToBrighten * X10_DIM_INCREMENTS) / 100;
if (brightens > 0) {
if (on != null) {
updateState(ON, "1".equals(on) ? OnOffType.ON : OnOffType.OFF);
}
- } else if (command instanceof OnOffType) {
- final OnOffType onoff = (OnOffType) command;
- controller.sendCommand(String.format("%s %s", onoff == OnOffType.ON ? "on" : "off", uid));
+ } else if (command instanceof OnOffType onOffCommand) {
+ controller
+ .sendCommand(String.format("%s %s", onOffCommand == OnOffType.ON ? "on" : "off", uid));
}
break;
case SET_TEMP:
final QuantityType<?> value = new QuantityType<>(temp, controller.getUnit());
updateState(SET_TEMP, value);
}
- } else if (command instanceof QuantityType) {
- final QuantityType<?> temp = (QuantityType) command;
- final QuantityType<?> converted = temp.toUnit(controller.getUnit());
+ } else if (command instanceof QuantityType quantityCommand) {
+ final QuantityType<?> converted = quantityCommand.toUnit(controller.getUnit());
final String formatted = converted.format("%.1f");
controller.sendCommand(String.format("temp %s %s", uid, formatted));
}
if (mode != null) {
updateState(MODE, new StringType(mode));
}
- } else if (command instanceof StringType) {
- final String mode = ((StringType) command).toString();
+ } else if (command instanceof StringType stringCommand) {
+ final String mode = stringCommand.toString();
controller.sendCommand(String.format("%s %s", mode, uid));
}
break;
if (fan != null) {
updateState(FAN_SPEED, new StringType(fan));
}
- } else if (command instanceof StringType) {
- final String fan = ((StringType) command).toString();
+ } else if (command instanceof StringType stringCommand) {
+ final String fan = stringCommand.toString();
controller.sendCommand(String.format("fspeed %s %s", uid, fan));
}
break;
if (louvre != null) {
updateState(LOUVRE, new StringType(louvre));
}
- } else if (command instanceof StringType) {
- final String louvre = ((StringType) command).toString();
+ } else if (command instanceof StringType stringCommand) {
+ final String louvre = stringCommand.toString();
controller.sendCommand(String.format("swing %s %s", uid, louvre));
}
break;
Bridge bridge = getBridge();
if (bridge != null) {
ThingHandler handler = bridge.getHandler();
- if (handler instanceof CoronaStatsWorldHandler) {
- return (CoronaStatsWorldHandler) handler;
+ if (handler instanceof CoronaStatsWorldHandler worldHandler) {
+ return worldHandler;
}
}
@Override
public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
- if (childHandler instanceof CoronaStatsCountryHandler) {
+ if (childHandler instanceof CoronaStatsCountryHandler listener) {
logger.debug("Register thing listener.");
- final CoronaStatsCountryHandler listener = (CoronaStatsCountryHandler) childHandler;
if (countryListeners.add(listener)) {
final CoronaStats localCoronaStats = coronaStats;
if (localCoronaStats != null) {
@Override
public void childHandlerDisposed(ThingHandler childHandler, Thing childThing) {
- if (childHandler instanceof CoronaStatsCountryHandler) {
+ if (childHandler instanceof CoronaStatsCountryHandler countryHandler) {
logger.debug("Unregister thing listener.");
- if (!countryListeners.remove((CoronaStatsCountryHandler) childHandler)) {
+ if (!countryListeners.remove(countryHandler)) {
logger.warn("Tried to remove listener {} but it was not registered. This is probably an error.",
childHandler);
}
private static final Logger LOGGER = LoggerFactory.getLogger(AirbaseZoneInfo.class);
public String zonenames = "";
- public boolean zone[] = new boolean[8];
+ public boolean[] zone = new boolean[8];
private AirbaseZoneInfo() {
}
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
private @Nullable ScheduledFuture<?> backgroundFuture;
public DaikinACUnitDiscoveryService() {
- super(Collections.singleton(DaikinBindingConstants.THING_TYPE_AC_UNIT), 600, true);
+ super(Set.of(DaikinBindingConstants.THING_TYPE_AC_UNIT), 600, true);
}
@Override
throws DaikinCommunicationException {
switch (channelUID.getId()) {
case DaikinBindingConstants.CHANNEL_AC_FAN_DIR:
- if (command instanceof StringType) {
- changeFanDir(((StringType) command).toString());
+ if (command instanceof StringType stringCommand) {
+ changeFanDir(stringCommand.toString());
return true;
}
break;
case DaikinBindingConstants.CHANNEL_AC_SPECIALMODE:
- if (command instanceof StringType) {
- changeSpecialMode(((StringType) command).toString());
+ if (command instanceof StringType stringCommand) {
+ changeSpecialMode(stringCommand.toString());
return true;
}
break;
case DaikinBindingConstants.CHANNEL_AC_STREAMER:
- if (command instanceof OnOffType) {
- changeStreamer(((OnOffType) command).equals(OnOffType.ON));
+ if (command instanceof OnOffType onOffCommand) {
+ changeStreamer(onOffCommand.equals(OnOffType.ON));
return true;
}
break;
}
switch (channelUID.getId()) {
case DaikinBindingConstants.CHANNEL_AC_POWER:
- if (command instanceof OnOffType) {
- changePower(((OnOffType) command).equals(OnOffType.ON));
+ if (command instanceof OnOffType onOffCommand) {
+ changePower(onOffCommand.equals(OnOffType.ON));
return;
}
break;
break;
case DaikinBindingConstants.CHANNEL_AIRBASE_AC_FAN_SPEED:
case DaikinBindingConstants.CHANNEL_AC_FAN_SPEED:
- if (command instanceof StringType) {
- changeFanSpeed(((StringType) command).toString());
+ if (command instanceof StringType stringCommand) {
+ changeFanSpeed(stringCommand.toString());
return;
}
break;
}
break;
case DaikinBindingConstants.CHANNEL_AC_MODE:
- if (command instanceof StringType) {
- changeMode(((StringType) command).toString());
+ if (command instanceof StringType stringCommand) {
+ changeMode(stringCommand.toString());
return;
}
break;
*/
private boolean changeSetPoint(Command command) throws DaikinCommunicationException {
double newTemperature;
- if (command instanceof DecimalType) {
- newTemperature = ((DecimalType) command).doubleValue();
+ if (command instanceof DecimalType decimalCommand) {
+ newTemperature = decimalCommand.doubleValue();
} else if (command instanceof QuantityType) {
newTemperature = ((QuantityType<Temperature>) command).toUnit(SIUnits.CELSIUS).doubleValue();
} else {
boolean queryDeviceState = false;
- if (command instanceof PercentType) {
- byte dimmValue = (byte) ((((PercentType) command).floatValue() * DALI_SWITCH_100_PERCENT) / 100);
+ if (command instanceof PercentType percentCommand) {
+ byte dimmValue = (byte) ((percentCommand.floatValue() * DALI_SWITCH_100_PERCENT) / 100);
// A dimm value of zero is handled correctly by DALI devices, i.e. they are turned off
getBridgeHandler().sendCommand(new DaliDAPCCommand(address, dimmValue));
- } else if (command instanceof OnOffType) {
- if ((OnOffType) command == OnOffType.ON) {
+ } else if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
getBridgeHandler().sendCommand(new DaliDAPCCommand(address, (byte) DALI_SWITCH_100_PERCENT));
} else {
getBridgeHandler().sendCommand(DaliStandardCommand.createOffCommand(address));
}
- } else if (command instanceof IncreaseDecreaseType) {
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
if (CHANNEL_DIM_AT_FADE_RATE.equals(channelUID.getId())) {
- if ((IncreaseDecreaseType) command == IncreaseDecreaseType.INCREASE) {
+ if (increaseDecreaseCommand == IncreaseDecreaseType.INCREASE) {
getBridgeHandler().sendCommand(DaliStandardCommand.createUpCommand(address));
} else {
getBridgeHandler().sendCommand(DaliStandardCommand.createDownCommand(address));
}
} else {
- if ((IncreaseDecreaseType) command == IncreaseDecreaseType.INCREASE) {
+ if (increaseDecreaseCommand == IncreaseDecreaseType.INCREASE) {
getBridgeHandler().sendCommand(DaliStandardCommand.createStepUpCommand(address));
} else {
getBridgeHandler().sendCommand(DaliStandardCommand.createStepDownCommand(address));
throw new DaliException("unknown device type");
}
int mirek;
- if (command instanceof DecimalType) {
+ if (command instanceof DecimalType decimalCommand) {
// Color temperature in DALI is represented in mirek ("reciprocal megakelvin")
// It is one million times the reciprocal of the color temperature (in Kelvin)
- mirek = (int) (1E6f / (Math.min(Math.max(((DecimalType) command).intValue(), 1000), 20000)));
- } else if (command instanceof QuantityType) {
+ mirek = (int) (1E6f / (Math.min(Math.max(decimalCommand.intValue(), 1000), 20000)));
+ } else if (command instanceof QuantityType quantityCommand) {
// ensure it's in the correct units
- QuantityType<?> commandQuantity = ((QuantityType) command).toInvertibleUnit(Units.MIRED);
+ QuantityType<?> commandQuantity = quantityCommand.toInvertibleUnit(Units.MIRED);
if (commandQuantity == null) {
logger.warn("Unable to convert command {} to mireks", command);
return;
} else {
throw new DaliException("unknown device type");
}
- if (command instanceof HSBType) {
- PercentType[] rgb = ((HSBType) command).toRGB();
+ if (command instanceof HSBType hsbCommand) {
+ PercentType[] rgb = hsbCommand.toRGB();
final int r = (int) (254 * (rgb[0].floatValue() / 100));
final int g = (int) (254 * (rgb[1].floatValue() / 100));
final int b = (int) (254 * (rgb[2].floatValue() / 100));
if (CHANNEL_COLOR.equals(channelUID.getId())) {
boolean queryDeviceState = false;
- if (command instanceof HSBType) {
- PercentType[] rgb = ((HSBType) command).toRGB();
+ if (command instanceof HSBType hsbCommand) {
+ PercentType[] rgb = hsbCommand.toRGB();
for (int i = 0; i < 3; i++) {
byte dimmValue = (byte) ((rgb[i].floatValue() * DALI_SWITCH_100_PERCENT) / 100);
getBridgeHandler().sendCommand(
new DaliDAPCCommand(DaliAddress.createShortAddress(outputs.get(i)), dimmValue));
}
- } else if (command instanceof OnOffType) {
- if ((OnOffType) command == OnOffType.ON) {
+ } else if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
for (Integer output : outputs) {
getBridgeHandler().sendCommand(new DaliDAPCCommand(DaliAddress.createShortAddress(output),
(byte) DALI_SWITCH_100_PERCENT));
DaliStandardCommand.createOffCommand(DaliAddress.createShortAddress(output)));
}
}
- } else if (command instanceof IncreaseDecreaseType) {
- if ((IncreaseDecreaseType) command == IncreaseDecreaseType.INCREASE) {
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ if (increaseDecreaseCommand == IncreaseDecreaseType.INCREASE) {
for (Integer output : outputs) {
getBridgeHandler().sendCommand(
DaliStandardCommand.createUpCommand(DaliAddress.createShortAddress(output)));
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.net.SocketTimeoutException;
-import java.util.Collections;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
*/
@NonNullByDefault
public class DaliserverBridgeHandler extends BaseBridgeHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(BRIDGE_TYPE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(BRIDGE_TYPE);
private final Logger logger = LoggerFactory.getLogger(DaliserverBridgeHandler.class);
private static final int DALI_DEFAULT_TIMEOUT = 5000;
}
private DecimalType setNumberTypeRegister(Command cmd, byte[] register) throws IOException {
- if (cmd instanceof DecimalType) {
- byte value = (byte) ((DecimalType) cmd).intValue();
+ if (cmd instanceof DecimalType decimalCommand) {
+ byte value = (byte) decimalCommand.intValue();
set(REGISTER_1_WRITE, register, value);
}
return new DecimalType(BigDecimal.valueOf(getByte(REGISTER_1_READ, register)));
}
private PercentType setPercentTypeRegister(Command cmd, byte[] register) throws IOException {
- if (cmd instanceof PercentType) {
- byte value = (byte) ((((PercentType) cmd).intValue() + 5) / 10);
+ if (cmd instanceof PercentType percentCommand) {
+ byte value = (byte) ((percentCommand.intValue() + 5) / 10);
set(REGISTER_1_WRITE, register, value);
}
return new PercentType(BigDecimal.valueOf(getByte(REGISTER_1_READ, register) * 10));
this.port = port;
}
+ @Override
public synchronized void connect() throws IOException {
if (connected) {
return;
connected = true;
}
+ @Override
public synchronized void disconnect() {
if (!connected) {
return;
connected = false;
}
+ @Override
public byte[] sendRobustRequest(byte[] operation, byte[] register) throws IOException {
return sendRobustRequest(operation, register, EMPTY);
}
+ @Override
public synchronized byte[] sendRobustRequest(byte[] operation, byte[] register, byte[] value) throws IOException {
connect();
byte[] request = new byte[4 + value.length];
import static org.openhab.binding.danfossairunit.internal.DanfossAirUnitBindingConstants.THING_TYPE_AIRUNIT;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.danfossairunit", service = ThingHandlerFactory.class)
public class DanfossAirUnitHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_AIRUNIT);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_AIRUNIT);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
@RuleAction(label = "Set query parameters", description = "Set query parameters for a query")
public void setQueryParameters(@ActionInput(name = "parameters") Map<String, @Nullable Object> parameters) {
logger.debug("setQueryParameters {}", parameters);
- var queryHandler = getThingHandler();
- if (queryHandler instanceof QueryHandler) {
- ((QueryHandler) queryHandler).setParameters(parameters);
+ var thingHandler = getThingHandler();
+ if (thingHandler instanceof QueryHandler queryHandler) {
+ queryHandler.setParameters(parameters);
} else {
logger.warn("setQueryParameters called on wrong Thing, it must be a Query Thing");
}
@Override
public void setThingHandler(ThingHandler thingHandler) {
- if (thingHandler instanceof QueryHandler) {
- this.queryHandler = ((QueryHandler) thingHandler);
- } else if (thingHandler instanceof DatabaseBridgeHandler) {
- this.databaseBridgeHandler = ((DatabaseBridgeHandler) thingHandler);
+ if (thingHandler instanceof QueryHandler queryHandler) {
+ this.queryHandler = queryHandler;
+ } else if (thingHandler instanceof DatabaseBridgeHandler databaseBridgeHandler) {
+ this.databaseBridgeHandler = databaseBridgeHandler;
} else {
throw new UnnexpectedCondition("Not expected thing handler " + thingHandler);
}
private void updateStateWithParentBridgeStatus() {
final @Nullable Bridge bridge = getBridge();
- DatabaseBridgeHandler databaseBridgeHandler;
if (bridge != null) {
@Nullable
BridgeHandler bridgeHandler = bridge.getHandler();
- if (bridgeHandler instanceof DatabaseBridgeHandler) {
- databaseBridgeHandler = (DatabaseBridgeHandler) bridgeHandler;
+ if (bridgeHandler instanceof DatabaseBridgeHandler databaseBridgeHandler) {
database = databaseBridgeHandler.getDatabase();
if (bridge.getStatus() == ThingStatus.ONLINE) {
updateStatus(ThingStatus.ONLINE);
}
private State convert2DateTime(Object value) {
- if (value instanceof Instant) {
- return new DateTimeType(ZonedDateTime.ofInstant((Instant) value, ZoneId.systemDefault()));
- } else if (value instanceof Date) {
- return new DateTimeType(ZonedDateTime.ofInstant(((Date) value).toInstant(), ZoneId.systemDefault()));
- } else if (value instanceof String) {
- return new DateTimeType((String) value);
+ if (value instanceof Instant instant) {
+ return new DateTimeType(ZonedDateTime.ofInstant(instant, ZoneId.systemDefault()));
+ } else if (value instanceof Date date) {
+ return new DateTimeType(ZonedDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()));
+ } else if (value instanceof String string) {
+ return new DateTimeType(string);
} else {
logger.warn("Can't convert {} to DateTimeType", value);
return UnDefType.NULL;
return new DecimalType((Float) value);
} else if (value instanceof Double) {
return new DecimalType((Double) value);
- } else if (value instanceof BigDecimal) {
- return new DecimalType((BigDecimal) value);
- } else if (value instanceof BigInteger) {
- return new DecimalType(new BigDecimal((BigInteger) value));
- } else if (value instanceof Number) {
- return new DecimalType(((Number) value).longValue());
- } else if (value instanceof String) {
- return DecimalType.valueOf((String) value);
- } else if (value instanceof Duration) {
- return new DecimalType(((Duration) value).toMillis());
+ } else if (value instanceof BigDecimal decimal) {
+ return new DecimalType(decimal);
+ } else if (value instanceof BigInteger integer) {
+ return new DecimalType(new BigDecimal(integer));
+ } else if (value instanceof Number number) {
+ return new DecimalType(number.longValue());
+ } else if (value instanceof String string) {
+ return DecimalType.valueOf(string);
+ } else if (value instanceof Duration duration) {
+ return new DecimalType(duration.toMillis());
} else {
logger.warn("Can't convert {} to DecimalType", value);
return UnDefType.NULL;
}
private State convert2String(Object value) {
- if (value instanceof String) {
- return new StringType((String) value);
- } else if (value instanceof byte[]) {
- return new StringType(Base64.getEncoder().encodeToString((byte[]) value));
- } else if (value instanceof QueryResult) {
- return new StringType(jsonEncoder.encode((QueryResult) value));
+ if (value instanceof String string) {
+ return new StringType(string);
+ } else if (value instanceof byte[] bytes) {
+ return new StringType(Base64.getEncoder().encodeToString(bytes));
+ } else if (value instanceof QueryResult result) {
+ return new StringType(jsonEncoder.encode(result));
} else {
return new StringType(String.valueOf(value));
}
}
private @Nullable Boolean convert2Boolean(Object value) {
- if (value instanceof Boolean) {
- return (Boolean) value;
- } else if (value instanceof Number) {
- return ((Number) value).doubleValue() != 0d;
- } else if (value instanceof String) {
- var svalue = (String) value;
- return Boolean.parseBoolean(svalue) || (svalue.equalsIgnoreCase("on")) || svalue.equals("1");
+ if (value instanceof Boolean boolean1) {
+ return boolean1;
+ } else if (value instanceof Number number) {
+ return number.doubleValue() != 0d;
+ } else if (value instanceof String svalue) {
+ return Boolean.parseBoolean(svalue) || ("on".equalsIgnoreCase(svalue)) || "1".equals(svalue);
} else {
logger.warn("Can't convert {} to OnOffType or OpenClosedType", value);
return null;
@Override
public CompletableFuture<QueryResult> executeQuery(Query query) {
try {
- if (query instanceof Influx2QueryFactory.Influx2Query) {
- Influx2QueryFactory.Influx2Query influxQuery = (Influx2QueryFactory.Influx2Query) query;
+ if (query instanceof Influx2QueryFactory.Influx2Query influxQuery) {
CompletableFuture<QueryResult> asyncResult = new CompletableFuture<>();
List<FluxRecord> records = new ArrayList<>();
}
private static JsonElement convertValueToJsonPrimitive(@Nullable Object value) {
- if (value instanceof Number) {
- return new JsonPrimitive((Number) value);
- } else if (value instanceof Boolean) {
- return new JsonPrimitive((Boolean) value);
+ if (value instanceof Number number) {
+ return new JsonPrimitive(number);
+ } else if (value instanceof Boolean boolean1) {
+ return new JsonPrimitive(boolean1);
} else if (value instanceof Character) {
return new JsonPrimitive((Character) value);
- } else if (value instanceof Date) {
- return new JsonPrimitive(DateTimeFormatter.ISO_INSTANT.format(((Date) value).toInstant()));
- } else if (value instanceof Instant) {
- return new JsonPrimitive(DateTimeFormatter.ISO_INSTANT.format((Instant) value));
+ } else if (value instanceof Date date) {
+ return new JsonPrimitive(DateTimeFormatter.ISO_INSTANT.format(date.toInstant()));
+ } else if (value instanceof Instant instant) {
+ return new JsonPrimitive(DateTimeFormatter.ISO_INSTANT.format(instant));
} else if (value != null) {
return new JsonPrimitive(value.toString());
} else {
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof DeconzBridgeHandler) {
- this.handler = (DeconzBridgeHandler) handler;
+ if (handler instanceof DeconzBridgeHandler bridgeHandler) {
+ this.handler = bridgeHandler;
}
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof GroupThingHandler) {
- this.handler = (GroupThingHandler) handler;
+ if (handler instanceof GroupThingHandler thingHandler) {
+ this.handler = thingHandler;
}
}
import java.net.URI;
import java.net.URL;
-import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(BRIDGE_TYPE);
+ return Set.of(BRIDGE_TYPE);
}
@Override
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof DeconzBridgeHandler) {
- this.handler = (DeconzBridgeHandler) handler;
+ if (handler instanceof DeconzBridgeHandler bridgeHandler) {
+ this.handler = bridgeHandler;
this.bridgeUID = handler.getThing().getUID();
}
}
newGroupAction.xy = new double[] { xy[0], xy[1] };
newGroupAction.bri = (int) (xy[2] * BRIGHTNESS_MAX);
}
- } else if (command instanceof PercentType) {
- newGroupAction.bri = Util.fromPercentType((PercentType) command);
- } else if (command instanceof DecimalType) {
- newGroupAction.bri = ((DecimalType) command).intValue();
+ } else if (command instanceof PercentType percentCommand) {
+ newGroupAction.bri = Util.fromPercentType(percentCommand);
+ } else if (command instanceof DecimalType decimalCommand) {
+ newGroupAction.bri = decimalCommand.intValue();
} else {
return;
}
import static org.openhab.core.library.unit.Units.PERCENT;
import java.math.BigDecimal;
-import java.util.Collections;
import java.util.List;
import java.util.Set;
*/
@NonNullByDefault
public class SensorThermostatThingHandler extends SensorBaseThingHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_THERMOSTAT);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_THERMOSTAT);
private static final List<String> CONFIG_CHANNELS = List.of(CHANNEL_EXTERNAL_WINDOW_OPEN, CHANNEL_BATTERY_LEVEL,
CHANNEL_BATTERY_LOW, CHANNEL_HEATSETPOINT, CHANNEL_TEMPERATURE_OFFSET, CHANNEL_THERMOSTAT_MODE,
newConfig.offset = newOffset;
}
case CHANNEL_THERMOSTAT_MODE -> {
- if (command instanceof StringType) {
- String thermostatMode = ((StringType) command).toString();
+ if (command instanceof StringType stringCommand) {
+ String thermostatMode = stringCommand.toString();
try {
newConfig.mode = ThermostatMode.valueOf(thermostatMode);
} catch (IllegalArgumentException ex) {
private @Nullable Integer getTemperatureFromCommand(Command command) {
BigDecimal newTemperature;
- if (command instanceof DecimalType) {
- newTemperature = ((DecimalType) command).toBigDecimal();
+ if (command instanceof DecimalType decimalCommand) {
+ newTemperature = decimalCommand.toBigDecimal();
} else if (command instanceof QuantityType) {
@SuppressWarnings("unchecked")
QuantityType<Temperature> temperatureCelsius = ((QuantityType<Temperature>) command).toUnit(CELSIUS);
import static org.openhab.binding.denonmarantz.internal.DenonMarantzBindingConstants.THING_TYPE_AVR;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@NonNullByDefault
public class DenonMarantzHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_AVR);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_AVR);
private final HttpClient httpClient;
cmd += "UP";
} else if (command == IncreaseDecreaseType.DECREASE) {
cmd += "DOWN";
- } else if (command instanceof DecimalType) {
- cmd += toDenonValue(((DecimalType) command));
- } else if (command instanceof PercentType) {
- cmd += percentToDenonValue(((PercentType) command).toBigDecimal());
+ } else if (command instanceof DecimalType decimalCommand) {
+ cmd += toDenonValue(decimalCommand);
+ } else if (command instanceof PercentType percentCommand) {
+ cmd += percentToDenonValue(percentCommand.toBigDecimal());
} else {
throw new UnsupportedCommandTypeException();
}
* Display info could contain some garbled text, attempt to clean it up.
*/
private String cleanupDisplayInfo(String titleValue) {
- byte firstByteRemoved[] = Arrays.copyOfRange(titleValue.getBytes(), 1, titleValue.getBytes().length);
+ byte[] firstByteRemoved = Arrays.copyOfRange(titleValue.getBytes(), 1, titleValue.getBytes().length);
return new String(firstByteRemoved).replaceAll("[\u0000-\u001f]", "");
}
}
import static org.openhab.binding.denonmarantz.internal.DenonMarantzBindingConstants.*;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(THING_TYPE_AVR);
+ return Set.of(THING_TYPE_AVR);
}
@Override
properties.put(Thing.PROPERTY_MODEL_ID, model);
String label = friendlyName + " (" + vendor + ' ' + model + ")";
- DiscoveryResult result = DiscoveryResultBuilder.create(thingUID).withProperties(properties).withLabel(label)
+ return DiscoveryResultBuilder.create(thingUID).withProperties(properties).withLabel(label)
.withRepresentationProperty(Thing.PROPERTY_SERIAL_NUMBER).build();
- return result;
} else {
return null;
@Override
public Boolean unmarshal(String v) throws Exception {
if (v != null) {
- return Boolean.valueOf(v.toLowerCase().equals("on"));
+ return Boolean.valueOf("on".equals(v.toLowerCase()));
}
return Boolean.FALSE;
@Override
public BigDecimal unmarshal(String v) throws Exception {
- if (v != null && !v.trim().equals("--")) {
+ if (v != null && !"--".equals(v.trim())) {
return new BigDecimal(v.trim()).add(DB_OFFSET);
}
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Arrays;
-import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.function.BiConsumer;
private static List<String> listFromEventStatus(final @Nullable EventStatus value) {
if (value == null) {
- return Collections.emptyList();
+ return List.of();
} else {
- return Collections.singletonList(value.value());
+ return List.of(value.value());
}
}
}
private static List<String> nullToEmptyList(@Nullable final List<String> value) {
- return value == null ? Collections.emptyList() : value;
+ return value == null ? List.of() : value;
}
/**
* Returns a list containing only the given value or empty list if value is <code>null</code>.
*/
private static List<String> singletonList(@Nullable String value) {
- return value == null ? Collections.emptyList() : Collections.singletonList(value);
+ return value == null ? List.of() : List.of(value);
}
private static OnOffType parseHidden(@Nullable Integer value) {
}
private static Function<Event, @Nullable Date> getDate(final Function<Event, @Nullable String> getValue) {
- return (final Event event) -> {
- return parseDate(getValue.apply(event));
- };
+ return (final Event event) -> parseDate(getValue.apply(event));
}
private static BiConsumer<Event, Date> setDate(final BiConsumer<Event, String> setter) {
*/
private static List<String> mapMessagesToList(final @Nullable List<Message> messages) {
if (messages == null || messages.isEmpty()) {
- return Collections.emptyList();
+ return List.of();
} else {
return messages //
.stream()//
private static List<String> mapIntegerToStringList(@Nullable Integer value) {
if (value == null) {
- return Collections.emptyList();
+ return List.of();
} else {
- return Collections.singletonList(String.valueOf(value));
+ return List.of(String.valueOf(value));
}
}
private static List<String> mapDateToStringList(@Nullable Date value) {
if (value == null) {
- return Collections.emptyList();
+ return List.of();
} else {
synchronized (DATETIME_FORMAT) {
- return Collections.singletonList(DATETIME_FORMAT.format(value));
+ return List.of(DATETIME_FORMAT.format(value));
}
}
}
if (value == null) {
return Collections.emptyList();
} else {
- return Collections.singletonList(value.value());
+ return List.of(value.value());
}
}
* Returns a list containing only the given value or empty list if value is <code>null</code>.
*/
private static List<String> singletonList(@Nullable String value) {
- return value == null ? Collections.emptyList() : Collections.singletonList(value);
+ return value == null ? Collections.emptyList() : List.of(value);
}
/**
@NonNullByDefault
public enum TroubleStatus {
TROUBLE_STARTED,
- TROUBLE_RESTORED;
+ TROUBLE_RESTORED
}
import static org.openhab.binding.digiplex.internal.DigiplexBindingConstants.*;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
private @Nullable DigiplexBridgeHandler bridgeHandler;
public DigiplexDiscoveryService() {
- super(Collections.singleton(THING_TYPE_ZONE), DISCOVERY_TIMEOUT, false);
+ super(Set.of(THING_TYPE_ZONE), DISCOVERY_TIMEOUT, false);
}
@Override
}
private boolean isDefaultName(ZoneLabelResponse response) {
- return ZONE_DEFAULT_NAMES.stream().anyMatch(format -> {
- return String.format(format, response.zoneNo).equals(response.zoneName);
- });
+ return ZONE_DEFAULT_NAMES.stream()
+ .anyMatch(format -> String.format(format, response.zoneNo).equals(response.zoneName));
}
@Override
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof DigiplexBridgeHandler) {
- bridgeHandler = (DigiplexBridgeHandler) handler;
+ if (handler instanceof DigiplexBridgeHandler digiplexBridgeHandler) {
+ bridgeHandler = digiplexBridgeHandler;
bridgeHandler.registerMessageHandler(this);
}
}
case AREA_CONTROL:
if (command == RefreshType.REFRESH) {
updateState(AREA_CONTROL, lastCommandResult);
- } else if (command instanceof StringType) {
- processControlCommand(((StringType) command).toString());
+ } else if (command instanceof StringType stringCommand) {
+ processControlCommand(stringCommand.toString());
}
break;
}
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
-import java.util.Collections;
+import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.TooManyListenersException;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singletonList(DigiplexDiscoveryService.class);
+ return List.of(DigiplexDiscoveryService.class);
}
private class BridgeMessageHandler implements DigiplexMessageHandler {
stream.write(request.getSerialMessage().getBytes());
stream.flush();
updateState(BRIDGE_MESSAGES_SENT, new DecimalType(messagesSent.incrementAndGet()));
- logger.debug("message sent: '{}'", request.getSerialMessage().replaceAll("\r", ""));
+ logger.debug("message sent: '{}'", request.getSerialMessage().replace("\r", ""));
Thread.sleep(SLEEP_TIME); // do not flood PRT3 with messages as it creates unpredictable responses
} catch (IOException e) {
handleCommunicationError();
if (dSSUID != null) {
return super.createThing(thingTypeUID, configuration, dSSUID, null);
} else {
- logger.error("Can't generate thing UID for thing type {}"
- + ", because digitalSTROM-Server is not reachable. Please check these points:\n"
- + "Are the server address and portnumber correct?\n" + "Is the server turned on?\n"
- + "Is the network configured correctly?", thingTypeUID);
+ logger.error("""
+ Can't generate thing UID for thing type {}\
+ , because digitalSTROM-Server is not reachable. Please check these points:
+ Are the server address and portnumber correct?
+ Is the server turned on?
+ Is the network configured correctly?\
+ """, thingTypeUID);
return null;
}
}
*/
package org.openhab.binding.digitalstrom.internal.discovery;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(DigitalSTROMBindingConstants.THING_TYPE_DSS_BRIDGE);
+ return Set.of(DigitalSTROMBindingConstants.THING_TYPE_DSS_BRIDGE);
}
@Override
private void onDeviceAddedInternal(GeneralDeviceInformation device) {
boolean isSupported = false;
- if (device instanceof Device) {
- Device tempDevice = (Device) device;
+ if (device instanceof Device tempDevice) {
if ((tempDevice.isSensorDevice() && deviceType.equals(tempDevice.getHWinfo().replaceAll("-", "")))
|| (deviceType.equals(tempDevice.getHWinfo().substring(0, 2))
&& (tempDevice.isDeviceWithOutput() || tempDevice.isBinaryInputDevice())
thingDiscovered(discoveryResult);
} else {
- if (device instanceof Device) {
- logger.debug("Discovered unsupported device hardware type '{}' with uid {}",
- ((Device) device).getHWinfo(), device.getDSUID());
+ if (device instanceof Device device1) {
+ logger.debug("Discovered unsupported device hardware type '{}' with uid {}", device1.getHWinfo(),
+ device.getDSUID());
}
}
} else {
- if (device instanceof Device) {
- logger.debug(
- "Discovered device with disabled or no output mode. Device was not added to inbox. "
- + "Device information: hardware info: {}, dSUID: {}, device-name: {}, output value: {}",
- ((Device) device).getHWinfo(), device.getDSUID(), device.getName(),
- ((Device) device).getOutputMode());
+ if (device instanceof Device device1) {
+ logger.debug("""
+ Discovered device with disabled or no output mode. Device was not added to inbox. \
+ Device information: hardware info: {}, dSUID: {}, device-name: {}, output value: {}\
+ """, device1.getHWinfo(), device.getDSUID(), device.getName(), device1.getOutputMode());
}
}
}
private ThingUID getThingUID(GeneralDeviceInformation device) {
ThingUID bridgeUID = bridgeHandler.getThing().getUID();
ThingTypeUID thingTypeUID = null;
- if (device instanceof Device) {
- Device tempDevice = (Device) device;
+ if (device instanceof Device tempDevice) {
thingTypeUID = new ThingTypeUID(BINDING_ID, tempDevice.getHWinfo().substring(0, 2));
if (tempDevice.isSensorDevice() && deviceType.equals(tempDevice.getHWinfo().replaceAll("-", ""))) {
thingTypeUID = new ThingTypeUID(BINDING_ID, deviceType);
}
if (getSupportedThingTypes().contains(thingTypeUID)) {
String thingDeviceId = device.getDSID().toString();
- ThingUID thingUID = new ThingUID(thingTypeUID, bridgeUID, thingDeviceId);
- return thingUID;
+ return new ThingUID(thingTypeUID, bridgeUID, thingDeviceId);
} else {
return null;
}
public void unregisterDiscoveryServices(BundleContext bundleContext) {
if (discoveryServices != null) {
for (AbstractDiscoveryService service : discoveryServices.values()) {
- if (service instanceof SceneDiscoveryService) {
- SceneDiscoveryService sceneDisServ = (SceneDiscoveryService) service;
+ if (service instanceof SceneDiscoveryService sceneDisServ) {
ServiceRegistration<?> serviceReg = this.discoveryServiceRegs.get(bridgeUID + sceneDisServ.getID());
sceneDisServ.deactivate();
serviceReg.unregister();
discoveryServiceRegs.remove(bridgeUID + sceneDisServ.getID());
}
- if (service instanceof DeviceDiscoveryService) {
- DeviceDiscoveryService devDisServ = (DeviceDiscoveryService) service;
+ if (service instanceof DeviceDiscoveryService devDisServ) {
ServiceRegistration<?> serviceReg = this.discoveryServiceRegs.get(bridgeUID + devDisServ.getID());
devDisServ.deactivate();
serviceReg.unregister();
discoveryServiceRegs.remove(bridgeUID + devDisServ.getID());
}
- if (service instanceof ZoneTemperatureControlDiscoveryService) {
- ZoneTemperatureControlDiscoveryService devDisServ = (ZoneTemperatureControlDiscoveryService) service;
+ if (service instanceof ZoneTemperatureControlDiscoveryService devDisServ) {
ServiceRegistration<?> serviceReg = this.discoveryServiceRegs.get(bridgeUID + devDisServ.getID());
devDisServ.deactivate();
serviceReg.unregister();
public void registerDiscoveryServices(BundleContext bundleContext) {
if (discoveryServices != null) {
for (AbstractDiscoveryService service : discoveryServices.values()) {
- if (service instanceof SceneDiscoveryService) {
- this.discoveryServiceRegs.put(bridgeUID + ((SceneDiscoveryService) service).getID(), bundleContext
+ if (service instanceof SceneDiscoveryService discoveryService) {
+ this.discoveryServiceRegs.put(bridgeUID + discoveryService.getID(), bundleContext
.registerService(DiscoveryService.class.getName(), service, new Hashtable<>()));
}
- if (service instanceof DeviceDiscoveryService) {
- this.discoveryServiceRegs.put(bridgeUID + ((DeviceDiscoveryService) service).getID(), bundleContext
+ if (service instanceof DeviceDiscoveryService discoveryService) {
+ this.discoveryServiceRegs.put(bridgeUID + discoveryService.getID(), bundleContext
.registerService(DiscoveryService.class.getName(), service, new Hashtable<>()));
}
- if (service instanceof ZoneTemperatureControlDiscoveryService) {
- this.discoveryServiceRegs
- .put(bridgeUID + ((ZoneTemperatureControlDiscoveryService) service).getID(), bundleContext
- .registerService(DiscoveryService.class.getName(), service, new Hashtable<>()));
+ if (service instanceof ZoneTemperatureControlDiscoveryService discoveryService) {
+ this.discoveryServiceRegs.put(bridgeUID + discoveryService.getID(), bundleContext
+ .registerService(DiscoveryService.class.getName(), service, new Hashtable<>()));
}
}
}
@Override
public void onDeviceRemoved(GeneralDeviceInformation device) {
- if (device instanceof Device) {
- String id = ((Device) device).getHWinfo().substring(0, 2);
- if (((Device) device).isSensorDevice()) {
- id = ((Device) device).getHWinfo().replace("-", "");
+ if (device instanceof Device dev) {
+ String id = dev.getHWinfo().substring(0, 2);
+ if (dev.isSensorDevice()) {
+ id = dev.getHWinfo().replace("-", "");
}
if (discoveryServices.get(id) != null) {
((DeviceDiscoveryService) discoveryServices.get(id)).onDeviceRemoved(device);
@Override
public void onDeviceAdded(GeneralDeviceInformation device) {
try {
- if (device instanceof Device) {
- String id = ((Device) device).getHWinfo().substring(0, 2);
- if (((Device) device).isSensorDevice()) {
- id = ((Device) device).getHWinfo();
+ if (device instanceof Device dev) {
+ String id = dev.getHWinfo().substring(0, 2);
+ if (dev.isSensorDevice()) {
+ id = dev.getHWinfo();
}
if (discoveryServices.get(id) != null) {
((DeviceDiscoveryService) discoveryServices.get(id)).onDeviceAdded(device);
if (getSupportedThingTypes().contains(thingTypeUID)) {
String thingSceneId = scene.getID();
- ThingUID thingUID = new ThingUID(thingTypeUID, bridgeUID, thingSceneId);
- return thingUID;
+ return new ThingUID(thingTypeUID, bridgeUID, thingSceneId);
} else {
return null;
}
ThingTypeUID thingTypeUID = new ThingTypeUID(BINDING_ID, thingTypeID);
if (getSupportedThingTypes().contains(thingTypeUID)) {
String thingID = tempControlStatus.getZoneID().toString();
- ThingUID thingUID = new ThingUID(thingTypeUID, bridgeUID, thingID);
- return thingUID;
+ return new ThingUID(thingTypeUID, bridgeUID, thingID);
} else {
return null;
}
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Contains all supported thing types of this handler
*/
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_DSS_BRIDGE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_DSS_BRIDGE);
private static final long RECONNECT_TRACKER_INTERVAL = 15;
switch (reason) {
case WRONG_APP_TOKEN:
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
- "User defined Application-Token is wrong. "
- + "Please set user name and password to generate an Application-Token or set a valid Application-Token.");
+ """
+ User defined Application-Token is wrong. \
+ Please set user name and password to generate an Application-Token or set a valid Application-Token.\
+ """);
stopServices();
return;
case WRONG_USER_OR_PASSWORD:
return;
}
case HOST_NOT_FOUND:
- updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
- "Server not found! Please check these points:\n" + " - Is digitalSTROM-Server turned on?\n"
- + " - Is the host address correct?\n"
- + " - Is the ethernet cable connection established?");
+ updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, """
+ Server not found! Please check these points:
+ - Is digitalSTROM-Server turned on?
+ - Is the host address correct?
+ - Is the ethernet cable connection established?\
+ """);
break;
case UNKNOWN_HOST:
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
}
ThingHandler handler = bridge.getHandler();
- if (handler instanceof BridgeHandler) {
- dssBridgeHandler = (BridgeHandler) handler;
+ if (handler instanceof BridgeHandler bridgeHandler) {
+ dssBridgeHandler = bridgeHandler;
} else {
return null;
}
@Override
public void onDeviceRemoved(GeneralDeviceInformation device) {
- if (device instanceof Circuit) {
- this.circuit = (Circuit) device;
+ if (device instanceof Circuit circ) {
+ this.circuit = circ;
if (getThing().getStatus().equals(ThingStatus.ONLINE)) {
if (!circuit.isPresent()) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE,
@Override
public void onDeviceAdded(GeneralDeviceInformation device) {
- if (device instanceof Circuit) {
- this.circuit = (Circuit) device;
+ if (device instanceof Circuit circ) {
+ this.circuit = circ;
if (this.circuit.isPresent()) {
ThingStatusInfo statusInfo = this.dssBridgeHandler.getThing().getStatusInfo();
updateStatus(statusInfo.getStatus(), statusInfo.getStatusDetail(), statusInfo.getDescription());
}
} else if (!device.isShade()) {
if (DsChannelTypeProvider.isOutputChannel(channelUID.getId())) {
- if (command instanceof PercentType) {
+ if (command instanceof PercentType percentCommand) {
device.setOutputValue(
- (short) fromPercentToValue(((PercentType) command).intValue(), device.getMaxOutputValue()));
+ (short) fromPercentToValue(percentCommand.intValue(), device.getMaxOutputValue()));
} else if (command instanceof OnOffType) {
if (OnOffType.ON.equals(command)) {
device.setIsOn(true);
} else {
device.decrease();
}
- } else if (command instanceof StringType) {
- device.setOutputValue(Short.parseShort(((StringType) command).toString()));
+ } else if (command instanceof StringType stringCommand) {
+ device.setOutputValue(Short.parseShort(stringCommand.toString()));
}
} else {
logger.debug("Command sent to an unknown channel id: {}", channelUID);
}
} else {
if (channelUID.getId().contains(DsChannelTypeProvider.ANGLE)) {
- if (command instanceof PercentType) {
+ if (command instanceof PercentType percentCommand) {
device.setAnglePosition(
- (short) fromPercentToValue(((PercentType) command).intValue(), device.getMaxSlatAngle()));
+ (short) fromPercentToValue(percentCommand.intValue(), device.getMaxSlatAngle()));
} else if (command instanceof OnOffType) {
if (OnOffType.ON.equals(command)) {
device.setAnglePosition(device.getMaxSlatAngle());
}
}
} else if (channelUID.getId().contains(DsChannelTypeProvider.SHADE)) {
- if (command instanceof PercentType) {
- int percent = ((PercentType) command).intValue();
- if (!device.getHWinfo().equals("GR-KL200")) {
+ if (command instanceof PercentType percentCommand) {
+ int percent = percentCommand.intValue();
+ if (!"GR-KL200".equals(device.getHWinfo())) {
percent = 100 - percent;
}
device.setSlatPosition(fromPercentToValue(percent, device.getMaxSlatPosition()));
}
ThingHandler handler = bridge.getHandler();
- if (handler instanceof BridgeHandler) {
- dssBridgeHandler = (BridgeHandler) handler;
+ if (handler instanceof BridgeHandler bridgeHandler) {
+ dssBridgeHandler = bridgeHandler;
} else {
return null;
}
default:
return;
}
- if (!device.getHWinfo().equals("GR-KL210")) {
+ if (!"GR-KL210".equals(device.getHWinfo())) {
percent = 100 - percent;
}
updateState(DsChannelTypeProvider.SHADE, new PercentType(percent));
@Override
public synchronized void onDeviceRemoved(GeneralDeviceInformation device) {
- if (device instanceof Device) {
- this.device = (Device) device;
+ if (device instanceof Device dev) {
+ this.device = dev;
if (this.getThing().getStatus().equals(ThingStatus.ONLINE)) {
- if (!((Device) device).isPresent()) {
+ if (!dev.isPresent()) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE,
"Device is not present in the digitalSTROM-System.");
} else {
@Override
public synchronized void onDeviceAdded(GeneralDeviceInformation device) {
- if (device instanceof Device) {
- this.device = (Device) device;
+ if (device instanceof Device dev) {
+ this.device = dev;
if (this.device.isPresent()) {
ThingStatusInfo statusInfo = this.dssBridgeHandler.getThing().getStatusInfo();
updateStatus(statusInfo.getStatus(), statusInfo.getStatusDetail(), statusInfo.getDescription());
checkOutputChannel();
} else if (this.device.isBlind()) {
// load channel for set the angle of jalousie devices
- ApplicationGroup.Color color = ((Device) device).getFunctionalColorGroup() != null
- ? ((Device) device).getFunctionalColorGroup().getColor()
+ ApplicationGroup.Color color = dev.getFunctionalColorGroup() != null
+ ? dev.getFunctionalColorGroup().getColor()
: null;
- String channelTypeID = DsChannelTypeProvider.getOutputChannelTypeID(color,
- ((Device) device).getOutputMode(), ((Device) device).getOutputChannels());
+ String channelTypeID = DsChannelTypeProvider.getOutputChannelTypeID(color, dev.getOutputMode(),
+ dev.getOutputChannels());
loadOutputChannel(new ChannelTypeUID(BINDING_ID, channelTypeID),
DsChannelTypeProvider.getItemType(channelTypeID));
}
if (loadedSensorChannels == null) {
loadedSensorChannels = new LinkedList<>();
}
- if (!loadedSensorChannels.contains(sensorChannelType.toString())) {
- return loadedSensorChannels.add(sensorChannelType.toString());
+ if (!loadedSensorChannels.contains(sensorChannelType)) {
+ return loadedSensorChannels.add(sensorChannelType);
}
return false;
}
}
ThingHandler handler = bridge.getHandler();
- if (handler instanceof BridgeHandler) {
- this.bridgeHandler = (BridgeHandler) handler;
+ if (handler instanceof BridgeHandler bridgeHandler) {
+ this.bridgeHandler = bridgeHandler;
} else {
logger.debug("BridgeHandler cannot be found");
return null;
import org.openhab.binding.digitalstrom.internal.lib.climate.jsonresponsecontainer.impl.TemperatureControlStatus;
import org.openhab.binding.digitalstrom.internal.lib.listener.TemperatureControlStatusListener;
import org.openhab.binding.digitalstrom.internal.lib.manager.StructureManager;
+import org.openhab.binding.digitalstrom.internal.lib.manager.impl.TemperatureControlManager;
import org.openhab.binding.digitalstrom.internal.lib.structure.devices.deviceparameters.constants.ApplicationGroup;
import org.openhab.binding.digitalstrom.internal.lib.structure.devices.deviceparameters.constants.OutputChannelEnum;
import org.openhab.binding.digitalstrom.internal.lib.structure.devices.deviceparameters.constants.OutputModeEnum;
}
ThingHandler handler = bridge.getHandler();
- if (handler instanceof BridgeHandler) {
- dssBridgeHandler = (BridgeHandler) handler;
+ if (handler instanceof BridgeHandler bridgeHandler) {
+ dssBridgeHandler = bridgeHandler;
} else {
return null;
}
@Override
public boolean equals(Object object) {
- return object instanceof TrashDevice
- ? this.device.getDSID().equals(((TrashDevice) object).getDevice().getDSID())
- : false;
+ return object instanceof TrashDevice td ? this.device.getDSID().equals(td.getDevice().getDSID()) : false;
}
}
@Override
public void scenesGenerated(char[] scenesGenerated) {
- if (String.valueOf(scenesGenerated).equals("1111")) {
+ if ("1111".equals(String.valueOf(scenesGenerated))) {
this.scenesGenerated = true;
stateChanged(ManagerStates.RUNNING);
}
@Override
public boolean equals(Object obj) {
- if (obj instanceof DeviceConsumptionSensorJob) {
- DeviceConsumptionSensorJob other = (DeviceConsumptionSensorJob) obj;
+ if (obj instanceof DeviceConsumptionSensorJob other) {
String device = this.device.getDSID().getValue() + this.sensorType.getSensorType();
return device.equals(other.device.getDSID().getValue() + other.sensorType.getSensorType());
}
@Override
public boolean equals(Object obj) {
- if (obj instanceof DeviceOutputValueSensorJob) {
- DeviceOutputValueSensorJob other = (DeviceOutputValueSensorJob) obj;
+ if (obj instanceof DeviceOutputValueSensorJob other) {
String key = this.device.getDSID().getValue() + this.index;
return key.equals((other.device.getDSID().getValue() + other.index));
}
@Override
public boolean equals(Object obj) {
- if (obj instanceof SceneConfigReadingJob) {
- SceneConfigReadingJob other = (SceneConfigReadingJob) obj;
+ if (obj instanceof SceneConfigReadingJob other) {
String str = other.device.getDSID().getValue() + "-" + other.sceneID;
return (this.device.getDSID().getValue() + "-" + this.sceneID).equals(str);
}
@Override
public boolean equals(Object obj) {
- if (obj instanceof SceneOutputValueReadingJob) {
- SceneOutputValueReadingJob other = (SceneOutputValueReadingJob) obj;
+ if (obj instanceof SceneOutputValueReadingJob other) {
String str = other.device.getDSID().getValue() + "-" + other.sceneID;
return (this.device.getDSID().getValue() + "-" + this.sceneID).equals(str);
}
.addRequestClass(ClassKeys.ZONE).addFunction(FunctionKeys.SET_TEMEPERATURE_CONTROL_VALUE)
.addDefaultZoneParameter(sessionToken, zoneID, zoneName);
for (Object[] objAry : controlValues) {
- if (objAry.length == 2 && objAry[0] instanceof String && objAry[1] instanceof Integer) {
- builder.addParameter((String) objAry[0], SimpleRequestBuilder.objectToString(objAry[1]));
+ if (objAry.length == 2 && objAry[0] instanceof String stringValue
+ && objAry[1] instanceof Integer) {
+ builder.addParameter(stringValue, SimpleRequestBuilder.objectToString(objAry[1]));
} else {
builder.buildRequestString();
throw new IllegalArgumentException(
* @return jsonObject
*/
public static JsonObject toJsonObject(String jsonResponse) {
- if (jsonResponse != null && !jsonResponse.trim().equals("")) {
+ if (jsonResponse != null && !"".equals(jsonResponse.trim())) {
try {
return (JsonObject) JsonParser.parseString(jsonResponse);
} catch (JsonParseException e) {
if (obj == null) {
return null;
}
- if (obj instanceof DSID) {
- return ((DSID) obj).getValue();
+ if (obj instanceof DSID id) {
+ return id.getValue();
}
- if (obj instanceof Number) {
- return ((Number) obj).intValue() > -1 ? obj.toString() : null;
+ if (obj instanceof Number number) {
+ return number.intValue() > -1 ? obj.toString() : null;
}
return obj.toString();
}
@Override
public boolean equals(Object obj) {
- if (obj instanceof DSID) {
- return ((DSID) obj).getValue().equals(this.getValue());
+ if (obj instanceof DSID id) {
+ return id.getValue().equals(this.getValue());
}
return false;
}
@Override
public boolean equals(Object obj) {
- if (obj instanceof DSUID) {
- return ((DSUID) obj).getValue().equals(this.getValue());
+ if (obj instanceof DSUID id) {
+ return id.getValue().equals(this.getValue());
}
return false;
}
if (value instanceof Short) {
return ((Short) value).intValue();
}
- if (value instanceof String) {
- return Integer.parseInt((String) value);
+ if (value instanceof String string) {
+ return Integer.parseInt(string);
}
} catch (Exception e) {
throw new ClassCastException();
if (value instanceof Short) {
return ((Short) value).toString();
}
- if (value instanceof String) {
- return (String) value;
+ if (value instanceof String string) {
+ return string;
}
throw new ClassCastException();
}
if (value instanceof Short) {
return (Short) value;
}
- if (value instanceof String) {
- return Short.parseShort((String) value);
+ if (value instanceof String string) {
+ return Short.parseShort(string);
}
} catch (Exception e) {
throw new ClassCastException();
if (value instanceof Short) {
return ((Short) value).floatValue();
}
- if (value instanceof String) {
- return Float.parseFloat((String) value);
+ if (value instanceof String string) {
+ return Float.parseFloat(string);
}
} catch (Exception e) {
throw new ClassCastException();
@Override
public boolean equals(Object obj) {
- if (obj instanceof Device) {
- Device device = (Device) obj;
+ if (obj instanceof Device device) {
return device.getDSID().equals(this.getDSID());
}
return false;
String[] scenes = propertries.split("\n");
for (int i = 0; i < scenes.length; i++) {
logger.debug("Find saved scene configuration for device with dSID {} and sceneID {}", dsid, i);
- String[] sceneIdToConfig = scenes[i].replaceAll(" ", "").split("=");
+ String[] sceneIdToConfig = scenes[i].replace(" ", "").split("=");
String[] sceneParm = sceneIdToConfig[1].split(",");
JSONDeviceSceneSpecImpl sceneSpecNew = null;
int sceneValue = -1;
@Override
public boolean equals(Object obj) {
- if (obj instanceof DetailedGroupInfo) {
- DetailedGroupInfo group = (DetailedGroupInfo) obj;
+ if (obj instanceof DetailedGroupInfo group) {
return group.getGroupID() == this.getGroupID();
}
return false;
@Override
public boolean equals(Object obj) {
- if (obj instanceof Zone) {
- Zone other = (Zone) obj;
+ if (obj instanceof Zone other) {
return (other.getZoneId() == this.getZoneId());
}
return false;
* @author Michael Ochel - Initial contribution
* @author Matthias Siegele - Initial contribution
*/
- public static enum SupportedThingTypes {
+ public enum SupportedThingTypes {
// ThingType, responsible ThingHanlder, Device config-description with power-sensors
GE(DeviceHandler.class.getSimpleName(), true),
GR(DeviceHandler.class.getSimpleName(), false),
*/
package org.openhab.binding.dlinksmarthome.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
// List of all Thing Type UIDs
public static final ThingTypeUID THING_TYPE_DCHS150 = new ThingTypeUID(BINDING_ID, "DCH-S150");
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_DCHS150);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_DCHS150);
// Motion trigger channel
public static final String MOTION = "motion";
if (model == null) {
return null;
- } else if (model.equals("DCH-S150")) {
+ } else if ("DCH-S150".equals(model)) {
return THING_TYPE_DCHS150;
} else {
logger.debug("D-Link HNAP Type: {}", model);
public static final ChannelTypeUID MUTE_CHANNEL_TYPEUID = new ChannelTypeUID(BINDING_ID, CHANNEL_MUTE);
// Listener Type for channel updates
- public static enum ListenerType {
+ public enum ListenerType {
VALUE,
ACTION
}
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singletonList(DmxActions.class);
+ return List.of(DmxActions.class);
}
}
protected @Nullable ThingHandler createHandler(Thing thing) {
ThingTypeUID thingTypeUID = thing.getThingTypeUID();
if (thingTypeUID.equals(THING_TYPE_ARTNET_BRIDGE)) {
- ArtnetBridgeHandler handler = new ArtnetBridgeHandler((Bridge) thing);
- return handler;
+ return new ArtnetBridgeHandler((Bridge) thing);
} else if (thingTypeUID.equals(THING_TYPE_LIB485_BRIDGE)) {
- Lib485BridgeHandler handler = new Lib485BridgeHandler((Bridge) thing);
- return handler;
+ return new Lib485BridgeHandler((Bridge) thing);
} else if (thingTypeUID.equals(THING_TYPE_SACN_BRIDGE)) {
- SacnBridgeHandler handler = new SacnBridgeHandler((Bridge) thing);
- return handler;
+ return new SacnBridgeHandler((Bridge) thing);
} else if (thingTypeUID.equals(THING_TYPE_DIMMER)) {
- DimmerThingHandler handler = new DimmerThingHandler(thing);
- return handler;
+ return new DimmerThingHandler(thing);
} else if (thingTypeUID.equals(THING_TYPE_COLOR)) {
- ColorThingHandler handler = new ColorThingHandler(thing);
- return handler;
+ return new ColorThingHandler(thing);
} else if (thingTypeUID.equals(THING_TYPE_TUNABLEWHITE)) {
- TunableWhiteThingHandler handler = new TunableWhiteThingHandler(thing);
- return handler;
+ return new TunableWhiteThingHandler(thing);
} else if (thingTypeUID.equals(THING_TYPE_CHASER)) {
- ChaserThingHandler handler = new ChaserThingHandler(thing);
- return handler;
+ return new ChaserThingHandler(thing);
}
return null;
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof DmxBridgeHandler) {
- this.handler = (DmxBridgeHandler) handler;
+ if (handler instanceof DmxBridgeHandler bridgeHandler) {
+ this.handler = bridgeHandler;
}
}
}
logger.debug("originating address is {} for {}", senderNode, this.thing.getUID());
- refreshAlways = configuration.refreshmode.equals("always");
+ refreshAlways = "always".equals(configuration.refreshmode);
logger.debug("refresh mode set to always: {}", refreshAlways);
public void handleCommand(ChannelUID channelUID, Command command) {
switch (channelUID.getId()) {
case CHANNEL_SWITCH:
- if (command instanceof OnOffType) {
- if (((OnOffType) command).equals(OnOffType.ON)) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand.equals(OnOffType.ON)) {
Integer channelCounter = 0;
for (DmxChannel channel : channels) {
if (resumeAfter) {
}
break;
case CHANNEL_CONTROL:
- if (command instanceof StringType) {
- List<ValueSet> newValues = ValueSet.parseChaseConfig(((StringType) command).toString());
+ if (command instanceof StringType stringCommand) {
+ List<ValueSet> newValues = ValueSet.parseChaseConfig(stringCommand.toString());
if (!newValues.isEmpty()) {
values = newValues;
logger.debug("updated chase config in {}", this.thing.getUID());
@Override
public void updateSwitchState(ChannelUID channelUID, State state) {
logger.trace("received {} for {}", state, channelUID);
- if (channelUID.getId().equals(CHANNEL_SWITCH) && (state instanceof OnOffType)) {
- this.isRunning = (OnOffType) state;
+ if (channelUID.getId().equals(CHANNEL_SWITCH) && (state instanceof OnOffType onOffState)) {
+ this.isRunning = onOffState;
updateState(channelUID, state);
} else {
logger.debug("unknown state received: {} in channel {} thing {}", state, channelUID, this.thing.getUID());
return;
}
case CHANNEL_COLOR: {
- if (command instanceof OnOffType) {
+ if (command instanceof OnOffType onOffCommand) {
logger.trace("adding {} fade to channels in thing {}", command, this.thing.getUID());
- if (((OnOffType) command) == OnOffType.ON) {
+ if (onOffCommand == OnOffType.ON) {
targetValueSet = turnOnValue;
} else {
if (dynamicTurnOnValue) {
}
targetValueSet = turnOffValue;
}
- } else if (command instanceof HSBType) {
+ } else if (command instanceof HSBType hsbCommand) {
logger.trace("adding color fade to channels in thing {}", this.thing.getUID());
- targetValueSet.addValue(((HSBType) command).getRed());
- targetValueSet.addValue(((HSBType) command).getGreen());
- targetValueSet.addValue(((HSBType) command).getBlue());
+ targetValueSet.addValue(hsbCommand.getRed());
+ targetValueSet.addValue(hsbCommand.getGreen());
+ targetValueSet.addValue(hsbCommand.getBlue());
} else if ((command instanceof PercentType) || (command instanceof DecimalType)) {
logger.trace("adding brightness fade to channels in thing {}", this.thing.getUID());
- PercentType brightness = (command instanceof PercentType) ? (PercentType) command
+ PercentType brightness = (command instanceof PercentType percentCommand) ? percentCommand
: Util.toPercentValue(((DecimalType) command).intValue());
HSBType targetColor = new HSBType(currentColor.getHue(), currentColor.getSaturation(), brightness);
targetValueSet.addValue(targetColor.getRed());
targetValueSet.addValue(targetColor.getGreen());
targetValueSet.addValue(targetColor.getBlue());
- } else if (command instanceof IncreaseDecreaseType) {
- if (isDimming && ((IncreaseDecreaseType) command).equals(IncreaseDecreaseType.INCREASE)) {
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ if (isDimming && increaseDecreaseCommand.equals(IncreaseDecreaseType.INCREASE)) {
logger.trace("stopping fade in thing {}", this.thing.getUID());
channels.forEach(DmxChannel::clearAction);
isDimming = false;
} else {
logger.trace("starting {} fade in thing {}", command, this.thing.getUID());
HSBType targetColor;
- if (((IncreaseDecreaseType) command).equals(IncreaseDecreaseType.INCREASE)) {
+ if (increaseDecreaseCommand.equals(IncreaseDecreaseType.INCREASE)) {
targetColor = new HSBType(currentColor.getHue(), currentColor.getSaturation(),
PercentType.HUNDRED);
} else {
dimTime = configuration.dimtime;
logger.trace("setting dimTime to {} ms in {}", fadeTime, this.thing.getUID());
- String turnOnValueString = String.valueOf(fadeTime) + ":" + configuration.turnonvalue + ":-1";
+ String turnOnValueString = fadeTime + ":" + configuration.turnonvalue + ":-1";
ValueSet turnOnValue = ValueSet.fromString(turnOnValueString);
if (turnOnValue.size() % 3 == 0) {
this.turnOnValue = turnOnValue;
dynamicTurnOnValue = configuration.dynamicturnonvalue;
- String turnOffValueString = String.valueOf(fadeTime) + ":" + configuration.turnoffvalue + ":-1";
+ String turnOffValueString = fadeTime + ":" + configuration.turnoffvalue + ":-1";
ValueSet turnOffValue = ValueSet.fromString(turnOffValueString);
if (turnOffValue.size() % 3 == 0) {
this.turnOffValue = turnOffValue;
import static org.openhab.binding.dmx.internal.DmxBindingConstants.*;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.IntStream;
*/
public class DimmerThingHandler extends DmxThingHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_DIMMER);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_DIMMER);
private final Logger logger = LoggerFactory.getLogger(DimmerThingHandler.class);
switch (channelUID.getId()) {
case CHANNEL_BRIGHTNESS: {
if (command instanceof PercentType || command instanceof DecimalType) {
- PercentType brightness = (command instanceof PercentType) ? (PercentType) command
+ PercentType brightness = (command instanceof PercentType percentCommand) ? percentCommand
: Util.toPercentValue(((DecimalType) command).intValue());
logger.trace("adding fade to channels in thing {}", this.thing.getUID());
targetValueSet.addValue(brightness);
- } else if (command instanceof OnOffType) {
+ } else if (command instanceof OnOffType onOffCommand) {
logger.trace("adding {} fade to channels in thing {}", command, this.thing.getUID());
- if (((OnOffType) command) == OnOffType.ON) {
+ if (onOffCommand == OnOffType.ON) {
targetValueSet = turnOnValue;
} else {
if (dynamicTurnOnValue) {
}
targetValueSet = turnOffValue;
}
- } else if (command instanceof IncreaseDecreaseType) {
- if (isDimming && ((IncreaseDecreaseType) command).equals(IncreaseDecreaseType.INCREASE)) {
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ if (isDimming && increaseDecreaseCommand.equals(IncreaseDecreaseType.INCREASE)) {
logger.trace("stopping fade in thing {}", this.thing.getUID());
channels.forEach(DmxChannel::clearAction);
isDimming = false;
return;
} else {
logger.trace("starting {} fade in thing {}", command, this.thing.getUID());
- targetValueSet = ((IncreaseDecreaseType) command).equals(IncreaseDecreaseType.INCREASE)
- ? turnOnValue
+ targetValueSet = increaseDecreaseCommand.equals(IncreaseDecreaseType.INCREASE) ? turnOnValue
: turnOffValue;
targetValueSet.setFadeTime(dimTime);
isDimming = true;
dimTime = configuration.dimtime;
logger.trace("setting dimTime to {} ms in {}", fadeTime, this.thing.getUID());
- String turnOnValueString = String.valueOf(fadeTime) + ":" + configuration.turnonvalue + ":-1";
+ String turnOnValueString = fadeTime + ":" + configuration.turnonvalue + ":-1";
ValueSet turnOnValue = ValueSet.fromString(turnOnValueString);
if (!turnOnValue.isEmpty()) {
dynamicTurnOnValue = configuration.dynamicturnonvalue;
- String turnOffValueString = String.valueOf(fadeTime) + ":" + configuration.turnoffvalue + ":-1";
+ String turnOffValueString = fadeTime + ":" + configuration.turnoffvalue + ":-1";
ValueSet turnOffValue = ValueSet.fromString(turnOffValueString);
if (!turnOffValue.isEmpty()) {
this.turnOffValue = turnOffValue;
packetTemplate.setUniverse(universe.getUniverseId());
receiverNodes.clear();
- if ((configuration.mode.equals("unicast"))) {
+ if (("unicast".equals(configuration.mode))) {
if (configuration.address.isEmpty()) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
"Could not initialize unicast sender (address not set)");
}
logger.debug("originating address is {} for {}", senderNode, this.thing.getUID());
- refreshAlways = configuration.refreshmode.equals("always");
+ refreshAlways = "always".equals(configuration.refreshmode);
logger.debug("refresh mode set to always: {}", refreshAlways);
updateStatus(ThingStatus.UNKNOWN);
switch (channelUID.getId()) {
case CHANNEL_BRIGHTNESS: {
if (command instanceof PercentType || command instanceof DecimalType) {
- PercentType brightness = (command instanceof PercentType) ? (PercentType) command
+ PercentType brightness = (command instanceof PercentType percentCommand) ? percentCommand
: Util.toPercentValue(((DecimalType) command).intValue());
logger.trace("adding fade to channels in thing {}", this.thing.getUID());
targetValueSet.addValue(Util.toDmxValue(
Util.toDmxValue(brightness) * (100 - currentColorTemperature.intValue()) / 100));
targetValueSet.addValue(
Util.toDmxValue(Util.toDmxValue(brightness) * currentColorTemperature.intValue() / 100));
- } else if (command instanceof OnOffType) {
+ } else if (command instanceof OnOffType onOffCommand) {
logger.trace("adding {} fade to channels in thing {}", command, this.thing.getUID());
- if (((OnOffType) command) == OnOffType.ON) {
+ if (onOffCommand == OnOffType.ON) {
targetValueSet = turnOnValue;
} else {
if (dynamicTurnOnValue) {
}
targetValueSet = turnOffValue;
}
- } else if (command instanceof IncreaseDecreaseType) {
- if (isDimming && ((IncreaseDecreaseType) command).equals(IncreaseDecreaseType.INCREASE)) {
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ if (isDimming && increaseDecreaseCommand.equals(IncreaseDecreaseType.INCREASE)) {
logger.trace("stopping fade in thing {}", this.thing.getUID());
channels.forEach(DmxChannel::clearAction);
isDimming = false;
return;
} else {
logger.trace("starting {} fade in thing {}", command, this.thing.getUID());
- targetValueSet = ((IncreaseDecreaseType) command).equals(IncreaseDecreaseType.INCREASE)
- ? turnOnValue
+ targetValueSet = increaseDecreaseCommand.equals(IncreaseDecreaseType.INCREASE) ? turnOnValue
: turnOffValue;
targetValueSet.setFadeTime(dimTime);
isDimming = true;
return;
}
case CHANNEL_COLOR_TEMPERATURE: {
- if (command instanceof PercentType) {
- PercentType colorTemperature = (PercentType) command;
+ if (command instanceof PercentType colorTemperature) {
targetValueSet.addValue(Util.toDmxValue(
Util.toDmxValue(currentBrightness) * (100 - colorTemperature.intValue()) / 100));
targetValueSet.addValue(
dimTime = configuration.dimtime;
logger.trace("setting dimTime to {} ms in {}", fadeTime, this.thing.getUID());
- String turnOnValueString = String.valueOf(fadeTime) + ":" + configuration.turnonvalue + ":-1";
+ String turnOnValueString = fadeTime + ":" + configuration.turnonvalue + ":-1";
ValueSet turnOnValue = ValueSet.fromString(turnOnValueString);
if (turnOnValue.size() % 2 == 0) {
this.turnOnValue = turnOnValue;
dynamicTurnOnValue = configuration.dynamicturnonvalue;
- String turnOffValueString = String.valueOf(fadeTime) + ":" + configuration.turnoffvalue + ":-1";
+ String turnOffValueString = fadeTime + ":" + configuration.turnoffvalue + ":-1";
ValueSet turnOffValue = ValueSet.fromString(turnOffValueString);
if (turnOffValue.size() % 2 == 0) {
this.turnOffValue = turnOffValue;
if (otherDmxChannel == null) {
return -1;
}
- int universeCompare = Integer.valueOf(getUniverseId()).compareTo(otherDmxChannel.getUniverseId());
+ int universeCompare = Integer.compare(getUniverseId(), otherDmxChannel.getUniverseId());
if (universeCompare == 0) {
return Integer.compare(getChannelId(), otherDmxChannel.getChannelId());
} else {
if (channelMatch.matches()) {
final int universeId = (channelMatch.group(1) == null) ? defaultUniverseId
: Integer.parseInt(channelMatch.group(1));
- dmxChannelWidth = channelMatch.group(3).equals("") ? 1 : Integer.parseInt(channelMatch.group(3));
+ dmxChannelWidth = "".equals(channelMatch.group(3)) ? 1 : Integer.parseInt(channelMatch.group(3));
dmxChannelId = Integer.parseInt(channelMatch.group(2));
LOGGER.trace("parsed channel string {} to universe {}, id {}, width {}", singleDmxChannelString,
universeId, dmxChannelId, dmxChannelWidth);
import static org.openhab.binding.dmx.internal.DmxBindingConstants.*;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@NonNullByDefault
public class TestBridgeHandler extends DmxBridgeHandler {
public static final ThingTypeUID THING_TYPE_TEST_BRIDGE = new ThingTypeUID(BINDING_ID, "test-bridge");
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_TEST_BRIDGE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_TEST_BRIDGE);
public static final int MIN_UNIVERSE_ID = 0;
public static final int MAX_UNIVERSE_ID = 0;
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof DoorbellHandler) {
- this.handler = (DoorbellHandler) handler;
+ if (handler instanceof DoorbellHandler doorbellHandler) {
+ this.handler = doorbellHandler;
}
}
private final String infoWithControllerId =
//@formatter:off
- "{" +
- "'BHA': {" +
- "'RETURNCODE': '1'," +
- "'VERSION': [{" +
- "'FIRMWARE': '000109'," +
- "'BUILD_NUMBER': '15120529'," +
- "'PRIMARY_MAC_ADDR': '1CCAE3711111'," +
- "'WIFI_MAC_ADDR': '1CCAE3799999'," +
- "'RELAYS': ['1', '2', 'gggaaa@1', 'gggaaa@2']," +
- "'DEVICE-TYPE': 'DoorBird D101'" +
- "}]" +
- "}" +
- "}";
+ """
+ {\
+ 'BHA': {\
+ 'RETURNCODE': '1',\
+ 'VERSION': [{\
+ 'FIRMWARE': '000109',\
+ 'BUILD_NUMBER': '15120529',\
+ 'PRIMARY_MAC_ADDR': '1CCAE3711111',\
+ 'WIFI_MAC_ADDR': '1CCAE3799999',\
+ 'RELAYS': ['1', '2', 'gggaaa@1', 'gggaaa@2'],\
+ 'DEVICE-TYPE': 'DoorBird D101'\
+ }]\
+ }\
+ }\
+ """;
//@formatter:on
private final String infoWithoutControllerId =
//@formatter:off
- "{" +
- "'BHA': {" +
- "'RETURNCODE': '1'," +
- "'VERSION': [{" +
- "'FIRMWARE': '000109'," +
- "'BUILD_NUMBER': '15120529'," +
- "'PRIMARY_MAC_ADDR': '1CCAE3711111'," +
- "'WIFI_MAC_ADDR': '1CCAE3799999'," +
- "'RELAYS': ['1', '2']," +
- "'DEVICE-TYPE': 'DoorBird D101'" +
- "}]" +
- "}" +
- "}";
+ """
+ {\
+ 'BHA': {\
+ 'RETURNCODE': '1',\
+ 'VERSION': [{\
+ 'FIRMWARE': '000109',\
+ 'BUILD_NUMBER': '15120529',\
+ 'PRIMARY_MAC_ADDR': '1CCAE3711111',\
+ 'WIFI_MAC_ADDR': '1CCAE3799999',\
+ 'RELAYS': ['1', '2'],\
+ 'DEVICE-TYPE': 'DoorBird D101'\
+ }]\
+ }\
+ }\
+ """;
//@formatter:on
@Test
private final String sipStatusJson =
//@formatter:off
- "{" +
- "'BHA': {" +
- "'RETURNCODE': '1'," +
- "'SIP': [{" +
- "'ENABLE': '10'," +
- "'PRIORITIZE_APP': '1'," +
- "'REGISTER_URL': '192.168.178.1'," +
- "'REGISTER_USER': 'xxxxx'," +
- "'REGISTER_PASSWORD': 'yyyyy'," +
- "'AUTOCALL_MOTIONSENSOR_URL': 'motion-url'," +
- "'AUTOCALL_DOORBELL_URL': 'doorbell-url'," +
- "'SPK_VOLUME': '70'," +
- "'MIC_VOLUME': '33'," +
- "'DTMF': '1'," +
- "'relais:1': '0'," +
- "'relais:2': '1'," +
- "'LIGHT_PASSCODE': 'light-passcode'," +
- "'INCOMING_CALL_ENABLE': '0'," +
- "'INCOMING_CALL_USER': 'abcde'," +
- "'ANC': '1'," +
- "'LASTERRORCODE': '901'," +
- "'LASTERRORTEXT': 'OK'," +
- "'RING_TIME_LIMIT': '60'," +
- "'CALL_TIME_LIMIT': '180'" +
- "}]" +
- "}" +
- "}";
+ """
+ {\
+ 'BHA': {\
+ 'RETURNCODE': '1',\
+ 'SIP': [{\
+ 'ENABLE': '10',\
+ 'PRIORITIZE_APP': '1',\
+ 'REGISTER_URL': '192.168.178.1',\
+ 'REGISTER_USER': 'xxxxx',\
+ 'REGISTER_PASSWORD': 'yyyyy',\
+ 'AUTOCALL_MOTIONSENSOR_URL': 'motion-url',\
+ 'AUTOCALL_DOORBELL_URL': 'doorbell-url',\
+ 'SPK_VOLUME': '70',\
+ 'MIC_VOLUME': '33',\
+ 'DTMF': '1',\
+ 'relais:1': '0',\
+ 'relais:2': '1',\
+ 'LIGHT_PASSCODE': 'light-passcode',\
+ 'INCOMING_CALL_ENABLE': '0',\
+ 'INCOMING_CALL_USER': 'abcde',\
+ 'ANC': '1',\
+ 'LASTERRORCODE': '901',\
+ 'LASTERRORTEXT': 'OK',\
+ 'RING_TIME_LIMIT': '60',\
+ 'CALL_TIME_LIMIT': '180'\
+ }]\
+ }\
+ }\
+ """;
//@formatter:on
@Test
*/
package org.openhab.binding.draytonwiser.internal;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
public static final String CHANNEL_SMARTPLUG_INSTANTANEOUS_POWER = "plugInstantaneousPower";
public static final String CHANNEL_SMARTPLUG_ENERGY_DELIVERED = "plugEnergyDelivered";
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .unmodifiableSet(new HashSet<>(Arrays.asList(THING_TYPE_CONTROLLER, THING_TYPE_ROOM, THING_TYPE_ROOMSTAT,
- THING_TYPE_BRIDGE, THING_TYPE_ITRV, THING_TYPE_HOTWATER, THING_TYPE_SMARTPLUG)));
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_CONTROLLER, THING_TYPE_ROOM,
+ THING_TYPE_ROOMSTAT, THING_TYPE_BRIDGE, THING_TYPE_ITRV, THING_TYPE_HOTWATER, THING_TYPE_SMARTPLUG);
// Lookups from text representations to useful values
@Override
public void setThingHandler(@Nullable final ThingHandler handler) {
- if (handler instanceof HeatHubHandler) {
- bridgeHandler = (HeatHubHandler) handler;
+ if (handler instanceof HeatHubHandler hubHandler) {
+ bridgeHandler = hubHandler;
bridgeUID = handler.getThing().getUID();
} else {
bridgeHandler = null;
import static org.openhab.binding.draytonwiser.internal.DraytonWiserBindingConstants.*;
import java.net.InetAddress;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(THING_TYPE_BRIDGE);
+ return Set.of(THING_TYPE_BRIDGE);
}
@Override
package org.openhab.binding.draytonwiser.internal.handler;
import java.util.Collection;
-import java.util.Collections;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(DraytonWiserDiscoveryService.class);
+ return Set.of(DraytonWiserDiscoveryService.class);
}
public void setDiscoveryService(final DraytonWiserRefreshListener discoveryService) {
protected void handleCommand(final String channelId, final Command command) throws DraytonWiserApiException {
switch (channelId) {
case CHANNEL_CURRENT_SETPOINT:
- if (command instanceof QuantityType) {
- setSetPoint((QuantityType<?>) command);
+ if (command instanceof QuantityType quantityCommand) {
+ setSetPoint(quantityCommand);
}
break;
case CHANNEL_MANUAL_MODE_STATE:
}
break;
case CHANNEL_ROOM_BOOST_DURATION:
- if (command instanceof DecimalType) {
- setBoostDuration(Math.round((((DecimalType) command).floatValue() * 60)));
+ if (command instanceof DecimalType decimalCommand) {
+ setBoostDuration(Math.round((decimalCommand.floatValue() * 60)));
}
break;
case CHANNEL_ROOM_WINDOW_STATE_DETECTION:
case UserClosing: /* 700 */
user = message.substring(4);
name = name.concat(": " + user);
- description = codeReceived + ": Partition " + String.valueOf(partition)
- + " has been armed by user " + user + ".";
+ description = codeReceived + ": Partition " + partition + " has been armed by user " + user
+ + ".";
messageType = DSCAlarmMessageType.PARTITION_EVENT;
break;
case UserOpening: /* 750 */
user = message.substring(4);
name = name.concat(": " + user);
- description = codeReceived + ": Partition " + String.valueOf(partition)
- + " has been disarmed by user " + user + ".";
+ description = codeReceived + ": Partition " + partition + " has been disarmed by user " + user
+ + ".";
messageType = DSCAlarmMessageType.PARTITION_EVENT;
break;
break;
case PARTITION:
if (partitionNumber >= 1 && partitionNumber <= 8) {
- thingID = "partition" + String.valueOf(partitionNumber);
- thingLabel = "Partition " + String.valueOf(partitionNumber);
+ thingID = "partition" + partitionNumber;
+ thingLabel = "Partition " + partitionNumber;
properties = new HashMap<>(0);
thingUID = new ThingUID(DSCAlarmBindingConstants.PARTITION_THING_TYPE, bridge.getUID(), thingID);
properties.put(DSCAlarmPartitionConfiguration.PARTITION_NUMBER, partitionNumber);
break;
case ZONE:
if (zoneNumber >= 1 && zoneNumber <= 64) {
- thingID = "zone" + String.valueOf(zoneNumber);
- thingLabel = "Zone " + String.valueOf(zoneNumber);
+ thingID = "zone" + zoneNumber;
+ thingLabel = "Zone " + zoneNumber;
properties = new HashMap<>(0);
thingUID = new ThingUID(DSCAlarmBindingConstants.ZONE_THING_TYPE, bridge.getUID(), thingID);
properties.put(DSCAlarmZoneConfiguration.ZONE_NUMBER, zoneNumber);
* @return
*/
private long convertIPToNumber(String ipAddress) {
- String octets[] = ipAddress.split("\\.");
+ String[] octets = ipAddress.split("\\.");
if (octets.length != 4) {
throw new IllegalArgumentException("Invalid IP address: " + ipAddress);
updateState(channelUID, new StringType(String.valueOf(-1)));
break;
case PANEL_TIME_STAMP:
- if (command instanceof OnOffType) {
+ if (command instanceof OnOffType onOffCommand) {
cmd = command == OnOffType.ON ? 1 : 0;
dscAlarmBridgeHandler.sendCommand(DSCAlarmCode.TimeStampControl, String.valueOf(cmd));
- updateState(channelUID, (OnOffType) command);
+ updateState(channelUID, onOffCommand);
}
break;
case PANEL_TIME_BROADCAST:
- if (command instanceof OnOffType) {
+ if (command instanceof OnOffType onOffCommand) {
cmd = command == OnOffType.ON ? 1 : 0;
dscAlarmBridgeHandler.sendCommand(DSCAlarmCode.TimeDateBroadcastControl, String.valueOf(cmd));
- updateState(channelUID, (OnOffType) command);
+ updateState(channelUID, onOffCommand);
}
break;
default:
if (dscAlarmBridgeHandler != null && dscAlarmBridgeHandler.isConnected()
&& channelUID.getId().equals(ZONE_BYPASS_MODE)) {
- String data = String.valueOf(getPartitionNumber()) + "*1" + String.format("%02d", getZoneNumber()) + "#";
+ String data = getPartitionNumber() + "*1" + String.format("%02d", getZoneNumber()) + "#";
dscAlarmBridgeHandler.sendCommand(DSCAlarmCode.KeySequence, data);
}
@Override
public boolean equals(@Nullable final Object other) {
OBISIdentifier o;
- if (other != null && other instanceof OBISIdentifier) {
- o = (OBISIdentifier) other;
+ if (other != null && other instanceof OBISIdentifier identifier) {
+ o = identifier;
} else {
return false;
}
logger.trace("Possible port to check:{}, owned:{} by:{}", currentScannedPortName,
portIdentifier.isCurrentlyOwned(), portIdentifier.getCurrentOwner());
if (DSMR_PORT_NAME.equals(portIdentifier.getCurrentOwner())) {
- logger.debug("The port {} is owned by this binding. If no DSMR meters will be found it "
- + "might indicate the port is locked by an older instance of this binding. "
- + "Restart the system to unlock the port.", currentScannedPortName);
+ logger.debug("""
+ The port {} is owned by this binding. If no DSMR meters will be found it \
+ might indicate the port is locked by an older instance of this binding. \
+ Restart the system to unlock the port.\
+ """, currentScannedPortName);
}
} else {
logger.debug("Start discovery on serial port: {}", currentScannedPortName);
@Override
public void setThingHandler(final ThingHandler handler) {
- if (handler instanceof DSMRBridgeHandler) {
- dsmrBridgeHandler = (DSMRBridgeHandler) handler;
+ if (handler instanceof DSMRBridgeHandler bridgeHandler) {
+ dsmrBridgeHandler = bridgeHandler;
}
}
reportUnregisteredMeters();
} else {
reportUnrecognizedCosemObjects(list);
- logger.info("There are unrecognized cosem values in the data received from the meter,"
- + " which means some meters might not be detected. Please report your raw data as reference: {}",
- telegram.getRawTelegram());
+ logger.info("""
+ There are unrecognized cosem values in the data received from the meter,\
+ which means some meters might not be detected. Please report your raw data as reference: {}\
+ """, telegram.getRawTelegram());
}
}
if (!telegram.getUnknownCosemObjects().isEmpty()) {
- logger.info("There are unrecognized cosem values in the data received from the meter,"
- + " which means you have values that can't be read by a channel: {}. Please report them and your raw data as reference: {}",
+ logger.info(
+ """
+ There are unrecognized cosem values in the data received from the meter,\
+ which means you have values that can't be read by a channel: {}. Please report them and your raw data as reference: {}\
+ """,
telegram.getUnknownCosemObjects().stream()
.map(e -> String.format("obis id:%s, value:%s", e.getKey(), e.getValue()))
.collect(Collectors.joining(", ")),
*/
protected void reportConfigurationValidationResults(final List<DSMRMeterType> invalidConfigured,
final List<DSMRMeterType> unconfiguredMeters) {
- logger.info(
- "Possible incorrect meters configured. These are configured: {}."
- + "But the following unconfigured meters are found in the data received from the meter: {}",
- invalidConfigured.stream().map(m -> m.name()).collect(Collectors.joining(", ")),
+ logger.info("""
+ Possible incorrect meters configured. These are configured: {}.\
+ But the following unconfigured meters are found in the data received from the meter: {}\
+ """, invalidConfigured.stream().map(m -> m.name()).collect(Collectors.joining(", ")),
unconfiguredMeters.stream().map(m -> m.name()).collect(Collectors.joining(", ")));
}
}
*/
public List<CosemObject> filterMeterValues(List<CosemObject> cosemObjects, int channel) {
logger.trace("supported identifiers: {}, searching for objects {}", supportedIdentifiers, cosemObjects);
- List<CosemObject> filteredValues = cosemObjects.stream()
+ return cosemObjects.stream()
.filter(cosemObject -> (DSMRMeterConstants.UNKNOWN_CHANNEL == channel
|| cosemObject.getObisIdentifier().getChannel() == channel)
&& supportedIdentifiers.contains(cosemObject.getObisIdentifier().getReducedOBISIdentifier()))
.collect(Collectors.toList());
- return filteredValues;
}
/**
public class P1TelegramParserTest {
// @formatter:off
- public static final List<Object[]> data() {
+ public static List<Object[]> data() {
return Arrays.asList(new Object[][] {
{ "ace4000", 59, 0},
{ "dsmr_40", 39, 0},
public class DSMRMeterDetectorTest {
// @formatter:off
- public static final List<Object[]> data() {
+ public static List<Object[]> data() {
return Arrays.asList(new Object[][] {
{ "ace4000", EnumSet.of(ELECTRICITY_ACE4000, GAS_ACE4000)},
{ "dsmr_40", EnumSet.of(DEVICE_V4, ELECTRICITY_V4_2, M3_V5_0)},
@Override
public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
- if (childHandler instanceof DWDPollenflugRegionHandler) {
+ if (childHandler instanceof DWDPollenflugRegionHandler regionListener) {
logger.debug("Register region listener.");
- final DWDPollenflugRegionHandler regionListener = (DWDPollenflugRegionHandler) childHandler;
if (regionListeners.add(regionListener)) {
final DWDPollenflug localPollenflug = pollenflug;
if (localPollenflug != null) {
@Override
public void childHandlerDisposed(ThingHandler childHandler, Thing childThing) {
- if (childHandler instanceof DWDPollenflugRegionHandler) {
+ if (childHandler instanceof DWDPollenflugRegionHandler handler) {
logger.debug("Unregister region listener.");
- if (!regionListeners.remove((DWDPollenflugRegionHandler) childHandler)) {
+ if (!regionListeners.remove(handler)) {
logger.warn("Tried to remove listener {} but it was not registered. This is probably an error.",
childHandler);
}
Bridge bridge = getBridge();
if (bridge != null) {
ThingHandler handler = bridge.getHandler();
- if (handler instanceof DWDPollenflugBridgeHandler) {
- DWDPollenflugBridgeHandler bridgeHandler = (DWDPollenflugBridgeHandler) handler;
+ if (handler instanceof DWDPollenflugBridgeHandler bridgeHandler) {
return bridgeHandler;
}
}
import static org.openhab.binding.dwdunwetter.internal.DwdUnwetterBindingConstants.THING_TYPE_WARNINGS;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.dwdunwetter", service = ThingHandlerFactory.class)
public class DwdUnwetterHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_WARNINGS);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_WARNINGS);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
private String getLabel(NodeList nodeList) {
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
- if (node.getNodeName().equals("label")) {
+ if ("label".equals(node.getNodeName())) {
return node.getTextContent();
}
}
formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssX");
}
LOGGER.trace("parsing: {}", date);
- ZonedDateTime zdt = ZonedDateTime.parse(date, formatter);
- return zdt;
+ return ZonedDateTime.parse(date, formatter);
}
/**
@NonNullByDefault
public abstract class AbstractCommand extends BufferingResponseListener implements EaseeCommand {
- public static enum RetryOnFailure {
+ public enum RetryOnFailure {
YES,
- NO;
+ NO
}
- public static enum ProcessFailureResponse {
+ public enum ProcessFailureResponse {
YES,
- NO;
+ NO
}
/**
* @return value as String without unit.
*/
protected String getCommandValue() {
- if (command instanceof QuantityType<?>) {
+ if (command instanceof QuantityType<?> quantityCommand) {
// this is necessary because we must not send the unit to the backend
- return String.valueOf(((QuantityType<?>) command).doubleValue());
+ return String.valueOf(quantityCommand.doubleValue());
} else if (command instanceof OnOffType) {
// this is necessary because we must send booleans and not ON/OFF to the backend
return String.valueOf(command.equals(OnOffType.ON));
@Override
public void setThingHandler(ThingHandler handler) {
- if (handler instanceof EaseeSiteHandler) {
- this.bridgeHandler = (EaseeSiteHandler) handler;
+ if (handler instanceof EaseeSiteHandler siteHandler) {
+ this.bridgeHandler = siteHandler;
this.bridgeHandler.setDiscoveryService(this);
}
}
import static org.openhab.binding.easee.internal.EaseeBindingConstants.*;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(EaseeSiteDiscoveryService.class);
+ return Set.of(EaseeSiteDiscoveryService.class);
}
public void setDiscoveryService(EaseeSiteDiscoveryService discoveryService) {
default @Nullable Channel getChannel(String groupId, String channelId) {
ThingUID thingUID = this.getThing().getUID();
ChannelGroupUID channelGroupUID = new ChannelGroupUID(thingUID, groupId);
- Channel channel = getThing().getChannel(new ChannelUID(channelGroupUID, channelId));
- return channel;
+ return getThing().getChannel(new ChannelUID(channelGroupUID, channelId));
}
}
String phase2 = Utils.getAsString(rawData, channelPhase2);
String phase3 = Utils.getAsString(rawData, channelPhase3);
if (channel != null && phase1 != null && phase2 != null && phase3 != null) {
- phase1 = phase1.replaceAll("\\.0", "");
- phase2 = phase2.replaceAll("\\.0", "");
- phase3 = phase3.replaceAll("\\.0", "");
+ phase1 = phase1.replace(".0", "");
+ phase2 = phase2.replace(".0", "");
+ phase3 = phase3.replace(".0", "");
result.put(channel, new StringType(phase1 + ";" + phase2 + ";" + phase3));
}
}
return classProperties;
}
+ @Override
public String toString() {
return name() + "{" + "groupCode=0x" + Integer.toHexString(groupCode) + ", classCode=0x"
+ Integer.toHexString(0xFF & classCode) + '}';
this.listener = listener;
}
+ @Override
public void applyProperty(InstanceKey sourceInstanceKey, Esv esv, final int epcCode, final int pdc,
final ByteBuffer edt) {
final Epc epc = Epc.lookup(instanceKey().klass.groupCode(), instanceKey().klass.classCode(), epcCode);
return identificationNumber.toString();
}
+ @Override
public boolean buildUpdateMessage(final EchonetMessageBuilder messageBuilder, final ShortSupplier tidSupplier,
final long nowMs, InstanceKey managementControllerKey) {
if (pendingSets.isEmpty()) {
return true;
}
+ @Override
public void update(String channelId, State state) {
final Epc epc = epcByChannelId.get(channelId);
if (null == epc) {
listener.onRemoved();
}
+ @Override
public void checkTimeouts() {
if (EchonetLiteBindingConstants.OFFLINE_TIMEOUT_COUNT <= inflightGetRequest.timeoutCount()) {
listener.onOffline();
}
}
+ @Override
public void refreshAll(long nowMs) {
final EchonetPropertyMap getPropertyMap = this.getPropertyMap;
if (lastPollMs + pollIntervalMs <= nowMs && null != getPropertyMap) {
@Override
public void setThingHandler(ThingHandler thingHandler) {
- if (thingHandler instanceof EchonetLiteBridgeHandler) {
- this.bridgeHandler = (EchonetLiteBridgeHandler) thingHandler;
+ if (thingHandler instanceof EchonetLiteBridgeHandler bridgeHandler) {
+ this.bridgeHandler = bridgeHandler;
}
}
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
private void newDeviceInternal(final NewDeviceMessage message) {
final EchonetObject echonetObject = devicesByKey.get(message.instanceKey);
if (null != echonetObject) {
- if (echonetObject instanceof EchonetDevice) {
+ if (echonetObject instanceof EchonetDevice device) {
logger.debug("Update item: {} already discovered", message.instanceKey);
- EchonetDevice device = (EchonetDevice) echonetObject;
device.setTimeouts(message.pollIntervalMs, message.retryTimeoutMs);
device.setListener(message.echonetDeviceListener);
} else {
Message message;
while (null != (message = requestsPoll())) {
logger.debug("Received request: {}", message);
- if (message instanceof NewDeviceMessage) {
- newDeviceInternal((NewDeviceMessage) message);
- } else if (message instanceof RefreshMessage) {
- refreshDeviceInternal((RefreshMessage) message);
- } else if (message instanceof RemoveDevice) {
- removeDeviceInternal((RemoveDevice) message);
- } else if (message instanceof UpdateDevice) {
- updateDeviceInternal((UpdateDevice) message);
- } else if (message instanceof StartDiscoveryMessage) {
- startDiscoveryInternal((StartDiscoveryMessage) message);
- } else if (message instanceof StopDiscoveryMessage) {
- stopDiscoveryInternal((StopDiscoveryMessage) message);
+ if (message instanceof NewDeviceMessage deviceMessage) {
+ newDeviceInternal(deviceMessage);
+ } else if (message instanceof RefreshMessage refreshMessage) {
+ refreshDeviceInternal(refreshMessage);
+ } else if (message instanceof RemoveDevice device) {
+ removeDeviceInternal(device);
+ } else if (message instanceof UpdateDevice device) {
+ updateDeviceInternal(device);
+ } else if (message instanceof StartDiscoveryMessage discoveryMessage) {
+ startDiscoveryInternal(discoveryMessage);
+ } else if (message instanceof StopDiscoveryMessage discoveryMessage) {
+ stopDiscoveryInternal(discoveryMessage);
}
}
}
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singletonList(EchonetDiscoveryService.class);
+ return List.of(EchonetDiscoveryService.class);
}
private abstract static class Message {
this.state = state;
}
+ @Override
public String toString() {
return "UpdateDevice{" + "instanceKey=" + instanceKey + ", channelId='" + channelId + '\'' + ", state="
+ state + "} " + super.toString();
} else {
updateState(channelUID, currentState);
}
- } else if (command instanceof State) {
+ } else if (command instanceof State stateCommand) {
logger.debug("Updating: {} to {}", channelUID, command);
- handler.updateDevice(requireNonNull(instanceKey), channelUID.getId(), (State) command);
+ handler.updateDevice(requireNonNull(instanceKey), channelUID.getId(), stateCommand);
}
}
}
}
+ @Override
public void handleRemoval() {
@Nullable
final EchonetLiteBridgeHandler bridgeHandler = bridgeHandler();
bridgeHandler.removeDevice(requireNonNull(instanceKey));
}
+ @Override
public void onInitialised(String identifier, InstanceKey instanceKey, Map<String, String> channelIdAndType) {
logger.debug("Initialised Channels: {}", channelIdAndType);
updateStatus(ThingStatus.ONLINE);
}
+ @Override
public void onUpdated(final String channelId, final State value) {
stateByChannelId.put(channelId, value);
updateState(channelId, value);
}
+ @Override
public void onRemoved() {
updateStatus(ThingStatus.REMOVED);
}
+ @Override
public void onOffline() {
if (ThingStatus.OFFLINE != getThing().getStatus()) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR);
public void refreshAll(long nowMs) {
}
+ @Override
public String toString() {
return "ItemBase{" + "instanceKey=" + instanceKey + ", pendingProperties=" + pendingGets + '}';
}
return properties;
}
+ @Override
public String toString() {
return "EnPropertyMap{" + "propertyMap=" + HexUtil.hex(propertyMap) + '}';
}
this(code, stateCodec, stateCodec);
}
+ @Override
public int code() {
return code;
}
@Nullable
+ @Override
public StateDecode decoder() {
return stateDecode;
}
@Nullable
+ @Override
public StateEncode encoder() {
return stateEncode;
}
this(code, stateCodec, stateCodec);
}
+ @Override
public int code() {
return code;
}
@Nullable
+ @Override
public StateDecode decoder() {
return stateDecode;
}
@Nullable
+ @Override
public StateEncode encoder() {
return stateEncode;
}
this.code = code;
}
+ @Override
public int code() {
return code;
}
this(code, stateCodec, stateCodec);
}
+ @Override
public int code() {
return code;
}
@Nullable
+ @Override
public StateDecode decoder() {
return stateDecode;
}
@Nullable
+ @Override
public StateEncode encoder() {
return stateEncode;
}
this.code = code;
}
+ @Override
public int code() {
return code;
}
this.code = code;
}
+ @Override
public int code() {
return code;
}
this.instance = instance;
}
+ @Override
public String toString() {
return "InstanceKey{" + "address=" + address + ", klass=" + klass + ", instance=" + instance + '}';
}
+ hex(instance);
}
+ @Override
public boolean equals(@Nullable final Object o) {
if (this == o) {
return true;
return instance == that.instance && address.equals(that.address) && klass == that.klass;
}
+ @Override
public int hashCode() {
return Objects.hash(address, klass, instance);
}
this.off = off;
}
+ @Override
public State decodeState(final ByteBuffer edt) {
return b(on) == edt.get() ? OnOffType.ON : OnOffType.OFF;
}
+ @Override
public void encodeState(final State state, final ByteBuffer edt) {
final OnOffType onOff = (OnOffType) state;
edt.put(onOff == OnOffType.ON ? b(on) : b(off));
}
+ @Override
public String itemType() {
return "Switch";
}
INSTANCE;
+ @Override
public State decodeState(final ByteBuffer edt) {
final int pdc = edt.remaining();
if (pdc != 4) {
return new StringType("" + (char) edt.get(edt.position() + 2));
}
+ @Override
public String itemType() {
return "String";
}
INSTANCE;
+ @Override
public State decodeState(final ByteBuffer edt) {
return new StringType(hex(edt, "", "", "", ""));
}
+ @Override
public String itemType() {
return "String";
}
enum OperatingTimeDecode implements StateDecode {
INSTANCE;
+ @Override
public State decodeState(final ByteBuffer edt) {
// Specification isn't explicit about byte order, but seems to be work with testing.
edt.order(ByteOrder.BIG_ENDIAN);
return new QuantityType<>(timeUnit.toSeconds(time), Units.SECOND);
}
+ @Override
public String itemType() {
return "Number:Time";
}
}
}
+ @Override
public String itemType() {
return "String";
}
+ @Override
public State decodeState(final ByteBuffer edt) {
final int value = edt.get() & 0xFF;
final Option option = optionByValue[value];
return null != option ? option.state : unknown;
}
+ @Override
public void encodeState(final State state, final ByteBuffer edt) {
final Option option = optionByName.get(state.toFullString());
if (null != option) {
INSTANCE;
+ @Override
public String itemType() {
return "Number";
}
+ @Override
public State decodeState(final ByteBuffer edt) {
final int value = edt.get(); // Should expand to typed value (mask excluded)
return new DecimalType(value);
}
+ @Override
public void encodeState(final State state, final ByteBuffer edt) {
edt.put((byte) (((DecimalType) state).intValue()));
}
enum Temperature8bitCodec implements StateCodec {
INSTANCE;
+ @Override
public State decodeState(final ByteBuffer edt) {
final int value = edt.get();
return new QuantityType<>(value, SIUnits.CELSIUS);
}
+ @Override
public String itemType() {
return "Number:Temperature";
}
+ @Override
public void encodeState(final State state, final ByteBuffer edt) {
final @Nullable QuantityType<?> tempCelsius = ((QuantityType<?>) state).toUnit(SIUnits.CELSIUS);
edt.put((byte) (Objects.requireNonNull(tempCelsius).intValue()));
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof EcobeeThermostatBridgeHandler) {
- this.handler = (EcobeeThermostatBridgeHandler) handler;
+ if (handler instanceof EcobeeThermostatBridgeHandler bridgeHandler) {
+ this.handler = bridgeHandler;
}
}
/*
* This state indicates that the "authorize" and "token" steps were successful.
*/
- COMPLETE;
+ COMPLETE
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof EcobeeAccountBridgeHandler) {
- this.bridgeHandler = (EcobeeAccountBridgeHandler) handler;
+ if (handler instanceof EcobeeAccountBridgeHandler accountBridgeHandler) {
+ this.bridgeHandler = accountBridgeHandler;
}
}
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(EcobeeDiscoveryService.class);
+ return Set.of(EcobeeDiscoveryService.class);
}
@Override
import java.lang.reflect.Field;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
public boolean actionPerformFunction(AbstractFunction function) {
logger.debug("ThermostatBridge: Perform function '{}' on thermostat {}", function.type, thermostatId);
SelectionDTO selection = new SelectionDTO();
- selection.setThermostats(Collections.singleton(thermostatId));
+ selection.setThermostats(Set.of(thermostatId));
FunctionRequest request = new FunctionRequest(selection);
- request.functions = Collections.singletonList(function);
+ request.functions = List.of(function);
EcobeeAccountBridgeHandler handler = getBridgeHandler();
if (handler != null) {
return handler.performThermostatFunction(request);
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singletonList(EcobeeActions.class);
+ return List.of(EcobeeActions.class);
}
public void updateChannels(ThermostatDTO thermostat) {
success = true;
}
} else if (Integer.class.isAssignableFrom(fieldClass)) {
- if (command instanceof DecimalType) {
+ if (command instanceof DecimalType decimalCommand) {
logger.debug("Set field of type Integer to value of DecimalType");
- field.set(object, Integer.valueOf(((DecimalType) command).intValue()));
+ field.set(object, Integer.valueOf(decimalCommand.intValue()));
success = true;
- } else if (command instanceof QuantityType) {
- Unit<?> unit = ((QuantityType<?>) command).getUnit();
+ } else if (command instanceof QuantityType quantityCommand) {
+ Unit<?> unit = quantityCommand.getUnit();
logger.debug("Set field of type Integer to value of QuantityType with unit {}", unit);
if (unit.equals(ImperialUnits.FAHRENHEIT) || unit.equals(SIUnits.CELSIUS)) {
- QuantityType<?> quantity = ((QuantityType<?>) command).toUnit(ImperialUnits.FAHRENHEIT);
+ QuantityType<?> quantity = quantityCommand.toUnit(ImperialUnits.FAHRENHEIT);
if (quantity != null) {
field.set(object, quantity.intValue() * 10);
success = true;
private void performThermostatUpdate(ThermostatDTO thermostat) {
SelectionDTO selection = new SelectionDTO();
- selection.setThermostats(Collections.singleton(thermostatId));
+ selection.setThermostats(Set.of(thermostatId));
ThermostatUpdateRequestDTO request = new ThermostatUpdateRequestDTO(selection);
request.thermostat = thermostat;
EcobeeAccountBridgeHandler handler = getBridgeHandler();
cause = e.toString();
}
- if (line2 != null && line2.trim().equals("#E_USER_DONT_EXIST")) {
+ if (line2 != null && "#E_USER_DONT_EXIST".equals(line2.trim())) {
throw new IOException("Username does not exist.");
}
- if (line2 != null && line2.trim().equals("#E_PASS_DONT_MATCH")) {
+ if (line2 != null && "#E_PASS_DONT_MATCH".equals(line2.trim())) {
throw new IOException("Password does not match.");
}
- if (line2 != null && line2.trim().equals("#E_TOO_MANY_USERS")) {
+ if (line2 != null && "#E_TOO_MANY_USERS".equals(line2.trim())) {
throw new IOException("Too many users already logged in.");
}
if (cookies == null) {
localConnector.setValue(ecoTouchTag.getTagName(), raw);
} else {
if (ecoTouchTag.getUnit() != ONE) {
- if (command instanceof QuantityType) {
- // convert from user unit to heat pump unit
- QuantityType<?> value = (QuantityType<?>) command;
- QuantityType<?> rawUnit = value.toUnit(ecoTouchTag.getUnit());
+ if (command instanceof QuantityType quantityCommand) {
+ QuantityType<?> rawUnit = quantityCommand.toUnit(ecoTouchTag.getUnit());
if (rawUnit != null) {
int raw = (int) (rawUnit.doubleValue() * ecoTouchTag.getDivisor());
localConnector.setValue(ecoTouchTag.getTagName(), raw);
}
public static void playSound(@Nullable ThingActions actions, String type) {
- if (actions instanceof EcovacsVacuumActions) {
- ((EcovacsVacuumActions) actions).playSound(type);
+ if (actions instanceof EcovacsVacuumActions action) {
+ action.playSound(type);
}
}
public static void playSoundWithId(@Nullable ThingActions actions, int soundId) {
- if (actions instanceof EcovacsVacuumActions) {
- ((EcovacsVacuumActions) actions).playSoundWithId(soundId);
+ if (actions instanceof EcovacsVacuumActions action) {
+ action.playSoundWithId(soundId);
}
}
}
@Override
public String convertResponse(AbstractPortalIotCommandResponse response, ProtocolVersion version, Gson gson)
throws DataParsingException {
- if (response instanceof PortalIotCommandJsonResponse) {
- CachedMapInfoReport resp = ((PortalIotCommandJsonResponse) response).getResponsePayloadAs(gson,
- CachedMapInfoReport.class);
+ if (response instanceof PortalIotCommandJsonResponse jsonResponse) {
+ CachedMapInfoReport resp = jsonResponse.getResponsePayloadAs(gson, CachedMapInfoReport.class);
return resp.mapInfos.stream().filter(i -> i.used != 0).map(i -> i.mapId).findFirst().orElse("");
} else {
String payload = ((PortalIotCommandXmlResponse) response).getResponsePayloadXml();
@Override
public Integer convertResponse(AbstractPortalIotCommandResponse response, ProtocolVersion version, Gson gson)
throws DataParsingException {
- if (response instanceof PortalIotCommandJsonResponse) {
- BatteryReport resp = ((PortalIotCommandJsonResponse) response).getResponsePayloadAs(gson,
- BatteryReport.class);
+ if (response instanceof PortalIotCommandJsonResponse jsonResponse) {
+ BatteryReport resp = jsonResponse.getResponsePayloadAs(gson, BatteryReport.class);
return resp.percent;
} else {
String payload = ((PortalIotCommandXmlResponse) response).getResponsePayloadXml();
@Override
public ChargeMode convertResponse(AbstractPortalIotCommandResponse response, ProtocolVersion version, Gson gson)
throws DataParsingException {
- if (response instanceof PortalIotCommandJsonResponse) {
- ChargeReport resp = ((PortalIotCommandJsonResponse) response).getResponsePayloadAs(gson,
- ChargeReport.class);
+ if (response instanceof PortalIotCommandJsonResponse jsonResponse) {
+ ChargeReport resp = jsonResponse.getResponsePayloadAs(gson, ChargeReport.class);
return resp.isCharging != 0 ? ChargeMode.CHARGING : ChargeMode.IDLE;
} else {
String payload = ((PortalIotCommandXmlResponse) response).getResponsePayloadXml();
@Override
public CleanMode convertResponse(AbstractPortalIotCommandResponse response, ProtocolVersion version, Gson gson)
throws DataParsingException {
- if (response instanceof PortalIotCommandJsonResponse) {
- final PortalIotCommandJsonResponse jsonResponse = (PortalIotCommandJsonResponse) response;
+ if (response instanceof PortalIotCommandJsonResponse jsonResponse) {
final CleanMode mode;
if (version == ProtocolVersion.JSON) {
CleanReport resp = jsonResponse.getResponsePayloadAs(gson, CleanReport.class);
@Override
public Integer convertResponse(AbstractPortalIotCommandResponse response, ProtocolVersion version, Gson gson)
throws DataParsingException {
- if (response instanceof PortalIotCommandJsonResponse) {
- JsonElement respPayloadRaw = ((PortalIotCommandJsonResponse) response).getResponsePayload(gson);
+ if (response instanceof PortalIotCommandJsonResponse jsonResponse) {
+ JsonElement respPayloadRaw = jsonResponse.getResponsePayload(gson);
Type type = new TypeToken<List<ComponentLifeSpanReport>>() {
}.getType();
try {
@Override
public Boolean convertResponse(AbstractPortalIotCommandResponse response, ProtocolVersion version, Gson gson)
throws DataParsingException {
- if (response instanceof PortalIotCommandJsonResponse) {
- EnabledStateReport resp = ((PortalIotCommandJsonResponse) response).getResponsePayloadAs(gson,
- EnabledStateReport.class);
+ if (response instanceof PortalIotCommandJsonResponse jsonResponse) {
+ EnabledStateReport resp = jsonResponse.getResponsePayloadAs(gson, EnabledStateReport.class);
return resp.enabled != 0;
} else {
String payload = ((PortalIotCommandXmlResponse) response).getResponsePayloadXml();
@Override
public Optional<Integer> convertResponse(AbstractPortalIotCommandResponse response, ProtocolVersion version,
Gson gson) throws DataParsingException {
- if (response instanceof PortalIotCommandJsonResponse) {
- ErrorReport resp = ((PortalIotCommandJsonResponse) response).getResponsePayloadAs(gson, ErrorReport.class);
+ if (response instanceof PortalIotCommandJsonResponse jsonResponse) {
+ ErrorReport resp = jsonResponse.getResponsePayloadAs(gson, ErrorReport.class);
if (resp.errorCodes.isEmpty()) {
return Optional.empty();
}
@Override
public List<String> convertResponse(AbstractPortalIotCommandResponse response, ProtocolVersion version, Gson gson)
throws DataParsingException {
- if (response instanceof PortalIotCommandJsonResponse) {
- MapSetReport resp = ((PortalIotCommandJsonResponse) response).getResponsePayloadAs(gson,
- MapSetReport.class);
+ if (response instanceof PortalIotCommandJsonResponse jsonResponse) {
+ MapSetReport resp = jsonResponse.getResponsePayloadAs(gson, MapSetReport.class);
return resp.subsets.stream().map(i -> i.id).collect(Collectors.toList());
} else {
String payload = ((PortalIotCommandXmlResponse) response).getResponsePayloadXml();
@Override
public MoppingWaterAmount convertResponse(AbstractPortalIotCommandResponse response, ProtocolVersion version,
Gson gson) throws DataParsingException {
- if (response instanceof PortalIotCommandJsonResponse) {
- WaterInfoReport resp = ((PortalIotCommandJsonResponse) response).getResponsePayloadAs(gson,
- WaterInfoReport.class);
+ if (response instanceof PortalIotCommandJsonResponse jsonResponse) {
+ WaterInfoReport resp = jsonResponse.getResponsePayloadAs(gson, WaterInfoReport.class);
return MoppingWaterAmount.fromApiValue(resp.waterAmount);
} else {
String payload = ((PortalIotCommandXmlResponse) response).getResponsePayloadXml();
@Override
public NetworkInfo convertResponse(AbstractPortalIotCommandResponse response, ProtocolVersion version, Gson gson)
throws DataParsingException {
- if (response instanceof PortalIotCommandJsonResponse) {
- NetworkInfoReport resp = ((PortalIotCommandJsonResponse) response).getResponsePayloadAs(gson,
- NetworkInfoReport.class);
+ if (response instanceof PortalIotCommandJsonResponse jsonResponse) {
+ NetworkInfoReport resp = jsonResponse.getResponsePayloadAs(gson, NetworkInfoReport.class);
try {
return new NetworkInfo(resp.ip, resp.mac, resp.ssid, Integer.valueOf(resp.rssi));
} catch (NumberFormatException e) {
@Override
public SuctionPower convertResponse(AbstractPortalIotCommandResponse response, ProtocolVersion version, Gson gson)
throws DataParsingException {
- if (response instanceof PortalIotCommandJsonResponse) {
- SpeedReport resp = ((PortalIotCommandJsonResponse) response).getResponsePayloadAs(gson, SpeedReport.class);
+ if (response instanceof PortalIotCommandJsonResponse jsonResponse) {
+ SpeedReport resp = jsonResponse.getResponsePayloadAs(gson, SpeedReport.class);
return SuctionPower.fromJsonValue(resp.speedLevel);
} else {
String payload = ((PortalIotCommandXmlResponse) response).getResponsePayloadXml();
@Override
public TotalStats convertResponse(AbstractPortalIotCommandResponse response, ProtocolVersion version, Gson gson)
throws DataParsingException {
- if (response instanceof PortalIotCommandJsonResponse) {
- return ((PortalIotCommandJsonResponse) response).getResponsePayloadAs(gson, TotalStats.class);
+ if (response instanceof PortalIotCommandJsonResponse jsonResponse) {
+ return jsonResponse.getResponsePayloadAs(gson, TotalStats.class);
} else {
String payload = ((PortalIotCommandXmlResponse) response).getResponsePayloadXml();
String area = XPathUtils.getFirstXPathMatch(payload, "//@a").getNodeValue();
@Override
public Integer convertResponse(AbstractPortalIotCommandResponse response, ProtocolVersion version, Gson gson)
throws DataParsingException {
- if (response instanceof PortalIotCommandJsonResponse) {
- JsonResponse resp = ((PortalIotCommandJsonResponse) response).getResponsePayloadAs(gson,
- JsonResponse.class);
+ if (response instanceof PortalIotCommandJsonResponse jsonResponse) {
+ JsonResponse resp = jsonResponse.getResponsePayloadAs(gson, JsonResponse.class);
return resp.volume;
} else {
// unsupported in XML case?
@Override
public Boolean convertResponse(AbstractPortalIotCommandResponse response, ProtocolVersion version, Gson gson)
throws DataParsingException {
- if (response instanceof PortalIotCommandJsonResponse) {
- WaterInfoReport resp = ((PortalIotCommandJsonResponse) response).getResponsePayloadAs(gson,
- WaterInfoReport.class);
+ if (response instanceof PortalIotCommandJsonResponse jsonResponse) {
+ WaterInfoReport resp = jsonResponse.getResponsePayloadAs(gson, WaterInfoReport.class);
return resp.waterPlatePresent != 0;
} else {
String payload = ((PortalIotCommandXmlResponse) response).getResponsePayloadXml();
List<EcovacsDevice> devices = new ArrayList<>();
for (Device dev : getDeviceList()) {
Optional<DeviceDescription> descOpt = Optional.ofNullable(descriptions.get(dev.getDeviceClass()));
- if (!descOpt.isPresent()) {
+ if (descOpt.isEmpty()) {
if (products == null) {
products = getIotProductMap();
}
DeviceDescription desc = descEntry.getValue();
if (desc.deviceClassLink != null) {
Optional<DeviceDescription> linkedDescOpt = Optional.ofNullable(descs.get(desc.deviceClassLink));
- if (!linkedDescOpt.isPresent()) {
+ if (linkedDescOpt.isEmpty()) {
logger.warn("Device description {} links unknown description {}", desc.deviceClass,
desc.deviceClassLink);
}
logger.debug("Established MQTT connection to device {}", getSerialNumber());
} catch (ExecutionException e) {
Throwable cause = e.getCause();
- boolean isAuthFailure = cause instanceof Mqtt3ConnAckException && ((Mqtt3ConnAckException) cause)
- .getMqttMessage().getReturnCode() == Mqtt3ConnAckReturnCode.NOT_AUTHORIZED;
+ boolean isAuthFailure = cause instanceof Mqtt3ConnAckException connAckException
+ && connAckException.getMqttMessage().getReturnCode() == Mqtt3ConnAckReturnCode.NOT_AUTHORIZED;
throw new EcovacsApiException(e, isAuthFailure);
}
}
return null;
}
- if (iqRequest instanceof DeviceCommandIQ) {
- DeviceCommandIQ iq = (DeviceCommandIQ) iqRequest;
+ if (iqRequest instanceof DeviceCommandIQ iq) {
try {
if (!iq.id.isEmpty()) {
} catch (DataParsingException e) {
listener.onEventStreamFailure(EcovacsXmppDevice.this, e);
}
- } else if (iqRequest instanceof ErrorIQ) {
- StanzaError error = ((ErrorIQ) iqRequest).getError();
+ } else if (iqRequest instanceof ErrorIQ errorIQ) {
+ StanzaError error = errorIQ.getError();
logger.trace("{}: Got error response {}", getSerialNumber(), error);
listener.onEventStreamFailure(EcovacsXmppDevice.this,
new XMPPException.XMPPErrorException(iqRequest, error));
@SerializedName("GetDeviceList")
GET_DEVICE_LIST,
@SerializedName("loginByItToken")
- LOGIN_BY_TOKEN;
+ LOGIN_BY_TOKEN
}
@SerializedName("SlotCharging")
CHARGING,
@SerializedName("Idle")
- IDLE;
+ IDLE
}
import static org.openhab.binding.ecovacs.internal.EcovacsBindingConstants.*;
-import java.util.Collections;
import java.util.List;
import java.util.Optional;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
this::scanForDevices);
public EcovacsDeviceDiscoveryService() {
- super(Collections.singleton(THING_TYPE_VACUUM), DISCOVER_TIMEOUT_SECONDS, true);
+ super(Set.of(THING_TYPE_VACUUM), DISCOVER_TIMEOUT_SECONDS, true);
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof EcovacsApiHandler) {
- this.apiHandler = (EcovacsApiHandler) handler;
+ if (handler instanceof EcovacsApiHandler ecovacsApiHandler) {
+ this.apiHandler = ecovacsApiHandler;
this.apiHandler.setDiscoveryService(this);
}
}
import static org.openhab.binding.ecovacs.internal.EcovacsBindingConstants.*;
import java.util.Collection;
-import java.util.Collections;
import java.util.Optional;
+import java.util.Set;
import java.util.UUID;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(EcovacsDeviceDiscoveryService.class);
+ return Set.of(EcovacsDeviceDiscoveryService.class);
}
@Override
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
+import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(EcovacsVacuumActions.class);
+ return Set.of(EcovacsVacuumActions.class);
}
@Override
device.sendCommand(cmd);
return;
}
- } else if (channel.equals(CHANNEL_ID_VOICE_VOLUME) && command instanceof DecimalType) {
- int volumePercent = ((DecimalType) command).intValue();
+ } else if (channel.equals(CHANNEL_ID_VOICE_VOLUME) && command instanceof DecimalType volume) {
+ int volumePercent = volume.intValue();
device.sendCommand(new SetVolumeCommand((volumePercent + 5) / 10));
return;
} else if (channel.equals(CHANNEL_ID_SUCTION_POWER) && command instanceof StringType) {
if (command instanceof OnOffType) {
device.sendCommand(new SetDustbinAutoEmptyCommand(command == OnOffType.ON));
return;
- } else if (command instanceof StringType && command.toString().equals("trigger")) {
+ } else if (command instanceof StringType && "trigger".equals(command.toString())) {
device.sendCommand(new EmptyDustbinCommand());
return;
}
} else if (channel.equals(CHANNEL_ID_CONTINUOUS_CLEANING) && command instanceof OnOffType) {
device.sendCommand(new SetContinuousCleaningCommand(command == OnOffType.ON));
return;
- } else if (channel.equals(CHANNEL_ID_CLEANING_PASSES) && command instanceof DecimalType) {
- int passes = ((DecimalType) command).intValue();
+ } else if (channel.equals(CHANNEL_ID_CLEANING_PASSES) && command instanceof DecimalType type) {
+ int passes = type.intValue();
device.sendCommand(new SetDefaultCleanPassesCommand(passes));
lastDefaultCleaningPasses = passes; // if we get here, the command was executed successfully
return;
// Invalidate the cache to be sure the next request will trigger the API
cachedApiResponse.invalidateValue();
- if (retryIfApiLimitReached && exception instanceof EcowattApiLimitException
- && ((EcowattApiLimitException) exception).getRetryAfter() > 0) {
+ if (retryIfApiLimitReached && exception instanceof EcowattApiLimitException limitException
+ && limitException.getRetryAfter() > 0) {
// Will retry when the API is available again (just after the limit expired)
- retryDelay = ((EcowattApiLimitException) exception).getRetryAfter();
+ retryDelay = limitException.getRetryAfter();
}
} else {
updateStatus(ThingStatus.ONLINE);
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof ElectroluxAirBridgeHandler) {
- this.handler = (ElectroluxAirBridgeHandler) handler;
+ if (handler instanceof ElectroluxAirBridgeHandler bridgeHandler) {
+ this.handler = bridgeHandler;
}
}
import static org.openhab.binding.electroluxair.internal.ElectroluxAirBindingConstants.*;
import java.util.Collection;
-import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@NonNullByDefault
public class ElectroluxAirBridgeHandler extends BaseBridgeHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_BRIDGE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BRIDGE);
private int refreshTimeInSeconds = 300;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(ElectroluxAirDiscoveryService.class);
+ return Set.of(ElectroluxAirDiscoveryService.class);
}
@Override
return bridgeHandler;
} else if (thingTypeUID.equals(THING_TYPE_ELERO_CHANNEL)) {
- EleroChannelHandler h = new EleroChannelHandler(thing);
-
- return h;
+ return new EleroChannelHandler(thing);
}
return null;
import static org.openhab.binding.elerotransmitterstick.internal.EleroTransmitterStickBindingConstants.*;
import java.util.ArrayList;
-import java.util.Collections;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
* Creates the discovery service for the given handler and converter.
*/
public EleroChannelDiscoveryService(EleroTransmitterStickHandler stickHandler) {
- super(Collections.singleton(THING_TYPE_ELERO_CHANNEL), DISCOVER_TIMEOUT_SECONDS, true);
+ super(Set.of(THING_TYPE_ELERO_CHANNEL), DISCOVER_TIMEOUT_SECONDS, true);
bridge = stickHandler;
}
import static org.openhab.binding.elerotransmitterstick.internal.EleroTransmitterStickBindingConstants.*;
-import java.util.Collections;
+import java.util.List;
import org.openhab.binding.elerotransmitterstick.internal.config.EleroChannelConfig;
import org.openhab.binding.elerotransmitterstick.internal.stick.CommandType;
if (channelUID.getIdWithoutGroup().equals(CONTROL_CHANNEL)) {
if (command == UpDownType.UP) {
- bridge.getStick().sendCommand(CommandType.UP, Collections.singletonList(channelId));
+ bridge.getStick().sendCommand(CommandType.UP, List.of(channelId));
} else if (command == UpDownType.DOWN) {
- bridge.getStick().sendCommand(CommandType.DOWN, Collections.singletonList(channelId));
+ bridge.getStick().sendCommand(CommandType.DOWN, List.of(channelId));
} else if (command == StopMoveType.STOP) {
- bridge.getStick().sendCommand(CommandType.STOP, Collections.singletonList(channelId));
- } else if (command instanceof PercentType) {
- CommandType cmd = CommandType.getForPercent(((PercentType) command).intValue());
+ bridge.getStick().sendCommand(CommandType.STOP, List.of(channelId));
+ } else if (command instanceof PercentType pt) {
+ CommandType cmd = CommandType.getForPercent(pt.intValue());
if (cmd != null) {
- bridge.getStick().sendCommand(cmd, Collections.singletonList(channelId));
+ bridge.getStick().sendCommand(cmd, List.of(channelId));
} else {
logger.debug("Unhandled command {}.", command);
}
} else if (command == RefreshType.REFRESH) {
- bridge.getStick().requestUpdate(Collections.singletonList(channelId));
+ bridge.getStick().requestUpdate(List.of(channelId));
}
}
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
-import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
// handle commands that are sent to multiple channels correctly
if (channelIds.size() > 1) {
for (int channelId : channelIds) {
- requestUpdates(Collections.singletonList(channelId));
+ requestUpdates(List.of(channelId));
}
} else if (!channelIds.isEmpty()) {
final Integer[] ids = channelIds.toArray(new Integer[channelIds.size()]);
// handle commands that are sent to multiple channels correctly
if (channelIds.size() > 1) {
for (int channelId : channelIds) {
- executeCommand(command, Collections.singletonList(channelId));
+ executeCommand(command, List.of(channelId));
}
} else if (!channelIds.isEmpty()) {
final Integer[] ids = channelIds.toArray(new Integer[channelIds.size()]);
}
}
- if (cmd instanceof TimedCommand) {
- long delay = 1000 * ((TimedCommand) cmd).getDuration();
+ if (cmd instanceof TimedCommand timedCommand) {
+ long delay = 1000 * timedCommand.getDuration();
logger.debug("adding timed command STOP for channel ids {} to queue with delay {}...",
cmd.getChannelIds(), delay);
.collect(Collectors.toUnmodifiableMap(Map.Entry::getValue, Map.Entry::getKey));
// ELRO device types
- public static enum ElroDeviceType {
+ public enum ElroDeviceType {
ENTRY_SENSOR,
CO_ALARM,
CXSM_ALARM,
.collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue));
// ELRO device status
- public static enum ElroDeviceStatus {
+ public enum ElroDeviceStatus {
NORMAL,
TRIGGERED,
TEST,
@Override
public @Nullable StateDescription getStateDescription(Channel channel,
@Nullable StateDescription originalStateDescription, @Nullable Locale locale) {
- StateDescription description = descriptions.get(channel.getUID());
- return description;
+ return descriptions.get(channel.getUID());
}
@Deactivate
typeName = getDeviceType();
}
- return deviceName.isEmpty() ? typeName + "-" + String.valueOf(deviceId) : deviceName;
+ return deviceName.isEmpty() ? typeName + "-" + deviceId : deviceName;
}
public String getDeviceType() {
String firmwareVersion = c.getValue().binVersion;
boolean legacy = false;
try {
- legacy = !(Integer.valueOf(firmwareVersion.substring(firmwareVersion.lastIndexOf(".") + 1)) > 14);
+ legacy = Integer.valueOf(firmwareVersion.substring(firmwareVersion.lastIndexOf(".") + 1)) <= 14;
} catch (NumberFormatException e) {
// Assume new firmware if we cannot decode firmwareVersion
logger.debug("Cannot get firmware version from {}, assume new firmware", firmwareVersion);
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- ElroConnectsAccountHandler account = null;
- if (handler instanceof ElroConnectsAccountHandler) {
- account = (ElroConnectsAccountHandler) handler;
- accountHandler = account;
- }
-
- if (account != null) {
- account.setDiscoveryService(this);
+ if (handler instanceof ElroConnectsAccountHandler accountHandler) {
+ this.accountHandler = accountHandler;
+ accountHandler.setDiscoveryService(this);
}
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- ElroConnectsBridgeHandler bridge = null;
- if (handler instanceof ElroConnectsBridgeHandler) {
- bridge = (ElroConnectsBridgeHandler) handler;
- bridgeHandler = bridge;
- }
-
- if (bridge != null) {
- bridge.setDiscoveryService(this);
+ if (handler instanceof ElroConnectsBridgeHandler bridgeHandler) {
+ this.bridgeHandler = bridgeHandler;
+ bridgeHandler.setDiscoveryService(this);
}
}
import java.net.SocketTimeoutException;
import java.net.URI;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledFuture;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(ElroConnectsBridgeDiscoveryService.class);
+ return Set.of(ElroConnectsBridgeDiscoveryService.class);
}
/**
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
if (SCENE.equals(channelUID.getId())) {
if (command instanceof RefreshType) {
updateState(SCENE, new StringType(String.valueOf(currentScene)));
- } else if (command instanceof StringType) {
+ } else if (command instanceof StringType stringCommand) {
try {
- selectScene(Integer.valueOf(((StringType) command).toString()));
+ selectScene(Integer.valueOf(stringCommand.toString()));
} catch (NumberFormatException nfe) {
logger.debug("Cannot interpret scene command {}", command);
}
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(ElroConnectsDiscoveryService.class);
+ return Set.of(ElroConnectsDiscoveryService.class);
}
public Map<Integer, String> listDevicesFromConsole() {
* @return Map of prices
*/
public static Map<Instant, BigDecimal> getPrices(@Nullable ThingActions actions, @Nullable String priceElements) {
- if (actions instanceof EnergiDataServiceActions) {
+ if (actions instanceof EnergiDataServiceActions serviceActions) {
if (priceElements != null && !priceElements.isBlank()) {
- return ((EnergiDataServiceActions) actions).getPrices(priceElements);
+ return serviceActions.getPrices(priceElements);
} else {
- return ((EnergiDataServiceActions) actions).getPrices();
+ return serviceActions.getPrices();
}
} else {
throw new IllegalArgumentException("Instance is not an EnergiDataServiceActions class.");
if (start == null || end == null || power == null) {
return BigDecimal.ZERO;
}
- if (actions instanceof EnergiDataServiceActions) {
- return ((EnergiDataServiceActions) actions).calculatePrice(start, end, power);
+ if (actions instanceof EnergiDataServiceActions serviceActions) {
+ return serviceActions.calculatePrice(start, end, power);
} else {
throw new IllegalArgumentException("Instance is not an EnergiDataServiceActions class.");
}
public static Map<String, Object> calculateCheapestPeriod(@Nullable ThingActions actions,
@Nullable Instant earliestStart, @Nullable Instant latestEnd, @Nullable Duration duration) {
- if (actions instanceof EnergiDataServiceActions) {
+ if (actions instanceof EnergiDataServiceActions serviceActions) {
if (earliestStart == null || latestEnd == null || duration == null) {
return Map.of();
}
- return ((EnergiDataServiceActions) actions).calculateCheapestPeriod(earliestStart, latestEnd, duration);
+ return serviceActions.calculateCheapestPeriod(earliestStart, latestEnd, duration);
} else {
throw new IllegalArgumentException("Instance is not an EnergiDataServiceActions class.");
}
public static Map<String, Object> calculateCheapestPeriod(@Nullable ThingActions actions,
@Nullable Instant earliestStart, @Nullable Instant latestEnd, @Nullable Duration duration,
@Nullable QuantityType<Power> power) {
- if (actions instanceof EnergiDataServiceActions) {
+ if (actions instanceof EnergiDataServiceActions serviceActions) {
if (earliestStart == null || latestEnd == null || duration == null || power == null) {
return Map.of();
}
- return ((EnergiDataServiceActions) actions).calculateCheapestPeriod(earliestStart, latestEnd, duration,
- power);
+ return serviceActions.calculateCheapestPeriod(earliestStart, latestEnd, duration, power);
} else {
throw new IllegalArgumentException("Instance is not an EnergiDataServiceActions class.");
}
public static Map<String, Object> calculateCheapestPeriod(@Nullable ThingActions actions,
@Nullable Instant earliestStart, @Nullable Instant latestEnd, @Nullable Duration totalDuration,
@Nullable List<Duration> durationPhases, @Nullable QuantityType<Energy> energyUsedPerPhase) {
- if (actions instanceof EnergiDataServiceActions) {
+ if (actions instanceof EnergiDataServiceActions serviceActions) {
if (earliestStart == null || latestEnd == null || totalDuration == null || durationPhases == null
|| energyUsedPerPhase == null) {
return Map.of();
}
- return ((EnergiDataServiceActions) actions).calculateCheapestPeriod(earliestStart, latestEnd, totalDuration,
- durationPhases, energyUsedPerPhase);
+ return serviceActions.calculateCheapestPeriod(earliestStart, latestEnd, totalDuration, durationPhases,
+ energyUsedPerPhase);
} else {
throw new IllegalArgumentException("Instance is not an EnergiDataServiceActions class.");
}
public static Map<String, Object> calculateCheapestPeriod(@Nullable ThingActions actions,
@Nullable Instant earliestStart, @Nullable Instant latestEnd, @Nullable List<Duration> durationPhases,
@Nullable List<QuantityType<Power>> powerPhases) {
- if (actions instanceof EnergiDataServiceActions) {
+ if (actions instanceof EnergiDataServiceActions serviceActions) {
if (earliestStart == null || latestEnd == null || durationPhases == null || powerPhases == null) {
return Map.of();
}
- return ((EnergiDataServiceActions) actions).calculateCheapestPeriod(earliestStart, latestEnd,
- durationPhases, powerPhases);
+ return serviceActions.calculateCheapestPeriod(earliestStart, latestEnd, durationPhases, powerPhases);
} else {
throw new IllegalArgumentException("Instance is not an EnergiDataServiceActions class.");
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof EnergiDataServiceHandler) {
- this.handler = (EnergiDataServiceHandler) handler;
+ if (handler instanceof EnergiDataServiceHandler serviceHandler) {
+ this.handler = serviceHandler;
}
}
@Override
public final int hashCode() {
- final int result = 1;
- return result;
+ return 1;
}
}
*/
package org.openhab.binding.enigma2.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
// List of all Thing Type UIDs
public static final ThingTypeUID THING_TYPE_DEVICE = new ThingTypeUID(BINDING_ID, "device");
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_DEVICE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_DEVICE);
// List of all Channel ids
public static final String CHANNEL_VOLUME = "volume";
import java.time.LocalDateTime;
import java.util.Collection;
-import java.util.Collections;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
if (command instanceof RefreshType) {
client.refreshVolume();
updateState(channelUID, new PercentType(client.getVolume()));
- } else if (command instanceof PercentType) {
- client.setVolume(((PercentType) command).intValue());
- } else if (command instanceof DecimalType) {
- client.setVolume(((DecimalType) command).intValue());
+ } else if (command instanceof PercentType percentCommand) {
+ client.setVolume(percentCommand.intValue());
+ } else if (command instanceof DecimalType decimalCommand) {
+ client.setVolume(decimalCommand.intValue());
} else {
logger.info("Channel {} only accepts PercentType, DecimalType, RefreshType. Type was {}.", channelUID,
command.getClass());
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(Enigma2Actions.class);
+ return Set.of(Enigma2Actions.class);
}
/**
}
private void whenAllServices() throws IOException {
- when(enigma2HttpClient.get(HOST + Enigma2Client.PATH_ALL_SERVICES))
- .thenReturn("<e2servicelistrecursive>" + "<e2bouquet>" + "<e2servicelist>" + "<e2service>"
- + "<e2servicereference>1</e2servicereference>" + "<e2servicename>Channel 1</e2servicename>"
- + "</e2service>" + "<e2service>" + "<e2servicereference>2</e2servicereference>"
- + "<e2servicename>Channel 2</e2servicename>" + "</e2service>" + "</e2servicelist>"
- + "</e2bouquet>" + "<e2bouquet>" + "<e2servicelist>" + "<e2service>"
- + "<e2servicereference>3</e2servicereference>" + "<e2servicename>Channel 3</e2servicename>"
- + "</e2service>" + "</e2servicelist>" + "</e2bouquet>" + "</e2servicelistrecursive>");
+ when(enigma2HttpClient.get(HOST + Enigma2Client.PATH_ALL_SERVICES)).thenReturn("""
+ <e2servicelistrecursive>\
+ <e2bouquet>\
+ <e2servicelist>\
+ <e2service>\
+ <e2servicereference>1</e2servicereference>\
+ <e2servicename>Channel 1</e2servicename>\
+ </e2service>\
+ <e2service>\
+ <e2servicereference>2</e2servicereference>\
+ <e2servicename>Channel 2</e2servicename>\
+ </e2service>\
+ </e2servicelist>\
+ </e2bouquet>\
+ <e2bouquet>\
+ <e2servicelist>\
+ <e2service>\
+ <e2servicereference>3</e2servicereference>\
+ <e2servicename>Channel 3</e2servicename>\
+ </e2service>\
+ </e2servicelist>\
+ </e2bouquet>\
+ </e2servicelistrecursive>\
+ """);
}
}
if (senderIdOffset == null) {
return;
}
- } else if ((eep instanceof _4BSMessage) && ((_4BSMessage) eep).isTeachInVariation3Supported()) {
+ } else if (eep instanceof _4BSMessage message && message.isTeachInVariation3Supported()) {
// if 4BS teach in variation 3 => send response
logger.debug("Sending 4BS teach in variation 3 response to {}", enoceanId);
senderIdOffset = sendTeachInResponse(msg, enoceanId);
}
private String getStatusRequestEvent() {
- return Boolean.valueOf(getBit(getDB0Value(), 6)).toString();
+ return Boolean.toString(getBit(getDB0Value(), 6));
// return getBit(getDB_0Value(), 6) ? "triggered" : null;
}
byte angle = 0; // for now, no angle configuration supported
boolean doStop = false;
- if (outputCommand instanceof DecimalType) {
- position = ((DecimalType) outputCommand).byteValue();
- } else if (outputCommand instanceof OnOffType) {
- position = (byte) (((OnOffType) outputCommand == OnOffType.ON) ? 0 : 100);
+ if (outputCommand instanceof DecimalType decimalCommand) {
+ position = decimalCommand.byteValue();
+ } else if (outputCommand instanceof OnOffType onOffCommand) {
+ position = (byte) ((onOffCommand == OnOffType.ON) ? 0 : 100);
} else if (outputCommand instanceof StopMoveType) {
position = ZERO;
doStop = true;
- } else if (outputCommand instanceof UpDownType) {
- position = (byte) (((UpDownType) outputCommand == UpDownType.UP) ? 0 : 100);
+ } else if (outputCommand instanceof UpDownType upDownCommand) {
+ position = (byte) ((upDownCommand == UpDownType.UP) ? 0 : 100);
} else {
logger.warn("Unknown command type {}", outputCommand.getClass().getCanonicalName());
return;
case CHANNEL_DIMMER:
byte dimmValue;
- if (outputCommand instanceof DecimalType) {
- dimmValue = ((DecimalType) outputCommand).byteValue();
- } else if (outputCommand instanceof OnOffType) {
- dimmValue = ((OnOffType) outputCommand == OnOffType.ON) ? SWITCH_100_PERCENT : ZERO;
- } else if (outputCommand instanceof IncreaseDecreaseType) {
- dimmValue = ((IncreaseDecreaseType) outputCommand == IncreaseDecreaseType.INCREASE)
- ? SWITCH_100_PERCENT
- : ZERO;
- } else if (outputCommand instanceof UpDownType) {
- dimmValue = ((UpDownType) outputCommand == UpDownType.UP) ? SWITCH_100_PERCENT : ZERO;
+ if (outputCommand instanceof DecimalType decimalCommand) {
+ dimmValue = decimalCommand.byteValue();
+ } else if (outputCommand instanceof OnOffType onOffCommand) {
+ dimmValue = (onOffCommand == OnOffType.ON) ? SWITCH_100_PERCENT : ZERO;
+ } else if (outputCommand instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ dimmValue = (increaseDecreaseCommand == IncreaseDecreaseType.INCREASE) ? SWITCH_100_PERCENT : ZERO;
+ } else if (outputCommand instanceof UpDownType upDownCommand) {
+ dimmValue = (upDownCommand == UpDownType.UP) ? SWITCH_100_PERCENT : ZERO;
} else {
throw new IllegalArgumentException(outputCommand.toFullString() + " is no valid dimming command.");
}
@Override
protected void convertFromCommandImpl(String channelId, String channelTypeId, Command command,
Function<String, State> getCurrentStateFunc, @Nullable Configuration config) {
- if (command instanceof PercentType) {
- PercentType target = (PercentType) command;
- int rawPosition = Math.round(
- (PercentType.HUNDRED.floatValue() - target.floatValue()) * TOP / PercentType.HUNDRED.floatValue());
+ if (command instanceof PercentType percentCommand) {
+ int rawPosition = Math.round((PercentType.HUNDRED.floatValue() - percentCommand.floatValue()) * TOP
+ / PercentType.HUNDRED.floatValue());
int position = Math.min(TOP, Math.max(BOTTOM, rawPosition));
setData((byte) position, ZERO, MOVE, TEACHIN_BIT);
- } else if (command instanceof UpDownType) {
- if ((UpDownType) command == UpDownType.UP) {
+ } else if (command instanceof UpDownType upDownCommand) {
+ if (upDownCommand == UpDownType.UP) {
setData((byte) TOP, ZERO, MOVE, TEACHIN_BIT); // => 0 percent
- } else if ((UpDownType) command == UpDownType.DOWN) {
+ } else if (upDownCommand == UpDownType.DOWN) {
setData((byte) BOTTOM, ZERO, MOVE, TEACHIN_BIT); // => 100 percent
}
- } else if (command instanceof StopMoveType) {
- if ((StopMoveType) command == StopMoveType.STOP) {
+ } else if (command instanceof StopMoveType stopMoveCommand) {
+ if (stopMoveCommand == StopMoveType.STOP) {
setData(ZERO, ZERO, STOP, TEACHIN_BIT);
}
}
shutTime = Math.min(255, config.as(EnOceanChannelRollershutterConfig.class).shutTime);
}
- if (command instanceof PercentType) {
+ if (command instanceof PercentType percentCommand) {
State channelState = getCurrentStateFunc.apply(channelId);
-
- PercentType target = (PercentType) command;
- if (target.intValue() == PercentType.ZERO.intValue()) {
+ if (percentCommand.intValue() == PercentType.ZERO.intValue()) {
setData(ZERO, (byte) shutTime, MOVE_UP, TEACHIN_BIT); // => move completely up
- } else if (target.intValue() == PercentType.HUNDRED.intValue()) {
+ } else if (percentCommand.intValue() == PercentType.HUNDRED.intValue()) {
setData(ZERO, (byte) shutTime, MOVE_DOWN, TEACHIN_BIT); // => move completely down
} else if (channelState != null) {
PercentType current = channelState.as(PercentType.class);
if (current != null) {
- if (current.intValue() != target.intValue()) {
- byte direction = current.intValue() > target.intValue() ? MOVE_UP : MOVE_DOWN;
+ if (current.intValue() != percentCommand.intValue()) {
+ byte direction = current.intValue() > percentCommand.intValue() ? MOVE_UP : MOVE_DOWN;
byte duration = (byte) Math.min(255,
- (Math.abs(current.intValue() - target.intValue()) * shutTime)
+ (Math.abs(current.intValue() - percentCommand.intValue()) * shutTime)
/ PercentType.HUNDRED.intValue());
setData(ZERO, duration, direction, TEACHIN_BIT);
}
}
- } else if (command instanceof UpDownType) {
- if ((UpDownType) command == UpDownType.UP) {
+ } else if (command instanceof UpDownType upDownCommand) {
+ if (upDownCommand == UpDownType.UP) {
setData(ZERO, (byte) shutTime, MOVE_UP, TEACHIN_BIT); // => 0 percent
- } else if ((UpDownType) command == UpDownType.DOWN) {
+ } else if (upDownCommand == UpDownType.DOWN) {
setData(ZERO, (byte) shutTime, MOVE_DOWN, TEACHIN_BIT); // => 100 percent
}
- } else if (command instanceof StopMoveType) {
- if ((StopMoveType) command == StopMoveType.STOP) {
+ } else if (command instanceof StopMoveType stopMoveCommand) {
+ if (stopMoveCommand == StopMoveType.STOP) {
setData(ZERO, (byte) 0xFF, STOP, TEACHIN_BIT);
}
}
protected void setDimmingData(Command command, byte outputChannel, Configuration config) {
byte outputValue;
- if (command instanceof DecimalType) {
- if (((DecimalType) command).equals(DecimalType.ZERO)) {
+ if (command instanceof DecimalType decimalCommand) {
+ if (decimalCommand.equals(DecimalType.ZERO)) {
outputValue = STATUS_SWITCHING_OFF;
} else {
- outputValue = ((DecimalType) command).byteValue();
+ outputValue = decimalCommand.byteValue();
}
} else if ((OnOffType) command == OnOffType.ON) {
outputValue = STATUS_DIMMING_100;
private void setRepeaterMode(Command command) {
if (command == RefreshType.REFRESH) {
senderId = new byte[0]; // make this message invalid as we do not support refresh of repeater status
- } else if (command instanceof StringType) {
- switch (((StringType) command).toString()) {
+ } else if (command instanceof StringType stringCommand) {
+ switch (stringCommand.toString()) {
case EnOceanBindingConstants.REPEATERMODE_LEVEL_1:
setRORG(RORG.MSC).setData((byte) 0x03, (byte) 0x35, (byte) 0x01);
break;
private void setEcoMode(Command command) {
if (command == RefreshType.REFRESH) {
senderId = new byte[0]; // make this message invalid as we do not support refresh of ecomode status
- } else if (command instanceof OnOffType) {
- if (((OnOffType) command) == OnOffType.ON) {
+ } else if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
setRORG(RORG.MSC).setData((byte) 0x03, (byte) 0x36, (byte) 0x01);
} else {
setRORG(RORG.MSC).setData((byte) 0x03, (byte) 0x36, (byte) 0x00);
if (channelId.equalsIgnoreCase(CHANNEL_REPEATERMODE)) {
if (command instanceof RefreshType) {
senderId = new byte[0]; // make this message invalid as we do not support refresh of repeter status
- } else if (command instanceof StringType) {
- switch (((StringType) command).toString()) {
+ } else if (command instanceof StringType stringCommand) {
+ switch (stringCommand.toString()) {
case EnOceanBindingConstants.REPEATERMODE_LEVEL_1:
setRORG(RORG.MSC).setData((byte) 0x00, (byte) 0x46, (byte) 0x08, (byte) 0x01, (byte) 0x01);
break;
if (channelId.equalsIgnoreCase(CHANNEL_REPEATERMODE)) {
if (command instanceof RefreshType) {
senderId = new byte[0]; // make this message invalid as we do not support refresh of repeter status
- } else if (command instanceof StringType) {
- switch (((StringType) command).toString()) {
+ } else if (command instanceof StringType stringCommand) {
+ switch (stringCommand.toString()) {
case EnOceanBindingConstants.REPEATERMODE_LEVEL_1:
setRORG(RORG.MSC).setData((byte) 0x00, (byte) 0x46, (byte) 0x08, (byte) 0x01, (byte) 0x01);
break;
if (command == StopMoveType.STOP) {
setData((byte) (outputChannel + CMD_ACTUATOR_STOP));
}
- } else if (command instanceof PercentType) {
- setData((byte) (((PercentType) command).intValue()), (byte) 0x00, (byte) 0x00,
+ } else if (command instanceof PercentType percentCommand) {
+ setData((byte) (percentCommand.intValue()), (byte) 0x00, (byte) 0x00,
(byte) (outputChannel + CMD_ACTUATOR_SET_POSITION));
}
}
if (channelId.equals(CHANNEL_REPEATERMODE)) {
if (command == RefreshType.REFRESH) {
senderId = new byte[0]; // make this message invalid as we do not support refresh of repeter status
- } else if (command instanceof StringType) {
- switch (((StringType) command).toString()) {
+ } else if (command instanceof StringType stringCommand) {
+ switch (stringCommand.toString()) {
case EnOceanBindingConstants.REPEATERMODE_LEVEL_1:
setRORG(RORG.MSC).setData((byte) 0x00, (byte) 0x46, (byte) 0x08, (byte) 0x01, (byte) 0x01);
break;
} else {
switch (channelId) {
case CHANNEL_VENTILATIONOPERATIONMODE:
- if (command instanceof StringType) {
- byte value = (byte) (Helper.tryParseInt(((StringType) command).toString(), 15) & 0x0f);
+ if (command instanceof StringType stringCommand) {
+ byte value = (byte) (Helper.tryParseInt(stringCommand.toString(), 15) & 0x0f);
setData((byte) (MT_CONTROL + value), CONTROL_NOACTION, TMOC_NOACTION, THRESHOLD_NOACTION,
THRESHOLD_NOACTION, CONTROL_NOACTION);
}
break;
case CHANNEL_TIMEROPERATIONMODE:
- if (command instanceof OnOffType) {
- byte value = (OnOffType) command == OnOffType.ON ? TMOC_ACTIVATE : TMOC_NOACTION;
+ if (command instanceof OnOffType onOffCommand) {
+ byte value = onOffCommand == OnOffType.ON ? TMOC_ACTIVATE : TMOC_NOACTION;
setData((byte) (MT_CONTROL + DOMC_NOACTION), CONTROL_NOACTION, value, THRESHOLD_NOACTION,
THRESHOLD_NOACTION, CONTROL_NOACTION);
}
}
public static @Nullable EEP buildEEPFromTeachInERP1(ERP1Message msg) {
- if (!msg.getIsTeachIn() && !(msg.getRORG() == RORG.RPS)) {
+ if (!msg.getIsTeachIn() && msg.getRORG() != RORG.RPS) {
return null;
}
@Override
protected void convertFromCommandImpl(String channelId, String channelTypeId, Command command,
Function<String, State> getCurrentStateFunc, @Nullable Configuration config) {
- if (command instanceof StringType) {
- String s = ((StringType) command).toString();
+ if (command instanceof StringType stringCommand) {
+ String s = stringCommand.toString();
if (s.equals(CommonTriggerEvents.DIR1_RELEASED) || s.equals(CommonTriggerEvents.DIR2_RELEASED)) {
setStatus(_RPSMessage.T21_FLAG);
@Override
protected void convertFromCommandImpl(String channelId, String channelTypeId, Command command,
Function<String, State> getCurrentStateFunc, @Nullable Configuration config) {
- if (command instanceof StringType) {
- String s = ((StringType) command).toString();
+ if (command instanceof StringType stringCommand) {
+ String s = stringCommand.toString();
if (s.equals(CommonTriggerEvents.DIR1_RELEASED) || s.equals(CommonTriggerEvents.DIR2_RELEASED)) {
setStatus(_RPSMessage.T21_FLAG);
return null;
}
ThingHandler handler = bridge.getHandler();
- if (handler instanceof EnOceanBridgeHandler) {
- this.gateway = (EnOceanBridgeHandler) handler;
+ if (handler instanceof EnOceanBridgeHandler bridgeHandler) {
+ this.gateway = bridgeHandler;
} else {
return null;
}
}
}
});
- } else if (command instanceof StringType) {
- sendMessage(ESP3PacketFactory.CO_WR_REPEATER((StringType) command),
+ } else if (command instanceof StringType stringCommand) {
+ sendMessage(ESP3PacketFactory.CO_WR_REPEATER(stringCommand),
new ResponseListenerIgnoringTimeouts<BaseResponse>() {
@Override
public void responseReceived(BaseResponse response) {
if (response.isOK()) {
- updateState(channelUID, (StringType) command);
+ updateState(channelUID, stringCommand);
}
}
});
break;
case CHANNEL_SETBASEID:
- if (command instanceof StringType) {
+ if (command instanceof StringType stringCommand) {
try {
- byte[] id = HexUtils.hexToBytes(((StringType) command).toFullString());
+ byte[] id = HexUtils.hexToBytes(stringCommand.toFullString());
sendMessage(ESP3PacketFactory.CO_WR_IDBASE(id),
new ResponseListenerIgnoringTimeouts<BaseResponse>() {
}
private @Nullable StringType convertToPressedCommand(Command command, SwitchMode switchMode) {
- if (command instanceof StringType) {
- return (StringType) command;
+ if (command instanceof StringType stringCommand) {
+ return stringCommand;
} else if (command instanceof OnOffType) {
switch (switchMode) {
case RockerSwitch:
return ZERO;
}
- private byte calcCheckSum(byte data[], int offset, int length) {
+ private byte calcCheckSum(byte[] data, int offset, int length) {
int checkSum = 0;
for (int i = 0; i < length; i++) {
checkSum += (data[offset + i] & 0xff);
}
}
- public static boolean validateCheckSum(byte data[], int length, byte checkSum) {
+ public static boolean validateCheckSum(byte[] data, int length, byte checkSum) {
int sum = 0;
for (int i = 0; i < length; i++) {
sum += (data[i] & 0xff);
this.basePacket = basePacket;
}
- private byte calcCRC8(byte data[], int offset, int length) {
+ private byte calcCRC8(byte[] data, int offset, int length) {
byte output = 0;
for (int i = offset; i < offset + length; i++) {
int index = (output ^ data[i]) & 0xff;
}
}
- public static boolean checkCRC8(byte data[], int length, byte crc8) {
+ public static boolean checkCRC8(byte[] data, int length, byte crc8) {
byte output = 0;
for (int i = 0; i < length; i++) {
int index = (output ^ data[i]) & 0xff;
import static org.openhab.binding.enphase.internal.EnphaseBindingConstants.*;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
private @Nullable EnvoyBridgeHandler envoyHandler;
public EnphaseDevicesDiscoveryService() {
- super(Collections.singleton(THING_TYPE_ENPHASE_INVERTER), TIMEOUT_SECONDS, false);
+ super(Set.of(THING_TYPE_ENPHASE_INVERTER), TIMEOUT_SECONDS, false);
}
@Override
public void setThingHandler(final @Nullable ThingHandler handler) {
- if (handler instanceof EnvoyBridgeHandler) {
- envoyHandler = (EnvoyBridgeHandler) handler;
+ if (handler instanceof EnvoyBridgeHandler bridgeHandler) {
+ envoyHandler = bridgeHandler;
}
}
import static org.openhab.binding.enphase.internal.EnphaseBindingConstants.*;
import java.net.Inet4Address;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(EnphaseBindingConstants.THING_TYPE_ENPHASE_ENVOY);
+ return Set.of(EnphaseBindingConstants.THING_TYPE_ENPHASE_ENVOY);
}
@Override
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Collection;
-import java.util.Collections;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(EnphaseDevicesDiscoveryService.class);
+ return Set.of(EnphaseDevicesDiscoveryService.class);
}
@Override
@Override
public void childHandlerInitialized(final ThingHandler childHandler, final Thing childThing) {
- if (childHandler instanceof EnphaseInverterHandler) {
- updateInverter(getInvertersData(false), (EnphaseInverterHandler) childHandler);
+ if (childHandler instanceof EnphaseInverterHandler handler) {
+ updateInverter(getInvertersData(false), handler);
}
- if (childHandler instanceof EnphaseDeviceHandler) {
+ if (childHandler instanceof EnphaseDeviceHandler handler) {
final Map<String, @Nullable DeviceDTO> devices = getDevices(false);
if (devices != null) {
- ((EnphaseDeviceHandler) childHandler)
- .refreshDeviceState(devices.get(((EnphaseDeviceHandler) childHandler).getSerialNumber()));
+ handler.refreshDeviceState(devices.get(handler.getSerialNumber()));
}
}
}
import static org.openhab.binding.enturno.internal.EnturNoBindingConstants.LINESTOP;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.enturno", service = ThingHandlerFactory.class)
public class EnturNoHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(LINESTOP);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(LINESTOP);
private final HttpClient httpClient;
@NonNullByDefault
public enum Switch {
ON,
- OFF;
+ OFF
}
*/
package org.openhab.binding.etherrain.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
// List of all Thing Type UIDs
public static final ThingTypeUID ETHERRAIN_THING = new ThingTypeUID(BINDING_ID, ETHERRAIN);
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(ETHERRAIN_THING);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(ETHERRAIN_THING);
// List of internal default values
*/
package org.openhab.binding.etherrain.internal.config;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
public static final ThingTypeUID ETHERRAIN_THING_TYPE = new ThingTypeUID(BINDING_ID, "etherrain");
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(ETHERRAIN_THING_TYPE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(ETHERRAIN_THING_TYPE);
/**
* Hostname of the EtherRain API.
updateState(channel, new QuantityType<>(targetSoC, Units.PERCENT));
String targetTime = loadpoint.getTargetTime();
- if (targetTime == null || targetTime.equals("0001-01-01T00:00:00Z")) {
+ if (targetTime == null || "0001-01-01T00:00:00Z".equals(targetTime)) {
channel = new ChannelUID(uid, loadpointName, CHANNEL_LOADPOINT_TARGET_TIME_ENABLED);
updateState(channel, OnOffType.OFF);
targetTimeEnabled = false;
for (Thing handler : getThing().getThings()) {
ThingHandler thingHandler = handler.getHandler();
- if (thingHandler instanceof EvohomeTemperatureControlSystemHandler) {
- EvohomeTemperatureControlSystemHandler tcsHandler = (EvohomeTemperatureControlSystemHandler) thingHandler;
+ if (thingHandler instanceof EvohomeTemperatureControlSystemHandler tcsHandler) {
tcsHandler.update(tcsIdToGatewayMap.get(tcsHandler.getId()), idToTcsMap.get(tcsHandler.getId()));
idToTcsThingsStatusMap.put(tcsHandler.getId(), tcsHandler.getThing().getStatus());
}
- if (thingHandler instanceof EvohomeHeatingZoneHandler) {
- EvohomeHeatingZoneHandler zoneHandler = (EvohomeHeatingZoneHandler) thingHandler;
+ if (thingHandler instanceof EvohomeHeatingZoneHandler zoneHandler) {
zoneHandler.update(idToTcsThingsStatusMap.get(zoneIdToTcsIdMap.get(zoneHandler.getId())),
idToZoneMap.get(zoneHandler.getId()));
}
if (bridge != null) {
String channelId = channelUID.getId();
if (EvohomeBindingConstants.ZONE_SET_POINT_CHANNEL.equals(channelId)) {
- if (command instanceof QuantityType) {
- QuantityType<?> state = ((QuantityType<?>) command).toUnit(SIUnits.CELSIUS);
+ if (command instanceof QuantityType quantityCommand) {
+ QuantityType<?> state = quantityCommand.toUnit(SIUnits.CELSIUS);
double newTempInCelsius = state.doubleValue();
if (newTempInCelsius == CANCEL_SET_POINT_OVERRIDE) {
import static org.openhab.binding.exec.internal.ExecBindingConstants.THING_COMMAND;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@NonNullByDefault
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.exec")
public class ExecHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_COMMAND);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_COMMAND);
private final Logger logger = LoggerFactory.getLogger(ExecHandlerFactory.class);
private final ExecWhitelistWatchService execWhitelistWatchService;
*/
package org.openhab.binding.feican.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
// List of all Thing Type UIDs
public static final ThingTypeUID THING_TYPE_BULB = new ThingTypeUID(BINDING_ID, "bulb");
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_BULB);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_BULB);
// List of all Channel ids
public static final String CHANNEL_COLOR = "color";
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
try {
- if (command instanceof OnOffType) {
- handleOnOff((OnOffType) command);
- } else if (command instanceof HSBType) {
- handleColor(channelUID, (HSBType) command);
- } else if (command instanceof PercentType) {
- handlePercentage(channelUID, (PercentType) command);
- } else if (command instanceof StringType) {
- handleString(channelUID, (StringType) command);
+ if (command instanceof OnOffType onOffCommand) {
+ handleOnOff(onOffCommand);
+ } else if (command instanceof HSBType hsbCommand) {
+ handleColor(channelUID, hsbCommand);
+ } else if (command instanceof PercentType percentCommand) {
+ handlePercentage(channelUID, percentCommand);
+ } else if (command instanceof StringType stringCommand) {
+ handleString(channelUID, stringCommand);
}
} catch (IOException e) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, e.getMessage());
protected @Nullable ThingHandler createHandler(Thing thing) {
ThingTypeUID thingTypeUID = thing.getThingTypeUID();
- if (THING_TYPE_GATEWAY.equals(thingTypeUID) && thing instanceof Bridge) {
- return new FineOffsetGatewayHandler((Bridge) thing, gatewayDiscoveryService, channelTypeRegistry,
+ if (THING_TYPE_GATEWAY.equals(thingTypeUID) && thing instanceof Bridge bridge) {
+ return new FineOffsetGatewayHandler(bridge, gatewayDiscoveryService, channelTypeRegistry,
translationProvider, localeProvider, timeZoneProvider);
}
if (THING_TYPE_SENSOR.equals(thingTypeUID)) {
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Activate
public FineOffsetGatewayDiscoveryService(@Reference TranslationProvider translationProvider,
@Reference LocaleProvider localeProvider) throws IllegalArgumentException {
- super(Collections.singleton(THING_TYPE_GATEWAY), DISCOVERY_TIME, true);
+ super(Set.of(THING_TYPE_GATEWAY), DISCOVERY_TIME, true);
this.translationProvider = translationProvider;
this.localeProvider = localeProvider;
this.bundle = FrameworkUtil.getBundle(FineOffsetGatewayDiscoveryService.class);
}
}
+ @Override
public int extractMeasuredValues(byte[] data, int offset, @Nullable Integer channel, ConversionContext context,
@Nullable ParserCustomizationType customizationType, List<MeasuredValue> result) {
MeasureType measureType = getMeasureType(customizationType);
return res;
}
- abstract protected void write(OutputStream stream) throws IOException;
+ protected abstract void write(OutputStream stream) throws IOException;
}
class CmdGetInfo extends CommandPacket {
}
}
- abstract protected void parseInternal(InputStream stream) throws IOException;
+ protected abstract void parseInternal(InputStream stream) throws IOException;
}
class EvtAdvertisementPacket extends EventPacket {
sb.append(String.format("%02x", uuidBytes[i]));
}
uuid = sb.toString();
- if (uuid.equals("00000000000000000000000000000000")) {
+ if ("00000000000000000000000000000000".equals(uuid)) {
uuid = null;
}
color = StreamUtils.getString(stream, 16);
public static final ThingTypeUID BRIDGE_THING_TYPE = new ThingTypeUID(BINDING_ID, "flicd-bridge");
public static final ThingTypeUID FLICBUTTON_THING_TYPE = new ThingTypeUID(BINDING_ID, "button");
- public static final Set<ThingTypeUID> BRIDGE_THING_TYPES_UIDS = Collections.singleton(BRIDGE_THING_TYPE);
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(FLICBUTTON_THING_TYPE);
+ public static final Set<ThingTypeUID> BRIDGE_THING_TYPES_UIDS = Set.of(BRIDGE_THING_TYPE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(FLICBUTTON_THING_TYPE);
// List of all configuration options
public static final String CONFIG_HOST_NAME = "hostname";
package org.openhab.binding.flicbutton.internal.handler;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
*/
@NonNullByDefault
public abstract class ChildThingHandler<BridgeHandlerType extends BridgeHandler> extends BaseThingHandler {
- private static final Collection<ThingStatus> DEFAULT_TOLERATED_BRIDGE_STATUSES = Collections
- .singleton(ThingStatus.ONLINE);
+ private static final Collection<ThingStatus> DEFAULT_TOLERATED_BRIDGE_STATUSES = Set.of(ThingStatus.ONLINE);
protected boolean bridgeValid = false;
protected @Nullable BridgeHandlerType bridgeHandler;
package org.openhab.binding.fmiweather.internal.client;
import java.util.AbstractMap;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
@Override
public List<Map.Entry<String, String>> toRequestParameters() {
- return Collections.singletonList(new AbstractMap.SimpleImmutableEntry<>("fmisid", fmisid));
+ return List.of(new AbstractMap.SimpleImmutableEntry<>("fmisid", fmisid));
}
}
import java.math.BigDecimal;
import java.util.AbstractMap;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
@Override
public List<Map.Entry<String, String>> toRequestParameters() {
- return Collections.singletonList(new AbstractMap.SimpleImmutableEntry<>("latlon", latlon));
+ return List.of(new AbstractMap.SimpleImmutableEntry<>("latlon", latlon));
}
}
}
}
- public static final List<Object[]> parametersForFloorToEvenMinutes() {
+ public static List<Object[]> parametersForFloorToEvenMinutes() {
return Arrays.asList(new Object[][] { //
{ 1626605128L /* 2021-07-18 10:45:28 */, 1, 1626605100 /* 10:45 */ }, //
{ 1626605128L /* 2021-07-18 10:45:28 */, 5, 1626605100 /* 10:45 */ }, //
assertEquals(expected, floorToEvenMinutes(epochSeconds, roundMinutes));
}
- public static final List<Object[]> parametersForCeilToEvenMinutes() {
+ public static List<Object[]> parametersForCeilToEvenMinutes() {
return Arrays.asList(new Object[][] { //
{ 1626605128L /* 2021-07-18 10:45:28 */, 1, 1626605160 /* 10:46 */ }, //
{ 1626605128L /* 2021-07-18 10:45:28 */, 5, 1626605400 /* 10:50 */ }, //
assertEquals(expected, ceilToEvenMinutes(epochSeconds, roundMinutes));
}
- public static final List<Object[]> parametersForLastValidIndex() {
+ public static List<Object[]> parametersForLastValidIndex() {
return Arrays.asList(new Object[][] { //
{ "no nulls", 1, new BigDecimal[] { bd(1), bd(2) } }, //
{ "one null in beginning", 1, new BigDecimal[] { null, bd(2) } }, //
@Test
public void testObservationRequestToUrl() {
ObservationRequest request = new ObservationRequest(new FMISID("101023"), 1552215664L, 1552215665L, 61);
- assertThat(request.toUrl(), is(
- "https://opendata.fmi.fi/wfs?service=WFS&version=2.0.0&request=getFeature&storedquery_id=fmi::observations::weather::multipointcoverage"
- + "&starttime=2019-03-10T11:01:04Z&endtime=2019-03-10T11:01:05Z×tep=61&fmisid=101023"
- + "¶meters=t2m,rh,wd_10min,ws_10min,wg_10min,p_sea,r_1h,snow_aws,vis,n_man,wawa"));
+ assertThat(request.toUrl(),
+ is("""
+ https://opendata.fmi.fi/wfs?service=WFS&version=2.0.0&request=getFeature&storedquery_id=fmi::observations::weather::multipointcoverage\
+ &starttime=2019-03-10T11:01:04Z&endtime=2019-03-10T11:01:05Z×tep=61&fmisid=101023\
+ ¶meters=t2m,rh,wd_10min,ws_10min,wg_10min,p_sea,r_1h,snow_aws,vis,n_man,wawa\
+ """));
}
@Test
public void testForecastRequestToUrl() {
ForecastRequest request = new ForecastRequest(new LatLon(new BigDecimal("9"), new BigDecimal("8")), 1552215664L,
1552215665L, 61);
- assertThat(request.toUrl(), is(
- "https://opendata.fmi.fi/wfs?service=WFS&version=2.0.0&request=getFeature&storedquery_id=fmi::forecast::harmonie::surface::point::multipointcoverage"
- + "&starttime=2019-03-10T11:01:04Z&endtime=2019-03-10T11:01:05Z×tep=61&latlon=9,8"
- + "¶meters=Temperature,Humidity,WindDirection,WindSpeedMS,WindGust,Pressure,Precipitation1h,TotalCloudCover,WeatherSymbol3"));
+ assertThat(request.toUrl(),
+ is("""
+ https://opendata.fmi.fi/wfs?service=WFS&version=2.0.0&request=getFeature&storedquery_id=fmi::forecast::harmonie::surface::point::multipointcoverage\
+ &starttime=2019-03-10T11:01:04Z&endtime=2019-03-10T11:01:05Z×tep=61&latlon=9,8\
+ ¶meters=Temperature,Humidity,WindDirection,WindSpeedMS,WindGust,Pressure,Precipitation1h,TotalCloudCover,WeatherSymbol3\
+ """));
}
@Test
}
};
ObservationRequest request = new ObservationRequest(location, 1552215664L, 1552215665L, 61);
- assertThat(request.toUrl(), is(
- "https://opendata.fmi.fi/wfs?service=WFS&version=2.0.0&request=getFeature&storedquery_id=fmi::observations::weather::multipointcoverage"
- + "&starttime=2019-03-10T11:01:04Z&endtime=2019-03-10T11:01:05Z×tep=61&lat=MYLAT&lon=FOO&special=x,y,z"
- + "¶meters=t2m,rh,wd_10min,ws_10min,wg_10min,p_sea,r_1h,snow_aws,vis,n_man,wawa"));
+ assertThat(request.toUrl(),
+ is("""
+ https://opendata.fmi.fi/wfs?service=WFS&version=2.0.0&request=getFeature&storedquery_id=fmi::observations::weather::multipointcoverage\
+ &starttime=2019-03-10T11:01:04Z&endtime=2019-03-10T11:01:05Z×tep=61&lat=MYLAT&lon=FOO&special=x,y,z\
+ ¶meters=t2m,rh,wd_10min,ws_10min,wg_10min,p_sea,r_1h,snow_aws,vis,n_man,wawa\
+ """));
}
}
nameNodesList = doc.getElementsByTagName("IsTruncated");
if (nameNodesList.getLength() > 0) {
- if (nameNodesList.item(0).getFirstChild().getTextContent().equals("true")) {
+ if ("true".equals(nameNodesList.item(0).getFirstChild().getTextContent())) {
nameNodesList = doc.getElementsByTagName("NextContinuationToken");
if (nameNodesList.getLength() > 0) {
String continueToken = nameNodesList.item(0).getFirstChild().getTextContent();
protected static String getCanonicalRequest(URL endpoint, String httpMethod, String queryParameters,
String canonicalizedHeaderNames, String canonicalizedHeaders, String bodyHash) {
- String canonicalRequest = httpMethod + "\n" + getCanonicalizedResourcePath(endpoint) + "\n" + queryParameters
- + "\n" + canonicalizedHeaders + "\n" + canonicalizedHeaderNames + "\n" + bodyHash;
- return canonicalRequest;
+ return httpMethod + "\n" + getCanonicalizedResourcePath(endpoint) + "\n" + queryParameters + "\n"
+ + canonicalizedHeaders + "\n" + canonicalizedHeaderNames + "\n" + bodyHash;
}
protected static String getCanonicalizedResourcePath(URL endpoint) {
protected static String getStringToSign(String scheme, String algorithm, String dateTime, String scope,
String canonicalRequest) {
- String stringToSign = scheme + "-" + algorithm + "\n" + dateTime + "\n" + scope + "\n"
+ return scheme + "-" + algorithm + "\n" + dateTime + "\n" + scope + "\n"
+ BinaryUtils.toHex(hash(canonicalRequest));
- return stringToSign;
}
public static byte[] hash(String text) {
String credentialsAuthorizationHeader = "Credential=" + awsAccessKey + "/" + scope;
String signedHeadersAuthorizationHeader = "SignedHeaders=" + canonicalizedHeaderNames;
String signatureAuthorizationHeader = "Signature=" + BinaryUtils.toHex(signature);
- String authorizationHeader = SCHEME + "-" + ALGORITHM + " " + credentialsAuthorizationHeader + ", "
- + signedHeadersAuthorizationHeader + ", " + signatureAuthorizationHeader;
- return authorizationHeader;
+ return SCHEME + "-" + ALGORITHM + " " + credentialsAuthorizationHeader + ", " + signedHeadersAuthorizationHeader
+ + ", " + signatureAuthorizationHeader;
}
}
Instant dateNow = Instant.now();
for (FTPFile file : ftpClient.listFiles(dirPath)) {
String currentFileName = file.getName();
- if (currentFileName.equals(".") || currentFileName.equals("..")) {
+ if (".".equals(currentFileName) || "..".equals(currentFileName)) {
continue;
}
String filePath = dirPath + "/" + currentFileName;
*/
package org.openhab.binding.folding.internal.discovery;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
+import java.util.Set;
import org.openhab.binding.folding.internal.FoldingBindingConstants;
import org.openhab.core.config.discovery.AbstractDiscoveryService;
public class FoldingSlotDiscoveryService extends AbstractDiscoveryService {
public FoldingSlotDiscoveryService() {
- super(Collections.singleton(FoldingBindingConstants.THING_TYPE_SLOT), 10, true);
+ super(Set.of(FoldingBindingConstants.THING_TYPE_SLOT), 10, true);
FoldingDiscoveryProxy.getInstance().setService(this);
}
try {
if (command instanceof RefreshType) {
refresh();
- } else if (channelUID.getId().equals("run")) {
+ } else if ("run".equals(channelUID.getId())) {
if (command == OnOffType.ON) {
sendCommand("unpause");
} else if (command == OnOffType.OFF) {
}
refresh();
delayedRefresh();
- } else if (channelUID.getId().equals("finish")) {
+ } else if ("finish".equals(channelUID.getId())) {
if (command == OnOffType.ON) {
sendCommand("finish");
} else if (command == OnOffType.OFF) {
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
try {
- if (channelUID.getId().equals("run")) {
+ if ("run".equals(channelUID.getId())) {
if (command == OnOffType.ON) {
getBridgeHandler().sendCommand("unpause " + myId());
} else if (command == OnOffType.OFF) {
getBridgeHandler().sendCommand("pause " + myId());
}
- } else if (channelUID.getId().equals("finish")) {
+ } else if ("finish".equals(channelUID.getId())) {
if (command == OnOffType.ON) {
getBridgeHandler().sendCommand("finish " + myId());
} else if (command == OnOffType.OFF) {
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPE_UIDS = Collections
.unmodifiableSet(Stream.of(BRIDGE_TYPE_FOOBOTACCOUNT, THING_TYPE_FOOBOT).collect(Collectors.toSet()));
- public static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPE_UIDS = Collections.singleton(THING_TYPE_FOOBOT);
+ public static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPE_UIDS = Set.of(THING_TYPE_FOOBOT);
private final FoobotApiConnector connector = new FoobotApiConnector();
@Override
public void setThingHandler(@Nullable final ThingHandler handler) {
- if (handler instanceof FoobotAccountHandler) {
- this.handler = (FoobotAccountHandler) handler;
+ if (handler instanceof FoobotAccountHandler accountHandler) {
+ this.handler = accountHandler;
}
}
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(FoobotAccountDiscoveryService.class);
+ return Set.of(FoobotAccountDiscoveryService.class);
}
public List<FoobotDevice> getDeviceList() throws FoobotApiException {
@Override
public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
- if (childHandler instanceof FoobotDeviceHandler) {
- final String uuid = ((FoobotDeviceHandler) childHandler).getUuid();
+ if (childHandler instanceof FoobotDeviceHandler handler) {
+ final String uuid = handler.getUuid();
try {
getDeviceList().stream().filter(d -> d.getUuid().equals(uuid)).findAny()
- .ifPresent(fd -> ((FoobotDeviceHandler) childHandler).handleUpdateProperties(fd));
+ .ifPresent(fd -> handler.handleUpdateProperties(fd));
} catch (FoobotApiException e) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
}
public static final ThingTypeUID FREEBOX_THING_TYPE_AIRPLAY = new ThingTypeUID(BINDING_ID, "airplay");
// All supported Bridge types
- public static final Set<ThingTypeUID> SUPPORTED_BRIDGE_TYPES_UIDS = Collections
- .singleton(FREEBOX_BRIDGE_TYPE_SERVER);
+ public static final Set<ThingTypeUID> SUPPORTED_BRIDGE_TYPES_UIDS = Set.of(FREEBOX_BRIDGE_TYPE_SERVER);
// All supported Thing types
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
// Parse the full response in case of success
T fullResponse = gson.fromJson(jsonResponse, responseClass);
fullResponse.evaluate();
- F result = fullResponse.getResult();
- return result;
+ return fullResponse.getResult();
}
private String encodeUrl(String url) throws FreeboxException {
*/
public class FreeboxAirMediaReceiverRequest {
- private static enum MediaAction {
+ private enum MediaAction {
START("start"),
STOP("stop");
}
}
- private static enum MediaType {
+ private enum MediaType {
VIDEO("video"),
PHOTO("photo");
*/
public class FreeboxAuthorizationStatus {
- private static enum AuthorizationStatus {
+ private enum AuthorizationStatus {
UNKNOWN("unknown"),
PENDING("pending"),
TIMEOUT("timeout"),
FreeboxHandler handler = null;
if (thing != null) {
thingHandler = thing.getHandler();
- if (thingHandler instanceof FreeboxHandler) {
- handler = (FreeboxHandler) thingHandler;
+ if (thingHandler instanceof FreeboxHandler freeboxHandler) {
+ handler = freeboxHandler;
}
}
if (thing == null) {
@Override
public void setThingHandler(ThingHandler handler) {
- if (handler instanceof FreeboxHandler) {
- bridgeHandler = (FreeboxHandler) handler;
+ if (handler instanceof FreeboxHandler freeboxHandler) {
+ bridgeHandler = freeboxHandler;
}
}
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(FreeboxDiscoveryService.class);
+ return Set.of(FreeboxDiscoveryService.class);
}
@Override
continue;
}
ThingHandler handler = thing.getHandler();
- if (handler instanceof FreeboxThingHandler) {
- ((FreeboxThingHandler) handler).updateNetInfo(hosts);
+ if (handler instanceof FreeboxThingHandler thingHandler) {
+ thingHandler.updateNetInfo(hosts);
}
}
continue;
}
ThingHandler handler = thing.getHandler();
- if (handler instanceof FreeboxThingHandler) {
- ((FreeboxThingHandler) handler).updateAirPlayDevice(devices);
+ if (handler instanceof FreeboxThingHandler thingHandler) {
+ thingHandler.updateAirPlayDevice(devices);
}
}
} else if (command instanceof OnOffType) {
updateChannelDecimalState(LCDBRIGHTNESS,
apiManager.setLcdBrightness((command == OnOffType.ON) ? 100 : 0));
- } else if (command instanceof DecimalType) {
- updateChannelDecimalState(LCDBRIGHTNESS,
- apiManager.setLcdBrightness(((DecimalType) command).intValue()));
- } else if (command instanceof PercentType) {
- updateChannelDecimalState(LCDBRIGHTNESS,
- apiManager.setLcdBrightness(((PercentType) command).intValue()));
+ } else if (command instanceof DecimalType decimalCommand) {
+ updateChannelDecimalState(LCDBRIGHTNESS, apiManager.setLcdBrightness(decimalCommand.intValue()));
+ } else if (command instanceof PercentType percentCommand) {
+ updateChannelDecimalState(LCDBRIGHTNESS, apiManager.setLcdBrightness(percentCommand.intValue()));
} else {
logger.debug("Thing {}: invalid command {} from channel {}", getThing().getUID(), command,
channelUID.getId());
}
private void setOrientation(ChannelUID channelUID, Command command) {
- if (command instanceof DecimalType) {
+ if (command instanceof DecimalType orientation) {
try {
- FreeboxLcdConfig config = apiManager.setLcdOrientation(((DecimalType) command).intValue());
+ FreeboxLcdConfig config = apiManager.setLcdOrientation(orientation.intValue());
updateChannelDecimalState(LCDORIENTATION, config.getOrientation());
updateChannelSwitchState(LCDFORCED, config.isOrientationForced());
} catch (FreeboxException e) {
*/
@NonNullByDefault
public class Response<ResultType> {
- public static enum ErrorCode {
+ public enum ErrorCode {
AUTH_REQUIRED,
BAD_LOGIN,
TOO_SHORT,
ERR_030,
ERR_031,
NONE,
- UNKNOWN;
+ UNKNOWN
}
private ErrorCode errorCode = ErrorCode.NONE;
}
}
- private static enum State {
+ private enum State {
ASSOCIATED,
AUTHENTICATED,
- UNKNOWN;
+ UNKNOWN
}
public static record Station(String id, MACAddress mac, String bssid, @Nullable String hostname, LanHost host,
protected static record ApStatus(ApState state, int channelWidth, int primaryChannel, int secondaryChannel,
int dfsCacRemainingTime, boolean dfsDisabled) {
- private static enum ApState {
+ private enum ApState {
SCANNING, // Ap is probing wifi channels
NO_PARAM, // Ap is not configured
BAD_PARAM, // Ap has an invalid configuration
DFS, // Ap is performing dynamic frequency selection
ACTIVE, // Ap is active
FAILED, // Ap has failed to start
- UNKNOWN;
+ UNKNOWN
}
}
protected static record Afp(boolean enabled, boolean guestAllow, ServerType serverType, @Nullable String loginName,
@Nullable String loginPassword) {
- private static enum ServerType {
+ private enum ServerType {
POWERBOOK,
POWERMAC,
MACMINI,
APPLETV,
AIRPORT,
XSERVE,
- UNKNOWN;
+ UNKNOWN
}
}
private static class Calls extends Response<Call> {
}
- public static enum Type {
+ public enum Type {
ACCEPTED,
MISSED,
OUTGOING,
INCOMING,
- UNKNOWN;
+ UNKNOWN
}
public static record Call(Type type, //
protected static class StatusResponse extends Response<Status> {
}
- private static enum State {
+ private enum State {
GOING_UP,
UP,
GOING_DOWN,
DOWN,
- UNKNOWN;
+ UNKNOWN
}
- private static enum Type {
+ private enum Type {
ETHERNET,
RFC2684,
PPPOATM,
- UNKNOWN;
+ UNKNOWN
}
- private static enum Media {
+ private enum Media {
FTTH,
ETHERNET,
XDSL,
BACKUP_4G,
- UNKNOWN;
+ UNKNOWN
}
public static record Status(State state, Type type, Media media, @Nullable List<Integer> ipv4PortRange,
private @Nullable Session session;
private String appToken = "";
- public static enum BoxModel {
+ public enum BoxModel {
FBXGW_R1_FULL, // Freebox Server (v6) revision 1
FBXGW_R2_FULL, // Freebox Server (v6) revision 2
FBXGW_R1_MINI, // Freebox Mini revision 1
FBXGW_R1_ONE, // Freebox One revision 1
FBXGW_R2_ONE, // Freebox One revision 2
FBXGW7_R1_FULL, // Freebox v7 revision 1
- UNKNOWN;
+ UNKNOWN
}
public static record ApiVersion(String apiBaseUrl, @Nullable String apiDomain, String apiVersion, BoxModel boxModel,
manager = addManager(clazz, managerConstructor.newInstance(this));
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
- if (cause instanceof PermissionException) {
- throw (PermissionException) cause;
+ if (cause instanceof PermissionException exception) {
+ throw exception;
}
throw new FreeboxException(e, "Unable to call RestManager constructor for %s", clazz.getName());
} catch (ReflectiveOperationException e) {
private static class Networks extends Response<Network> {
}
- public static enum NetRole {
+ public enum NetRole {
STA, // Freeplug station
PCO, // Freeplug proxy coordinator
CCO, // Central Coordinator
- UNKNOWN;
+ UNKNOWN
}
private enum Status {
private static class HomeNodesResponse extends Response<HomeNode> {
}
- private static enum AccessType {
+ private enum AccessType {
R,
W,
RW,
- UNKNOWN;
+ UNKNOWN
}
- private static enum DisplayType {
+ private enum DisplayType {
TEXT,
ICON,
BUTTON,
TOGGLE,
COLOR,
WARNING,
- UNKNOWN;
+ UNKNOWN
}
private static record EndpointValue<T> (T value) {
private static record EndpointUi(AccessType access, DisplayType display, String iconUrl, @Nullable String unit) {
}
- private static enum ValueType {
+ private enum ValueType {
BOOL,
INT,
FLOAT,
VOID,
STRING,
- UNKNOWN;
+ UNKNOWN
}
public static record EndpointState(@Nullable String value, ValueType valueType, long refresh) {
}
}
- public static enum EpType {
+ public enum EpType {
SIGNAL,
SLOT,
UNKNOWN;
public static record Endpoint(int id, String name, String label, EpType epType, Visibility visibility, int refresh,
ValueType valueType, EndpointUi ui, @Nullable String category, Object value, List<LogEntry> history) {
- private static enum Visibility {
+ private enum Visibility {
INTERNAL,
NORMAL,
DASHBOARD,
- UNKNOWN;
+ UNKNOWN
}
}
- private static enum Status {
+ private enum Status {
UNREACHABLE,
DISABLED,
ACTIVE,
UNPAIRED,
- UNKNOWN;
+ UNKNOWN
}
- public static enum Category {
+ public enum Category {
BASIC_SHUTTER,
SHUTTER,
ALARM,
protected static class InterfacesResponse extends Response<Interface> {
}
- public static enum Source {
+ public enum Source {
DHCP,
NETBIOS,
MDNS,
MDNS_SRV,
UPNP,
WSD,
- UNKNOWN;
+ UNKNOWN
}
public record HostName(@Nullable String name, Source source) {
private static record WakeOnLineData(String mac, String password) {
}
- private static enum Type {
+ private enum Type {
MAC_ADDRESS,
- UNKNOWN;
+ UNKNOWN
}
private static record L2Ident(MACAddress id, Type type) {
private static record L3Connectivity(String addr, Af af, boolean active, boolean reachable,
ZonedDateTime lastActivity, ZonedDateTime lastTimeReachable, String model) {
- private static enum Af {
+ private enum Af {
IPV4,
IPV6,
- UNKNOWN;
+ UNKNOWN
}
public IPAddress getIPAddress() {
public static record HostIntf(LanHost host, Interface intf) {
}
- private static enum HostType {
+ private enum HostType {
WORKSTATION,
LAPTOP,
SMARTPHONE,
MULTIMEDIA_DEVICE,
CAR,
OTHER,
- UNKNOWN;
+ UNKNOWN
}
public static record LanHost(String id, @Nullable String primaryName, HostType hostType, boolean primaryNameManual,
protected static class Config extends Response<LanConfig> {
}
- private static enum Mode {
+ private enum Mode {
ROUTER,
BRIDGE,
- UNKNOWN;
+ UNKNOWN
}
public static record LanConfig(IPAddress ip, String name, String nameDns, String nameMdns, String nameNetbios,
private static final String AUTHORIZE_ACTION = "authorize";
private static final String LOGOUT = "logout";
- private static enum Status {
+ private enum Status {
PENDING, // the user has not confirmed the autorization request yet
TIMEOUT, // the user did not confirmed the authorization within the given time
GRANTED, // the app_token is valid and can be used to open a session
DENIED, // the user denied the authorization request
- UNKNOWN; // the app_token is invalid or has been revoked
+ UNKNOWN // the app_token is invalid or has been revoked
}
private static record AuthorizationStatus(Status status, boolean loggedIn, String challenge,
private static class AuthResponse extends Response<Authorization> {
}
- public static enum Permission {
+ public enum Permission {
PARENTAL,
CONTACTS,
EXPLORER,
VM,
PLAYER,
NONE,
- UNKNOWN;
+ UNKNOWN
}
public static record Session(Map<LoginManager.Permission, @Nullable Boolean> permissions,
protected static class ReceiverResponse extends Response<Receiver> {
}
- public static enum Action {
+ public enum Action {
START,
STOP,
- UNKNOWN;
+ UNKNOWN
}
- public static enum MediaType {
+ public enum MediaType {
VIDEO,
PHOTO,
AUDIO,
SCREEN,
- UNKNOWN;
+ UNKNOWN
}
private static record Request(String password, Action action, MediaType mediaType, @Nullable String media,
protected class StatusResponse extends Response<Status> {
}
- private static enum NetworkStatus {
+ private enum NetworkStatus {
WORKING,
- UNKNOWN;
+ UNKNOWN
}
public static record Config(NetworkStatus network, boolean dectEcoMode, String dectPin, int dectRingPattern,
public enum Type {
FXS,
DECT,
- UNKNOWN;
+ UNKNOWN
}
public static record Status(int id, boolean isRinging, boolean onHook, boolean hardwareDefect, Type type,
protected static class PlayerResponse extends Response<Player> {
}
- public static enum DeviceModel {
+ public enum DeviceModel {
FBX7HD_DELTA, // Freebox Player Devialet
TBX8AM, // Player Pop
FBX6HD,
FBX7HD,
FBX7HD_ONE,
FBX8AM,
- UNKNOWN;
+ UNKNOWN
}
public static record Player(MACAddress mac, StbType stbType, int id, ZonedDateTime lastTimeReachable,
boolean apiAvailable, String deviceName, DeviceModel deviceModel, boolean reachable, String uid,
@Nullable String apiVersion, List<String> lanGids) {
- private static enum StbType {
+ private enum StbType {
STB_ANDROID,
STB_V6,
STB_V7,
STB_V8,
- UNKNOWN;
+ UNKNOWN
}
/**
private static class StatusResponse extends Response<Status> {
}
- public static enum PowerState {
+ public enum PowerState {
STANDBY,
RUNNING,
- UNKNOWN;
+ UNKNOWN
}
public static record Status(PowerState powerState, StatusInformation player,
private enum MediaState {
READY,
- UNKNOWN;
+ UNKNOWN
}
private static record AudioTrack(int bitrate, @SerializedName("channelCount") int channelCount,
@SerializedName("metadataId") @Nullable String metadataId, int pid, int samplerate, long uid) {
}
- private static enum Type {
+ private enum Type {
NORMAL,
HEARINGIMPAIRED,
- UNKNOWN;
+ UNKNOWN
}
protected static record Metadata(@Nullable String album,
@Nullable String title, @SerializedName("trackNumber") int trackNumber,
@SerializedName("trackTotal") int trackTotal, @Nullable String url) {
- protected static enum PlaybackState {
+ protected enum PlaybackState {
PLAY,
PAUSE,
- UNKNOWN;
+ UNKNOWN
}
protected static record SubtitleTrack(@Nullable String codec, @Nullable String language, @Nullable String pid,
}
}
- private static enum BouquetType {
+ private enum BouquetType {
ADSL,
- UNKNOWN;
+ UNKNOWN
}
- private static enum ChannelType {
+ private enum ChannelType {
REGULAR,
- UNKNOWN;
+ UNKNOWN
}
private static record Service(long id, @Nullable String name,
public static record RepeaterLed(int id, boolean ledActivated) {
}
- private static enum Connection {
+ private enum Connection {
CONNECTED,
DISCONNECTED,
- UNKNOWN;
+ UNKNOWN
}
- private static enum Status {
+ private enum Status {
STARTING,
RUNNING,
REBOOTING,
UPDATING,
REBOOT_FAILURE,
UPDATE_FAILURE,
- UNKNOWN;
+ UNKNOWN
}
- public static enum Model {
+ public enum Model {
FBXWMR, // Répéteur Wifi
- UNKNOWN;
+ UNKNOWN
}
public static record Repeater(int id, boolean ledActivated, boolean enabled, MACAddress mainMac,
public enum SensorKind {
FAN,
TEMP,
- UNKNOWN;
+ UNKNOWN
}
public SensorKind getKind() {
private static record Expansion(int slot, boolean probeDone, boolean present, boolean supported, String bundle,
Type type) {
- private static enum Type {
+ private enum Type {
UNKNOWN, // unknown module
DSL_LTE, // xDSL + LTE
DSL_LTE_EXTERNAL_ANTENNAS, // xDSL + LTE with external antennas switch
FTTH_P2P, // FTTH P2P
FTTH_PON, // FTTH PON
- SECURITY; // Security module
+ SECURITY // Security module
}
}
public static record Config(String firmwareVersion, MACAddress mac, String serial, String uptime, long uptimeVal,
String boardName, boolean boxAuthenticated, DiskStatus diskStatus, String userMainStorage,
List<Sensor> sensors, ModelInfo modelInfo, List<Sensor> fans, List<Expansion> expansions) {
- private static enum DiskStatus {
+ private enum DiskStatus {
NOT_DETECTED,
DISABLED,
INITIALIZING,
ERROR,
ACTIVE,
- UNKNOWN;
+ UNKNOWN
}
}
protected class VirtualMachineResponse extends Response<VirtualMachine> {
}
- public static enum Status {
+ public enum Status {
STOPPED,
RUNNING,
- UNKNOWN;
+ UNKNOWN
}
public static record VirtualMachine(int id, String name, MACAddress mac, Status status) {
FreeboxOsHandler handler = null;
if (thing != null) {
thingHandler = thing.getHandler();
- if (thingHandler instanceof FreeboxOsHandler) {
- handler = (FreeboxOsHandler) thingHandler;
+ if (thingHandler instanceof FreeboxOsHandler osHandler) {
+ handler = osHandler;
}
}
if (thing == null) {
import static org.openhab.binding.freeboxos.internal.FreeboxOsBindingConstants.*;
import java.util.Collection;
-import java.util.Collections;
+import java.util.List;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singletonList(ActivePlayerActions.class);
+ return List.of(ActivePlayerActions.class);
}
@Override
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.freeboxos.internal.action.CallActions;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(CallActions.class);
+ return Set.of(CallActions.class);
}
}
return true;
}
}
- if (command instanceof PercentType) {
- PercentType percent = (PercentType) command;
+ if (command instanceof PercentType percentCommand) {
if (GAIN_RX.equals(channelId)) {
- phoneManager.setGainRx(getClientId(), percent.intValue());
- updateIfActive(GAIN_RX, percent);
+ phoneManager.setGainRx(getClientId(), percentCommand.intValue());
+ updateIfActive(GAIN_RX, percentCommand);
return true;
} else if (GAIN_TX.equals(channelId)) {
- phoneManager.setGainTx(getClientId(), percent.intValue());
- updateIfActive(GAIN_RX, percent);
+ phoneManager.setGainTx(getClientId(), percentCommand.intValue());
+ updateIfActive(GAIN_RX, percentCommand);
return true;
}
}
package org.openhab.binding.freeboxos.internal.handler;
import java.util.Collection;
-import java.util.Collections;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(FreeboxOsDiscoveryService.class);
+ return Set.of(FreeboxOsDiscoveryService.class);
}
@Override
properties.put(ROLE, plug.netRole().name());
properties.put(NET_ID, plug.netId());
properties.put(ETHERNET_SPEED, "%d Mb/s".formatted(plug.ethSpeed()));
- properties.put(LOCAL, Boolean.valueOf(plug.local()).toString());
- properties.put(FULL_DUPLEX, Boolean.valueOf(plug.ethFullDuplex()).toString());
+ properties.put(LOCAL, Boolean.toString(plug.local()));
+ properties.put(FULL_DUPLEX, Boolean.toString(plug.ethFullDuplex()));
if (plug.local()) { // Plug connected to the freebox does not provide rate up or down
List<Channel> channels = new ArrayList<>(getThing().getChannels());
import java.util.Arrays;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singletonList(PlayerActions.class);
+ return List.of(PlayerActions.class);
}
}
import static org.openhab.binding.freeboxos.internal.FreeboxOsBindingConstants.*;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.freeboxos.internal.action.RepeaterActions;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(RepeaterActions.class);
+ return Set.of(RepeaterActions.class);
}
@Override
}
private void setOrientation(LcdManager manager, Config config, Command command) throws FreeboxException {
- if (command instanceof DecimalType) {
- manager.setOrientation(((DecimalType) command).intValue());
+ if (command instanceof DecimalType orientation) {
+ manager.setOrientation(orientation.intValue());
} else {
logger.warn("Invalid command {} from channel {}", command, LCD_ORIENTATION);
}
manager.setBrightness(() -> config.brightness() + (command == IncreaseDecreaseType.INCREASE ? 1 : -1));
} else if (command instanceof OnOffType) {
manager.setBrightness(() -> command == OnOffType.ON ? 100 : 0);
- } else if (command instanceof QuantityType) {
- manager.setBrightness(() -> ((QuantityType<?>) command).intValue());
+ } else if (command instanceof QuantityType brightness) {
+ manager.setBrightness(() -> brightness.intValue());
} else if (command instanceof DecimalType || command instanceof PercentType) {
manager.setBrightness(() -> ((DecimalType) command).intValue());
} else {
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.freeboxos.internal.action.ServerActions;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(ServerActions.class);
+ return Set.of(ServerActions.class);
}
@Override
@Override
public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
- if (childHandler instanceof FroniusBaseThingHandler) {
- this.services.add((FroniusBaseThingHandler) childHandler);
+ if (childHandler instanceof FroniusBaseThingHandler handler) {
+ this.services.add(handler);
restartAutomaticRefresh();
} else {
logger.debug("Child handler {} not added because it is not an instance of FroniusBaseThingHandler",
import static org.openhab.binding.fsinternetradio.internal.FSInternetRadioBindingConstants.*;
-import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(THING_TYPE_RADIO);
+ return Set.of(THING_TYPE_RADIO);
}
@Override
import static org.openhab.binding.fsinternetradio.internal.FSInternetRadioBindingConstants.THING_TYPE_RADIO;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@NonNullByDefault
public class FSInternetRadioHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_RADIO);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_RADIO);
private final HttpClient httpClient;
radio.increaseVolumeAbsolute();
} else if (IncreaseDecreaseType.DECREASE.equals(command) || UpDownType.DOWN.equals(command)) {
radio.decreaseVolumeAbsolute();
- } else if (command instanceof PercentType) {
- radio.setVolumePercent(((PercentType) command).intValue());
+ } else if (command instanceof PercentType percentCommand) {
+ radio.setVolumePercent(percentCommand.intValue());
}
// absolute value should also be updated now, so let's update all items
scheduler.schedule(updateRunnable, 1, SECONDS);
radio.increaseVolumeAbsolute();
} else if (IncreaseDecreaseType.DECREASE.equals(command) || UpDownType.DOWN.equals(command)) {
radio.decreaseVolumeAbsolute();
- } else if (command instanceof DecimalType) {
- radio.setVolumeAbsolute(((DecimalType) command).intValue());
+ } else if (command instanceof DecimalType decimalCommand) {
+ radio.setVolumeAbsolute(decimalCommand.intValue());
}
// percent value should also be updated now, so let's update all items
scheduler.schedule(updateRunnable, 1, SECONDS);
break;
case CHANNEL_MODE:
- if (command instanceof DecimalType) {
- radio.setMode(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ radio.setMode(decimalCommand.intValue());
}
break;
case CHANNEL_PRESET:
- if (command instanceof DecimalType) {
- radio.setPreset(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ radio.setPreset(decimalCommand.intValue());
}
break;
case CHANNEL_MUTE:
logger.trace("converting to XML failed: '{}' with {}: {}", requestResultString, e.getClass().getName(),
e.getMessage());
logger.debug("converting to XML failed with {}: {}", e.getClass().getName(), e.getMessage());
- if (e instanceof IOException) {
- throw (IOException) e;
+ if (e instanceof IOException exception) {
+ throw exception;
}
throw new IOException(e);
}
*/
public String getSessionId() {
final NodeList sessionIdTagList = xmlDoc.getElementsByTagName("sessionId");
- final String givenSessId = getCharacterDataFromElement((Element) sessionIdTagList.item(0));
- return givenSessId;
+ return getCharacterDataFromElement((Element) sessionIdTagList.item(0));
}
/**
factory.setXIncludeAware(false);
factory.setExpandEntityReferences(false);
final DocumentBuilder builder = factory.newDocumentBuilder();
- final Document xmlDocument = builder.parse(new InputSource(new StringReader(xmlString)));
- return xmlDocument;
+ return builder.parse(new InputSource(new StringReader(xmlString)));
}
/**
*/
private static String getCharacterDataFromElement(Element e) {
final Node child = e.getFirstChild();
- if (child instanceof CharacterData) {
- final CharacterData cd = (CharacterData) child;
+ if (child instanceof CharacterData cd) {
return cd.getData();
}
return "";
private boolean isConfigurationComplete(Configuration config) {
String ip = (String) config.get(FSInternetRadioBindingConstants.CONFIG_PROPERTY_IP);
- BigDecimal port = (BigDecimal) config.get(FSInternetRadioBindingConstants.CONFIG_PROPERTY_PORT.toString());
- String pin = (String) config.get(FSInternetRadioBindingConstants.CONFIG_PROPERTY_PIN.toString());
+ BigDecimal port = (BigDecimal) config.get(FSInternetRadioBindingConstants.CONFIG_PROPERTY_PORT);
+ String pin = (String) config.get(FSInternetRadioBindingConstants.CONFIG_PROPERTY_PIN);
return !(ip == null || port.compareTo(BigDecimal.ZERO) == 0 || pin == null || pin.isEmpty());
}
import static org.openhab.binding.ftpupload.internal.FtpUploadBindingConstants.THING_TYPE_IMAGERECEIVER;
-import java.util.Collections;
import java.util.Dictionary;
import java.util.Set;
public class FtpUploadHandlerFactory extends BaseThingHandlerFactory {
private final Logger logger = LoggerFactory.getLogger(FtpUploadHandlerFactory.class);
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_IMAGERECEIVER);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_IMAGERECEIVER);
private final int DEFAULT_PORT = 2121;
private final int DEFAULT_IDLE_TIMEOUT = 60;
import java.time.format.DateTimeParseException;
import java.time.format.FormatStyle;
import java.util.Collection;
-import java.util.Collections;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(GardenaDeviceDiscoveryService.class);
+ return Set.of(GardenaDeviceDiscoveryService.class);
}
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
logger.debug("Command received: {}", command);
try {
- boolean isOnCommand = command instanceof OnOffType && ((OnOffType) command) == OnOffType.ON;
+ boolean isOnCommand = command instanceof OnOffType onOffCommand && onOffCommand == OnOffType.ON;
String dataItemProperty = getDeviceDataItemProperty(channelUID);
if (RefreshType.REFRESH == command) {
logger.debug("Refreshing Gardena connection");
public class ValveCommand extends GardenaCommand {
private static final String COMMAND_TYPE = "VALVE_CONTROL";
- public static enum ValveControl {
+ public enum ValveControl {
START_SECONDS_TO_OVERRIDE,
STOP_UNTIL_NEXT_TASK,
PAUSE,
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof Ipx800v3Handler) {
- this.handler = (Ipx800v3Handler) handler;
+ if (handler instanceof Ipx800v3Handler ipx800v3Handler) {
+ this.handler = ipx800v3Handler;
}
}
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
if (channel == null || groupId == null) {
return;
}
- if (command instanceof OnOffType && isValidPortId(channelUID)
+ if (command instanceof OnOffType onOffCommand && isValidPortId(channelUID)
&& PortDefinition.fromGroupId(groupId) == PortDefinition.RELAY) {
RelayOutputConfiguration config = channel.getConfiguration().as(RelayOutputConfiguration.class);
String id = channelUID.getIdWithoutGroup();
- parser.ifPresent(p -> p.setOutput(id, (OnOffType) command == OnOffType.ON ? 1 : 0, config.pulse));
+ parser.ifPresent(p -> p.setOutput(id, onOffCommand == OnOffType.ON ? 1 : 0, config.pulse));
return;
}
logger.debug("Can not handle command '{}' on channel '{}'", command, channelUID);
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singletonList(Ipx800Actions.class);
+ return List.of(Ipx800Actions.class);
}
}
decodeDataLine(portDefinition, data);
} else if (VALIDATION_PATTERN.matcher(data).matches()) {
for (String status : data.split("&")) {
- String statusPart[] = status.split("=");
+ String[] statusPart = status.split("=");
int portNumShift = 1;
PortDefinition portDefinition = PortDefinition.fromPortName(statusPart[0].substring(0, 1));
switch (portDefinition) {
private Optional<Document> doc = Optional.empty();
- public static enum StatusEntry {
+ public enum StatusEntry {
VERSION,
- CONFIG_MAC;
+ CONFIG_MAC
}
public StatusFileInterpreter(String hostname, Ipx800EventListener listener) {
DiscoveryResult result = DiscoveryResultBuilder
.create(new ThingUID(THING_TYPE_GENERATOR, bridgeUID, String.valueOf(apparatus.apparatusId)))
.withLabel("MobileLink Generator " + apparatus.name)
- .withProperty(Thing.PROPERTY_SERIAL_NUMBER, String.valueOf(apparatus.serialNumber))
+ .withProperty(Thing.PROPERTY_SERIAL_NUMBER, apparatus.serialNumber)
.withProperty(PROPERTY_GENERATOR_ID, String.valueOf(apparatus.apparatusId))
.withRepresentationProperty(PROPERTY_GENERATOR_ID).withBridge(bridgeUID).build();
thingDiscovered(result);
private static final String API_BASE = "https://app.mobilelinkgen.com/api";
private static final String LOGIN_BASE = "https://generacconnectivity.b2clogin.com/generacconnectivity.onmicrosoft.com/B2C_1A_MobileLink_SignIn";
private static final Pattern SETTINGS_PATTERN = Pattern.compile("^var SETTINGS = (.*);$", Pattern.MULTILINE);
- private static final Gson GSON = new GsonBuilder().registerTypeAdapter(ZonedDateTime.class,
- (JsonDeserializer<ZonedDateTime>) (json, type, jsonDeserializationContext) -> {
- return ZonedDateTime.parse(json.getAsJsonPrimitive().getAsString());
- }).create();
+ private static final Gson GSON = new GsonBuilder()
+ .registerTypeAdapter(ZonedDateTime.class, (JsonDeserializer<ZonedDateTime>) (json, type,
+ jsonDeserializationContext) -> ZonedDateTime.parse(json.getAsJsonPrimitive().getAsString()))
+ .create();
private HttpClient httpClient;
private GeneracMobileLinkDiscoveryService discoveryService;
private Map<String, Apparatus> apparatusesCache = new HashMap<String, Apparatus>();
Optional<Thing> thing = getThing().getThings().stream().filter(
t -> t.getConfiguration().as(GeneracMobileLinkGeneratorConfiguration.class).generatorId.equals(id))
.findFirst();
- if (!thing.isPresent()) {
+ if (thing.isEmpty()) {
discoveryService.generatorDiscovered(apparatus, getThing().getUID());
} else {
ThingHandler handler = thing.get().getHandler();
try {
if (p.value.signalStrength != null) {
updateState(CHANNEL_SIGNAL_STRENGH, new QuantityType<Dimensionless>(
- Integer.parseInt(p.value.signalStrength.replaceAll("%", "")), Units.PERCENT));
+ Integer.parseInt(p.value.signalStrength.replace("%", "")), Units.PERCENT));
}
} catch (NumberFormatException e) {
logger.debug("Could not parse signalStrength {}", p.value.signalStrength);
return;
}
- String fields[] = deviceReply.split(",");
+ String[] fields = deviceReply.split(",");
if (fields.length != 5) {
return;
}
super(thing, queue, "sendir", CommandType.COMMAND);
this.command = command;
- deviceCommand = "sendir," + mod + ":" + con + "," + String.valueOf(sendCounter) + "," + code;
+ deviceCommand = "sendir," + mod + ":" + con + "," + sendCounter + "," + code;
}
@Override
String con, String code) {
super(thing, queue, "sendserial", CommandType.SERIAL1);
// Check to see if this is for the second serial port on a GC-100-12
- if (isGC100Model12() && mod.equals("2")) {
+ if (isGC100Model12() && "2".equals(mod)) {
setCommandType(CommandType.SERIAL2);
}
this.command = command;
return;
}
- String fields[] = deviceReply.split(",");
+ String[] fields = deviceReply.split(",");
if (fields.length != 5) {
return;
}
if (m.groupCount() == 4) {
setModule(m.group(2));
setConnector(m.group(3));
- setState(m.group(4).equals("0") ? OnOffType.OFF : OnOffType.ON);
+ setState("0".equals(m.group(4)) ? OnOffType.OFF : OnOffType.ON);
return true;
}
}
throw new HexCodeConversionException("Hex code is too short");
}
- if (!hexCodeArray[0].equals("0000")) {
+ if (!"0000".equals(hexCodeArray[0])) {
throw new HexCodeConversionException("Illegal hex code element 0, should be 0000");
}
import static org.openhab.binding.goecharger.internal.GoEChargerBindingConstants.*;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@NonNullByDefault
@Component(configurationPid = "binding.goecharger", service = ThingHandlerFactory.class)
public class GoEChargerHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_GOE);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_GOE);
private final HttpClient httpClient;
@Activate
switch (channelUID.getId()) {
case MAX_CURRENT:
key = "amp";
- if (command instanceof DecimalType) {
- value = String.valueOf(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ value = String.valueOf(decimalCommand.intValue());
} else if (command instanceof QuantityType<?>) {
value = String.valueOf(((QuantityType<ElectricCurrent>) command).toUnit(Units.AMPERE).intValue());
}
break;
case MAX_CURRENT_TEMPORARY:
key = "amx";
- if (command instanceof DecimalType) {
- value = String.valueOf(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ value = String.valueOf(decimalCommand.intValue());
} else if (command instanceof QuantityType<?>) {
value = String.valueOf(((QuantityType<ElectricCurrent>) command).toUnit(Units.AMPERE).intValue());
}
case SESSION_CHARGE_CONSUMPTION_LIMIT:
key = "dwo";
var multiplier = 10;
- if (command instanceof DecimalType) {
- value = String.valueOf(((DecimalType) command).intValue() * multiplier);
+ if (command instanceof DecimalType decimalCommand) {
+ value = String.valueOf(decimalCommand.intValue() * multiplier);
} else if (command instanceof QuantityType<?>) {
value = String.valueOf(
((QuantityType<Energy>) command).toUnit(Units.KILOWATT_HOUR).intValue() * multiplier);
}
return new DecimalType(goeResponse.transaction);
case ALLOW_CHARGING:
- return goeResponse.allowCharging == true ? OnOffType.ON : OnOffType.OFF;
+ return goeResponse.allowCharging ? OnOffType.ON : OnOffType.OFF;
case TEMPERATURE_TYPE2_PORT:
// It was reported that the temperature is invalid when only one value is returned
// That's why it is checked that at least 2 values are returned
switch (channelUID.getId()) {
case MAX_CURRENT:
key = "amp";
- if (command instanceof DecimalType) {
- value = String.valueOf(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ value = String.valueOf(decimalCommand.intValue());
} else if (command instanceof QuantityType<?>) {
value = String.valueOf(((QuantityType<ElectricCurrent>) command).toUnit(Units.AMPERE).intValue());
}
case SESSION_CHARGE_CONSUMPTION_LIMIT:
key = "dwo";
var multiplier = 1000;
- if (command instanceof DecimalType) {
- value = String.valueOf(((DecimalType) command).intValue() * multiplier);
+ if (command instanceof DecimalType decimalCommand) {
+ value = String.valueOf(decimalCommand.intValue() * multiplier);
} else if (command instanceof QuantityType<?>) {
value = String.valueOf(
((QuantityType<Energy>) command).toUnit(Units.KILOWATT_HOUR).intValue() * multiplier);
break;
case PHASES:
key = "psm";
- if (command instanceof DecimalType) {
+ if (command instanceof DecimalType decimalCommand) {
var phases = 1;
- var help = (DecimalType) command;
- if (help.intValue() == 3) {
+ if (decimalCommand.intValue() == 3) {
// set value 2 for 3 phases
phases = 2;
}
break;
case FORCE_STATE:
key = "frc";
- if (command instanceof DecimalType) {
- value = String.valueOf(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ value = String.valueOf(decimalCommand.intValue());
}
break;
case TRANSACTION:
key = "trx";
- if (command instanceof DecimalType) {
- value = String.valueOf(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ value = String.valueOf(decimalCommand.intValue());
}
break;
}
public void handleNotification(LocationMessage msg) {
synchronized (this) {
String trackerId = msg.getTrackerId();
- if (msg instanceof TransitionMessage) {
+ if (msg instanceof TransitionMessage message) {
List<TransitionMessage> transitionMessages = transitionNotifications.computeIfAbsent(trackerId,
k -> new ArrayList<>());
if (transitionMessages != null) {
- transitionMessages.add((TransitionMessage) msg);
+ transitionMessages.add(message);
}
} else {
locationNotifications.put(trackerId, msg);
if (!trackerId.isEmpty()) {
TrackerHandler recorder = getHandlerById(trackerId);
if (recorder != null) {
- if (message instanceof TransitionMessage) {
- TransitionMessage tm = (TransitionMessage) message;
- recorder.doTransition(tm);
+ if (message instanceof TransitionMessage transitionMessage) {
+ recorder.doTransition(transitionMessage);
} else {
recorder.updateLocation(message);
}
*/
package org.openhab.binding.gree.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
public static final String BINDING_ID = "gree";
public static final ThingTypeUID THING_TYPE_GREEAIRCON = new ThingTypeUID(BINDING_ID, "airconditioner");
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_GREEAIRCON);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_GREEAIRCON);
// List of all Thing Type UIDs
public static final ThingTypeUID GREE_THING_TYPE = new ThingTypeUID(BINDING_ID, "airconditioner");
scanResponseGson.packJson = GSON.fromJson(decryptedMsg, GreeScanReponsePackDTO.class);
// Now make sure the device is reported as a Gree device
- if (scanResponseGson.packJson.brand.equalsIgnoreCase("gree")) {
+ if ("gree".equalsIgnoreCase(scanResponseGson.packJson.brand)) {
// Create a new GreeDevice
logger.debug("Discovered device at {}:{}", remoteAddress.getHostAddress(), remotePort);
GreeAirDevice newDevice = new GreeAirDevice(remoteAddress, remotePort, scanResponseGson);
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
int valueArrayposition = colList.indexOf(valueName);
if (valueArrayposition != -1) {
// get the Corresponding value
- Integer value = valList.get(valueArrayposition);
- return value;
+ return valList.get(valueArrayposition);
}
}
}
public boolean hasStatusValChanged(String valueName) throws GreeException {
- if (!prevStatusResponsePackGson.isPresent()) {
+ if (prevStatusResponsePackGson.isEmpty()) {
return true; // update value if there is no previous one
}
// Find the valueName in the Current Status object
}
private void setCommandValue(DatagramSocket clientSocket, String command, int value) throws GreeException {
- executeCommand(clientSocket, Collections.singletonMap(command, value));
+ executeCommand(clientSocket, Map.of(command, value));
}
private void setCommandValue(DatagramSocket clientSocket, String command, int value, int min, int max)
if ((value < min) || (value > max)) {
throw new GreeException("Command value out of range!");
}
- executeCommand(clientSocket, Collections.singletonMap(command, value));
+ executeCommand(clientSocket, Map.of(command, value));
}
private DatagramPacket createPackRequest(int i, String pack) {
request.tcid = getId();
request.pack = pack;
byte[] sendData = GSON.toJson(request).getBytes(StandardCharsets.UTF_8);
- DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress, port);
- return sendPacket;
+ return new DatagramPacket(sendData, sendData.length, ipAddress, port);
}
private <T> T receiveResponse(DatagramSocket clientSocket, Class<T> classOfT)
private void initializeThing() {
String message = "";
try {
- if (!clientSocket.isPresent()) {
+ if (clientSocket.isEmpty()) {
clientSocket = Optional.of(new DatagramSocket());
clientSocket.get().setSoTimeout(DATAGRAM_SOCKET_TIMEOUT);
}
int mode = -1;
String modeStr = "";
boolean isNumber = false;
- if (command instanceof DecimalType) {
+ if (command instanceof DecimalType decimalCommand) {
// backward compatibility when channel was Number
- mode = ((DecimalType) command).intValue();
+ mode = decimalCommand.intValue();
} else if (command instanceof OnOffType) {
// Switch
logger.debug("{}: Send Power-{}", thingId, command);
private void handleQuietCommand(DatagramSocket socket, Command command) throws GreeException {
int mode = -1;
- if (command instanceof DecimalType) {
- mode = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ mode = decimalCommand.intValue();
} else if (command instanceof StringType) {
switch (command.toString().toLowerCase()) {
case QUIET_OFF:
if (command instanceof OnOffType) {
return command == OnOffType.ON ? 1 : 0;
}
- if (command instanceof DecimalType) {
- int value = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ int value = decimalCommand.intValue();
if ((value == 0) || (value == 1)) {
return value;
}
}
private int getNumber(Command command) {
- if (command instanceof DecimalType) {
- return ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ return decimalCommand.intValue();
}
throw new IllegalArgumentException("Invalid Number type");
}
private QuantityType<?> convertTemp(Command command) {
- if (command instanceof DecimalType) {
+ if (command instanceof DecimalType temperature) {
// The Number alone doesn't specify the temp unit
// for this get current setting from the A/C unit
int unit = device.getIntStatusVal(GREE_PROP_TEMPUNIT);
- return toQuantityType((DecimalType) command, DIGITS_TEMP,
+ return toQuantityType(temperature, DIGITS_TEMP,
unit == TEMP_UNIT_CELSIUS ? SIUnits.CELSIUS : ImperialUnits.FAHRENHEIT);
}
- if (command instanceof QuantityType) {
- return (QuantityType<?>) command;
+ if (command instanceof QuantityType quantityCommand) {
+ return quantityCommand;
}
throw new IllegalArgumentException("Invalud Temp type");
}
logger.debug("Could not get appliance command", e);
return null;
}
- if (!commandOptional.isPresent()) {
+ if (commandOptional.isEmpty()) {
return null;
}
if (commandOptional.get().getType() != Appliance.TYPE) {
Optional<ApplianceStatus> applianceStatusOptional;
try {
applianceStatusOptional = ondusService.applianceStatus(appliance);
- if (!applianceStatusOptional.isPresent()) {
+ if (applianceStatusOptional.isEmpty()) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "@text/error.empty.response");
return null;
}
import java.io.IOException;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
*/
@NonNullByDefault
public class GroupePSABridgeHandler extends BaseBridgeHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_BRIDGE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BRIDGE);
private static final long DEFAULT_POLLING_INTERVAL_M = TimeUnit.HOURS.toMinutes(1);
private final OAuthFactory oAuthFactory;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(GroupePSADiscoveryService.class);
+ return Set.of(GroupePSADiscoveryService.class);
}
}
import static org.openhab.binding.groupepsa.internal.GroupePSABindingConstants.THING_TYPE_VEHICLE;
-import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
private @Nullable GroupePSABridgeHandler bridgeHandler;
public GroupePSADiscoveryService() {
- super(Collections.singleton(THING_TYPE_VEHICLE), 10, false);
+ super(Set.of(THING_TYPE_VEHICLE), 10, false);
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof GroupePSABridgeHandler) {
- bridgeHandler = (GroupePSABridgeHandler) handler;
+ if (handler instanceof GroupePSABridgeHandler bridgeHandler) {
+ this.bridgeHandler = bridgeHandler;
}
}
public @Nullable VehicleStatus getVehicleStatus(String vin) throws GroupePSACommunicationException {
ContentResponse responseOdometer = executeRequest(getBaseUrl() + "/user/vehicles/" + vin + "/status");
- VehicleStatus status = parseResponse(responseOdometer, VehicleStatus.class);
-
- return status;
+ return parseResponse(responseOdometer, VehicleStatus.class);
}
}
Bridge bridge = getBridge();
if (bridge != null) {
ThingHandler handler = bridge.getHandler();
- if (handler instanceof GroupePSABridgeHandler) {
- return (GroupePSABridgeHandler) handler;
+ if (handler instanceof GroupePSABridgeHandler bridgeHandler) {
+ return bridgeHandler;
}
}
return null;