public AnalogValue getAnalogValue(int portNumber) {
// Get the internal index for portNumber within the message
int idx = (portNumber - 1) % 4;
- AnalogValue value = new AnalogValue(this.getValue(idx), getMeasureType(idx));
- return value;
+ return new AnalogValue(this.getValue(idx), getMeasureType(idx));
}
/**
@NonNullByDefault
public class ApiPageEntry {
- static enum Type {
+ enum Type {
READ_ONLY_SWITCH(true),
READ_ONLY_NUMERIC(true),
NUMERIC_FORM(false),
public static final String NUMBER_MAX = "max";
public static final String NUMBER_STEP = "step";
- static enum OptionType {
+ enum OptionType {
NUMBER,
SELECT,
}
// iterate over all mode capability elements and build the superset of their inner capabilities
allCapabilities.forEach(e -> {
if (e != null) {
- light |= e.getLight() != null ? e.getLight().size() > 0 : false;
- swing |= e.getSwings() != null ? e.getSwings().size() > 0 : false;
- fanLevel |= e.getFanLevel() != null ? e.getFanLevel().size() > 0 : false;
- fanSpeed |= e.getFanSpeeds() != null ? e.getFanSpeeds().size() > 0 : false;
- verticalSwing |= e.getVerticalSwing() != null ? e.getVerticalSwing().size() > 0 : false;
- horizontalSwing |= e.getHorizontalSwing() != null ? e.getHorizontalSwing().size() > 0 : false;
+ light |= e.getLight() != null ? !e.getLight().isEmpty() : false;
+ swing |= e.getSwings() != null ? !e.getSwings().isEmpty() : false;
+ fanLevel |= e.getFanLevel() != null ? !e.getFanLevel().isEmpty() : false;
+ fanSpeed |= e.getFanSpeeds() != null ? !e.getFanSpeeds().isEmpty() : false;
+ verticalSwing |= e.getVerticalSwing() != null ? !e.getVerticalSwing().isEmpty() : false;
+ horizontalSwing |= e.getHorizontalSwing() != null ? !e.getHorizontalSwing().isEmpty() : false;
}
});
}
// List of all Channel IDs
public static final String PROPERTY_HOME_TEMPERATURE_UNIT = "temperatureUnit";
- public static enum TemperatureUnit {
+ public enum TemperatureUnit {
CELSIUS,
FAHRENHEIT
}
public static final String CHANNEL_ZONE_HVAC_MODE = "hvacMode";
- public static enum HvacMode {
+ public enum HvacMode {
OFF,
HEAT,
COOL,
public static final String CHANNEL_ZONE_FAN_SPEED = "fanspeed";
- public static enum FanSpeed {
+ public enum FanSpeed {
LOW,
MIDDLE,
HIGH,
public static final String CHANNEL_ZONE_FAN_LEVEL = "fanLevel";
- public static enum FanLevel {
+ public enum FanLevel {
SILENT,
LEVEL1,
LEVEL2,
public static final String CHANNEL_ZONE_HORIZONTAL_SWING = "horizontalSwing";
- public static enum HorizontalSwing {
+ public enum HorizontalSwing {
OFF,
ON,
LEFT,
public static final String CHANNEL_ZONE_VERTICAL_SWING = "verticalSwing";
- public static enum VerticalSwing {
+ public enum VerticalSwing {
OFF,
ON,
UP,
public static final String CHANNEL_ZONE_OPERATION_MODE = "operationMode";
- public static enum OperationMode {
+ public enum OperationMode {
SCHEDULE,
TIMER,
MANUAL,
public static final String PROPERTY_ZONE_NAME = "name";
public static final String PROPERTY_ZONE_TYPE = "type";
- public static enum ZoneType {
+ public enum ZoneType {
HEATING,
AIR_CONDITIONING,
HOT_WATER
break;
}
- return power.getValue().equals("ON");
+ return "ON".equals(power.getValue());
}
private static DecimalType toDecimalType(double value) {
@Nullable GenericZoneCapabilities capabilities) {
AirConditioningCapabilities acCapabilities;
- if (capabilities instanceof AirConditioningCapabilities) {
- acCapabilities = (AirConditioningCapabilities) capabilities;
+ if (capabilities instanceof AirConditioningCapabilities conditioningCapabilities) {
+ acCapabilities = conditioningCapabilities;
} else {
acCapabilities = new AirConditioningCapabilities();
}
}
private OverlayTerminationCondition getDefaultTerminationCondition() throws IOException, ApiException {
- OverlayTerminationCondition defaultTerminationCondition = zoneHandler.getDefaultTerminationCondition();
- return defaultTerminationCondition;
+ return zoneHandler.getDefaultTerminationCondition();
}
private TimerTerminationCondition getCurrentOrDefaultTimerTermination(ZoneStateProvider zoneStateProvider)
import static org.openhab.binding.tado.internal.TadoBindingConstants.*;
-import java.util.Arrays;
-import java.util.Collections;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;
@Component(configurationPid = "binding.tado", service = ThingHandlerFactory.class)
public class TadoHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .unmodifiableSet(new HashSet<>(Arrays.asList(THING_TYPE_HOME, THING_TYPE_ZONE, THING_TYPE_MOBILE_DEVICE)));
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_HOME, THING_TYPE_ZONE,
+ THING_TYPE_MOBILE_DEVICE);
private final Map<ThingUID, ServiceRegistration<?>> discoveryServiceRegs = new HashMap<>();
switch (id) {
case TadoBindingConstants.CHANNEL_HOME_PRESENCE_MODE:
HomePresence presence = new HomePresence();
- presence.setHomePresence(command.toFullString().toUpperCase().equals("ON")
- || command.toFullString().toUpperCase().equals("HOME") ? PresenceState.HOME
+ presence.setHomePresence("ON".equals(command.toFullString().toUpperCase())
+ || "HOME".equals(command.toFullString().toUpperCase()) ? PresenceState.HOME
: PresenceState.AWAY);
try {
api.updatePresenceLock(homeId, presence);
*/
package org.openhab.binding.tankerkoenig.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
public static final ThingTypeUID THING_TYPE_TANKSTELLE = new ThingTypeUID(BINDING_ID, "station");
public static final ThingTypeUID BRIDGE_THING_TYPE = new ThingTypeUID(BINDING_ID, "webservice");
- 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(THING_TYPE_TANKSTELLE);
+ 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(THING_TYPE_TANKSTELLE);
// List of all Channel ids
public static final String CHANNEL_DIESEL = "diesel";
protected @Nullable ThingHandler createHandler(Thing thing) {
ThingTypeUID thingTypeUID = thing.getThingTypeUID();
if (thingTypeUID.equals(BRIDGE_THING_TYPE)) {
- WebserviceHandler handler = new WebserviceHandler((Bridge) thing);
- return handler;
+ return new WebserviceHandler((Bridge) thing);
} else if (thingTypeUID.equals(THING_TYPE_TANKSTELLE)) {
return new StationHandler(thing);
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof TapoBridgeHandler) {
- TapoBridgeHandler tapoBridge = (TapoBridgeHandler) handler;
+ if (handler instanceof TapoBridgeHandler tapoBridge) {
tapoBridge.setDiscoveryService(this);
this.bridge = tapoBridge;
}
httpRequest.content(new StringContentProvider(payload, CONTENT_CHARSET), CONTENT_TYPE_JSON);
try {
- ContentResponse httpResponse = httpRequest.send();
- return httpResponse;
+ return httpRequest.send();
} catch (InterruptedException e) {
logger.debug("({}) sending request interrupted: {}", uid, e.toString());
handleError(new TapoErrorHandler(e));
String payload = plBuilder.getPayload();
/* send request (create ) */
- logger.trace("({}) create handhsake with payload: {}", uid, payload.toString());
+ logger.trace("({}) create handhsake with payload: {}", uid, payload);
ContentResponse response = sendRequest(this.deviceURL, payload);
if (response != null && getErrorCode(response) == 0) {
String encryptedKey = getKeyFromResponse(response);
httpRequest.content(new StringContentProvider(payload, CONTENT_CHARSET), CONTENT_TYPE_JSON);
try {
- ContentResponse httpResponse = httpRequest.send();
- return httpResponse;
+ return httpRequest.send();
} catch (InterruptedException e) {
logger.debug("({}) sending request interrupted: {}", uid, e.toString());
handleError(new TapoErrorHandler(e));
package org.openhab.binding.tapocontrol.internal.device;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
*/
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(TapoDiscoveryService.class);
+ return Set.of(TapoDiscoveryService.class);
}
/**
TapoErrorHandler configErr = new TapoErrorHandler();
/* check bridge */
- if (bridge == null || !(bridge instanceof TapoBridgeHandler)) {
+ if (!(bridge instanceof TapoBridgeHandler)) {
configErr.raiseError(ERR_CONFIG_NO_BRIDGE);
return configErr;
}
refreshInfo = true;
break;
case CHANNEL_BRIGHTNESS:
- if (command instanceof PercentType) {
- Float percent = ((PercentType) command).floatValue();
+ if (command instanceof PercentType percentCommand) {
+ Float percent = percentCommand.floatValue();
setBrightness(percent.intValue()); // 0..100% = 0..100
refreshInfo = true;
- } else if (command instanceof DecimalType) {
- setBrightness(((DecimalType) command).intValue());
+ } else if (command instanceof DecimalType decimalCommand) {
+ setBrightness(decimalCommand.intValue());
refreshInfo = true;
}
break;
case CHANNEL_COLOR_TEMP:
- if (command instanceof DecimalType) {
- setColorTemp(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ setColorTemp(decimalCommand.intValue());
refreshInfo = true;
}
break;
case CHANNEL_COLOR:
- if (command instanceof HSBType) {
- setColor((HSBType) command);
+ if (command instanceof HSBType hsbCommand) {
+ setColor(hsbCommand);
refreshInfo = true;
}
break;
TapoLightEffect lightEffect = deviceInfo.getLightEffect();
switch (channel) {
case CHANNEL_FX_BRIGHTNESS:
- if (command instanceof PercentType) {
- Float percent = ((PercentType) command).floatValue();
+ if (command instanceof PercentType percentCommand) {
+ Float percent = percentCommand.floatValue();
lightEffect.setBrightness(percent.intValue()); // 0..100% = 0..100
- } else if (command instanceof DecimalType) {
- lightEffect.setBrightness(((DecimalType) command).intValue());
+ } else if (command instanceof DecimalType decimalCommand) {
+ lightEffect.setBrightness(decimalCommand.intValue());
}
break;
case CHANNEL_FX_COLORS:
refreshInfo = true;
break;
case CHANNEL_BRIGHTNESS:
- if (command instanceof PercentType) {
- Float percent = ((PercentType) command).floatValue();
+ if (command instanceof PercentType percentCommand) {
+ Float percent = percentCommand.floatValue();
setBrightness(percent.intValue()); // 0..100% = 0..100
refreshInfo = true;
- } else if (command instanceof DecimalType) {
- setBrightness(((DecimalType) command).intValue());
+ } else if (command instanceof DecimalType decimalCommand) {
+ setBrightness(decimalCommand.intValue());
refreshInfo = true;
}
break;
case CHANNEL_COLOR_TEMP:
- if (command instanceof DecimalType) {
- setColorTemp(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ setColorTemp(decimalCommand.intValue());
refreshInfo = true;
}
break;
case CHANNEL_COLOR:
- if (command instanceof HSBType) {
- setColor((HSBType) command);
+ if (command instanceof HSBType hsbCommand) {
+ setColor(hsbCommand);
refreshInfo = true;
}
break;
refreshInfo = true;
break;
case CHANNEL_BRIGHTNESS:
- if (command instanceof PercentType) {
- Float percent = ((PercentType) command).floatValue();
+ if (command instanceof PercentType percentCommand) {
+ Float percent = percentCommand.floatValue();
setBrightness(percent.intValue()); // 0..100% = 0..100
refreshInfo = true;
- } else if (command instanceof DecimalType) {
- setBrightness(((DecimalType) command).intValue());
+ } else if (command instanceof DecimalType decimalCommand) {
+ setBrightness(decimalCommand.intValue());
refreshInfo = true;
}
break;
case CHANNEL_COLOR_TEMP:
- if (command instanceof DecimalType) {
- setColorTemp(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ setColorTemp(decimalCommand.intValue());
refreshInfo = true;
}
break;
case CHANNEL_COLOR:
- if (command instanceof HSBType) {
- setColor((HSBType) command);
+ if (command instanceof HSBType hsbCommand) {
+ setColor(hsbCommand);
refreshInfo = true;
}
break;
*
* @param responseBody
*/
+ @Override
public void responsePasstrough(String responseBody) {
logger.debug("({}) received response {}", uid, responseBody);
publishState(getChannelID(CHANNEL_GROUP_DEBUG, CHANNEL_RESPONSE), getStringType(responseBody));
* @param channelID String channelID
* @return String channel-name
*/
+ @Override
protected String getChannelFromID(ChannelUID channelID) {
String channel = channelID.getIdWithoutGroup();
channel = channel.replace(CHANNEL_GROUP_ACTUATOR + "#", "");
* @param value parameter value (typeOf Bool,Number or String)
*/
public void addParameter(String name, Object value) {
- if (value instanceof Boolean) {
- this.parameters.addProperty(name, (Boolean) value);
- } else if (value instanceof Number) {
- this.parameters.addProperty(name, (Number) value);
+ if (value instanceof Boolean bool) {
+ this.parameters.addProperty(name, bool);
+ } else if (value instanceof Number number) {
+ this.parameters.addProperty(name, number);
} else {
this.parameters.addProperty(name, value.toString());
}
*/
public static String formatMac(String mac, char newDivisionChar) {
String unformatedMac = unformatMac(mac);
- String formatedMac = unformatedMac.replaceAll("(.{2})", "$1" + newDivisionChar).substring(0, 17);
- return formatedMac;
+ return unformatedMac.replaceAll("(.{2})", "$1" + newDivisionChar).substring(0, 17);
}
/**
private Boolean custom = false;
private Integer brightness = 0;
private Integer[] colorTempRange = { 9000, 9000 }; // :[9000,9000]
- private Color displayColors[] = { Color.WHITE };
+ private Color[] displayColors = { Color.WHITE };
private JsonObject jsonObject = new JsonObject();
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof TapoBridgeHandler) {
- TapoBridgeHandler tapoBridge = (TapoBridgeHandler) handler;
+ if (handler instanceof TapoBridgeHandler tapoBridge) {
tapoBridge.setDiscoveryService(this);
this.bridge = tapoBridge;
}
package org.openhab.binding.tapocontrol.internal.device;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
*/
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(TapoDiscoveryService.class);
+ return Set.of(TapoDiscoveryService.class);
}
/**
refreshInfo = true;
break;
case CHANNEL_BRIGHTNESS:
- if (command instanceof PercentType) {
- Float percent = ((PercentType) command).floatValue();
+ if (command instanceof PercentType percentCommand) {
+ Float percent = percentCommand.floatValue();
setBrightness(percent.intValue()); // 0..100% = 0..100
refreshInfo = true;
- } else if (command instanceof DecimalType) {
- setBrightness(((DecimalType) command).intValue());
+ } else if (command instanceof DecimalType decimalCommand) {
+ setBrightness(decimalCommand.intValue());
refreshInfo = true;
}
break;
case CHANNEL_COLOR_TEMP:
- if (command instanceof DecimalType) {
- setColorTemp(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ setColorTemp(decimalCommand.intValue());
refreshInfo = true;
}
break;
case CHANNEL_COLOR:
- if (command instanceof HSBType) {
- setColor((HSBType) command);
+ if (command instanceof HSBType hsbCommand) {
+ setColor(hsbCommand);
refreshInfo = true;
}
break;
*
* @param responseBody
*/
+ @Override
public void responsePasstrough(String responseBody) {
logger.info("({}) received response {}", uid, responseBody);
publishState(getChannelID(CHANNEL_GROUP_DEBUG, CHANNEL_RESPONSE), getStringType(responseBody));
* @param channelID String channelID
* @return String channel-name
*/
+ @Override
protected String getChannelFromID(ChannelUID channelID) {
String channel = channelID.getIdWithoutGroup();
channel = channel.replace(CHANNEL_GROUP_ACTUATOR + "#", "");
private Integer custom = 0;
private Integer brightness = 0;
private Integer[] colorTempRange = { 9000, 9000 }; // :[9000,9000]
- private Color displayColors[] = { Color.WHITE };
+ private Color[] displayColors = { Color.WHITE };
private JsonObject jsonObject = new JsonObject();
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.List;
import java.util.Map;
import java.util.Objects;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(TelegramActions.class);
+ return Set.of(TelegramActions.class);
}
/**
import static org.openhab.binding.telegram.internal.TelegramBindingConstants.TELEGRAM_THING;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.telegram", service = ThingHandlerFactory.class)
public class TelegramHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(TELEGRAM_THING);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(TELEGRAM_THING);
private final HttpClient httpClient;
public static boolean sendTelegramAnswer(ThingActions actions, @Nullable String chatId, @Nullable String replyId,
@Nullable String message) {
- if (actions instanceof TelegramActions) {
+ if (actions instanceof TelegramActions telegramActions) {
if (chatId == null) {
return false;
}
- return ((TelegramActions) actions).sendTelegramAnswer(Long.valueOf(chatId), replyId, message);
+ return telegramActions.sendTelegramAnswer(Long.valueOf(chatId), replyId, message);
} else {
throw new IllegalArgumentException("Actions is not an instance of TelegramActions");
}
public static boolean sendTelegramAnswer(ThingActions actions, @Nullable String chatId, @Nullable String callbackId,
@Nullable String messageId, @Nullable String message) {
- if (actions instanceof TelegramActions) {
+ if (actions instanceof TelegramActions telegramActions) {
if (chatId == null) {
return false;
}
- return ((TelegramActions) actions).sendTelegramAnswer(Long.valueOf(chatId), callbackId,
+ return telegramActions.sendTelegramAnswer(Long.valueOf(chatId), callbackId,
messageId != null ? Long.parseLong(messageId) : null, message);
} else {
throw new IllegalArgumentException("Actions is not an instance of TelegramActions");
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof TeleinfoAbstractControllerHandler) {
- controllerHandler = (TeleinfoAbstractControllerHandler) handler;
+ if (handler instanceof TeleinfoAbstractControllerHandler teleinfoAbstractControllerHandler) {
+ controllerHandler = teleinfoAbstractControllerHandler;
}
}
package org.openhab.binding.teleinfo.internal.handler;
import java.util.Collection;
-import java.util.Collections;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(TeleinfoDiscoveryService.class);
+ return Set.of(TeleinfoDiscoveryService.class);
}
}
@Override
protected void removeHandler(ThingHandler thingHandler) {
- if (thingHandler instanceof TelldusBridgeHandler) {
- unregisterDeviceDiscoveryService((TelldusBridgeHandler) thingHandler);
+ if (thingHandler instanceof TelldusBridgeHandler telldusBridgeHandler) {
+ unregisterDeviceDiscoveryService(telldusBridgeHandler);
}
}
}
turnOn(device);
} else if (command == OnOffType.OFF) {
turnOff(device);
- } else if (command instanceof PercentType) {
- dim(device, (PercentType) command);
- } else if (command instanceof IncreaseDecreaseType) {
- increaseDecrease(device, ((IncreaseDecreaseType) command));
+ } else if (command instanceof PercentType percentCommand) {
+ dim(device, percentCommand);
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ increaseDecrease(device, increaseDecreaseCommand);
}
} else if (device instanceof SwitchableDevice) {
if (command == OnOffType.ON) {
double value = command.doubleValue();
// 0 means OFF and 100 means ON
- if (value == 0 && dev instanceof SwitchableDevice) {
- ((SwitchableDevice) dev).off();
- } else if (value == 100 && dev instanceof SwitchableDevice) {
- ((SwitchableDevice) dev).on();
- } else if (dev instanceof DimmableDevice) {
+ if (value == 0 && dev instanceof SwitchableDevice device) {
+ device.off();
+ } else if (value == 100 && dev instanceof SwitchableDevice device) {
+ device.on();
+ } else if (dev instanceof DimmableDevice device) {
long tdVal = Math.round((value / 100) * 255);
- ((DimmableDevice) dev).dim((int) tdVal);
+ device.dim((int) tdVal);
} else {
throw new TelldusBindingException("Cannot send DIM to " + dev);
}
}
private void turnOff(Device dev) throws TellstickException {
- if (dev instanceof SwitchableDevice) {
- ((SwitchableDevice) dev).off();
+ if (dev instanceof SwitchableDevice device) {
+ device.off();
} else {
throw new TelldusBindingException("Cannot send OFF to " + dev);
}
}
private void turnOn(Device dev) throws TellstickException {
- if (dev instanceof SwitchableDevice) {
- ((SwitchableDevice) dev).on();
+ if (dev instanceof SwitchableDevice device) {
+ device.on();
} else {
throw new TelldusBindingException("Cannot send ON to " + dev);
}
} else if (device instanceof SwitchableDevice) {
thingUID = new ThingUID(TellstickBindingConstants.SWITCH_THING_TYPE, bridge.getUID(),
device.getUUId());
- } else if (device instanceof TellstickNetDevice) {
- if ((((TellstickNetDevice) device).getMethods() & JNA.CLibrary.TELLSTICK_DIM) > 0) {
+ } else if (device instanceof TellstickNetDevice netDevice) {
+ if ((netDevice.getMethods() & JNA.CLibrary.TELLSTICK_DIM) > 0) {
thingUID = new ThingUID(TellstickBindingConstants.DIMMER_THING_TYPE, bridge.getUID(),
device.getUUId());
} else {
thingUID = new ThingUID(TellstickBindingConstants.SWITCH_THING_TYPE, bridge.getUID(),
device.getUUId());
}
- } else if (device instanceof TellstickLocalDeviceDTO) {
- if ((((TellstickLocalDeviceDTO) device).getMethods() & JNA.CLibrary.TELLSTICK_DIM) > 0) {
+ } else if (device instanceof TellstickLocalDeviceDTO localDevice) {
+ if ((localDevice.getMethods() & JNA.CLibrary.TELLSTICK_DIM) > 0) {
thingUID = new ThingUID(TellstickBindingConstants.DIMMER_THING_TYPE, bridge.getUID(),
device.getUUId());
} else {
private ThingTypeUID findSensorType(Device device) {
logger.debug("Device: {}", device);
ThingTypeUID sensorThingId;
- if (device instanceof TellstickSensor) {
- TellstickSensor sensor = (TellstickSensor) device;
+ if (device instanceof TellstickSensor sensor) {
logger.debug("Sensor: {}", device);
if (sensor.getData(DataType.WINDAVERAGE) != null || sensor.getData(DataType.WINDGUST) != null
|| sensor.getData(DataType.WINDDIRECTION) != null) {
} else {
sensorThingId = TellstickBindingConstants.SENSOR_THING_TYPE;
}
- } else if (device instanceof TellstickNetSensor) {
- TellstickNetSensor sensor = (TellstickNetSensor) device;
+ } else if (device instanceof TellstickNetSensor sensor) {
if (sensor.isSensorOfType(LiveDataType.WINDAVERAGE) || sensor.isSensorOfType(LiveDataType.WINDDIRECTION)
|| sensor.isSensorOfType(LiveDataType.WINDGUST)) {
sensorThingId = TellstickBindingConstants.WINDSENSOR_THING_TYPE;
}
private boolean isSensor() {
- return (getThing().getThingTypeUID().equals(TellstickBindingConstants.SENSOR_THING_TYPE)
+ return getThing().getThingTypeUID().equals(TellstickBindingConstants.SENSOR_THING_TYPE)
|| getThing().getThingTypeUID().equals(TellstickBindingConstants.RAINSENSOR_THING_TYPE)
|| getThing().getThingTypeUID().equals(TellstickBindingConstants.WINDSENSOR_THING_TYPE)
- || getThing().getThingTypeUID().equals(TellstickBindingConstants.POWERSENSOR_THING_TYPE));
+ || getThing().getThingTypeUID().equals(TellstickBindingConstants.POWERSENSOR_THING_TYPE);
}
private void updateSensorStates(Device dev) {
- if (dev instanceof TellstickSensor) {
+ if (dev instanceof TellstickSensor sensor) {
updateStatus(ThingStatus.ONLINE);
- for (DataType type : ((TellstickSensor) dev).getData().keySet()) {
- updateSensorDataState(type, ((TellstickSensor) dev).getData(type));
+ for (DataType type : sensor.getData().keySet()) {
+ updateSensorDataState(type, sensor.getData(type));
}
- } else if (dev instanceof TellstickNetSensor) {
- if (((TellstickNetSensor) dev).getOnline()) {
+ } else if (dev instanceof TellstickNetSensor netSensor) {
+ if (netSensor.getOnline()) {
updateStatus(ThingStatus.ONLINE);
} else {
updateStatus(ThingStatus.OFFLINE);
}
- for (DataTypeValue type : ((TellstickNetSensor) dev).getData()) {
+ for (DataTypeValue type : netSensor.getData()) {
updateSensorDataState(type);
}
- } else if (dev instanceof TellstickLocalSensorDTO) {
- for (LocalDataTypeValueDTO type : ((TellstickLocalSensorDTO) dev).getData()) {
+ } else if (dev instanceof TellstickLocalSensorDTO localSensor) {
+ for (LocalDataTypeValueDTO type : localSensor.getData()) {
updateSensorDataState(type);
}
}
if (device.getUUId().equals(deviceId)) {
if (event instanceof TellstickDeviceEvent) {
updateDeviceState(device);
- } else if (event instanceof TellstickNetSensorEvent) {
- TellstickNetSensorEvent sensorevent = (TellstickNetSensorEvent) event;
+ } else if (event instanceof TellstickNetSensorEvent sensorevent) {
updateSensorDataState(sensorevent.getDataTypeValue());
- } else if (event instanceof TellstickLocalSensorEventDTO) {
- TellstickLocalSensorEventDTO sensorevent = (TellstickLocalSensorEventDTO) event;
+ } else if (event instanceof TellstickLocalSensorEventDTO sensorevent) {
updateSensorDataState(sensorevent.getDataTypeValue());
- } else if (event instanceof TellstickSensorEvent) {
- TellstickSensorEvent sensorevent = (TellstickSensorEvent) event;
+ } else if (event instanceof TellstickSensorEvent sensorevent) {
updateSensorDataState(sensorevent.getDataType(), sensorevent.getData());
} else {
logger.debug("Unhandled Device {}.", device.getDeviceType());
new QuantityType<>(new BigDecimal(dataType.getValue()), WIND_SPEED_UNIT_MS));
break;
case WATT:
- if (dataType.getUnit() != null && dataType.getUnit().equals("A")) {
+ if ("A".equals(dataType.getUnit())) {
updateState(ampereChannel, new QuantityType<>(new BigDecimal(dataType.getValue()), ELECTRIC_UNIT));
} else {
updateState(wattChannel, new QuantityType<>(new BigDecimal(dataType.getValue()), POWER_UNIT));
turnOn(device);
} else if (command == OnOffType.OFF) {
turnOff(device);
- } else if (command instanceof PercentType) {
- dim(device, (PercentType) command);
- } else if (command instanceof IncreaseDecreaseType) {
- increaseDecrease(device, ((IncreaseDecreaseType) command));
+ } else if (command instanceof PercentType percentCommand) {
+ dim(device, percentCommand);
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ increaseDecrease(device, increaseDecreaseCommand);
}
} else if (device instanceof SwitchableDevice) {
if (command == OnOffType.ON) {
turnOff(dev);
} else if (value == 100 && dev instanceof TellstickNetDevice) {
turnOn(dev);
- } else if (dev instanceof TellstickNetDevice
- && (((TellstickNetDevice) dev).getMethods() & JNA.CLibrary.TELLSTICK_DIM) > 0) {
+ } else if (dev instanceof TellstickNetDevice device && (device.getMethods() & JNA.CLibrary.TELLSTICK_DIM) > 0) {
long tdVal = Math.round((value / 100) * 255);
TelldusLiveResponse response = callRestMethod(String.format(HTTP_TELLDUS_DEVICE_DIM, dev.getId(), tdVal),
TelldusLiveResponse.class);
- handleResponse((TellstickNetDevice) dev, response);
+ handleResponse(device, response);
} else {
throw new TelldusBindingException("Cannot send DIM to " + dev);
}
}
private void turnOff(Device dev) throws TellstickException {
- if (dev instanceof TellstickNetDevice) {
+ if (dev instanceof TellstickNetDevice device) {
TelldusLiveResponse response = callRestMethod(String.format(HTTP_TELLDUS_DEVICE_TURNOFF, dev.getId()),
TelldusLiveResponse.class);
- handleResponse((TellstickNetDevice) dev, response);
+ handleResponse(device, response);
} else {
throw new TelldusBindingException("Cannot send OFF to " + dev);
}
if (response == null || (response.status == null && response.error == null)) {
throw new TelldusBindingException("No response " + response);
} else if (response.error != null) {
- if (response.error.equals("The client for this device is currently offline")) {
+ if ("The client for this device is currently offline".equals(response.error)) {
device.setOnline(false);
device.setUpdated(true);
}
throw new TelldusBindingException("Error " + response.error);
- } else if (!response.status.trim().equals("success")) {
+ } else if (!"success".equals(response.status.trim())) {
throw new TelldusBindingException("Response " + response.status);
}
}
private void turnOn(Device dev) throws TellstickException {
- if (dev instanceof TellstickNetDevice) {
+ if (dev instanceof TellstickNetDevice device) {
TelldusLiveResponse response = callRestMethod(String.format(HTTP_TELLDUS_DEVICE_TURNON, dev.getId()),
TelldusLiveResponse.class);
- handleResponse((TellstickNetDevice) dev, response);
+ handleResponse(device, response);
} else {
throw new TelldusBindingException("Cannot send ON to " + dev);
}
turnOn(device);
} else if (command == OnOffType.OFF) {
turnOff(device);
- } else if (command instanceof PercentType) {
- dim(device, (PercentType) command);
- } else if (command instanceof IncreaseDecreaseType) {
- increaseDecrease(device, ((IncreaseDecreaseType) command));
+ } else if (command instanceof PercentType percentCommand) {
+ dim(device, percentCommand);
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ increaseDecrease(device, increaseDecreaseCommand);
}
} else if (device instanceof SwitchableDevice) {
if (command == OnOffType.ON) {
turnOff(dev);
} else if (value == 100 && dev instanceof TellstickLocalDeviceDTO) {
turnOn(dev);
- } else if (dev instanceof TellstickLocalDeviceDTO
- && (((TellstickLocalDeviceDTO) dev).getMethods() & JNA.CLibrary.TELLSTICK_DIM) > 0) {
+ } else if (dev instanceof TellstickLocalDeviceDTO device
+ && (device.getMethods() & JNA.CLibrary.TELLSTICK_DIM) > 0) {
long tdVal = Math.round((value / 100) * 255);
TelldusLocalResponseDTO response = callRestMethod(
String.format(HTTP_LOCAL_API_DEVICE_DIM, dev.getId(), tdVal), TelldusLocalResponseDTO.class);
- handleResponse((TellstickLocalDeviceDTO) dev, response);
+ handleResponse(device, response);
} else {
throw new TelldusBindingException("Cannot send DIM to " + dev);
}
}
private void turnOff(Device dev) throws TellstickException, InterruptedException {
- if (dev instanceof TellstickLocalDeviceDTO) {
+ if (dev instanceof TellstickLocalDeviceDTO device) {
TelldusLocalResponseDTO response = callRestMethod(String.format(HTTP_LOCAL_API_DEVICE_TURNOFF, dev.getId()),
TelldusLocalResponseDTO.class);
- handleResponse((TellstickLocalDeviceDTO) dev, response);
+ handleResponse(device, response);
} else {
throw new TelldusBindingException("Cannot send OFF to " + dev);
}
} else if (response.getError() != null) {
device.setUpdated(true);
throw new TelldusBindingException("Error " + response.getError());
- } else if (!response.getStatus().trim().equals("success")) {
+ } else if (!"success".equals(response.getStatus().trim())) {
throw new TelldusBindingException("Response " + response.getStatus());
}
}
private void turnOn(Device dev) throws TellstickException, InterruptedException {
- if (dev instanceof TellstickLocalDeviceDTO) {
+ if (dev instanceof TellstickLocalDeviceDTO device) {
TelldusLocalResponseDTO response = callRestMethod(String.format(HTTP_LOCAL_DEVICE_TURNON, dev.getId()),
TelldusLocalResponseDTO.class);
- handleResponse((TellstickLocalDeviceDTO) dev, response);
+ handleResponse(device, response);
} else {
throw new TelldusBindingException("Cannot send ON to " + dev);
}
VEHICLE_NAME("vehicle_name", "name", StringType.class, true) {
@Override
public State getState(String s, TeslaChannelSelectorProxy proxy, Map<String, String> properties) {
- return super.getState(s.replaceAll("\"", ""));
+ return super.getState(s.replace("\"", ""));
}
},
VALET_MODE("valet_mode", "valetmode", OnOffType.class, false) {
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singletonList(TeslaVehicleDiscoveryService.class);
+ return List.of(TeslaVehicleDiscoveryService.class);
}
}
try {
switch (selector) {
case CHARGE_LIMIT_SOC: {
- if (command instanceof PercentType) {
- setChargeLimit(((PercentType) command).intValue());
+ if (command instanceof PercentType percentCommand) {
+ setChargeLimit(percentCommand.intValue());
} else if (command instanceof OnOffType && command == OnOffType.ON) {
setChargeLimit(100);
} else if (command instanceof OnOffType && command == OnOffType.OFF) {
}
case CHARGE_AMPS:
Integer amps = null;
- if (command instanceof DecimalType) {
- amps = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ amps = decimalCommand.intValue();
}
- if (command instanceof QuantityType<?>) {
- QuantityType<?> qamps = ((QuantityType<?>) command).toUnit(Units.AMPERE);
+ if (command instanceof QuantityType<?> quantityCommand) {
+ QuantityType<?> qamps = quantityCommand.toUnit(Units.AMPERE);
if (qamps != null) {
amps = qamps.intValue();
}
break;
}
case CHARGE_TO_MAX: {
- if (command instanceof OnOffType) {
- if (((OnOffType) command) == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
setMaxRangeCharging(true);
} else {
setMaxRangeCharging(false);
break;
}
case CHARGE: {
- if (command instanceof OnOffType) {
- if (((OnOffType) command) == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
charge(true);
} else {
charge(false);
break;
}
case FLASH: {
- if (command instanceof OnOffType) {
- if (((OnOffType) command) == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
flashLights();
}
}
break;
}
case HONK_HORN: {
- if (command instanceof OnOffType) {
- if (((OnOffType) command) == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
honkHorn();
}
}
break;
}
case CHARGEPORT: {
- if (command instanceof OnOffType) {
- if (((OnOffType) command) == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
openChargePort();
}
}
break;
}
case DOOR_LOCK: {
- if (command instanceof OnOffType) {
- if (((OnOffType) command) == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
lockDoors(true);
} else {
lockDoors(false);
break;
}
case AUTO_COND: {
- if (command instanceof OnOffType) {
- if (((OnOffType) command) == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
autoConditioning(true);
} else {
autoConditioning(false);
break;
}
case WAKEUP: {
- if (command instanceof OnOffType) {
- if (((OnOffType) command) == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
wakeUp();
}
}
break;
}
case FT: {
- if (command instanceof OnOffType) {
- if (((OnOffType) command) == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
openFrunk();
}
}
break;
}
case RT: {
- if (command instanceof OnOffType) {
- if (((OnOffType) command) == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
if (vehicleState.rt == 0) {
openTrunk();
}
break;
}
case VALET_MODE: {
- if (command instanceof OnOffType) {
+ if (command instanceof OnOffType onOffCommand) {
int valetpin = ((BigDecimal) getConfig().get(VALETPIN)).intValue();
- if (((OnOffType) command) == OnOffType.ON) {
+ if (onOffCommand == OnOffType.ON) {
setValetMode(true, valetpin);
} else {
setValetMode(false, valetpin);
break;
}
case RESET_VALET_PIN: {
- if (command instanceof OnOffType) {
- if (((OnOffType) command) == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
resetValetPin();
}
}
break;
}
case STEERINGWHEEL_HEATER: {
- if (command instanceof OnOffType) {
- boolean commandBooleanValue = ((OnOffType) command) == OnOffType.ON ? true : false;
+ if (command instanceof OnOffType onOffCommand) {
+ boolean commandBooleanValue = onOffCommand == OnOffType.ON ? true : false;
setSteeringWheelHeater(commandBooleanValue);
}
break;
case "data:update":
logger.debug("Event : Received an update: '{}'", event.value);
- String vals[] = event.value.split(",");
+ String[] vals = event.value.split(",");
long currentTimeStamp = Long.parseLong(vals[0]);
long systemTimeStamp = System.currentTimeMillis();
if (logger.isDebugEnabled()) {
public String option_codes;
public String vehicle_id;
public String vin;
- public String tokens[];
+ public String[] tokens;
public String state;
public boolean remote_start_enabled;
public boolean calendar_enabled;
public String option_codes;
public String vehicle_id;
public String vin;
- public String tokens[];
+ public String[] tokens;
public String state;
public boolean remote_start_enabled;
public boolean calendar_enabled;
import static org.openhab.binding.tivo.internal.TiVoBindingConstants.THING_TYPE_TIVO;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@NonNullByDefault
@Component(configurationPid = "binding.tivo", service = ThingHandlerFactory.class)
public class TiVoHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_TIVO);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_TIVO);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
import static org.openhab.binding.tivo.internal.TiVoBindingConstants.*;
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_TIVO);
+ return Set.of(THING_TYPE_TIVO);
}
@Override
// Handles the commands from the various TiVo channel objects
logger.debug("handleCommand '{}', parameter: {}", channelUID, command);
- if (!isInitialized() || !tivoConnection.isPresent()) {
+ if (!isInitialized() || tivoConnection.isEmpty()) {
logger.debug("handleCommand '{}' device is not initialized yet, command '{}' will be ignored.",
getThing().getUID(), channelUID + " " + command);
return;
private void sendCommand(String commandKeyword, String commandParameter, TivoStatusData currentStatus)
throws InterruptedException {
- if (!tivoConnection.isPresent()) {
+ if (tivoConnection.isEmpty()) {
return;
}
}
} catch (NumberFormatException e) {
- logger.warn("TiVo'{}' unable to parse channel integer, value sent was: '{}'", getThing().getUID(),
- command.toString());
+ logger.warn("TiVo'{}' unable to parse channel integer, value sent was: '{}'", getThing().getUID(), command);
}
return tmpStatus;
}
UNKNOWN,
OFFLINE,
STANDBY,
- ONLINE;
+ ONLINE
}
/**
}
for (int i = 1; i <= repeatCount; i++) {
// Send the command
- streamWriter.println(tivoCommand.toString() + "\r");
+ streamWriter.println(tivoCommand + "\r");
if (streamWriter.checkError()) {
logger.debug("TiVo '{}' - called cmdTivoSend and encountered an IO error",
tivoConfigData.getCfgIdentifier());
@Override
void updateTouchWandUnitState(TouchWandUnitData unitData) {
- if (unitData instanceof TouchWandUnitDataAlarmSensor) {
- TouchWandUnitDataAlarmSensor sensor = (TouchWandUnitDataAlarmSensor) unitData;
+ if (unitData instanceof TouchWandUnitDataAlarmSensor sensor) {
if (isFirstUpdateTouchWandUnitState) {
removeUnsupportedChannels(sensor);
isFirstUpdateTouchWandUnitState = false;
@Override
void updateTouchWandUnitState(TouchWandUnitData unitData) {
- if (unitData instanceof TouchWandBSensorUnitData) {
+ if (unitData instanceof TouchWandBSensorUnitData bSensorUnitData) {
if (isFirstUpdateTouchWandUnitState) {
- removeUnsupportedChannels((TouchWandBSensorUnitData) unitData);
+ removeUnsupportedChannels(bSensorUnitData);
isFirstUpdateTouchWandUnitState = false;
}
- String sensorSubType = ((TouchWandBSensorUnitData) unitData).getIdData().getSubType();
+ String sensorSubType = bSensorUnitData.getIdData().getSubType();
switch (sensorSubType) {
case BSENSOR_SUBTYPE_DOORWINDOW:
- updateChannelDoorWindow((TouchWandBSensorUnitData) unitData);
+ updateChannelDoorWindow(bSensorUnitData);
break;
case BSENSOR_SUBTYPE_MOTION:
- updateChannelMotion((TouchWandBSensorUnitData) unitData);
+ updateChannelMotion(bSensorUnitData);
break;
case BSENSOR_SUBTYPE_SMOKE:
- updateChannelSmoke((TouchWandBSensorUnitData) unitData);
+ updateChannelSmoke(bSensorUnitData);
break;
default:
}
@Override
public void onItemStatusUpdate(TouchWandUnitData unitData) {
- if (unitData.getStatus().equals("ALIVE")) {
+ if ("ALIVE".equals(unitData.getStatus())) {
updateStatus(ThingStatus.ONLINE);
} else {
// updateStatus(ThingStatus.OFFLINE); // comment - OFFLINE status is not accurate at the moment
import static org.openhab.binding.touchwand.internal.TouchWandBindingConstants.THING_TYPE_BRIDGE;
import java.util.Collection;
-import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
*/
@NonNullByDefault
public class TouchWandBridgeHandler extends BaseBridgeHandler implements TouchWandUnitStatusUpdateListener {
- 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 final Logger logger = LoggerFactory.getLogger(TouchWandBridgeHandler.class);
private boolean addSecondaryUnits;
private @Nullable TouchWandWebSockets touchWandWebSockets;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(TouchWandUnitDiscoveryService.class);
+ return Set.of(TouchWandUnitDiscoveryService.class);
}
}
void touchWandUnitHandleCommand(Command command) {
TouchWandBridgeHandler touchWandBridgeHandler = bridgeHandler;
if (touchWandBridgeHandler != null) {
- if (command instanceof OnOffType) {
- touchWandBridgeHandler.touchWandClient.cmdSwitchOnOff(unitId, (OnOffType) command);
+ if (command instanceof OnOffType onOffCommand) {
+ touchWandBridgeHandler.touchWandClient.cmdSwitchOnOff(unitId, onOffCommand);
} else {
touchWandBridgeHandler.touchWandClient.cmdDimmerPosition(unitId, command.toString());
}
@Override
void updateTouchWandUnitState(TouchWandUnitData unitData) {
- if (unitData instanceof TouchWandShutterSwitchUnitData) {
- int status = ((TouchWandShutterSwitchUnitData) unitData).getCurrStatus();
+ if (unitData instanceof TouchWandShutterSwitchUnitData shutterSwitchUnitData) {
+ int status = shutterSwitchUnitData.getCurrStatus();
PercentType state = PercentType.ZERO;
int convertStatus = status;
state = new PercentType(convertStatus);
}
private String buildUrl(String command) {
- String url = "http://" + touchWandIpAddr + ":" + touchWandPort + COMMAND_MAP.get(command);
- return url;
+ return "http://" + touchWandIpAddr + ":" + touchWandPort + COMMAND_MAP.get(command);
}
private synchronized String sendCommand(String command, HttpMethod method, String content) {
@Override
void updateTouchWandUnitState(TouchWandUnitData unitData) {
- if (unitData instanceof TouchWandShutterSwitchUnitData) {
- int status = ((TouchWandShutterSwitchUnitData) unitData).getCurrStatus();
+ if (unitData instanceof TouchWandShutterSwitchUnitData shutterSwitchUnitData) {
+ int status = shutterSwitchUnitData.getCurrStatus();
PercentType state = PercentType.ZERO;
int convertStatus = 100 - status;
state = new PercentType(convertStatus);
@Override
void updateTouchWandUnitState(TouchWandUnitData unitData) {
- if (unitData instanceof TouchWandShutterSwitchUnitData) {
+ if (unitData instanceof TouchWandShutterSwitchUnitData shutterSwitchUnitData) {
OnOffType state;
- int status = ((TouchWandShutterSwitchUnitData) unitData).getCurrStatus();
+ int status = shutterSwitchUnitData.getCurrStatus();
String sStatus = Integer.toString(status);
if (sStatus.equals(SWITCH_STATUS_OFF)) {
@Override
void touchWandUnitHandleCommand(Command command) {
- if (command instanceof OnOffType) {
+ if (command instanceof OnOffType onOffCommand) {
TouchWandBridgeHandler touchWandBridgeHandler = bridgeHandler;
if (touchWandBridgeHandler != null) {
- touchWandBridgeHandler.touchWandClient.cmdSwitchOnOff(unitId, (OnOffType) command);
+ touchWandBridgeHandler.touchWandClient.cmdSwitchOnOff(unitId, onOffCommand);
}
}
}
@Override
void updateTouchWandUnitState(TouchWandUnitData unitData) {
- if (unitData instanceof TouchWandThermostatUnitData) {
- TouchWandThermostatUnitData thermostat = (TouchWandThermostatUnitData) unitData;
+ if (unitData instanceof TouchWandThermostatUnitData thermostat) {
updateThermostatState(thermostat);
updateTargetTemperature(thermostat);
updateRoomTemperature(thermostat);
void touchWandUnitHandleCommand(Command command) {
TouchWandBridgeHandler touchWandBridgeHandler = bridgeHandler;
if (touchWandBridgeHandler != null) {
- if (command instanceof OnOffType) {
- touchWandBridgeHandler.touchWandClient.cmdThermostatOnOff(unitId, (OnOffType) command);
+ if (command instanceof OnOffType onOffCommand) {
+ touchWandBridgeHandler.touchWandClient.cmdThermostatOnOff(unitId, onOffCommand);
return;
}
- if (command instanceof QuantityType) {
- final QuantityType<?> value = ((QuantityType<?>) command).toUnit(SIUnits.CELSIUS);
+ if (command instanceof QuantityType quantityCommand) {
+ final QuantityType<?> value = quantityCommand.toUnit(SIUnits.CELSIUS);
String targetTemperature = String.valueOf(value.intValue());
touchWandBridgeHandler.touchWandClient.cmdThermostatTargetTemperature(unitId, targetTemperature);
return;
@Override
void updateTouchWandUnitState(TouchWandUnitData unitData) {
- if (unitData instanceof TouchWandUnitDataWallController) {
- Csc status = ((TouchWandUnitDataWallController) unitData).getCurrStatus();
+ if (unitData instanceof TouchWandUnitDataWallController unitDataWallController) {
+ Csc status = unitDataWallController.getCurrStatus();
long ts = status.getTs();
long timeDiff = ts - timeLastEventMs;
if ((timeDiff) > ADJACENT_EVENT_FILTER_TIME_MILLISEC) {
public void connect() {
try {
- uri = new URI("ws://" + controllerAddress + ":" + String.valueOf(port) + WS_ENDPOINT_TOUCHWAND);
+ uri = new URI("ws://" + controllerAddress + ":" + port + WS_ENDPOINT_TOUCHWAND);
} catch (URISyntaxException e) {
logger.warn("URI not valid {} message {}", uri, e.getMessage());
return;
TouchWandUnitData touchWandUnit;
try {
JsonObject unitObj = JsonParser.parseString(msg).getAsJsonObject();
- boolean eventUnitChanged = unitObj.get("type").getAsString().equals("UNIT_CHANGED");
+ boolean eventUnitChanged = "UNIT_CHANGED".equals(unitObj.get("type").getAsString());
if (!eventUnitChanged) {
return;
}
touchWandUnit = TouchWandUnitFromJson.parseResponse(unitObj.get("unit").getAsJsonObject());
- if (!touchWandUnit.getStatus().equals("ALIVE")) {
+ if (!"ALIVE".equals(touchWandUnit.getStatus())) {
logger.debug("UNIT_CHANGED unit status not ALIVE : {}", touchWandUnit.getStatus());
}
boolean supportedUnitType = Arrays.asList(SUPPORTED_TOUCHWAND_TYPES).contains(touchWandUnit.getType());
}
private void addDeviceDiscoveryResult(String label, String ip) {
- String id = ip.replaceAll("\\.", "");
+ String id = ip.replace(".", "");
ThingUID thingUID = new ThingUID(THING_TYPE_BRIDGE, id);
Map<String, Object> properties = new HashMap<>();
properties.put("label", label);
String sentence = new String(dgram.getData(), 0, dgram.getLength(), StandardCharsets.US_ASCII);
JsonObject bridge = JsonParser.parseString(sentence).getAsJsonObject();//
String name = bridge.get("name").getAsString();
- addDeviceDiscoveryResult(name, address.getHostAddress().toString());
+ addDeviceDiscoveryResult(name, address.getHostAddress());
logger.debug("Received Datagram from {}:{} on Port {} message {}", address.getHostAddress(),
dgram.getPort(), mySocket.getLocalPort(), sentence);
}
@Override
public void setThingHandler(@NonNullByDefault({}) ThingHandler handler) {
- if (handler instanceof TouchWandBridgeHandler) {
- touchWandBridgeHandler = (TouchWandBridgeHandler) handler;
+ if (handler instanceof TouchWandBridgeHandler touchWandBridgeHandler) {
+ this.touchWandBridgeHandler = touchWandBridgeHandler;
}
}
for (Entry<String, JsonElement> entry : currentStatusObj.entrySet()) {
String key = entry.getKey();
- String splits[] = key.split("_"); // the key is xxxx_n where xxx is sensor type and n is
+ String[] splits = key.split("_"); // the key is xxxx_n where xxx is sensor type and n is
String keyName = splits[0];
int index = 0;
final int transitionPeriod = configuration.transitionPeriod;
final HasErrorResponse response;
- if (command instanceof OnOffType && CHANNELS_BULB_SWITCH.contains(channelId)) {
- response = handleOnOffType(channelId, (OnOffType) command, transitionPeriod);
- } else if (command instanceof HSBType && CHANNEL_COLOR.equals(channelId)) {
- response = handleHSBType(channelId, (HSBType) command, transitionPeriod);
- } else if (command instanceof DecimalType) {
- response = handleDecimalType(channelId, (DecimalType) command, transitionPeriod);
+ if (command instanceof OnOffType onOffCommand && CHANNELS_BULB_SWITCH.contains(channelId)) {
+ response = handleOnOffType(channelId, onOffCommand, transitionPeriod);
+ } else if (command instanceof HSBType hsbCommand && CHANNEL_COLOR.equals(channelId)) {
+ response = handleHSBType(channelId, hsbCommand, transitionPeriod);
+ } else if (command instanceof DecimalType decimalCommand) {
+ response = handleDecimalType(channelId, decimalCommand, transitionPeriod);
} else {
return false;
}
private boolean handleBrightnessChannel(ChannelUID channelUid, Command command) throws IOException {
HasErrorResponse response = null;
- if (command instanceof OnOffType) {
- response = setOnOffState(channelUid, (OnOffType) command);
- } else if (command instanceof PercentType) {
- PercentType percentCommand = (PercentType) command;
-
+ if (command instanceof OnOffType onOffCommand) {
+ response = setOnOffState(channelUid, onOffCommand);
+ } else if (command instanceof PercentType percentCommand) {
// Don't send value 0 as brightness value as it will give an error from the device.
if (percentCommand.intValue() > 0) {
response = commands.setDimmerBrightnessResponse(
@Override
public boolean handleCommand(ChannelUID channelUid, Command command) throws IOException {
- return command instanceof OnOffType && handleOnOffType(channelUid, (OnOffType) command);
+ return command instanceof OnOffType onOffCommand && handleOnOffType(channelUid, onOffCommand);
}
/**
@Override
public void setThingHandler(final ThingHandler handler) {
- if (handler instanceof SmartHomeHandler) {
- this.handler = (SmartHomeHandler) handler;
+ if (handler instanceof SmartHomeHandler smartHomeHandler) {
+ this.handler = smartHomeHandler;
}
}
Optional<SCPDServiceType> scpdService = scpdUtil.getDevice("")
.flatMap(deviceType -> deviceType.getServiceList().stream().filter(
- service -> service.getServiceId().equals("urn:DeviceConfig-com:serviceId:DeviceConfig1"))
+ service -> "urn:DeviceConfig-com:serviceId:DeviceConfig1".equals(service.getServiceId()))
.findFirst());
if (scpdService.isEmpty()) {
logger.warn("Could not get service.");
@Override
public void setThingHandler(ThingHandler thingHandler) {
- if (thingHandler instanceof Tr064RootHandler) {
- this.bridgeHandler = (Tr064RootHandler) thingHandler;
+ if (thingHandler instanceof Tr064RootHandler tr064RootHandler) {
+ this.bridgeHandler = tr064RootHandler;
}
}
@Override
protected void removeHandler(ThingHandler thingHandler) {
- if (thingHandler instanceof Tr064RootHandler) {
- phonebookProfileFactory.unregisterPhonebookProvider((Tr064RootHandler) thingHandler);
+ if (thingHandler instanceof Tr064RootHandler tr064RootHandler) {
+ phonebookProfileFactory.unregisterPhonebookProvider(tr064RootHandler);
}
}
}
SCPDDeviceType device = scpdUtil.getDevice("")
.orElseThrow(() -> new SCPDException("Root device not found"));
SCPDServiceType deviceService = device.getServiceList().stream()
- .filter(service -> service.getServiceId().equals("urn:DeviceInfo-com:serviceId:DeviceInfo1"))
+ .filter(service -> "urn:DeviceInfo-com:serviceId:DeviceInfo1".equals(service.getServiceId()))
.findFirst().orElseThrow(() -> new SCPDException(
"service 'urn:DeviceInfo-com:serviceId:DeviceInfo1' not found"));
SCPDActionType getInfoAction = scpdUtil.getService(deviceService.getServiceId())
.orElseThrow(() -> new SCPDException(
"Could not get service definition for 'urn:DeviceInfo-com:serviceId:DeviceInfo1'"))
- .getActionList().stream().filter(action -> action.getName().equals("GetInfo")).findFirst()
+ .getActionList().stream().filter(action -> "GetInfo".equals(action.getName())).findFirst()
.orElseThrow(() -> new SCPDException("Action 'GetInfo' not found"));
SOAPMessage soapResponse1 = soapConnector
.doSOAPRequest(new SOAPRequest(deviceService, getInfoAction.getName()));
phonebookName = UIDUtils.decode(phonebookParams[1]);
}
if (matchCountParam != null) {
- if (matchCountParam instanceof BigDecimal) {
- matchCount = ((BigDecimal) matchCountParam).intValue();
- } else if (matchCountParam instanceof String) {
- matchCount = Integer.parseInt((String) matchCountParam);
+ if (matchCountParam instanceof BigDecimal bigDecimal) {
+ matchCount = bigDecimal.intValue();
+ } else if (matchCountParam instanceof String string) {
+ matchCount = Integer.parseInt(string);
}
}
if (phoneNumberIndexParam != null) {
- if (phoneNumberIndexParam instanceof BigDecimal) {
- phoneNumberIndex = ((BigDecimal) phoneNumberIndexParam).intValue();
- } else if (phoneNumberIndexParam instanceof String) {
- phoneNumberIndex = Integer.parseInt((String) phoneNumberIndexParam);
+ if (phoneNumberIndexParam instanceof BigDecimal bigDecimal) {
+ phoneNumberIndex = bigDecimal.intValue();
+ } else if (phoneNumberIndexParam instanceof String string) {
+ phoneNumberIndex = Integer.parseInt(string);
}
}
} catch (IllegalArgumentException e) {
return soapMessage;
} catch (IllegalArgumentException e) {
Throwable cause = e.getCause();
- if (cause instanceof Tr064CommunicationException) {
- throw (Tr064CommunicationException) cause;
+ if (cause instanceof Tr064CommunicationException tr064CommunicationException) {
+ throw tr064CommunicationException;
} else {
throw e;
}
// we don't have data to send
return Optional.of("");
}
- if (command instanceof QuantityType) {
- QuantityType<?> value = (unit.isEmpty()) ? ((QuantityType<?>) command)
- : ((QuantityType<?>) command).toUnit(unit);
+ if (command instanceof QuantityType quantityCommand) {
+ QuantityType<?> value = (unit.isEmpty()) ? quantityCommand : quantityCommand.toUnit(unit);
if (value == null) {
logger.warn("Could not convert {} to unit {}", command, unit);
return Optional.empty();
default -> {
}
}
- } else if (command instanceof DecimalType) {
- BigDecimal value = ((DecimalType) command).toBigDecimal();
+ } else if (command instanceof DecimalType decimalCommand) {
+ BigDecimal value = decimalCommand.toBigDecimal();
switch (dataType) {
case "ui1", "ui2" -> {
return Optional.of(String.valueOf(value.shortValue()));
// map rawValue to State
switch (dataType) {
case "boolean" -> {
- return rawValue.equals("0") ? OnOffType.OFF : OnOffType.ON;
+ return "0".equals(rawValue) ? OnOffType.OFF : OnOffType.ON;
}
case "string" -> {
return new StringType(rawValue);
Method method = SOAPValueConverter.class.getDeclaredMethod(postProcessor, State.class,
Tr064ChannelConfig.class);
Object o = method.invoke(this, state, channelConfig);
- if (o instanceof State) {
- return (State) o;
+ if (o instanceof State stateInstance) {
+ return stateInstance;
}
} catch (NoSuchMethodException | IllegalAccessException e) {
logger.warn("Postprocessor {} not found, this most likely is a programming error", postProcessor, e);
// get parameters by reflection from thing config
Field paramField = thingConfig.getClass().getField(parameter.getThingParameter());
Object rawFieldValue = paramField.get(thingConfig);
- if ((rawFieldValue instanceof List<?>)) {
- ((List<?>) rawFieldValue).forEach(obj -> {
- if (obj instanceof String) {
- parameters.add((String) obj);
+ if ((rawFieldValue instanceof List<?> list)) {
+ list.forEach(obj -> {
+ if (obj instanceof String string) {
+ parameters.add(string);
}
});
}
.unmodifiableSet(Stream.of(THING_TYPE_DIMMABLE_LIGHT, THING_TYPE_COLOR_TEMP_LIGHT, THING_TYPE_COLOR_LIGHT)
.collect(Collectors.toSet()));
- public static final Set<ThingTypeUID> SUPPORTED_PLUG_TYPES_UIDS = Collections.singleton(THING_TYPE_ONOFF_PLUG);
+ public static final Set<ThingTypeUID> SUPPORTED_PLUG_TYPES_UIDS = Set.of(THING_TYPE_ONOFF_PLUG);
- public static final Set<ThingTypeUID> SUPPORTED_BLINDS_TYPES_UIDS = Collections.singleton(THING_TYPE_BLINDS);
+ public static final Set<ThingTypeUID> SUPPORTED_BLINDS_TYPES_UIDS = Set.of(THING_TYPE_BLINDS);
public static final Set<ThingTypeUID> SUPPORTED_AIR_PURIFIER_TYPES_UIDS = Set.of(THING_TYPE_AIR_PURIFIER);
.unmodifiableSet(Stream.of(THING_TYPE_DIMMER, THING_TYPE_REMOTE_CONTROL,
THING_TYPE_OPEN_CLOSE_REMOTE_CONTROL, THING_TYPE_MOTION_SENSOR).collect(Collectors.toSet()));
- public static final Set<ThingTypeUID> SUPPORTED_BRIDGE_TYPES_UIDS = Collections.singleton(GATEWAY_TYPE_UID);
+ public static final Set<ThingTypeUID> SUPPORTED_BRIDGE_TYPES_UIDS = Set.of(GATEWAY_TYPE_UID);
public static final Set<ThingTypeUID> SUPPORTED_DEVICE_TYPES_UIDS = Collections.unmodifiableSet(Stream
.of(SUPPORTED_LIGHT_TYPES_UIDS.stream(), SUPPORTED_CONTROLLER_TYPES_UIDS.stream(),
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof TradfriGatewayHandler) {
- this.handler = (TradfriGatewayHandler) handler;
+ if (handler instanceof TradfriGatewayHandler gatewayHandler) {
+ this.handler = gatewayHandler;
}
}
}
private void handleFanModeCommand(Command command) {
- if (command instanceof Number) {
- set(new TradfriAirPurifierData().setFanMode((Number) command).getJsonString());
+ if (command instanceof Number numberCommand) {
+ set(new TradfriAirPurifierData().setFanMode(numberCommand).getJsonString());
} else {
logger.debug("Cannot handle command '{}' of type {} for channel '{}'", command, command.getClass(),
CHANNEL_FAN_MODE);
}
private void handleDisableLed(Command command) {
- if (command instanceof OnOffType) {
- set(new TradfriAirPurifierData().setDisableLed((OnOffType) command).getJsonString());
+ if (command instanceof OnOffType onOffCommand) {
+ set(new TradfriAirPurifierData().setDisableLed(onOffCommand).getJsonString());
} else {
logger.debug("Cannot handle command '{}' of type {} for channel '{}'", command, command.getClass(),
CHANNEL_DISABLE_LED);
}
private void handleLockButton(Command command) {
- if (command instanceof OnOffType) {
- set(new TradfriAirPurifierData().setLockPhysicalButton((OnOffType) command).getJsonString());
+ if (command instanceof OnOffType onOffCommand) {
+ set(new TradfriAirPurifierData().setLockPhysicalButton(onOffCommand).getJsonString());
} else {
logger.debug("Cannot handle command '{}' of type {} for channel '{}'", command, command.getClass(),
CHANNEL_DISABLE_LED);
}
private void handlePositionCommand(Command command) {
- if (command instanceof PercentType) {
- setPosition((PercentType) command);
+ if (command instanceof PercentType percentCommand) {
+ setPosition(percentCommand);
} else if (command instanceof StopMoveType) {
if (StopMoveType.STOP.equals(command)) {
triggerStop();
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
-import java.util.Collections;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(TradfriDiscoveryService.class);
+ return Set.of(TradfriDiscoveryService.class);
}
private void establishConnection() {
}
private void handleBrightnessCommand(Command command) {
- if (command instanceof PercentType) {
- setBrightness((PercentType) command);
- } else if (command instanceof OnOffType) {
- setState(((OnOffType) command));
+ if (command instanceof PercentType percentCommand) {
+ setBrightness(percentCommand);
+ } else if (command instanceof OnOffType onOffCommand) {
+ setState(onOffCommand);
} else if (command instanceof IncreaseDecreaseType) {
final TradfriLightData state = this.state;
if (state != null && state.getBrightness() != null) {
}
private void handleColorTemperatureCommand(Command command) {
- if (command instanceof PercentType) {
- setColorTemperature((PercentType) command);
+ if (command instanceof PercentType percentCommand) {
+ setColorTemperature(percentCommand);
} else if (command instanceof IncreaseDecreaseType) {
final TradfriLightData state = this.state;
if (state != null && state.getColorTemperature() != null) {
}
private void handleColorCommand(Command command) {
- if (command instanceof HSBType) {
- setColor((HSBType) command);
- setBrightness(((HSBType) command).getBrightness());
- } else if (command instanceof OnOffType) {
- setState(((OnOffType) command));
- } else if (command instanceof PercentType) {
- setBrightness((PercentType) command);
+ if (command instanceof HSBType hsbCommand) {
+ setColor(hsbCommand);
+ setBrightness(hsbCommand.getBrightness());
+ } else if (command instanceof OnOffType onOffCommand) {
+ setState(onOffCommand);
+ } else if (command instanceof PercentType percentCommand) {
+ setBrightness(percentCommand);
} else if (command instanceof IncreaseDecreaseType) {
final TradfriLightData state = this.state;
// increase or decrease only the brightness, but keep color
switch (channelUID.getId()) {
case CHANNEL_POWER:
- if (command instanceof OnOffType) {
- setState(((OnOffType) command));
+ if (command instanceof OnOffType onOffCommand) {
+ setState(onOffCommand);
} else {
logger.debug("Cannot handle command '{}' for channel '{}'", command, CHANNEL_POWER);
}
public @Nullable State getAirQualityRating() {
State pm25State = getAirQualityPM25();
if (pm25State != null) {
- if (pm25State instanceof Number) {
- int pm25Value = ((Number) pm25State).intValue();
+ if (pm25State instanceof Number number) {
+ int pm25Value = number.intValue();
int qualityRating = 1;
if (pm25Value >= AIR_PURIFIER_AIR_QUALITY_BAD) {
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
-import java.util.Collections;
+import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
// creates list of available Actions
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singletonList(TwitterActions.class);
+ return List.of(TwitterActions.class);
}
@Override
Twitter localClient = client;
if (localClient != null) {
ResponseList<Status> statuses = localClient.getUserTimeline();
- if (statuses.size() > 0) {
+ if (!statuses.isEmpty()) {
updateState(CHANNEL_LASTTWEET, StringType.valueOf(statuses.get(0).getText()));
} else {
logger.debug("No Statuses Found");
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof TwitterHandler) {
- this.handler = (TwitterHandler) handler;
+ if (handler instanceof TwitterHandler twitterHandler) {
+ this.handler = twitterHandler;
}
}
@Override
public void setThingHandler(ThingHandler handler) {
- if (handler instanceof UniFiSiteThingHandler) {
- this.handler = (UniFiSiteThingHandler) handler;
+ if (handler instanceof UniFiSiteThingHandler siteThingHandler) {
+ this.handler = siteThingHandler;
}
}
} else if (cause instanceof SSLException) {
// cannot establish ssl connection
throw new UniFiSSLException(cause);
- } else if (cause instanceof HttpResponseException
- && ((HttpResponseException) cause).getResponse() instanceof ContentResponse) {
+ } else if (cause instanceof HttpResponseException httpResponseException
+ && httpResponseException.getResponse() instanceof ContentResponse) {
// the UniFi controller violates the HTTP protocol
// - it returns 401 UNAUTHORIZED without the WWW-Authenticate response header
// - this causes an ExecutionException to be thrown
// - we unwrap the response from the exception for proper handling of the 401 status code
- response = ((HttpResponseException) cause).getResponse();
+ response = httpResponseException.getResponse();
} else {
// catch all
throw new UniFiException(cause);
@Override
public String toString() {
return String.format(
- "UniFiVoucher{id: '%s', code: '%s', created: '%s', duration: '%s', quota: '%s', used: '%s', qosUsageQuota: '%s', "
- + "qosRateMaxUp: '%s', qosRateMaxDown: '%s', qosOverwrite: '%s', note: '%s', status: '%s', site: %s}",
+ """
+ UniFiVoucher{id: '%s', code: '%s', created: '%s', duration: '%s', quota: '%s', used: '%s', qosUsageQuota: '%s', \
+ qosRateMaxUp: '%s', qosRateMaxDown: '%s', qosOverwrite: '%s', note: '%s', status: '%s', site: %s}\
+ """,
id, code, createTime, duration, quota, used, qosUsageQuota, qosRateMaxUp, qosRateMaxDown, qosOverwrite,
note, status, getSite());
}
default:
// mgb: additional wired client channels
- if (client.isWired() && (client instanceof UniFiWiredClient)) {
- state = getWiredChannelState((UniFiWiredClient) client, channelId, state);
+ if (client.isWired() && (client instanceof UniFiWiredClient wiredClient)) {
+ state = getWiredChannelState(wiredClient, channelId, state);
}
// mgb: additional wireless client channels
- else if (client.isWireless() && (client instanceof UniFiWirelessClient)) {
- state = getWirelessChannelState((UniFiWirelessClient) client, channelId, state);
+ else if (client.isWireless() && (client instanceof UniFiWirelessClient wirelessClient)) {
+ state = getWirelessChannelState(wirelessClient, channelId, state);
}
break;
}
getThing().getThings().forEach((thing) -> {
final ThingHandler handler = thing.getHandler();
- if (handler instanceof UniFiBaseThingHandler) {
- ((UniFiBaseThingHandler<?, ?>) handler).refresh();
+ if (handler instanceof UniFiBaseThingHandler baseThingHandler) {
+ baseThingHandler.refresh();
}
});
}
import static org.openhab.binding.unifi.internal.UniFiBindingConstants.*;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Set;
import java.util.function.Predicate;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(UniFiSiteActions.class);
+ return Set.of(UniFiSiteActions.class);
}
}
@Override
public void setThingHandler(final ThingHandler handler) {
- if (handler instanceof UniFiControllerThingHandler) {
- bridgeHandler = (UniFiControllerThingHandler) handler;
+ if (handler instanceof UniFiControllerThingHandler controllerThingHandler) {
+ bridgeHandler = controllerThingHandler;
}
}
return UnDefType.UNDEF;
} else {
return new DecimalType(site.getCache().countClients(site,
- c -> c instanceof UniFiWirelessClient
- && (wlan.getName() != null && wlan.getName().equals(((UniFiWirelessClient) c).getEssid()))
+ c -> c instanceof UniFiWirelessClient wirelessClient
+ && (wlan.getName() != null && wlan.getName().equals(wirelessClient.getEssid()))
&& filter.test(c)));
}
}
*/
package org.openhab.binding.unifiedremote.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_UNIFIED_REMOTE_SERVER = new ThingTypeUID(BINDING_ID, "server");
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections
- .singleton(THING_TYPE_UNIFIED_REMOTE_SERVER);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_UNIFIED_REMOTE_SERVER);
// List of all Channel ids
public static final String MOUSE_CHANNEL = "mouse-move";
}
public void deviceAdded(final ThingHandler childHandler, final Thing childThing) {
- if (childHandler instanceof UPBThingHandler) {
- final UPBThingHandler hnd = (UPBThingHandler) childHandler;
- things.put(mkAddr(hnd.getNetworkId(), hnd.getUnitId()), hnd);
+ if (childHandler instanceof UPBThingHandler upbThingHandler) {
+ things.put(mkAddr(upbThingHandler.getNetworkId(), upbThingHandler.getUnitId()), upbThingHandler);
}
}
public void deviceRemoved(final ThingHandler childHandler, final Thing childThing) {
- if (childHandler instanceof UPBThingHandler) {
- final UPBThingHandler hnd = (UPBThingHandler) childHandler;
- things.remove(mkAddr(hnd.getNetworkId(), hnd.getUnitId()), hnd);
+ if (childHandler instanceof UPBThingHandler upbThingHandler) {
+ things.remove(mkAddr(upbThingHandler.getNetworkId(), upbThingHandler.getUnitId()), upbThingHandler);
}
}
message = MessageBuilder.forCommand(ACTIVATE);
} else if (cmd == OnOffType.OFF) {
message = MessageBuilder.forCommand(DEACTIVATE);
- } else if (cmd instanceof PercentType) {
- message = MessageBuilder.forCommand(GOTO).args(((PercentType) cmd).byteValue());
+ } else if (cmd instanceof PercentType percentCommand) {
+ message = MessageBuilder.forCommand(GOTO).args(percentCommand.byteValue());
} else if (cmd == RefreshType.REFRESH) {
refreshDeviceState();
return;
@Override
public @Nullable CommandDescription getCommandDescription(Channel channel,
@Nullable CommandDescription originalCommandDescription, @Nullable Locale locale) {
- CommandDescription description = descriptions.get(channel.getUID());
- return description;
+ return descriptions.get(channel.getUID());
}
@Deactivate
@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
* Invoke ConnectionComplete on UPnP Connection Manager.
*/
protected void connectionComplete() {
- Map<String, String> inputs = Collections.singletonMap(CONNECTION_ID, Integer.toString(connectionId));
+ Map<String, String> inputs = Map.of(CONNECTION_ID, Integer.toString(connectionId));
invokeAction(CONNECTION_MANAGER, "ConnectionComplete", inputs);
}
isRcsIdSet = new CompletableFuture<Boolean>();
// ConnectionID will default to 0 if not set through prepareForConnection method
- Map<String, String> inputs = Collections.singletonMap(CONNECTION_ID, Integer.toString(connectionId));
+ Map<String, String> inputs = Map.of(CONNECTION_ID, Integer.toString(connectionId));
invokeAction(CONNECTION_MANAGER, "GetCurrentConnectionInfo", inputs);
}
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
// received
}
- Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
+ Map<String, String> inputs = Map.of(INSTANCE_ID, Integer.toString(avTransportId));
invokeAction(AV_TRANSPORT, "Stop", inputs);
}
* Invoke Pause on UPnP AV Transport.
*/
protected void pause() {
- Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
+ Map<String, String> inputs = Map.of(INSTANCE_ID, Integer.toString(avTransportId));
invokeAction(AV_TRANSPORT, "Pause", inputs);
}
* Invoke Next on UPnP AV Transport.
*/
protected void next() {
- Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
+ Map<String, String> inputs = Map.of(INSTANCE_ID, Integer.toString(avTransportId));
invokeAction(AV_TRANSPORT, "Next", inputs);
}
* Invoke Previous on UPnP AV Transport.
*/
protected void previous() {
- Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
+ Map<String, String> inputs = Map.of(INSTANCE_ID, Integer.toString(avTransportId));
invokeAction(AV_TRANSPORT, "Previous", inputs);
}
* Result is received in {@link #onValueReceived}.
*/
protected void getTransportState() {
- Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
+ Map<String, String> inputs = Map.of(INSTANCE_ID, Integer.toString(avTransportId));
invokeAction(AV_TRANSPORT, "GetTransportInfo", inputs);
}
* Result is received in {@link #onValueReceived}.
*/
protected void getPositionInfo() {
- Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
+ Map<String, String> inputs = Map.of(INSTANCE_ID, Integer.toString(avTransportId));
invokeAction(AV_TRANSPORT, "GetPositionInfo", inputs);
}
* Result is received in {@link #onValueReceived}.
*/
protected void getMediaInfo() {
- Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
+ Map<String, String> inputs = Map.of(INSTANCE_ID, Integer.toString(avTransportId));
invokeAction(AV_TRANSPORT, "smarthome:audio stream http://icecast.vrtcdn.be/stubru_tijdloze-high.mp3", inputs);
}
private void handleCommandVolume(Command command, String id) {
if (command instanceof RefreshType) {
getVolume("volume".equals(id) ? UPNP_MASTER : id.replace("volume", ""));
- } else if (command instanceof PercentType) {
- setVolume("volume".equals(id) ? UPNP_MASTER : id.replace("volume", ""), (PercentType) command);
+ } else if (command instanceof PercentType percentCommand) {
+ setVolume("volume".equals(id) ? UPNP_MASTER : id.replace("volume", ""), percentCommand);
}
}
private void handleCommandMute(Command command, String id) {
if (command instanceof RefreshType) {
getMute("mute".equals(id) ? UPNP_MASTER : id.replace("mute", ""));
- } else if (command instanceof OnOffType) {
- setMute("mute".equals(id) ? UPNP_MASTER : id.replace("mute", ""), (OnOffType) command);
+ } else if (command instanceof OnOffType onOffCommand) {
+ setMute("mute".equals(id) ? UPNP_MASTER : id.replace("mute", ""), onOffCommand);
}
}
private void handleCommandLoudness(Command command, String id) {
if (command instanceof RefreshType) {
getLoudness("loudness".equals(id) ? UPNP_MASTER : id.replace("loudness", ""));
- } else if (command instanceof OnOffType) {
- setLoudness("loudness".equals(id) ? UPNP_MASTER : id.replace("loudness", ""), (OnOffType) command);
+ } else if (command instanceof OnOffType onOffCommand) {
+ setLoudness("loudness".equals(id) ? UPNP_MASTER : id.replace("loudness", ""), onOffCommand);
}
}
private void handleCommandTrackPosition(ChannelUID channelUID, Command command) {
if (command instanceof RefreshType) {
updateState(channelUID, new QuantityType<>(trackPosition, Units.SECOND));
- } else if (command instanceof QuantityType<?>) {
- QuantityType<?> position = ((QuantityType<?>) command).toUnit(Units.SECOND);
+ } else if (command instanceof QuantityType<?> quantityCommand) {
+ QuantityType<?> position = quantityCommand.toUnit(Units.SECOND);
if (position != null) {
int pos = Integer.min(trackDuration, position.intValue());
seek(String.format("%02d:%02d:%02d", pos / 3600, (pos % 3600) / 60, pos % 60));
if (command instanceof RefreshType) {
int relPosition = (trackDuration != 0) ? (trackPosition * 100) / trackDuration : 0;
updateState(channelUID, new PercentType(relPosition));
- } else if (command instanceof PercentType) {
- int pos = ((PercentType) command).intValue() * trackDuration / 100;
+ } else if (command instanceof PercentType percentCommand) {
+ int pos = percentCommand.intValue() * trackDuration / 100;
seek(String.format("%02d:%02d:%02d", pos / 3600, (pos % 3600) / 60, pos % 60));
}
}
private void handleCommandUpnpRenderer(ChannelUID channelUID, Command command) {
UpnpRendererHandler renderer = null;
UpnpRendererHandler previousRenderer = currentRendererHandler;
- if (command instanceof StringType) {
- renderer = (upnpRenderers.get(((StringType) command).toString()));
+ if (command instanceof StringType stringCommand) {
+ renderer = (upnpRenderers.get(stringCommand.toString()));
currentRendererHandler = renderer;
if (config.filter) {
// only refresh title list if filtering by renderer capabilities
* ' - '
*/
public static 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 static String unEscapeXml(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;
}
}
return Collections.emptyList();
}
- List<String> result = (Arrays.asList(files)).stream().map(p -> p.getName().replace(extension, ""))
+ return (Arrays.asList(files)).stream().map(p -> p.getName().replace(extension, ""))
.collect(Collectors.toList());
- return result;
}
private static void delete(String name, @Nullable String path, String extension) {
((Runnable) invocation.getArguments()[0]).run();
return null;
}).when(executor).scheduleWithFixedDelay(any(Runnable.class), eq(0L), anyLong(), any(TimeUnit.class));
- doAnswer(invocation -> {
- return SCHEDULER.schedule((Runnable) invocation.getArguments()[0], 500, TimeUnit.MILLISECONDS);
- }).when(executor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
+ doAnswer(invocation -> SCHEDULER.schedule((Runnable) invocation.getArguments()[0], 500, TimeUnit.MILLISECONDS))
+ .when(executor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
}
public void tearDown() {
private static final String THING_TYPE_UID = "upnpcontrol:upnprenderer";
private static final String THING_UID = THING_TYPE_UID + ":mockrenderer";
- private static final String LAST_CHANGE_HEADER = "<Event xmlns=\"urn:schemas-upnp-org:metadata-1-0/AVT/\">"
- + "<InstanceID val=\"0\">";
+ private static final String LAST_CHANGE_HEADER = """
+ <Event xmlns="urn:schemas-upnp-org:metadata-1-0/AVT/">\
+ <InstanceID val="0">\
+ """;
private static final String LAST_CHANGE_FOOTER = "</InstanceID></Event>";
private static final String AV_TRANSPORT_URI = "<AVTransportURI val=\"";
private static final String AV_TRANSPORT_URI_METADATA = "<AVTransportURIMetaData val=\"";
private static final String THING_TYPE_UID = "upnpcontrol:upnpserver";
private static final String THING_UID = THING_TYPE_UID + ":mockserver";
- private static final String RESPONSE_HEADER = "<DIDL-Lite xmlns=\"urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/\" "
- + "xmlns:dc=\"http://purl.org/dc/elements/1.1/\" "
- + "xmlns:upnp=\"urn:schemas-upnp-org:metadata-1-0/upnp/\">";
+ private static final String RESPONSE_HEADER = """
+ <DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/" \
+ xmlns:dc="http://purl.org/dc/elements/1.1/" \
+ xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/">\
+ """;
private static final String RESPONSE_FOOTER = "</DIDL-Lite>";
private static final String BASE_CONTAINER = RESPONSE_HEADER
protected @Nullable ThingHandler createHandler(Thing thing) {
ThingTypeUID thingTypeUID = thing.getThingTypeUID();
- if (thingTypeUID.equals(URTSI_DEVICE_THING_TYPE) && thing instanceof Bridge) {
- return new UrtsiDeviceHandler((Bridge) thing, serialPortManager);
+ if (thingTypeUID.equals(URTSI_DEVICE_THING_TYPE) && thing instanceof Bridge bridge) {
+ return new UrtsiDeviceHandler(bridge, serialPortManager);
} else if (thingTypeUID.equals(RTS_DEVICE_THING_TYPE)) {
return new RtsDeviceHandler(thing);
}
public void handleCommand(ChannelUID channelUID, Command command) {
if (channelUID.getId().equals(UrtsiBindingConstants.POSITION)) {
RtsCommand rtsCommand = null;
- if (command instanceof UpDownType) {
- switch ((UpDownType) command) {
+ if (command instanceof UpDownType upDownCommand) {
+ switch (upDownCommand) {
case UP:
rtsCommand = RtsCommand.UP;
break;
default:
break;
}
- } else if (command instanceof StopMoveType) {
- switch ((StopMoveType) command) {
+ } else if (command instanceof StopMoveType stopMoveCommand) {
+ switch (stopMoveCommand) {
case STOP:
rtsCommand = RtsCommand.STOP;
break;
if (rtsCommand != null) {
// We delegate the execution to the bridge handler
ThingHandler bridgeHandler = getBridge().getHandler();
- if (bridgeHandler instanceof UrtsiDeviceHandler) {
- boolean executedSuccessfully = ((UrtsiDeviceHandler) bridgeHandler).executeRtsCommand(getThing(),
- rtsCommand);
- if (executedSuccessfully && command instanceof State) {
- updateState(channelUID, (State) command);
+ if (bridgeHandler instanceof UrtsiDeviceHandler deviceHandler) {
+ boolean executedSuccessfully = deviceHandler.executeRtsCommand(getThing(), rtsCommand);
+ if (executedSuccessfully && command instanceof State state) {
+ updateState(channelUID, state);
}
}
}
}
String urtsiCommand = new StringBuilder(address).append(mappedChannel).append(rtsCommand.getActionKey())
.toString();
- boolean executedSuccessfully = writeString(urtsiCommand);
- return executedSuccessfully;
+ return writeString(urtsiCommand);
}
/**
*/
package org.openhab.binding.valloxmv.internal;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* Set of writable channels that are Switches
*/
- public static final Set<String> WRITABLE_CHANNELS_SWITCHES = Collections
- .unmodifiableSet(new HashSet<>(Arrays.asList(CHANNEL_ONOFF, CHANNEL_BOOST_TIMER_ENABLED,
- CHANNEL_FIREPLACE_TIMER_ENABLED, CHANNEL_EXTRA_TIMER_ENABLED, CHANNEL_WEEKLY_TIMER_ENABLED)));
+ public static final Set<String> WRITABLE_CHANNELS_SWITCHES = Set.of(CHANNEL_ONOFF, CHANNEL_BOOST_TIMER_ENABLED,
+ CHANNEL_FIREPLACE_TIMER_ENABLED, CHANNEL_EXTRA_TIMER_ENABLED, CHANNEL_WEEKLY_TIMER_ENABLED);
/**
*
* Set of writable channels that are dimensionless
*/
- public static final Set<String> WRITABLE_CHANNELS_DIMENSIONLESS = Collections
- .unmodifiableSet(new HashSet<>(Arrays.asList(CHANNEL_EXTR_FAN_BALANCE_BASE, CHANNEL_SUPP_FAN_BALANCE_BASE,
- CHANNEL_HOME_SPEED_SETTING, CHANNEL_AWAY_SPEED_SETTING, CHANNEL_BOOST_SPEED_SETTING,
- CHANNEL_BOOST_TIME, CHANNEL_BOOST_TIMER_ENABLED, CHANNEL_FIREPLACE_EXTR_FAN,
- CHANNEL_FIREPLACE_SUPP_FAN, CHANNEL_FIREPLACE_TIME, CHANNEL_FIREPLACE_TIMER_ENABLED,
- CHANNEL_EXTRA_EXTR_FAN, CHANNEL_EXTRA_SUPP_FAN, CHANNEL_EXTRA_TIME, CHANNEL_EXTRA_TIMER_ENABLED,
- CHANNEL_WEEKLY_TIMER_ENABLED)));
+ public static final Set<String> WRITABLE_CHANNELS_DIMENSIONLESS = Set.of(CHANNEL_EXTR_FAN_BALANCE_BASE,
+ CHANNEL_SUPP_FAN_BALANCE_BASE, CHANNEL_HOME_SPEED_SETTING, CHANNEL_AWAY_SPEED_SETTING,
+ CHANNEL_BOOST_SPEED_SETTING, CHANNEL_BOOST_TIME, CHANNEL_BOOST_TIMER_ENABLED, CHANNEL_FIREPLACE_EXTR_FAN,
+ CHANNEL_FIREPLACE_SUPP_FAN, CHANNEL_FIREPLACE_TIME, CHANNEL_FIREPLACE_TIMER_ENABLED, CHANNEL_EXTRA_EXTR_FAN,
+ CHANNEL_EXTRA_SUPP_FAN, CHANNEL_EXTRA_TIME, CHANNEL_EXTRA_TIMER_ENABLED, CHANNEL_WEEKLY_TIMER_ENABLED);
/**
* Set of writable channels that are temperatures
*/
- public static final Set<String> WRITABLE_CHANNELS_TEMPERATURE = Collections
- .unmodifiableSet(new HashSet<>(Arrays.asList(CHANNEL_HOME_AIR_TEMP_TARGET, CHANNEL_AWAY_AIR_TEMP_TARGET,
- CHANNEL_BOOST_AIR_TEMP_TARGET, CHANNEL_EXTRA_AIR_TEMP_TARGET)));
+ public static final Set<String> WRITABLE_CHANNELS_TEMPERATURE = Set.of(CHANNEL_HOME_AIR_TEMP_TARGET,
+ CHANNEL_AWAY_AIR_TEMP_TARGET, CHANNEL_BOOST_AIR_TEMP_TARGET, CHANNEL_EXTRA_AIR_TEMP_TARGET);
// Thing configuration
/**
import static org.openhab.binding.valloxmv.internal.ValloxMVBindingConstants.THING_TYPE_VALLOXMV;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@NonNullByDefault()
public class ValloxMVHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_VALLOXMV);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_VALLOXMV);
private final WebSocketClient webSocketClient;
Map<String, String> properties = editProperties();
// set vdr version to properties of thing
String version = client.getSVDRPVersion();
- properties.put(VDRBindingConstants.PROPERTY_VERSION, version.toString());
+ properties.put(VDRBindingConstants.PROPERTY_VERSION, version);
// persist changes only if there are any changes.
if (!editProperties().equals(properties)) {
import static org.openhab.binding.vdr.internal.VDRBindingConstants.THING_TYPE_VDR;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.vdr", service = ThingHandlerFactory.class)
public class VDRHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_VDR);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_VDR);
private final TimeZoneProvider timeZoneProvider;
public String toString() {
StringBuilder sb = new StringBuilder();
if (number >= 0) {
- sb.append("Number: " + String.valueOf(number) + System.lineSeparator());
+ sb.append("Number: " + number + System.lineSeparator());
}
sb.append("Name: " + name + System.lineSeparator());
return sb.toString();
res = execute("STAT disk");
if (res.getCode() == 250) {
- SVDRPDiskStatus status = SVDRPDiskStatus.parse(res.getMessage());
- return status;
+ return SVDRPDiskStatus.parse(res.getMessage());
} else {
throw new SVDRPParseResponseException(res);
}
}
if (res != null && res.getCode() == 215) {
- SVDRPEpgEvent entry = SVDRPEpgEvent.parse(res.getMessage());
- return entry;
+ return SVDRPEpgEvent.parse(res.getMessage());
} else if (res != null) {
throw new SVDRPParseResponseException(res);
} else {
res = execute("VOLU");
if (res.getCode() == 250) {
- SVDRPVolume volume = SVDRPVolume.parse(res.getMessage());
- return volume;
+ return SVDRPVolume.parse(res.getMessage());
} else {
throw new SVDRPParseResponseException(res);
}
res = execute(String.format("VOLU %s", String.valueOf(Math.round(newVolumeDouble))));
if (res.getCode() == 250) {
- SVDRPVolume volume = SVDRPVolume.parse(res.getMessage());
- return volume;
+ return SVDRPVolume.parse(res.getMessage());
} else {
throw new SVDRPParseResponseException(res);
}
res = execute("CHAN");
if (res.getCode() == 250) {
- SVDRPChannel channel = SVDRPChannel.parse(res.getMessage());
- return channel;
+ return SVDRPChannel.parse(res.getMessage());
} else {
throw new SVDRPParseResponseException(res);
}
res = execute(String.format("CHAN %s", number));
if (res.getCode() == 250) {
- SVDRPChannel channel = SVDRPChannel.parse(res.getMessage());
- return channel;
+ return SVDRPChannel.parse(res.getMessage());
} else {
throw new SVDRPParseResponseException(res);
}
*/
@NonNullByDefault
public class SVDRPEpgEventTest {
- private final String epgResponseComplete = "C S19.2E-1-1201-28326 WDR HD Bielefeld\n"
- + "E 9886 1610391600 900 4E F\n" + "T Tagesschau\n" + "S Aktuelle Nachrichten aus der Welt\n"
- + "D Themen u.a.:|* Corona-Pandemie in Deutschland: Verschärfter Lockdown bundesweit in Kraft|* Entmachtung des US-Präsidenten: Demokraten planen Schritte gegen Trump|* Wintereinbruch in Bosnien-Herzegowina: Dramatische Lage der Flüchtlinge an der Grenze zu Kroatien\n"
- + "G 20 80\n" + "X 2 03 deu stereo\n" + "X 2 03 deu ohne Audiodeskription\n"
- + "X 3 01 deu Teletext-Untertitel\n" + "X 3 20 deu mit DVB-Untertitel\n" + "X 5 0B deu HD-Video\n"
- + "V 1610391600\n" + "e\n" + "c\n" + "End of EPG data";
- private final String epgMissingSubtitle = "C S19.2E-1-1201-28326 WDR HD Bielefeld\n"
- + "E 9886 1610391600 900 4E F\n" + "T Tagesschau\n"
- + "D Themen u.a.:|* Corona-Pandemie in Deutschland: Verschärfter Lockdown bundesweit in Kraft|* Entmachtung des US-Präsidenten: Demokraten planen Schritte gegen Trump|* Wintereinbruch in Bosnien-Herzegowina: Dramatische Lage der Flüchtlinge an der Grenze zu Kroatien\n"
- + "G 20 80\n" + "X 2 03 deu stereo\n" + "X 2 03 deu ohne Audiodeskription\n"
- + "X 3 01 deu Teletext-Untertitel\n" + "X 3 20 deu mit DVB-Untertitel\n" + "X 5 0B deu HD-Video\n"
- + "V 1610391600\n" + "e\n" + "c\n" + "End of EPG data";
+ private final String epgResponseComplete = """
+ C S19.2E-1-1201-28326 WDR HD Bielefeld
+ E 9886 1610391600 900 4E F
+ T Tagesschau
+ S Aktuelle Nachrichten aus der Welt
+ D Themen u.a.:|* Corona-Pandemie in Deutschland: Verschärfter Lockdown bundesweit in Kraft|* Entmachtung des US-Präsidenten: Demokraten planen Schritte gegen Trump|* Wintereinbruch in Bosnien-Herzegowina: Dramatische Lage der Flüchtlinge an der Grenze zu Kroatien
+ G 20 80
+ X 2 03 deu stereo
+ X 2 03 deu ohne Audiodeskription
+ X 3 01 deu Teletext-Untertitel
+ X 3 20 deu mit DVB-Untertitel
+ X 5 0B deu HD-Video
+ V 1610391600
+ e
+ c
+ End of EPG data\
+ """;
+ private final String epgMissingSubtitle = """
+ C S19.2E-1-1201-28326 WDR HD Bielefeld
+ E 9886 1610391600 900 4E F
+ T Tagesschau
+ D Themen u.a.:|* Corona-Pandemie in Deutschland: Verschärfter Lockdown bundesweit in Kraft|* Entmachtung des US-Präsidenten: Demokraten planen Schritte gegen Trump|* Wintereinbruch in Bosnien-Herzegowina: Dramatische Lage der Flüchtlinge an der Grenze zu Kroatien
+ G 20 80
+ X 2 03 deu stereo
+ X 2 03 deu ohne Audiodeskription
+ X 3 01 deu Teletext-Untertitel
+ X 3 20 deu mit DVB-Untertitel
+ X 5 0B deu HD-Video
+ V 1610391600
+ e
+ c
+ End of EPG data\
+ """;
private final String epgParseError = "E 9999999999999999999999999";
- private final String epgCorruptDate = "C S19.2E-1-1201-28326 WDR HD Bielefeld\n" + "E 9886 2a10391600 900 4E F\n"
- + "T Tagesschau\n"
- + "D Themen u.a.:|* Corona-Pandemie in Deutschland: Verschärfter Lockdown bundesweit in Kraft|* Entmachtung des US-Präsidenten: Demokraten planen Schritte gegen Trump|* Wintereinbruch in Bosnien-Herzegowina: Dramatische Lage der Flüchtlinge an der Grenze zu Kroatien\n"
- + "G 20 80\n" + "X 2 03 deu stereo\n" + "X 2 03 deu ohne Audiodeskription\n"
- + "X 3 01 deu Teletext-Untertitel\n" + "X 3 20 deu mit DVB-Untertitel\n" + "X 5 0B deu HD-Video\n"
- + "V 1610391600\n" + "e\n" + "c\n" + "End of EPG data";
+ private final String epgCorruptDate = """
+ C S19.2E-1-1201-28326 WDR HD Bielefeld
+ E 9886 2a10391600 900 4E F
+ T Tagesschau
+ D Themen u.a.:|* Corona-Pandemie in Deutschland: Verschärfter Lockdown bundesweit in Kraft|* Entmachtung des US-Präsidenten: Demokraten planen Schritte gegen Trump|* Wintereinbruch in Bosnien-Herzegowina: Dramatische Lage der Flüchtlinge an der Grenze zu Kroatien
+ G 20 80
+ X 2 03 deu stereo
+ X 2 03 deu ohne Audiodeskription
+ X 3 01 deu Teletext-Untertitel
+ X 3 20 deu mit DVB-Untertitel
+ X 5 0B deu HD-Video
+ V 1610391600
+ e
+ c
+ End of EPG data\
+ """;
- private final String epgMissingEnd = "C S19.2E-1-1201-28326 WDR HD Bielefeld\n" + "E 9886 1610391600 900 4E F\n"
- + "T Tagesschau\n"
- + "D Themen u.a.:|* Corona-Pandemie in Deutschland: Verschärfter Lockdown bundesweit in Kraft|* Entmachtung des US-Präsidenten: Demokraten planen Schritte gegen Trump|* Wintereinbruch in Bosnien-Herzegowina: Dramatische Lage der Flüchtlinge an der Grenze zu Kroatien\n"
- + "G 20 80\n" + "X 2 03 deu stereo\n" + "X 2 03 deu ohne Audiodeskription\n"
- + "X 3 01 deu Teletext-Untertitel\n" + "X 3 20 deu mit DVB-Untertitel\n" + "X 5 0B deu HD-Video\n"
- + "V 1610391600\n" + "e\n" + "c\n";
+ private final String epgMissingEnd = """
+ C S19.2E-1-1201-28326 WDR HD Bielefeld
+ E 9886 1610391600 900 4E F
+ T Tagesschau
+ D Themen u.a.:|* Corona-Pandemie in Deutschland: Verschärfter Lockdown bundesweit in Kraft|* Entmachtung des US-Präsidenten: Demokraten planen Schritte gegen Trump|* Wintereinbruch in Bosnien-Herzegowina: Dramatische Lage der Flüchtlinge an der Grenze zu Kroatien
+ G 20 80
+ X 2 03 deu stereo
+ X 2 03 deu ohne Audiodeskription
+ X 3 01 deu Teletext-Untertitel
+ X 3 20 deu mit DVB-Untertitel
+ X 5 0B deu HD-Video
+ V 1610391600
+ e
+ c
+ """;
@Test
public void testParseEpgEventComplete() throws SVDRPException, ParseException {
*/
@NonNullByDefault
public class SVDRPTimerListTest {
- private final String timerListResponseTimerActive = "1 1:1:2021-01-12:2013:2110:50:99:Charité (1/6)~Eiserne Lunge:Test\n"
- + "2 9:1:2021-01-12:2058:2200:50:99:Charité (2/6)~Blutsauger:Test";
- private final String timerListResponseTimerNotActive = "1 1:1:2021-01-12:2013:2110:50:99:Charité (1/6)~Eiserne Lunge:Test\n"
- + "2 1:1:2021-01-12:2058:2200:50:99:Charité (2/6)~Blutsauger:Test";
+ private final String timerListResponseTimerActive = """
+ 1 1:1:2021-01-12:2013:2110:50:99:Charité (1/6)~Eiserne Lunge:Test
+ 2 9:1:2021-01-12:2058:2200:50:99:Charité (2/6)~Blutsauger:Test\
+ """;
+ private final String timerListResponseTimerNotActive = """
+ 1 1:1:2021-01-12:2013:2110:50:99:Charité (1/6)~Eiserne Lunge:Test
+ 2 1:1:2021-01-12:2058:2200:50:99:Charité (2/6)~Blutsauger:Test\
+ """;
@Test
public void testParseTimerList() throws SVDRPException {
import static org.openhab.binding.vektiva.internal.VektivaBindingConstants.THING_TYPE_SMARWI;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.vektiva", service = ThingHandlerFactory.class)
public class VektivaHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_SMARWI);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_SMARWI);
/**
* the shared http client
statusMessage = "Blocked";
}
- int position = values.getOrDefault("pos", NA).equals("o") ? 0 : 100;
+ int position = "o".equals(values.getOrDefault("pos", NA)) ? 0 : 100;
if (position == 0 && lastPosition != -1) {
position = lastPosition;
}
*/
package org.openhab.binding.velbus.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 ThingTypeUID THING_TYPE_VMB4PB = new ThingTypeUID(BINDING_ID, "vmb4pb");
// thing type sets
- public static final Set<ThingTypeUID> BRIDGE_THING_TYPES_UIDS = Collections
- .unmodifiableSet(new HashSet<>(Arrays.asList(BRIDGE_THING_TYPE, NETWORK_BRIDGE_THING_TYPE)));
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.unmodifiableSet(
- new HashSet<>(Arrays.asList(THING_TYPE_VMB1BL, THING_TYPE_VMB1BLS, THING_TYPE_VMB1DM, THING_TYPE_VMB1LED,
- THING_TYPE_VMB1RY, THING_TYPE_VMB1RYNO, THING_TYPE_VMB1RYNOS, THING_TYPE_VMB1RYS, THING_TYPE_VMB1TS,
- THING_TYPE_VMB2BL, THING_TYPE_VMB2BLE, THING_TYPE_VMB2PBN, THING_TYPE_VMB4AN, THING_TYPE_VMB4DC,
- THING_TYPE_VMB4RY, THING_TYPE_VMB4RYLD, THING_TYPE_VMB4RYNO, THING_TYPE_VMB6IN, THING_TYPE_VMB6PBN,
- THING_TYPE_VMB7IN, THING_TYPE_VMB8IR, THING_TYPE_VMB8PB, THING_TYPE_VMB8PBU, THING_TYPE_VMBDME,
- THING_TYPE_VMBDMI, THING_TYPE_VMBDMIR, THING_TYPE_VMBEL1, THING_TYPE_VMBEL2, THING_TYPE_VMBEL4,
- THING_TYPE_VMBELO, THING_TYPE_VMBELPIR, THING_TYPE_VMBGP1, THING_TYPE_VMBGP1_2, THING_TYPE_VMBGP2,
- THING_TYPE_VMBGP2_2, THING_TYPE_VMBGP4, THING_TYPE_VMBGP4_2, THING_TYPE_VMBGP4PIR,
- THING_TYPE_VMBGP4PIR_2, THING_TYPE_VMBGPO, THING_TYPE_VMBGPOD, THING_TYPE_VMBGPOD_2,
- THING_TYPE_VMBMETEO, THING_TYPE_VMBPIRC, THING_TYPE_VMBPIRM, THING_TYPE_VMBPIRO,
- THING_TYPE_VMBRFR8S, THING_TYPE_VMBVP1, THING_TYPE_VMBKP, THING_TYPE_VMBIN, THING_TYPE_VMB4PB)));
+ public static final Set<ThingTypeUID> BRIDGE_THING_TYPES_UIDS = Set.of(BRIDGE_THING_TYPE,
+ NETWORK_BRIDGE_THING_TYPE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_VMB1BL, THING_TYPE_VMB1BLS,
+ THING_TYPE_VMB1DM, THING_TYPE_VMB1LED, THING_TYPE_VMB1RY, THING_TYPE_VMB1RYNO, THING_TYPE_VMB1RYNOS,
+ THING_TYPE_VMB1RYS, THING_TYPE_VMB1TS, THING_TYPE_VMB2BL, THING_TYPE_VMB2BLE, THING_TYPE_VMB2PBN,
+ THING_TYPE_VMB4AN, THING_TYPE_VMB4DC, THING_TYPE_VMB4RY, THING_TYPE_VMB4RYLD, THING_TYPE_VMB4RYNO,
+ THING_TYPE_VMB6IN, THING_TYPE_VMB6PBN, THING_TYPE_VMB7IN, THING_TYPE_VMB8IR, THING_TYPE_VMB8PB,
+ THING_TYPE_VMB8PBU, THING_TYPE_VMBDME, THING_TYPE_VMBDMI, THING_TYPE_VMBDMIR, THING_TYPE_VMBEL1,
+ THING_TYPE_VMBEL2, THING_TYPE_VMBEL4, THING_TYPE_VMBELO, THING_TYPE_VMBELPIR, THING_TYPE_VMBGP1,
+ THING_TYPE_VMBGP1_2, THING_TYPE_VMBGP2, THING_TYPE_VMBGP2_2, THING_TYPE_VMBGP4, THING_TYPE_VMBGP4_2,
+ THING_TYPE_VMBGP4PIR, THING_TYPE_VMBGP4PIR_2, THING_TYPE_VMBGPO, THING_TYPE_VMBGPOD, THING_TYPE_VMBGPOD_2,
+ THING_TYPE_VMBMETEO, THING_TYPE_VMBPIRC, THING_TYPE_VMBPIRM, THING_TYPE_VMBPIRO, THING_TYPE_VMBRFR8S,
+ THING_TYPE_VMBVP1, THING_TYPE_VMBKP, THING_TYPE_VMBIN, THING_TYPE_VMB4PB);
// Velbus module types
public static final byte MODULE_TYPE_VMB8PB = 0x01;
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof VelbusBridgeHandler) {
- final VelbusBridgeHandler velbusBridgeHandler = (VelbusBridgeHandler) handler;
+ if (handler instanceof VelbusBridgeHandler velbusBridgeHandler) {
this.velbusBridgeHandler = velbusBridgeHandler;
velbusBridgeHandler.setDefaultPacketListener(this);
}
byte[] packetBytes = packet.getBytes();
velbusBridgeHandler.sendPacket(packetBytes);
- } else if (command instanceof UpDownType) {
- UpDownType s = (UpDownType) command;
- if (s == UpDownType.UP) {
+ } else if (command instanceof UpDownType upDownCommand) {
+ if (upDownCommand == UpDownType.UP) {
byte commandByte = COMMAND_BLIND_UP;
VelbusBlindUpDownPacket packet = new VelbusBlindUpDownPacket(
byte[] packetBytes = packet.getBytes();
velbusBridgeHandler.sendPacket(packetBytes);
}
- } else if (command instanceof StopMoveType) {
- StopMoveType s = (StopMoveType) command;
- if (s == StopMoveType.STOP) {
+ } else if (command instanceof StopMoveType stopMoveCommand) {
+ if (stopMoveCommand == StopMoveType.STOP) {
VelbusBlindOffPacket packet = new VelbusBlindOffPacket(
getModuleAddress().getChannelIdentifier(channelUID));
byte[] packetBytes = packet.getBytes();
velbusBridgeHandler.sendPacket(packetBytes);
}
- } else if (command instanceof PercentType) {
+ } else if (command instanceof PercentType percentCommand) {
VelbusBlindPositionPacket packet = new VelbusBlindPositionPacket(
- getModuleAddress().getChannelIdentifier(channelUID), ((PercentType) command).byteValue());
+ getModuleAddress().getChannelIdentifier(channelUID), percentCommand.byteValue());
byte[] packetBytes = packet.getBytes();
velbusBridgeHandler.sendPacket(packetBytes);
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
+import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
}
case CHANNEL_BRIDGE_CLOCK_ALARM1_WAKEUP_HOUR:
case CHANNEL_BRIDGE_CLOCK_ALARM2_WAKEUP_HOUR: {
- if (command instanceof DecimalType) {
- byte wakeupHour = ((DecimalType) command).byteValue();
+ if (command instanceof DecimalType decimalCommand) {
+ byte wakeupHour = decimalCommand.byteValue();
alarmClock.setWakeupHour(wakeupHour);
}
break;
}
case CHANNEL_BRIDGE_CLOCK_ALARM1_WAKEUP_MINUTE:
case CHANNEL_BRIDGE_CLOCK_ALARM2_WAKEUP_MINUTE: {
- if (command instanceof DecimalType) {
- byte wakeupMinute = ((DecimalType) command).byteValue();
+ if (command instanceof DecimalType decimalCommand) {
+ byte wakeupMinute = decimalCommand.byteValue();
alarmClock.setWakeupMinute(wakeupMinute);
}
break;
}
case CHANNEL_BRIDGE_CLOCK_ALARM1_BEDTIME_HOUR:
case CHANNEL_BRIDGE_CLOCK_ALARM2_BEDTIME_HOUR: {
- if (command instanceof DecimalType) {
- byte bedTimeHour = ((DecimalType) command).byteValue();
+ if (command instanceof DecimalType decimalCommand) {
+ byte bedTimeHour = decimalCommand.byteValue();
alarmClock.setBedtimeHour(bedTimeHour);
}
break;
}
case CHANNEL_BRIDGE_CLOCK_ALARM1_BEDTIME_MINUTE:
case CHANNEL_BRIDGE_CLOCK_ALARM2_BEDTIME_MINUTE: {
- if (command instanceof DecimalType) {
- byte bedTimeMinute = ((DecimalType) command).byteValue();
+ if (command instanceof DecimalType decimalCommand) {
+ byte bedTimeMinute = decimalCommand.byteValue();
alarmClock.setBedtimeMinute(bedTimeMinute);
}
break;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(VelbusThingDiscoveryService.class);
+ return Set.of(VelbusThingDiscoveryService.class);
}
public void setDefaultPacketListener(VelbusPacketListener velbusPacketListener) {
byte[] packetBytes = packet.getBytes();
velbusBridgeHandler.sendPacket(packetBytes);
- } else if (command instanceof PercentType) {
+ } else if (command instanceof PercentType percentCommand) {
byte commandByte = COMMAND_SET_VALUE;
VelbusDimmerPacket packet = new VelbusDimmerPacket(getModuleAddress().getChannelIdentifier(channelUID),
- commandByte, ((PercentType) command).byteValue(), this.dimmerConfig.dimspeed,
- isFirstGenerationDevice());
+ commandByte, percentCommand.byteValue(), this.dimmerConfig.dimspeed, isFirstGenerationDevice());
byte[] packetBytes = packet.getBytes();
velbusBridgeHandler.sendPacket(packetBytes);
- } else if (command instanceof OnOffType) {
- byte commandByte = determineCommandByte((OnOffType) command);
+ } else if (command instanceof OnOffType onOffCommand) {
+ byte commandByte = determineCommandByte(onOffCommand);
VelbusDimmerPacket packet = new VelbusDimmerPacket(getModuleAddress().getChannelIdentifier(channelUID),
commandByte, (byte) 0x00, this.dimmerConfig.dimspeed, isFirstGenerationDevice());
return;
}
- if (channelUID.equals(memoChannel) && command instanceof StringType) {
- String memoText = ((StringType) command).toFullString();
+ if (channelUID.equals(memoChannel) && command instanceof StringType stringCommand) {
+ String memoText = stringCommand.toFullString();
String trucatedMemoText = memoText.substring(0, Math.min(memoText.length(), MEMO_TEXT_MAX_LENGTH));
String[] splittedMemoText = trucatedMemoText.split("(?<=\\G.....)");
byte[] packetBytes = packet.getBytes();
velbusBridgeHandler.sendPacket(packetBytes);
- } else if (command instanceof OnOffType) {
- byte commandByte = determineCommandByte((OnOffType) command);
+ } else if (command instanceof OnOffType onOffCommand) {
+ byte commandByte = determineCommandByte(onOffCommand);
VelbusRelayPacket packet = new VelbusRelayPacket(getModuleAddress().getChannelIdentifier(channelUID),
commandByte);
return;
}
- if (isButtonChannel(channelUID) && command instanceof StringType) {
- StringType stringTypeCommand = (StringType) command;
-
- if (stringTypeCommand.equals(PRESSED) || stringTypeCommand.equals(LONG_PRESSED)) {
+ if (isButtonChannel(channelUID) && command instanceof StringType stringCommand) {
+ if (stringCommand.equals(PRESSED) || stringCommand.equals(LONG_PRESSED)) {
VelbusButtonPacket packet = new VelbusButtonPacket(getModuleAddress().getChannelIdentifier(channelUID));
packet.Pressed();
velbusBridgeHandler.sendPacket(packet.getBytes());
triggerChannel("CH6t", CommonTriggerEvents.PRESSED);
- if (stringTypeCommand.equals(LONG_PRESSED)) {
+ if (stringCommand.equals(LONG_PRESSED)) {
packet.LongPressed();
velbusBridgeHandler.sendPacket(packet.getBytes());
triggerChannel("CH6t", CommonTriggerEvents.LONG_PRESSED);
return;
}
- if (isFeedbackChannel(channelUID) && command instanceof StringType) {
+ if (isFeedbackChannel(channelUID) && command instanceof StringType stringCommand) {
byte commandByte;
-
- StringType stringTypeCommand = (StringType) command;
- if (stringTypeCommand.equals(SET_LED)) {
+ if (stringCommand.equals(SET_LED)) {
commandByte = COMMAND_SET_LED;
- } else if (stringTypeCommand.equals(SLOW_BLINK_LED)) {
+ } else if (stringCommand.equals(SLOW_BLINK_LED)) {
commandByte = COMMAND_SLOW_BLINK_LED;
- } else if (stringTypeCommand.equals(FAST_BLINK_LED)) {
+ } else if (stringCommand.equals(FAST_BLINK_LED)) {
commandByte = COMMAND_FAST_BLINK_LED;
- } else if (stringTypeCommand.equals(VERY_FAST_BLINK_LED)) {
+ } else if (stringCommand.equals(VERY_FAST_BLINK_LED)) {
commandByte = COMMAND_VERY_FAST_BLINK_LED;
- } else if (stringTypeCommand.equals(CLEAR_LED)) {
+ } else if (stringCommand.equals(CLEAR_LED)) {
commandByte = COMMAND_CLEAR_LED;
} else {
throw new UnsupportedOperationException(
velbusBridgeHandler.sendPacket(packetBytes);
}
- if (isButtonChannel(channelUID) && command instanceof StringType) {
- StringType stringTypeCommand = (StringType) command;
-
- if (stringTypeCommand.equals(PRESSED) || stringTypeCommand.equals(LONG_PRESSED)) {
+ if (isButtonChannel(channelUID) && command instanceof StringType stringCommand) {
+ if (stringCommand.equals(PRESSED) || stringCommand.equals(LONG_PRESSED)) {
VelbusButtonPacket packet = new VelbusButtonPacket(getModuleAddress().getChannelIdentifier(channelUID));
packet.Pressed();
triggerChannel("input#CH" + getModuleAddress().getChannelNumber(channelUID),
CommonTriggerEvents.PRESSED);
- if (stringTypeCommand.equals(LONG_PRESSED)) {
+ if (stringCommand.equals(LONG_PRESSED)) {
packet.LongPressed();
velbusBridgeHandler.sendPacket(packet.getBytes());
triggerChannel("input#CH" + getModuleAddress().getChannelNumber(channelUID),
byte command = packet[4];
if (command == COMMAND_PUSH_BUTTON_STATUS && packet.length >= 6) {
-
for (int channel = 0; channel < 8; channel++) {
byte channelMask = (byte) Math.pow(2, channel);
}
case CHANNEL_MODULE_CLOCK_ALARM1_WAKEUP_HOUR:
case CHANNEL_MODULE_CLOCK_ALARM2_WAKEUP_HOUR: {
- if (command instanceof DecimalType) {
- byte wakeupHour = ((DecimalType) command).byteValue();
+ if (command instanceof DecimalType decimalCommand) {
+ byte wakeupHour = decimalCommand.byteValue();
alarmClock.setWakeupHour(wakeupHour);
}
break;
}
case CHANNEL_MODULE_CLOCK_ALARM1_WAKEUP_MINUTE:
case CHANNEL_MODULE_CLOCK_ALARM2_WAKEUP_MINUTE: {
- if (command instanceof DecimalType) {
- byte wakeupMinute = ((DecimalType) command).byteValue();
+ if (command instanceof DecimalType decimalCommand) {
+ byte wakeupMinute = decimalCommand.byteValue();
alarmClock.setWakeupMinute(wakeupMinute);
}
break;
}
case CHANNEL_MODULE_CLOCK_ALARM1_BEDTIME_HOUR:
case CHANNEL_MODULE_CLOCK_ALARM2_BEDTIME_HOUR: {
- if (command instanceof DecimalType) {
- byte bedTimeHour = ((DecimalType) command).byteValue();
+ if (command instanceof DecimalType decimalCommand) {
+ byte bedTimeHour = decimalCommand.byteValue();
alarmClock.setBedtimeHour(bedTimeHour);
}
break;
}
case CHANNEL_MODULE_CLOCK_ALARM1_BEDTIME_MINUTE:
case CHANNEL_MODULE_CLOCK_ALARM2_BEDTIME_MINUTE: {
- if (command instanceof DecimalType) {
- byte bedTimeMinute = ((DecimalType) command).byteValue();
+ if (command instanceof DecimalType decimalCommand) {
+ byte bedTimeMinute = decimalCommand.byteValue();
alarmClock.setBedtimeMinute(bedTimeMinute);
}
break;
} else if (isThermostatChannel(channelUID)
&& (command instanceof QuantityType<?> || command instanceof DecimalType)) {
byte temperatureVariable = determineTemperatureVariable(channelUID);
- QuantityType<?> temperatureInDegreesCelcius = (command instanceof QuantityType<?>)
- ? ((QuantityType<?>) command).toUnit(SIUnits.CELSIUS)
+ QuantityType<?> temperatureInDegreesCelcius = (command instanceof QuantityType<?> qt)
+ ? qt.toUnit(SIUnits.CELSIUS)
: new QuantityType<>(((DecimalType) command), SIUnits.CELSIUS);
if (temperatureInDegreesCelcius != null) {
byte[] packetBytes = packet.getBytes();
velbusBridgeHandler.sendPacket(packetBytes);
}
- } else if (channelUID.equals(operatingModeChannel) && command instanceof StringType) {
- byte commandByte = ((StringType) command).equals(OPERATING_MODE_HEATING) ? COMMAND_SET_HEATING_MODE
+ } else if (channelUID.equals(operatingModeChannel) && command instanceof StringType stringCommand) {
+ byte commandByte = stringCommand.equals(OPERATING_MODE_HEATING) ? COMMAND_SET_HEATING_MODE
: COMMAND_SET_COOLING_MODE;
VelbusThermostatOperatingModePacket packet = new VelbusThermostatOperatingModePacket(
byte[] packetBytes = packet.getBytes();
velbusBridgeHandler.sendPacket(packetBytes);
- } else if (channelUID.equals(modeChannel) && command instanceof StringType) {
+ } else if (channelUID.equals(modeChannel) && command instanceof StringType stringCommand) {
byte commandByte = COMMAND_SWITCH_TO_SAFE_MODE;
-
- StringType stringTypeCommand = (StringType) command;
- if (stringTypeCommand.equals(MODE_COMFORT)) {
+ if (stringCommand.equals(MODE_COMFORT)) {
commandByte = COMMAND_SWITCH_TO_COMFORT_MODE;
- } else if (stringTypeCommand.equals(MODE_DAY)) {
+ } else if (stringCommand.equals(MODE_DAY)) {
commandByte = COMMAND_SWITCH_TO_DAY_MODE;
- } else if (stringTypeCommand.equals(MODE_NIGHT)) {
+ } else if (stringCommand.equals(MODE_NIGHT)) {
commandByte = COMMAND_SWITCH_TO_NIGHT_MODE;
}
return null;
}
ThingHandler bridgeHandler = bridge.getHandler();
- if (bridgeHandler instanceof VelbusBridgeHandler) {
- VelbusBridgeHandler velbusBridgeHandler = (VelbusBridgeHandler) bridgeHandler;
+ if (bridgeHandler instanceof VelbusBridgeHandler velbusBridgeHandler) {
this.velbusBridgeHandler = velbusBridgeHandler;
if (velbusModuleAddress != null) {
byte[] packetBytes = packet.getBytes();
velbusBridgeHandler.sendPacket(packetBytes);
- } else if (command instanceof PercentType && isAnalogOutputChannel(channelUID)) {
+ } else if (command instanceof PercentType percentCommand && isAnalogOutputChannel(channelUID)) {
VelbusDimmerPacket packet = new VelbusDimmerPacket(
new VelbusChannelIdentifier(this.getModuleAddress().getAddress(), channelByte), COMMAND_SET_VALUE,
- ((PercentType) command).byteValue(), 0x00, false);
+ percentCommand.byteValue(), 0x00, false);
byte[] packetBytes = packet.getBytes();
velbusBridgeHandler.sendPacket(packetBytes);
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof VeluxBridgeHandler) {
- this.bridgeHandler = (VeluxBridgeHandler) handler;
+ if (handler instanceof VeluxBridgeHandler veluxBridgeHandler) {
+ this.bridgeHandler = veluxBridgeHandler;
}
}
*/
@Override
public VeluxGwFirmware getFirmware() {
- VeluxGwFirmware gwFirmware = new VeluxGwFirmware(response.data.version);
- return gwFirmware;
+ return new VeluxGwFirmware(response.data.version);
}
}
*/
@Override
public VeluxGwLAN getLANConfig() {
- VeluxGwLAN gwLAN = new VeluxGwLAN(response.data.ipAddress, response.data.subnetMask,
- response.data.defaultGateway, response.data.dhcp);
- return gwLAN;
+ return new VeluxGwLAN(response.data.ipAddress, response.data.subnetMask, response.data.defaultGateway,
+ response.data.dhcp);
}
}
*/
@Override
public VeluxGwWLAN getWLANConfig() {
- VeluxGwWLAN gwWLAN = new VeluxGwWLAN(response.data.name, response.data.password);
- return gwWLAN;
+ return new VeluxGwWLAN(response.data.name, response.data.password);
}
}
veluxBindingHandlers.remove(thingHandler);
} else
// Handle Bridge removal
- if (thingHandler instanceof VeluxBridgeHandler) {
+ if (thingHandler instanceof VeluxBridgeHandler veluxBridgeHandler) {
logger.trace("removeHandler() removing bridge '{}'.", thingHandler.toString());
veluxBridgeHandlers.remove(thingHandler);
- unregisterDeviceDiscoveryService((VeluxBridgeHandler) thingHandler);
+ unregisterDeviceDiscoveryService(veluxBridgeHandler);
} else
// Handle removal of Things behind the Bridge
if (thingHandler instanceof VeluxHandler) {
switch (channelId) {
case CHANNEL_VANE_POSITION:
- if (command instanceof PercentType) {
+ if (command instanceof PercentType percentCommand) {
VeluxProduct existingProductClone = existingProducts.get(productBridgeIndex).clone();
- existingProductClone.setVanePosition(
- new VeluxProductPosition((PercentType) command).getPositionAsVeluxType());
+ existingProductClone
+ .setVanePosition(new VeluxProductPosition(percentCommand).getPositionAsVeluxType());
functionalParameters = existingProductClone.getFunctionalParameters();
}
break;
: new VeluxProductPosition(PercentType.HUNDRED);
} else if (command instanceof StopMoveType) {
mainParameter = StopMoveType.STOP.equals(command) ? new VeluxProductPosition() : mainParameter;
- } else if (command instanceof PercentType) {
- PercentType ptCommand = (PercentType) command;
+ } else if (command instanceof PercentType percentCommand) {
if (veluxActuator.isInverted()) {
- ptCommand = new PercentType(PercentType.HUNDRED.intValue() - ptCommand.intValue());
+ percentCommand = new PercentType(
+ PercentType.HUNDRED.intValue() - percentCommand.intValue());
}
- mainParameter = new VeluxProductPosition(ptCommand);
+ mainParameter = new VeluxProductPosition(percentCommand);
}
break;
LOGGER.debug("handleCommand(): sending command '{}' for channel id '{}'.", command, channelId);
RunProductCommand bcp = thisBridgeHandler.thisBridge.bridgeAPI().runProductCommand();
boolean success = false;
- if (bcp instanceof SCrunProductCommand) {
+ if (bcp instanceof SCrunProductCommand productCommand) {
synchronized (bcp) {
if (bcp.setNodeIdAndParameters(productBridgeIndex.toInt(), mainParameter, functionalParameters)
&& thisBridgeHandler.thisBridge.bridgeCommunicate(bcp)
.autoRefresh(thisBridgeHandler.thisBridge)) {
LOGGER.trace("handleCommand(): actuator position will be updated via polling.");
}
- if (existingProducts.update(((SCrunProductCommand) bcp).getProduct())) {
+ if (existingProducts.update(productCommand.getProduct())) {
LOGGER.trace("handleCommand(): actuator position immediate update requested.");
}
}
private void updateDynamicChannels() {
getThing().getThings().stream().forEach(thing -> {
ThingHandler thingHandler = thing.getHandler();
- if (thingHandler instanceof VeluxHandler) {
- ((VeluxHandler) thingHandler).updateDynamicChannels(this);
+ if (thingHandler instanceof VeluxHandler veluxHandler) {
+ veluxHandler.updateDynamicChannels(this);
}
});
}
*
* @author AndrewFG - Initial contribution.
*/
- public static enum ProductState {
+ public enum ProductState {
NON_EXECUTING(0),
ERROR(1),
NOT_USED(2),
*
* @author AndrewFG - Initial contribution.
*/
- public static enum DataSource {
+ public enum DataSource {
GATEWAY,
- BINDING;
+ BINDING
}
// Class internal
*
* @author AndrewFG - Initial contribution.
*/
- public static enum PositionType {
+ public enum PositionType {
ABSOLUTE_VALUE(0f),
OFFSET_POSITIVE(1f),
OFFSET_NEGATIVE(-1f);
SWITCH,
UNDEFTYPE;
- public static enum ActuatorType {
+ public enum ActuatorType {
UNDEFTYPE((short) 0xffff, VeluxBindingConstants.UNKNOWN, VeluxProductType.SWITCH),
BLIND_1_0((short) 0x0040, "Interior Venetian Blind", VeluxProductType.SLIDER_SHUTTER),
ROLLERSHUTTER_2_0((short) 0x0080, "Roller Shutter", VeluxProductType.SLIDER_SHUTTER),
* @return <B>bundleVersion</B> the resulted bundle version as {@link String}.
*/
public static String getBundleVersion() {
- String osgiBundleVersion = FrameworkUtil.getBundle(ManifestInformation.class).getBundleContext().getBundle()
- .toString();
- return osgiBundleVersion;
+ return FrameworkUtil.getBundle(ManifestInformation.class).getBundleContext().getBundle().toString();
}
}
@Order(3)
public void testSCgetProduct() {
// initialise the test parameters
- final String packet = "06 00 06 00 48 6F 62 62 79 6B 61 6D 65 72 00 00 00 00 00 00 00 00 00 00 00 00 00 00"
- + " 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"
- + " 00 00 00 00 00 01 04 40 00 00 00 00 00 00 00 00 00 00 00 00 00 2D C8 00 C8 00 F7 FF F7 FF 00 00 F7 FF 00"
- + " 00 4F 00 4A EA 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00";
+ final String packet = """
+ 06 00 06 00 48 6F 62 62 79 6B 61 6D 65 72 00 00 00 00 00 00 00 00 00 00 00 00 00 00\
+ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\
+ 00 00 00 00 00 01 04 40 00 00 00 00 00 00 00 00 00 00 00 00 00 2D C8 00 C8 00 F7 FF F7 FF 00 00 F7 FF 00\
+ 00 4F 00 4A EA 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\
+ """;
final Command command = VeluxKLFAPI.Command.GW_GET_NODE_INFORMATION_NTF;
// initialise the BCP
@Order(5)
public void testSCgetProductStatus() {
// initialise the test parameters
- final String packet = "00 D8 01 06 00 01 01 02 00 C8 00 03 63 4F 00 00 00 00 00 00 00 00 00 00 00 00 00"
- + " 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00";
+ final String packet = """
+ 00 D8 01 06 00 01 01 02 00 C8 00 03 63 4F 00 00 00 00 00 00 00 00 00 00 00 00 00\
+ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\
+ """;
final Command command = VeluxKLFAPI.Command.GW_STATUS_REQUEST_NTF;
// initialise the BCP
@Order(9)
public void testSCgetProductOnVelux() {
// initialise the test parameters
- final String packet = "00 00 00 00 53 68 65 64 20 57 69 6E 64 6F 77 00 00 00 00 00 00 00 00 00 00 00 00 00"
- + " 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"
- + " 00 00 00 00 00 00 00 00 01 01 01 03 07 00 01 16 56 24 5C 26 14 19 00 FC 05 46 00 46 00 F7 FF F7"
- + " FF F7 FF F7 FF 00 00 4F 05 B3 5F 01 D8 03 B2 1C 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00";
+ final String packet = """
+ 00 00 00 00 53 68 65 64 20 57 69 6E 64 6F 77 00 00 00 00 00 00 00 00 00 00 00 00 00\
+ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\
+ 00 00 00 00 00 00 00 00 01 01 01 03 07 00 01 16 56 24 5C 26 14 19 00 FC 05 46 00 46 00 F7 FF F7\
+ FF F7 FF F7 FF 00 00 4F 05 B3 5F 01 D8 03 B2 1C 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\
+ """;
final short command = VeluxKLFAPI.Command.GW_GET_NODE_INFORMATION_NTF.getShort();
// initialise the BCP
@Test
@Order(12)
public void testSCrunProductA() {
- final String expectedString = "02 1C 08 05 00 20 00 90 00 00 00 00 00 A0 00 00 00 00 00 00 00 00 00 00 00"
- + " 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 06 00 00 00 00 00 00 00 00 00 00 00 00 00 00"
- + " 00 00 00 00 00 00 00 00 00";
+ final String expectedString = """
+ 02 1C 08 05 00 20 00 90 00 00 00 00 00 A0 00 00 00 00 00 00 00 00 00 00 00\
+ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 06 00 00 00 00 00 00 00 00 00 00 00 00 00 00\
+ 00 00 00 00 00 00 00 00 00\
+ """;
final byte[] expectedPacket = toByteArray(expectedString);
final int targetMainPosition = 0x9000;
final int targetVanePosition = 0xA000;
@Order(21)
public void testErrorStateMapping() {
// initialise the test parameters
- final String packet = "0F A3 01 06 01 00 01 02 00 9A 36 03 00 00 00 00 00 00 00 00 00 00 00 00 00"
- + " 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"
- + " 00 00 00 00 00";
+ final String packet = """
+ 0F A3 01 06 01 00 01 02 00 9A 36 03 00 00 00 00 00 00 00 00 00 00 00 00 00\
+ 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\
+ 00 00 00 00 00\
+ """;
final Command command = VeluxKLFAPI.Command.GW_STATUS_REQUEST_NTF;
// initialise the BCP
*/
package org.openhab.binding.venstarthermostat.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_COLOR_TOUCH = new ThingTypeUID(BINDING_ID, "colorTouchThermostat");
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_COLOR_TOUCH);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_COLOR_TOUCH);
// List of all Channel ids
public static final String CHANNEL_TEMPERATURE = "temperature";
public static final String CHANNEL_HUMIDITY = "humidity";
import static org.openhab.binding.venstarthermostat.internal.VenstarThermostatBindingConstants.THING_TYPE_COLOR_TOUCH;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.venstarthermostat")
public class VenstarThermostatHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_COLOR_TOUCH);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_COLOR_TOUCH);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
@Component(service = DiscoveryService.class, configurationPid = "discovery.venstarthermostat")
public class VenstarThermostatDiscoveryService extends AbstractDiscoveryService {
private final Logger logger = LoggerFactory.getLogger(VenstarThermostatDiscoveryService.class);
- private static final String COLOR_TOUCH_DISCOVERY_MESSAGE = "M-SEARCH * HTTP/1.1\r\n"
- + "Host: 239.255.255.250:1900\r\n" + "Man: ssdp:discover\r\n" + "ST: colortouch:ecp\r\n" + "\r\n";
+ private static final String COLOR_TOUCH_DISCOVERY_MESSAGE = """
+ M-SEARCH * HTTP/1.1
+ Host: 239.255.255.250:1900
+ Man: ssdp:discover
+ ST: colortouch:ecp
+
+ """;
private static final Pattern USN_PATTERN = Pattern
.compile("^(colortouch:)?ecp((?::[0-9a-fA-F]{2}){6}):name:(.+)(?::type:(\\w+))");
private static final String SSDP_MATCH = "colortouch:ecp";
@Override
public VenstarFanState deserialize(JsonElement element, Type arg1, JsonDeserializationContext arg2)
throws JsonParseException {
-
int key = element.getAsInt();
try {
return VenstarFanState.fromInt(key);
} else if (channelUID.getId().equals(CHANNEL_SYSTEM_MODE)) {
VenstarSystemMode value;
try {
- if (command instanceof StringType) {
- value = VenstarSystemMode.valueOf(((StringType) command).toString().toUpperCase());
+ if (command instanceof StringType stringCommand) {
+ value = VenstarSystemMode.valueOf(stringCommand.toString().toUpperCase());
} else {
value = VenstarSystemMode.fromInt(((DecimalType) command).intValue());
}
} else if (channelUID.getId().equals(CHANNEL_AWAY_MODE)) {
VenstarAwayMode value;
try {
- if (command instanceof StringType) {
- value = VenstarAwayMode.valueOf(((StringType) command).toString().toUpperCase());
+ if (command instanceof StringType stringCommand) {
+ value = VenstarAwayMode.valueOf(stringCommand.toString().toUpperCase());
} else {
value = VenstarAwayMode.fromInt(((DecimalType) command).intValue());
}
} else if (channelUID.getId().equals(CHANNEL_FAN_MODE)) {
VenstarFanMode value;
try {
- if (command instanceof StringType) {
- value = VenstarFanMode.valueOf(((StringType) command).toString().toUpperCase());
+ if (command instanceof StringType stringCommand) {
+ value = VenstarFanMode.valueOf(stringCommand.toString().toUpperCase());
} else {
value = VenstarFanMode.fromInt(((DecimalType) command).intValue());
}
} else if (channelUID.getId().equals(CHANNEL_SCHEDULE_MODE)) {
VenstarScheduleMode value;
try {
- if (command instanceof StringType) {
- value = VenstarScheduleMode.valueOf(((StringType) command).toString().toUpperCase());
+ if (command instanceof StringType stringCommand) {
+ value = VenstarScheduleMode.valueOf(stringCommand.toString().toUpperCase());
} else {
value = VenstarScheduleMode.fromInt(((DecimalType) command).intValue());
}
private State getTemperature() {
Optional<VenstarSensor> optSensor = sensorData.stream()
- .filter(sensor -> sensor.getName().equalsIgnoreCase("Thermostat")).findAny();
+ .filter(sensor -> "Thermostat".equalsIgnoreCase(sensor.getName())).findAny();
if (optSensor.isPresent()) {
return new QuantityType<Temperature>(optSensor.get().getTemp(), unitSystem);
}
private State getHumidity() {
Optional<VenstarSensor> optSensor = sensorData.stream()
- .filter(sensor -> sensor.getName().equalsIgnoreCase("Thermostat")).findAny();
+ .filter(sensor -> "Thermostat".equalsIgnoreCase(sensor.getName())).findAny();
if (optSensor.isPresent()) {
return new QuantityType<Dimensionless>(optSensor.get().getHum(), Units.PERCENT);
}
private State getOutdoorTemperature() {
Optional<VenstarSensor> optSensor = sensorData.stream()
- .filter(sensor -> sensor.getName().equalsIgnoreCase("Outdoor")).findAny();
+ .filter(sensor -> "Outdoor".equalsIgnoreCase(sensor.getName())).findAny();
if (optSensor.isPresent()) {
return new QuantityType<Temperature>(optSensor.get().getTemp(), unitSystem);
}
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime now = LocalDateTime.now().atZone(zoneId);
int diff = now.getOffset().getTotalSeconds();
- ZonedDateTime z = ZonedDateTime.ofInstant(Instant.ofEpochSecond(runtime.getTimeStamp() - diff), zoneId);
- return z;
+ return ZonedDateTime.ofInstant(Instant.ofEpochSecond(runtime.getTimeStamp() - diff), zoneId);
}
private void updateScheduleMode(VenstarScheduleMode schedule) {
}
protected DecimalType commandToDecimalType(Command command) {
- if (command instanceof DecimalType) {
- return (DecimalType) command;
+ if (command instanceof DecimalType decimalCommand) {
+ return decimalCommand;
}
return new DecimalType(new BigDecimal(command.toString()));
}
}
}
br.close();
- socket.close();
} catch (IOException e) {
callback.communicationProblem();
}
logger.debug("sendingArray: {}", Arrays.toString(dataToSend));
output.write(dataToSend);
- socket.close();
}
}
}
break;
case VentaAirBindingConstants.CHANNEL_FAN_SPEED:
- if (command instanceof DecimalType) {
- int fanStage = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ int fanStage = decimalCommand.intValue();
dispatchActionToDevice(new FanAction(fanStage));
}
break;
case VentaAirBindingConstants.CHANNEL_TARGET_HUMIDITY:
- if (command instanceof DecimalType) {
- int targetHumidity = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ int targetHumidity = decimalCommand.intValue();
dispatchActionToDevice(new HumidityAction(targetHumidity));
}
break;
case VentaAirBindingConstants.CHANNEL_TIMER:
- if (command instanceof DecimalType) {
- int timer = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ int timer = decimalCommand.intValue();
dispatchActionToDevice(new TimerAction(timer));
}
break;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
@Component(service = DiscoveryService.class, configurationPid = "discovery.ventaair")
public class VentaDeviceDiscovery extends AbstractDiscoveryService {
private static final String REPRESENTATION_PROPERTY = "macAddress";
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .singleton(VentaAirBindingConstants.THING_TYPE_LW60T);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set
+ .of(VentaAirBindingConstants.THING_TYPE_LW60T);
// defined as int, because AbstractDiscoveryService wants and int and not long as provided by Duration.getSeconds()
private static final int MANUAL_DISCOVERY_TIME = 30;
private static final Duration TIME_BETWEEN_SCANS = Duration.ofSeconds(30);
if (deviceId != null) {
deviceId = VerisureThingConfiguration.normalizeDeviceId(deviceId);
VerisureThingDTO mouseThing = verisureThings.get(deviceId);
- if (mouseThing != null && mouseThing instanceof VerisureMiceDetectionDTO) {
+ if (mouseThing instanceof VerisureMiceDetectionDTO) {
VerisureMiceDetectionDTO miceDetectorThing = (VerisureMiceDetectionDTO) mouseThing;
miceDetectorThing.setTemperatureValue(climate.getTemperatureValue());
miceDetectorThing.setTemperatureTime(climate.getTemperatureTimestamp());
package org.openhab.binding.verisure.internal.discovery;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
@Override
public void activate() {
- super.activate(Collections.singletonMap(DiscoveryService.CONFIG_PROPERTY_BACKGROUND_DISCOVERY, true));
+ super.activate(Map.of(DiscoveryService.CONFIG_PROPERTY_BACKGROUND_DISCOVERY, true));
}
@Override
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof VerisureBridgeHandler) {
- verisureBridgeHandler = (VerisureBridgeHandler) handler;
+ if (handler instanceof VerisureBridgeHandler verisureBridgeHandler) {
+ this.verisureBridgeHandler = verisureBridgeHandler;
bridgeUID = verisureBridgeHandler.getUID();
}
}
import java.math.BigDecimal;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@NonNullByDefault
public class VerisureAlarmThingHandler extends VerisureThingHandler<VerisureAlarmsDTO> {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_ALARM);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_ALARM);
private static final int REFRESH_DELAY_SECONDS = 10;
String alarmStatus = armState.getStatusType();
if (alarmStatus != null) {
getThing().getChannels().stream().map(Channel::getUID)
- .filter(channelUID -> isLinked(channelUID) && !channelUID.getId().equals("timestamp"))
+ .filter(channelUID -> isLinked(channelUID) && !"timestamp".equals(channelUID.getId()))
.forEach(channelUID -> {
State state = getValue(channelUID.getId(), armState);
updateState(channelUID, state);
import static org.openhab.binding.verisure.internal.VerisureBindingConstants.*;
import java.util.Collection;
-import java.util.Collections;
import java.util.Set;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledFuture;
@NonNullByDefault
public class VerisureBridgeHandler 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 int REFRESH_DELAY_SECONDS = 30;
private final Logger logger = LoggerFactory.getLogger(VerisureBridgeHandler.class);
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(VerisureThingDiscoveryService.class);
+ return Set.of(VerisureThingDiscoveryService.class);
}
private void refreshAndUpdateStatus() {
import static org.openhab.binding.verisure.internal.VerisureBindingConstants.*;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@NonNullByDefault
public class VerisureBroadbandConnectionThingHandler extends VerisureThingHandler<VerisureBroadbandConnectionsDTO> {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections
- .singleton(THING_TYPE_BROADBAND_CONNECTION);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BROADBAND_CONNECTION);
public VerisureBroadbandConnectionThingHandler(Thing thing) {
super(thing);
private void updateClimateDeviceState(VerisureClimatesDTO climateJSON) {
getThing().getChannels().stream().map(Channel::getUID)
- .filter(channelUID -> isLinked(channelUID) && !channelUID.getId().equals("timestamp"))
+ .filter(channelUID -> isLinked(channelUID) && !"timestamp".equals(channelUID.getId()))
.forEach(channelUID -> {
State state = getValue(channelUID.getId(), climateJSON);
updateState(channelUID, state);
import static org.openhab.binding.verisure.internal.VerisureBindingConstants.*;
-import java.util.Collections;
import java.util.List;
import java.util.Set;
@NonNullByDefault
public class VerisureDoorWindowThingHandler extends VerisureThingHandler<VerisureDoorWindowsDTO> {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_DOORWINDOW);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_DOORWINDOW);
public VerisureDoorWindowThingHandler(Thing thing) {
super(thing);
DoorWindow doorWindow = doorWindowList.get(0);
getThing().getChannels().stream().map(Channel::getUID)
- .filter(channelUID -> isLinked(channelUID) && !channelUID.getId().equals("timestamp"))
+ .filter(channelUID -> isLinked(channelUID) && !"timestamp".equals(channelUID.getId()))
.forEach(channelUID -> {
State state = getValue(channelUID.getId(), doorWindow, doorWindowJSON);
updateState(channelUID, state);
private BigDecimal lastEventId = BigDecimal.ZERO;
private long lastEventTime = 0;
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_EVENT_LOG);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_EVENT_LOG);
public VerisureEventLogThingHandler(Thing thing) {
super(thing);
private void updateEventLogState(VerisureEventLogDTO eventLogJSON) {
EventLog eventLog = eventLogJSON.getData().getInstallation().getEventLog();
- if (eventLog.getPagedList().size() > 0) {
+ if (!eventLog.getPagedList().isEmpty()) {
getThing().getChannels().stream().map(Channel::getUID).filter(channelUID -> isLinked(channelUID))
.forEach(channelUID -> {
State state = getValue(channelUID.getId(), eventLogJSON, eventLog);
import static org.openhab.binding.verisure.internal.VerisureBindingConstants.*;
-import java.util.Collections;
import java.util.List;
import java.util.Set;
@NonNullByDefault
public class VerisureGatewayThingHandler extends VerisureThingHandler<VerisureGatewayDTO> {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_GATEWAY);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_GATEWAY);
public VerisureGatewayThingHandler(Thing thing) {
super(thing);
import static org.openhab.binding.verisure.internal.VerisureBindingConstants.*;
-import java.util.Collections;
import java.util.List;
import java.util.Set;
@NonNullByDefault
public class VerisureMiceDetectionThingHandler extends VerisureThingHandler<VerisureMiceDetectionDTO> {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_MICE_DETECTION);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_MICE_DETECTION);
public VerisureMiceDetectionThingHandler(Thing thing) {
super(thing);
if (!miceList.isEmpty()) {
Mouse mouse = miceList.get(0);
getThing().getChannels().stream().map(Channel::getUID).filter(channelUID -> isLinked(channelUID)
- && !channelUID.getId().equals("timestamp") && !channelUID.getId().equals("temperatureTimestamp"))
+ && !"timestamp".equals(channelUID.getId()) && !"temperatureTimestamp".equals(channelUID.getId()))
.forEach(channelUID -> {
State state = getValue(channelUID.getId(), miceDetectionJSON, mouse);
updateState(channelUID, state);
});
- if (mouse.getDetections().size() != 0) {
+ if (!mouse.getDetections().isEmpty()) {
updateTimeStamp(mouse.getDetections().get(0).getNodeTime());
}
updateTimeStamp(miceDetectionJSON.getTemperatureTime(), CHANNEL_TEMPERATURE_TIMESTAMP);
public State getValue(String channelId, VerisureMiceDetectionDTO miceDetectionJSON, Mouse mouse) {
switch (channelId) {
case CHANNEL_COUNT_LATEST_DETECTION:
- if (mouse.getDetections().size() == 0) {
+ if (mouse.getDetections().isEmpty()) {
return new DecimalType(0);
} else {
return new DecimalType(mouse.getDetections().get(0).getCount());
}
case CHANNEL_COUNT_LAST_24_HOURS:
- if (mouse.getDetections().size() == 0) {
+ if (mouse.getDetections().isEmpty()) {
return new DecimalType(0);
} else {
return new DecimalType(mouse.getDetections().stream().mapToInt(Detection::getCount).sum());
}
case CHANNEL_DURATION_LATEST_DETECTION:
- if (mouse.getDetections().size() == 0) {
+ if (mouse.getDetections().isEmpty()) {
return new QuantityType<Time>(0, Units.SECOND);
} else {
return new QuantityType<Time>(mouse.getDetections().get(0).getDuration(), Units.SECOND);
}
case CHANNEL_DURATION_LAST_24_HOURS:
- if (mouse.getDetections().size() == 0) {
+ if (mouse.getDetections().isEmpty()) {
return new QuantityType<Time>(0, Units.SECOND);
} else {
return new QuantityType<Time>(mouse.getDetections().stream().mapToInt(Detection::getDuration).sum(),
import java.math.BigDecimal;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
@NonNullByDefault
public class VerisureSmartLockThingHandler extends VerisureThingHandler<VerisureSmartLocksDTO> {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_SMARTLOCK);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_SMARTLOCK);
private static final int REFRESH_DELAY_SECONDS = 10;
VerisureSmartLockDTO smartLockJSON = smartLocksJSON.getSmartLockJSON();
if (smartLockStatus != null) {
getThing().getChannels().stream().map(Channel::getUID)
- .filter(channelUID -> isLinked(channelUID) && !channelUID.getId().equals("timestamp"))
+ .filter(channelUID -> isLinked(channelUID) && !"timestamp".equals(channelUID.getId()))
.forEach(channelUID -> {
State state = getValue(channelUID.getId(), doorlock, smartLockStatus, smartLockJSON);
updateState(channelUID, state);
import java.math.BigDecimal;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
import java.util.Set;
@NonNullByDefault
public class VerisureSmartPlugThingHandler extends VerisureThingHandler<VerisureSmartPlugsDTO> {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_SMARTPLUG);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_SMARTPLUG);
private static final int REFRESH_DELAY_SECONDS = 10;
String smartPlugStatus = smartplug.getCurrentState();
if (smartPlugStatus != null) {
getThing().getChannels().stream().map(Channel::getUID)
- .filter(channelUID -> isLinked(channelUID) && !channelUID.getId().equals("timestamp"))
+ .filter(channelUID -> isLinked(channelUID) && !"timestamp".equals(channelUID.getId()))
.forEach(channelUID -> {
State state = getValue(channelUID.getId(), smartplug, smartPlugStatus);
updateState(channelUID, state);
import static org.openhab.binding.verisure.internal.VerisureBindingConstants.*;
-import java.util.Collections;
import java.util.List;
import java.util.Set;
@NonNullByDefault
public class VerisureUserPresenceThingHandler extends VerisureThingHandler<VerisureUserPresencesDTO> {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_USERPRESENCE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_USERPRESENCE);
public VerisureUserPresenceThingHandler(Thing thing) {
super(thing);
if (!userTrackingList.isEmpty()) {
UserTracking userTracking = userTrackingList.get(0);
getThing().getChannels().stream().map(Channel::getUID)
- .filter(channelUID -> isLinked(channelUID) && !channelUID.getId().equals("timestamp"))
+ .filter(channelUID -> isLinked(channelUID) && !"timestamp".equals(channelUID.getId()))
.forEach(channelUID -> {
State state = getValue(channelUID.getId(), userTracking);
updateState(channelUID, state);
requestData.applyAuthentication(loggedInSession);
// Apply specific addressing parameters
- if (requestData instanceof VeSyncRequestManagedDeviceBypassV2) {
+ if (requestData instanceof VeSyncRequestManagedDeviceBypassV2 veSyncRequestManagedDeviceBypassV2) {
final VeSyncManagedDeviceBase deviceData = macLookup.get(macId);
if (deviceData == null) {
throw new DeviceUnknownException(String.format("Device not discovered with mac id: %s", macId));
}
- ((VeSyncRequestManagedDeviceBypassV2) requestData).cid = deviceData.cid;
- ((VeSyncRequestManagedDeviceBypassV2) requestData).configModule = deviceData.configModule;
- ((VeSyncRequestManagedDeviceBypassV2) requestData).deviceRegion = deviceData.deviceRegion;
+ veSyncRequestManagedDeviceBypassV2.cid = deviceData.cid;
+ veSyncRequestManagedDeviceBypassV2.configModule = deviceData.configModule;
+ veSyncRequestManagedDeviceBypassV2.deviceRegion = deviceData.deviceRegion;
}
return reqV1Authorized(url, requestData);
}
public String reqV1Authorized(final String url, final VeSyncAuthenticatedRequest requestData)
throws AuthenticationException {
- try {
- return directReqV1Authorized(url, requestData);
- } catch (final AuthenticationException ae) {
- throw ae;
- }
+ return directReqV1Authorized(url, requestData);
}
private String directReqV1Authorized(final String url, final VeSyncAuthenticatedRequest requestData)
import static org.openhab.binding.vesync.internal.VeSyncConstants.*;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class VeSyncDiscoveryService extends AbstractDiscoveryService
implements DiscoveryService, ThingHandlerService, DeviceMetaDataUpdatedHandler {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_BRIDGE);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BRIDGE);
private static final int DISCOVER_TIMEOUT_SECONDS = 5;
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof VeSyncBridgeHandler) {
- bridgeHandler = (VeSyncBridgeHandler) handler;
+ if (handler instanceof VeSyncBridgeHandler veSyncBridgeHandler) {
+ bridgeHandler = veSyncBridgeHandler;
bridgeUID = bridgeHandler.getUID();
}
}
protected boolean isDeviceOnline() {
BridgeHandler bridgeHandler = getBridgeHandler();
- if (bridgeHandler != null && bridgeHandler instanceof VeSyncBridgeHandler) {
- VeSyncBridgeHandler vesyncBridgeHandler = (VeSyncBridgeHandler) bridgeHandler;
+ if (bridgeHandler instanceof VeSyncBridgeHandler veSyncBridgeHandler) {
@Nullable
- VeSyncManagedDeviceBase metadata = vesyncBridgeHandler.api.getMacLookupMap().get(deviceLookupKey);
+ VeSyncManagedDeviceBase metadata = veSyncBridgeHandler.api.getMacLookupMap().get(deviceLookupKey);
if (metadata == null) {
return false;
Map<String, String> newProps = null;
BridgeHandler bridgeHandler = getBridgeHandler();
- if (bridgeHandler != null && bridgeHandler instanceof VeSyncBridgeHandler) {
- VeSyncBridgeHandler vesyncBridgeHandler = (VeSyncBridgeHandler) bridgeHandler;
+ if (bridgeHandler instanceof VeSyncBridgeHandler veSyncBridgeHandler) {
@Nullable
- VeSyncManagedDeviceBase metadata = vesyncBridgeHandler.api.getMacLookupMap().get(deviceLookupKey);
+ VeSyncManagedDeviceBase metadata = veSyncBridgeHandler.api.getMacLookupMap().get(deviceLookupKey);
if (metadata == null) {
return;
return null;
}
ThingHandler handler = bridge.getHandler();
- if (handler instanceof VeSyncClient) {
- veSyncClient = (VeSyncClient) handler;
+ if (handler instanceof VeSyncClient client) {
+ veSyncClient = client;
} else {
return null;
}
protected void requestBridgeFreqScanMetadataIfReq() {
if (requiresMetaDataFrequentUpdates()) {
BridgeHandler bridgeHandler = getBridgeHandler();
- if (bridgeHandler != null && bridgeHandler instanceof VeSyncBridgeHandler) {
- VeSyncBridgeHandler vesyncBridgeHandler = (VeSyncBridgeHandler) bridgeHandler;
+ if (bridgeHandler instanceof VeSyncBridgeHandler vesyncBridgeHandler) {
vesyncBridgeHandler.checkIfIncreaseScanRateRequired();
}
}
final VeSyncDeviceConfiguration config = getConfigAs(VeSyncDeviceConfiguration.class);
BridgeHandler bridgeHandler = getBridgeHandler();
- if (bridgeHandler != null && bridgeHandler instanceof VeSyncBridgeHandler) {
- VeSyncBridgeHandler vesyncBridgeHandler = (VeSyncBridgeHandler) bridgeHandler;
+ if (bridgeHandler instanceof VeSyncBridgeHandler vesyncBridgeHandler) {
final String configMac = config.macId;
import static org.openhab.binding.vesync.internal.VeSyncConstants.*;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
boolean frequentScanReq = false;
for (Thing th : getThing().getThings()) {
ThingHandler handler = th.getHandler();
- if (handler instanceof VeSyncBaseDeviceHandler) {
- if (((VeSyncBaseDeviceHandler) handler).requiresMetaDataFrequentUpdates()) {
+ if (handler instanceof VeSyncBaseDeviceHandler veSyncBaseDeviceHandler) {
+ if (veSyncBaseDeviceHandler.requiresMetaDataFrequentUpdates()) {
frequentScanReq = true;
break;
}
}
private void updateThing(VeSyncBridgeConfiguration config, @Nullable ThingHandler handler) {
- if (handler instanceof VeSyncBaseDeviceHandler) {
- ((VeSyncBaseDeviceHandler) handler).updateDeviceMetaData();
- ((VeSyncBaseDeviceHandler) handler).updateBridgeBasedPolls(config);
+ if (handler instanceof VeSyncBaseDeviceHandler veSyncBaseDeviceHandler) {
+ veSyncBaseDeviceHandler.updateDeviceMetaData();
+ veSyncBaseDeviceHandler.updateBridgeBasedPolls(config);
}
}
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(VeSyncDiscoveryService.class);
+ return Set.of(VeSyncDiscoveryService.class);
}
@Override
this.updateProperties(newProps);
}
+ @Override
public String reqV2Authorized(final String url, final String macId, final VeSyncAuthenticatedRequest requestData)
throws AuthenticationException, DeviceUnknownException {
return api.reqV2Authorized(url, macId, requestData);
logger.warn("Warm mode API is unknown in order to send the command");
break;
}
- } else if (command instanceof QuantityType) {
+ } else if (command instanceof QuantityType quantityCommand) {
switch (channelUID.getId()) {
case DEVICE_CHANNEL_CONFIG_TARGET_HUMIDITY:
- int targetHumidity = ((QuantityType<?>) command).intValue();
+ int targetHumidity = quantityCommand.intValue();
if (targetHumidity < 30) {
logger.warn("Target Humidity less than 30 - adjusting to 30 as the valid API value");
targetHumidity = 30;
new VeSyncRequestManagedDeviceBypassV2.SetTargetHumidity(targetHumidity));
break;
case DEVICE_CHANNEL_MIST_LEVEL:
- int targetMistLevel = ((QuantityType<?>) command).intValue();
+ int targetMistLevel = quantityCommand.intValue();
// If more devices have this the hope is it's those with the prefix LUH so the check can
// be simplified, originally devices mapped 1/5/9 to 1/2/3.
if (DEV_FAMILY_DUAL_200S.equals(deviceFamily)) {
}
break;
}
- } else if (command instanceof QuantityType) {
+ } else if (command instanceof QuantityType quantityCommand) {
switch (channelUID.getId()) {
case DEVICE_CHANNEL_FAN_SPEED_ENABLED:
// If the fan speed is being set enforce manual mode
sendV2BypassControlCommand(DEVICE_SET_PURIFIER_MODE,
new VeSyncRequestManagedDeviceBypassV2.SetMode(MODE_MANUAL), false);
- int requestedLevel = ((QuantityType<?>) command).intValue();
+ int requestedLevel = quantityCommand.intValue();
if (requestedLevel < 1) {
logger.warn("Fan speed command less than 1 - adjusting to 1 as the valid API value");
requestedLevel = 1;
@NonNullByDefault
public class VesyncAuthenticatedRequestTest {
- public final static VesyncLoginResponse.VesyncUserSession testUser = VeSyncConstants.GSON.fromJson(
+ public static final VesyncLoginResponse.VesyncUserSession testUser = VeSyncConstants.GSON.fromJson(
org.openhab.binding.vesync.internal.handler.responses.VesyncLoginResponseTest.testGoodLoginResponseBody,
VesyncLoginResponse.class).result;
public void checkEmptyPayload() {
final VesyncRequestManagedDeviceBypassV2.EmptyPayload testPaylaod = new VesyncRequestManagedDeviceBypassV2.EmptyPayload();
final String contentTest1 = VeSyncConstants.GSON.toJson(testPaylaod);
- assertEquals(true, contentTest1.equals("{}"));
+ assertEquals(true, "{}".equals(contentTest1));
}
@Test
@NonNullByDefault
public class VesyncLoginResponseTest {
- public final static String testGoodLoginResponseBody = "{\r\n" + " \"traceId\": \"1634253816\",\r\n"
- + " \"code\": 0,\r\n" + " \"msg\": \"request success\",\r\n" + " \"result\": {\r\n"
- + " \"isRequiredVerify\": true,\r\n" + " \"accountID\": \"5328043\",\r\n"
- + " \"avatarIcon\": \"https://image.vesync.com/defaultImages/user/avatar_nor.png\",\r\n"
- + " \"birthday\": \"\",\r\n" + " \"gender\": \"\",\r\n"
- + " \"acceptLanguage\": \"en\",\r\n" + " \"userType\": \"1\",\r\n"
- + " \"nickName\": \"david.goodyear\",\r\n" + " \"mailConfirmation\": true,\r\n"
- + " \"termsStatus\": true,\r\n" + " \"gdprStatus\": true,\r\n"
- + " \"countryCode\": \"GB\",\r\n" + " \"registerAppVersion\": \"VeSync 3.1.37 build3\",\r\n"
- + " \"registerTime\": \"2021-10-14 17:35:50\",\r\n"
- + " \"verifyEmail\": \"david.goodyear@gmail.com\",\r\n" + " \"heightCm\": 0.0,\r\n"
- + " \"weightTargetSt\": 0.0,\r\n" + " \"heightUnit\": \"FT\",\r\n"
- + " \"heightFt\": 0.0,\r\n" + " \"weightTargetKg\": 0.0,\r\n"
- + " \"weightTargetLb\": 0.0,\r\n" + " \"weightUnit\": \"LB\",\r\n"
- + " \"targetBfr\": 0.0,\r\n" + " \"displayFlag\": [],\r\n"
- + " \"real_weight_kg\": 0.0,\r\n" + " \"real_weight_lb\": 0.0,\r\n"
- + " \"real_weight_unit\": \"lb\",\r\n" + " \"heart_rate_zones\": 0.0,\r\n"
- + " \"run_step_long_cm\": 0.0,\r\n" + " \"walk_step_long_cm\": 0.0,\r\n"
- + " \"step_target\": 0.0,\r\n" + " \"sleep_target_mins\": 0.0,\r\n"
- + " \"token\": \"AccessTokenString=\"\r\n" + " }\r\n" + "}";
+ public static final String testGoodLoginResponseBody = """
+ {
+ "traceId": "1634253816",
+ "code": 0,
+ "msg": "request success",
+ "result": {
+ "isRequiredVerify": true,
+ "accountID": "5328043",
+ "avatarIcon": "https://image.vesync.com/defaultImages/user/avatar_nor.png",
+ "birthday": "",
+ "gender": "",
+ "acceptLanguage": "en",
+ "userType": "1",
+ "nickName": "david.goodyear",
+ "mailConfirmation": true,
+ "termsStatus": true,
+ "gdprStatus": true,
+ "countryCode": "GB",
+ "registerAppVersion": "VeSync 3.1.37 build3",
+ "registerTime": "2021-10-14 17:35:50",
+ "verifyEmail": "david.goodyear@gmail.com",
+ "heightCm": 0.0,
+ "weightTargetSt": 0.0,
+ "heightUnit": "FT",
+ "heightFt": 0.0,
+ "weightTargetKg": 0.0,
+ "weightTargetLb": 0.0,
+ "weightUnit": "LB",
+ "targetBfr": 0.0,
+ "displayFlag": [],
+ "real_weight_kg": 0.0,
+ "real_weight_lb": 0.0,
+ "real_weight_unit": "lb",
+ "heart_rate_zones": 0.0,
+ "run_step_long_cm": 0.0,
+ "walk_step_long_cm": 0.0,
+ "step_target": 0.0,
+ "sleep_target_mins": 0.0,
+ "token": "AccessTokenString="
+ }
+ }\
+ """;
@Test
public void testParseLoginGoodResponse() {
@Test
public void testParseLoginFailResponse() {
- String testReponse = "{\r\n" + " \"traceId\": \"1634253816\",\r\n" + " \"code\": -11201022,\r\n"
- + " \"msg\": \"password incorrect\",\r\n" + " \"result\": null\r\n" + "}";
+ String testReponse = """
+ {
+ "traceId": "1634253816",
+ "code": -11201022,
+ "msg": "password incorrect",
+ "result": null
+ }\
+ """;
VesyncLoginResponse response = VeSyncConstants.GSON.fromJson(testReponse,
VesyncLoginResponse.class);
if (response != null) {
@NonNullByDefault
public class VesyncManagedDevicesPageTest {
- public final static String testGoodSearchResponsePageBody = "{\n" +
- " \"traceId\": \"1634387642\",\n" +
- " \"code\": 0,\n" +
- " \"msg\": \"request success\",\n" +
- " \"result\": {\n" +
- " \"total\": 2,\n" +
- " \"pageSize\": 100,\n" +
- " \"pageNo\": 1,\n" +
- " \"list\": [\n" +
- " {\n" +
- " \"deviceRegion\": \"EU\",\n" +
- " \"isOwner\": true,\n" +
- " \"authKey\": null,\n" +
- " \"deviceName\": \"Air Filter\",\n" +
- " \"deviceImg\": \"https://image.vesync.com/defaultImages/Core_400S_Series/icon_core400s_purifier_160.png\",\n" +
- " \"cid\": \"cidValue1\",\n" +
- " \"deviceStatus\": \"on\",\n" +
- " \"connectionStatus\": \"online\",\n" +
- " \"connectionType\": \"WiFi+BTOnboarding+BTNotify\",\n" +
- " \"deviceType\": \"Core400S\",\n" +
- " \"type\": \"wifi-air\",\n" +
- " \"uuid\": \"abcdefab-1234-1234-abcd-123498761234\",\n" +
- " \"configModule\": \"WiFiBTOnboardingNotify_AirPurifier_Core400S_EU\",\n" +
- " \"macID\": \"ab:cd:ef:12:34:56\",\n" +
- " \"mode\": \"simModeData\",\n" +
- " \"speed\": 4,\n" +
- " \"extension\": {\n" +
- " \"airQuality\": -1,\n" +
- " \"airQualityLevel\": 1,\n" +
- " \"mode\": \"auto\",\n" +
- " \"fanSpeedLevel\": \"1\"\n" +
- " },\n" +
- " \"currentFirmVersion\": null,\n" +
- " \"subDeviceNo\": \"simSubDevice\",\n" +
- " \"subDeviceType\": \"simSubDeviceType\",\n" +
- " \"deviceFirstSetupTime\": \"Oct 15, 2021 3:43:02 PM\"\n" +
- " }\n" +
- " ]\n" +
- " }\n" +
- "}";
+ public static final String testGoodSearchResponsePageBody = """
+ {
+ "traceId": "1634387642",
+ "code": 0,
+ "msg": "request success",
+ "result": {
+ "total": 2,
+ "pageSize": 100,
+ "pageNo": 1,
+ "list": [
+ {
+ "deviceRegion": "EU",
+ "isOwner": true,
+ "authKey": null,
+ "deviceName": "Air Filter",
+ "deviceImg": "https://image.vesync.com/defaultImages/Core_400S_Series/icon_core400s_purifier_160.png",
+ "cid": "cidValue1",
+ "deviceStatus": "on",
+ "connectionStatus": "online",
+ "connectionType": "WiFi+BTOnboarding+BTNotify",
+ "deviceType": "Core400S",
+ "type": "wifi-air",
+ "uuid": "abcdefab-1234-1234-abcd-123498761234",
+ "configModule": "WiFiBTOnboardingNotify_AirPurifier_Core400S_EU",
+ "macID": "ab:cd:ef:12:34:56",
+ "mode": "simModeData",
+ "speed": 4,
+ "extension": {
+ "airQuality": -1,
+ "airQualityLevel": 1,
+ "mode": "auto",
+ "fanSpeedLevel": "1"
+ },
+ "currentFirmVersion": null,
+ "subDeviceNo": "simSubDevice",
+ "subDeviceType": "simSubDeviceType",
+ "deviceFirstSetupTime": "Oct 15, 2021 3:43:02 PM"
+ }
+ ]
+ }
+ }\
+ """;
@Test
public void testParseManagedDevicesSearchGoodResponse() {
@NonNullByDefault
public class VesyncV1AirPurifierDeviceDetailsTest {
- public final static String testAirPurifierResponseBasedOnCore400S = "{\n" +
- " \"code\": 0,\n" +
- " \"msg\": \"request success\",\n" +
- " \"traceId\": \"1634255391\",\n" +
- " \"screenStatus\": \"on1\",\n" +
- " \"airQuality\": 1,\n" +
- " \"level\": 2,\n" +
- " \"mode\": \"manual\",\n" +
- " \"deviceName\": \"Lounge Air Purifier\",\n" +
- " \"currentFirmVersion\": \"1.0.17\",\n" +
- " \"childLock\": \"off1\",\n" +
- " \"deviceStatus\": \"on2\",\n" +
- " \"deviceImg\": \"https://image.vesync.com/defaultImages/Core_400S_Series/icon_core400s_purifier_160.png\",\n" +
- " \"connectionStatus\": \"online\"\n" +
- "}";
+ public static final String testAirPurifierResponseBasedOnCore400S = """
+ {
+ "code": 0,
+ "msg": "request success",
+ "traceId": "1634255391",
+ "screenStatus": "on1",
+ "airQuality": 1,
+ "level": 2,
+ "mode": "manual",
+ "deviceName": "Lounge Air Purifier",
+ "currentFirmVersion": "1.0.17",
+ "childLock": "off1",
+ "deviceStatus": "on2",
+ "deviceImg": "https://image.vesync.com/defaultImages/Core_400S_Series/icon_core400s_purifier_160.png",
+ "connectionStatus": "online"
+ }\
+ """;
@Test
public void testParseV1AirPurifierDeviceDetailsResponse() {
THING_TYPE_UID_TEMPERATURESENSOR, THING_TYPE_UID_PUMP, THING_TYPE_UID_VALVE)
.collect(Collectors.toSet()));
- public static final Set<ThingTypeUID> SUPPORTED_BRIDGE_THING_TYPES_UIDS = Collections
- .singleton(THING_TYPE_UID_BRIDGE);
+ public static final Set<ThingTypeUID> SUPPORTED_BRIDGE_THING_TYPES_UIDS = Set.of(THING_TYPE_UID_BRIDGE);
}
VitotronicBridgeHandler bridgeHandler = null;
ThingHandler handler = bridge.getHandler();
- if (handler instanceof VitotronicBridgeHandler) {
- bridgeHandler = (VitotronicBridgeHandler) handler;
+ if (handler instanceof VitotronicBridgeHandler vitotronicBridgeHandler) {
+ bridgeHandler = vitotronicBridgeHandler;
} else {
logger.debug("No available bridge handler found yet. Bridge: {} .", bridge.getUID());
bridgeHandler = null;
*/
package org.openhab.binding.vizio.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_VIZIO_TV = new ThingTypeUID(BINDING_ID, "vizio_tv");
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_VIZIO_TV);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_VIZIO_TV);
// List of all Channel id's
public static final String POWER = "power";
ThingTypeUID thingTypeUID = thing.getThingTypeUID();
if (SUPPORTED_THING_TYPES_UIDS.contains(thingTypeUID)) {
- VizioHandler handler = new VizioHandler(thing, httpClientFactory, stateDescriptionProvider, vizioAppsJson);
- return handler;
+ return new VizioHandler(thing, httpClientFactory, stateDescriptionProvider, vizioAppsJson);
}
return null;
VizioHandler handler = null;
if (thing != null) {
thingHandler = thing.getHandler();
- if (thingHandler instanceof VizioHandler) {
- handler = (VizioHandler) thingHandler;
+ if (thingHandler instanceof VizioHandler vizioHandler) {
+ handler = vizioHandler;
}
}
if (thing == null) {
private final Logger logger = LoggerFactory.getLogger(VolvoOnCallException.class);
private static final long serialVersionUID = -6215621577081394328L;
- public static enum ErrorType {
+ public enum ErrorType {
UNKNOWN,
SERVICE_UNAVAILABLE,
SERVICE_UNABLE_TO_START,
IOEXCEPTION,
INTERRUPTED,
- JSON_SYNTAX;
+ JSON_SYNTAX
}
private final ErrorType cause;
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof VehicleHandler) {
- this.handler = (VehicleHandler) handler;
+ if (handler instanceof VehicleHandler vehicleHandler) {
+ this.handler = vehicleHandler;
}
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof VolvoOnCallBridgeHandler) {
- this.handler = (VolvoOnCallBridgeHandler) handler;
+ if (handler instanceof VolvoOnCallBridgeHandler volvoOnCallBridgeHandler) {
+ this.handler = volvoOnCallBridgeHandler;
}
}
logger.warn("Error while discovering vehicle: {}", e.getMessage());
}
}
- ;
}
stopScan();
}
@NonNullByDefault
public class PostResponse extends VocAnswer {
- public static enum Status {
+ public enum Status {
@SerializedName("Started")
STARTED,
@SerializedName("MessageDelivered")
SUCCESSFULL
}
- public static enum ServiceType {
+ public enum ServiceType {
RHBLF, // Remote Honk and Blink Lights ?
RDU, // Remote door unlock
ERS, // Remote engine start
LOW,
@SerializedName("VeryLow")
VERY_LOW,
- UNKNOWN;
+ UNKNOWN
}
public double averageFuelConsumption = UNDEFINED;
NORMAL,
@SerializedName("LowSoft")
LOW_SOFT,
- UNKNOWN;
+ UNKNOWN
}
public PressureLevel frontLeftTyrePressure = PressureLevel.UNKNOWN;
if (api != null) {
queryApiAndUpdateChannels(api);
}
- } else if (command instanceof OnOffType) {
- OnOffType onOffCommand = (OnOffType) command;
+ } else if (command instanceof OnOffType onOffCommand) {
if (ENGINE_START.equals(channelID) && onOffCommand == OnOffType.ON) {
actionStart(5);
} else if (REMOTE_HEATER.equals(channelID) || PRECLIMATIZATION.equals(channelID)) {
VocHttpApi api = bridgeHandler.getApi();
if (api != null) {
try {
- PostResponse postResponse = api.postURL(url.toString(), param);
+ PostResponse postResponse = api.postURL(url, param);
if (postResponse != null) {
pendingActions
.add(scheduler.schedule(new ActionResultController(api, postResponse, scheduler, this),
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
}
}
- ;
pendingActions.removeIf(ScheduledFuture::isDone);
}
public void actionOpenClose(String action, OnOffType controlState) {
if (activeOptions.containsKey(action)) {
- if (!vehicleStatus.getCarLocked().isPresent() || vehicleStatus.getCarLocked().get() != controlState) {
+ if (vehicleStatus.getCarLocked().isEmpty() || vehicleStatus.getCarLocked().get() != controlState) {
post(String.format("vehicles/%s/%s", configuration.vin, action), "{}");
} else {
logger.info("The car {} is already {}ed", configuration.vin, action);
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singletonList(VolvoOnCallActions.class);
+ return List.of(VolvoOnCallActions.class);
}
}
package org.openhab.binding.volvooncall.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;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(VolvoVehicleDiscoveryService.class);
+ return Set.of(VolvoVehicleDiscoveryService.class);
}
@Override
AuthResponseDTO ar = GSON.fromJson(response.getContentAsString(), AuthResponseDTO.class);
- if (ar != null && ar.getStatus() != null && ar.getStatus().getResult().equals("success")) {
+ if (ar != null && ar.getStatus() != null && "success".equals(ar.getStatus().getResult())) {
authToken = ar.getResponse().getToken();
} else {
throw new MyWarmupApiException("Authentication Failed");
* @throws MyWarmupApiException API callout error
*/
public synchronized QueryResponseDTO getStatus() throws MyWarmupApiException {
- return callWarmupGraphQL("query QUERY { user { locations{ id name "
- + " rooms { id roomName runMode overrideDur targetTemp currentTemp "
- + " thermostat4ies{ deviceSN lastPoll }}}}}");
+ return callWarmupGraphQL("""
+ query QUERY { user { locations{ id name \
+ rooms { id roomName runMode overrideDur targetTemp currentTemp \
+ thermostat4ies{ deviceSN lastPoll }}}}}\
+ """);
}
/**
QueryResponseDTO qr = GSON.fromJson(response.getContentAsString(), QueryResponseDTO.class);
- if (qr != null && qr.getStatus().equals("success")) {
+ if (qr != null && "success".equals(qr.getStatus())) {
return qr;
} else {
throw new MyWarmupApiException("Unexpected reponse from API");
@Override
public void setThingHandler(@Nullable final ThingHandler handler) {
- if (handler instanceof MyWarmupAccountHandler) {
- bridgeHandler = (MyWarmupAccountHandler) handler;
+ if (handler instanceof MyWarmupAccountHandler accountHandler) {
+ bridgeHandler = accountHandler;
bridgeUID = handler.getThing().getUID();
} else {
bridgeHandler = null;
package org.openhab.binding.warmup.internal.handler;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(WarmupDiscoveryService.class);
+ return Set.of(WarmupDiscoveryService.class);
}
@Override
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
super.handleCommand(channelUID, command);
- if (CHANNEL_TARGET_TEMPERATURE.equals(channelUID.getId()) && command instanceof QuantityType<?>) {
- setOverride((QuantityType<?>) command);
+ if (CHANNEL_TARGET_TEMPERATURE.equals(channelUID.getId())
+ && command instanceof QuantityType<?> quantityCommand) {
+ setOverride(quantityCommand);
}
- if (CHANNEL_FROST_PROTECTION_MODE.equals(channelUID.getId()) && command instanceof OnOffType) {
- toggleFrostProtectionMode((OnOffType) command);
+ if (CHANNEL_FROST_PROTECTION_MODE.equals(channelUID.getId()) && command instanceof OnOffType onOffCommand) {
+ toggleFrostProtectionMode(onOffCommand);
}
}
protected DateTimeType getLocalDateTimeType(long epochSeconds) {
Instant instant = Instant.ofEpochSecond(epochSeconds);
ZonedDateTime localDateTime = instant.atZone(getZoneId());
- DateTimeType dateTimeType = new DateTimeType(localDateTime);
- return dateTimeType;
+ return new DateTimeType(localDateTime);
}
/*
package org.openhab.binding.weatherunderground.internal;
import java.util.Arrays;
-import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public static final ThingTypeUID THING_TYPE_WEATHER = new ThingTypeUID(BINDING_ID, "weather");
public static final ThingTypeUID THING_TYPE_BRIDGE = new ThingTypeUID(BINDING_ID, "bridge");
- public static final Set<ThingTypeUID> BRIDGE_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_BRIDGE);
+ public static final Set<ThingTypeUID> BRIDGE_THING_TYPES_UIDS = Set.of(THING_TYPE_BRIDGE);
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = new HashSet<>(Arrays.asList(THING_TYPE_WEATHER));
// Channel configuration Properties
import static org.openhab.binding.weatherunderground.internal.WeatherUndergroundBindingConstants.*;
import static org.openhab.binding.weatherunderground.internal.config.WeatherUndergroundConfiguration.*;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
public class WeatherUndergroundDiscoveryService extends AbstractDiscoveryService {
private final Logger logger = LoggerFactory.getLogger(WeatherUndergroundDiscoveryService.class);
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_WEATHER);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_WEATHER);
private static final int DISCOVER_TIMEOUT_SECONDS = 2;
private static final int LOCATION_CHANGED_CHECK_INTERVAL = 60;
// Check if an api key has been provided during the bridge creation
Object configApiKey = config.get(WeatherUndergroundBindingConstants.APIKEY);
- if (configApiKey == null || !(configApiKey instanceof String) || ((String) configApiKey).trim().isEmpty()) {
+ if (!(configApiKey instanceof String) || ((String) configApiKey).trim().isEmpty()) {
logger.debug("Setting thing '{}' to OFFLINE: Parameter 'apikey' must be configured.", getThing().getUID());
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
"@text/offline.conf-error-missing-apikey");
* @return the current relative humidity or null if not defined
*/
public Integer getRelativeHumidity() {
- if (relative_humidity != null && !relative_humidity.isEmpty() && !relative_humidity.equalsIgnoreCase("N/A")) {
+ if (relative_humidity != null && !relative_humidity.isEmpty() && !"N/A".equalsIgnoreCase(relative_humidity)) {
return WeatherUndergroundJsonUtils.convertToInteger(relative_humidity.replace("%", ""));
}
return null;
}
private static boolean isValid(String value) {
- return (value != null) && !value.isEmpty() && !value.equalsIgnoreCase("N/A") && !value.equalsIgnoreCase("NA")
- && !value.equals("-") && !value.equals("--");
+ return (value != null) && !value.isEmpty() && !"N/A".equalsIgnoreCase(value) && !"NA".equalsIgnoreCase(value)
+ && !"-".equals(value) && !"--".equals(value);
}
/**
}
public static boolean sendMessage(@Nullable ThingActions actions, @Nullable String text) {
- if (actions instanceof WebexTeamsActions) {
- return ((WebexTeamsActions) actions).sendMessage(text);
+ if (actions instanceof WebexTeamsActions teamsActions) {
+ return teamsActions.sendMessage(text);
} else {
throw new IllegalArgumentException("Instance is not a WebexTeamsActions class.");
}
}
public static boolean sendMessage(@Nullable ThingActions actions, @Nullable String text, @Nullable String attach) {
- if (actions instanceof WebexTeamsActions) {
- return ((WebexTeamsActions) actions).sendMessage(text, attach);
+ if (actions instanceof WebexTeamsActions teamsActions) {
+ return teamsActions.sendMessage(text, attach);
} else {
throw new IllegalArgumentException("Instance is not a WebexTeamsActions class.");
}
public static boolean sendRoomMessage(@Nullable ThingActions actions, @Nullable String roomId,
@Nullable String text) {
- if (actions instanceof WebexTeamsActions) {
- return ((WebexTeamsActions) actions).sendRoomMessage(roomId, text);
+ if (actions instanceof WebexTeamsActions teamsActions) {
+ return teamsActions.sendRoomMessage(roomId, text);
} else {
throw new IllegalArgumentException("Instance is not a WebexTeamsActions class.");
}
public static boolean sendRoomMessage(@Nullable ThingActions actions, @Nullable String roomId,
@Nullable String text, @Nullable String attach) {
- if (actions instanceof WebexTeamsActions) {
- return ((WebexTeamsActions) actions).sendRoomMessage(roomId, text, attach);
+ if (actions instanceof WebexTeamsActions teamsActions) {
+ return teamsActions.sendRoomMessage(roomId, text, attach);
} else {
throw new IllegalArgumentException("Instance is not a WebexTeamsActions class.");
}
public static boolean sendPersonMessage(@Nullable ThingActions actions, @Nullable String personEmail,
@Nullable String text) {
- if (actions instanceof WebexTeamsActions) {
- return ((WebexTeamsActions) actions).sendPersonMessage(personEmail, text);
+ if (actions instanceof WebexTeamsActions teamsActions) {
+ return teamsActions.sendPersonMessage(personEmail, text);
} else {
throw new IllegalArgumentException("Instance is not a WebexTeamsActions class.");
}
public static boolean sendPersonMessage(@Nullable ThingActions actions, @Nullable String personEmail,
@Nullable String text, @Nullable String attach) {
- if (actions instanceof WebexTeamsActions) {
- return ((WebexTeamsActions) actions).sendPersonMessage(personEmail, text, attach);
+ if (actions instanceof WebexTeamsActions teamsActions) {
+ return teamsActions.sendPersonMessage(personEmail, text, attach);
} else {
throw new IllegalArgumentException("Instance is not a WebexTeamsActions class.");
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof WebexTeamsHandler) {
- this.handler = (WebexTeamsHandler) handler;
+ if (handler instanceof WebexTeamsHandler teamsHandler) {
+ this.handler = teamsHandler;
}
}
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
-import java.util.Collections;
+import java.util.List;
import java.util.Objects;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
// creates list of available Actions
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singletonList(WebexTeamsActions.class);
+ return List.of(WebexTeamsActions.class);
}
@Override
@Override
protected synchronized void removeHandler(ThingHandler thingHandler) {
- if (thingHandler instanceof WebexTeamsHandler) {
- authService.removeWebexTeamsHandler((WebexTeamsHandler) thingHandler);
+ if (thingHandler instanceof WebexTeamsHandler webexTeamsHandler) {
+ authService.removeWebexTeamsHandler(webexTeamsHandler);
}
}
}
public Person getPerson() throws WebexTeamsApiException, WebexAuthenticationException {
URI url = getUri(WEBEX_API_ENDPOINT + "/people/me");
- Person person = request(url, HttpMethod.GET, Person.class, null);
- return person;
+ return request(url, HttpMethod.GET, Person.class, null);
}
private URI getUri(String url) throws WebexTeamsApiException {
// Obtain the input stream on the response content
try (InputStream input = new ByteArrayInputStream(response.getContent())) {
Reader reader = new InputStreamReader(input);
- O entity = gson.fromJson(reader, clazz);
- return entity;
+ return gson.fromJson(reader, clazz);
} catch (IOException | JsonIOException | JsonSyntaxException e) {
logger.warn("Exception while processing API response: {}", e.getMessage());
throw new WebexTeamsApiException("Exception while processing API response", e);
package org.openhab.binding.webthing.internal;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.core.thing.ThingTypeUID;
public static final ThingTypeUID THING_TYPE_UID = new ThingTypeUID(BINDING_ID, "generic");
- public static final Collection<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .singleton(WebThingBindingConstants.THING_TYPE_UID);
+ public static final Collection<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set
+ .of(WebThingBindingConstants.THING_TYPE_UID);
public static final String MDNS_SERVICE_TYPE = "_webthing._tcp.local.";
}
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
- if (command instanceof State) {
+ if (command instanceof State stateCommand) {
itemChangedListenerMap.getOrDefault(channelUID, EMPTY_ITEM_CHANGED_LISTENER).onItemStateChanged(channelUID,
- (State) command);
+ stateCommand);
} else if (command instanceof RefreshType) {
tryReconnect();
}
if (optionalProperty.isPresent()) {
var propertyDescription = optionalProperty.get();
for (var link : propertyDescription.links) {
- if ((link.rel != null) && (link.href != null) && link.rel.equals("property")) {
+ if ((link.rel != null) && (link.href != null) && "property".equals(link.rel)) {
return Optional.of(webThingURI.resolve(link.href));
}
}
// currently, the old and new location of the WebThings schema are supported only.
// In the future, other schemas such as http://iotschema.org/docs/full.html may be supported
- if (schema.equals("https://webthings.io/schemas") || schema.equals("https://iot.mozilla.org/schemas")) {
+ if ("https://webthings.io/schemas".equals(schema) || "https://iot.mozilla.org/schemas".equals(schema)) {
return description;
}
logger.debug(
var href = link.href;
if ((href != null) && href.startsWith("ws")) {
var rel = Optional.ofNullable(link.rel).orElse("<undefined>");
- if (rel.equals("alternate")) {
+ if ("alternate".equals(rel)) {
return Optional.of(URI.create(href));
}
}
case "color":
return new ColorTypeConverter();
case "number":
- if (propertyType.toLowerCase(Locale.ENGLISH).equals("integer")) {
+ if ("integer".equals(propertyType.toLowerCase(Locale.ENGLISH))) {
return new IntegerTypeConverter();
} else {
return new NumberTypeConverter();
@Override
public Command toStateCommand(Object propertyValue) {
String textValue = propertyValue.toString();
- if (propertyValue instanceof Collection) {
- textValue = ((Collection<Object>) propertyValue).stream()
+ if (propertyValue instanceof Collection collection) {
+ textValue = collection.stream()
.reduce("", (entry1, entry2) -> entry1.toString() + "\n" + entry2.toString()).toString();
}
return StringType.valueOf(textValue);
break;
case "LevelProperty":
if ((propertyMetadata.unit != null)
- && propertyMetadata.unit.toLowerCase(Locale.ENGLISH).equals("percent")) {
+ && "percent".equals(propertyMetadata.unit.toLowerCase(Locale.ENGLISH))) {
type = CoreItemFactory.DIMMER;
} else {
type = CoreItemFactory.NUMBER;
public static String createBinaryStateContent(boolean binaryState) {
String binary = binaryState ? "1" : "0";
- String content = "<?xml version=\"1.0\"?>"
- + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
- + "<s:Body>" + "<u:SetBinaryState xmlns:u=\"urn:Belkin:service:basicevent:1\">" + "<BinaryState>"
+ return """
+ <?xml version="1.0"?>\
+ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">\
+ <s:Body>\
+ <u:SetBinaryState xmlns:u="urn:Belkin:service:basicevent:1">\
+ <BinaryState>\
+ """
+ binary + "</BinaryState>" + "</u:SetBinaryState>" + "</s:Body>" + "</s:Envelope>";
- return content;
}
public static String createStateRequestContent(String action, String actionService) {
- String content = "<?xml version=\"1.0\"?>"
- + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
- + "<s:Body>" + "<u:" + action + " xmlns:u=\"urn:Belkin:service:" + actionService + ":1\">" + "</u:"
- + action + ">" + "</s:Body>" + "</s:Envelope>";
- return content;
+ return """
+ <?xml version="1.0"?>\
+ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">\
+ <s:Body>\
+ <u:\
+ """
+ + action + " xmlns:u=\"urn:Belkin:service:" + actionService + ":1\">" + "</u:" + action + ">"
+ + "</s:Body>" + "</s:Envelope>";
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
- if (child instanceof CharacterData) {
- CharacterData cd = (CharacterData) child;
+ if (child instanceof CharacterData cd) {
return cd.getData();
}
return "?";
import java.io.StringReader;
import java.net.URL;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
private final Logger logger = LoggerFactory.getLogger(WemoLinkDiscoveryService.class);
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_MZ100);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_MZ100);
public static final String NORMALIZE_ID_REGEX = "[^a-zA-Z0-9_]";
logger.trace("devUDN = '{}'", devUDN);
String soapHeader = "\"urn:Belkin:service:bridge:1#GetEndDevices\"";
- String content = "<?xml version=\"1.0\"?>"
- + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
- + "<s:Body>" + "<u:GetEndDevices xmlns:u=\"urn:Belkin:service:bridge:1\">" + "<DevUDN>" + devUDN
- + "</DevUDN><ReqListType>PAIRED_LIST</ReqListType>" + "</u:GetEndDevices>" + "</s:Body>"
- + "</s:Envelope>";
+ String content = """
+ <?xml version="1.0"?>\
+ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">\
+ <s:Body>\
+ <u:GetEndDevices xmlns:u="urn:Belkin:service:bridge:1">\
+ <DevUDN>\
+ """
+ + devUDN + """
+ </DevUDN>\
+ <ReqListType>PAIRED_LIST</ReqListType>\
+ </u:GetEndDevices>\
+ </s:Body>\
+ </s:Envelope>\
+ """;
URL descriptorURL = service.getDescriptorURL(this);
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
- if (child instanceof CharacterData) {
- CharacterData cd = (CharacterData) child;
+ if (child instanceof CharacterData cd) {
return cd.getData();
}
return "?";
import static org.openhab.binding.wemo.internal.WemoBindingConstants.*;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@NonNullByDefault
public class WemoBridgeHandler 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 final Logger logger = LoggerFactory.getLogger(WemoBridgeHandler.class);
import java.io.StringReader;
import java.time.Instant;
import java.time.ZonedDateTime;
-import java.util.Collections;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.ScheduledFuture;
private final Logger logger = LoggerFactory.getLogger(WemoCoffeeHandler.class);
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_COFFEE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_COFFEE);
private final Object jobLock = new Object();
try {
String soapHeader = "\"urn:Belkin:service:deviceevent:1#SetAttributes\"";
- String content = "<?xml version=\"1.0\"?>"
- + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
- + "<s:Body>" + "<u:SetAttributes xmlns:u=\"urn:Belkin:service:deviceevent:1\">"
- + "<attributeList><attribute><name>Brewed</name><value>NULL</value></attribute>"
- + "<attribute><name>LastCleaned</name><value>NULL</value></attribute><attribute>"
- + "<name>ModeTime</name><value>NULL</value></attribute><attribute><name>Brewing</name>"
- + "<value>NULL</value></attribute><attribute><name>TimeRemaining</name><value>NULL</value>"
- + "</attribute><attribute><name>WaterLevelReached</name><value>NULL</value></attribute><"
- + "attribute><name>Mode</name><value>4</value></attribute><attribute><name>CleanAdvise</name>"
- + "<value>NULL</value></attribute><attribute><name>FilterAdvise</name><value>NULL</value></attribute>"
- + "<attribute><name>Cleaning</name><value>NULL</value></attribute></attributeList>"
- + "</u:SetAttributes>" + "</s:Body>" + "</s:Envelope>";
+ String content = """
+ <?xml version="1.0"?>\
+ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">\
+ <s:Body>\
+ <u:SetAttributes xmlns:u="urn:Belkin:service:deviceevent:1">\
+ <attributeList><attribute><name>Brewed</name><value>NULL</value></attribute>\
+ <attribute><name>LastCleaned</name><value>NULL</value></attribute><attribute>\
+ <name>ModeTime</name><value>NULL</value></attribute><attribute><name>Brewing</name>\
+ <value>NULL</value></attribute><attribute><name>TimeRemaining</name><value>NULL</value>\
+ </attribute><attribute><name>WaterLevelReached</name><value>NULL</value></attribute><\
+ attribute><name>Mode</name><value>4</value></attribute><attribute><name>CleanAdvise</name>\
+ <value>NULL</value></attribute><attribute><name>FilterAdvise</name><value>NULL</value></attribute>\
+ <attribute><name>Cleaning</name><value>NULL</value></attribute></attributeList>\
+ </u:SetAttributes>\
+ </s:Body>\
+ </s:Envelope>\
+ """;
wemoHttpCaller.executeCall(wemoURL, soapHeader, content);
updateState(CHANNEL_STATE, OnOffType.ON);
private final Logger logger = LoggerFactory.getLogger(WemoCrockpotHandler.class);
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_CROCKPOT);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_CROCKPOT);
private final Object jobLock = new Object();
}
try {
String soapHeader = "\"urn:Belkin:service:basicevent:1#SetBinaryState\"";
- String content = "<?xml version=\"1.0\"?>"
- + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
- + "<s:Body>" + "<u:SetCrockpotState xmlns:u=\"urn:Belkin:service:basicevent:1\">" + "<mode>"
+ String content = """
+ <?xml version="1.0"?>\
+ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">\
+ <s:Body>\
+ <u:SetCrockpotState xmlns:u="urn:Belkin:service:basicevent:1">\
+ <mode>\
+ """
+ mode + "</mode>" + "<time>" + time + "</time>" + "</u:SetCrockpotState>" + "</s:Body>"
+ "</s:Envelope>";
wemoHttpCaller.executeCall(wemoURL, soapHeader, content);
private final Logger logger = LoggerFactory.getLogger(WemoDimmerHandler.class);
- 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 Object jobLock = new Object();
State brightnessState = new PercentType(currentBrightness);
updateState(CHANNEL_BRIGHTNESS, brightnessState);
}
- } else if (command instanceof PercentType) {
- int newBrightness = ((PercentType) command).intValue();
+ } else if (command instanceof PercentType percentCommand) {
+ int newBrightness = percentCommand.intValue();
value = String.valueOf(newBrightness);
currentBrightness = newBrightness;
argument = "brightness";
int commandValue = Integer.valueOf(String.valueOf(command));
commandValue = commandValue * 60;
String commandString = String.valueOf(commandValue);
- value = "<BinaryState></BinaryState>" + "<Duration></Duration>" + "<EndAction></EndAction>"
- + "<brightness></brightness>" + "<fader>" + commandString + ":-1:1:0:0</fader>"
- + "<UDN></UDN>";
+ value = """
+ <BinaryState></BinaryState>\
+ <Duration></Duration>\
+ <EndAction></EndAction>\
+ <brightness></brightness>\
+ <fader>\
+ """ + commandString + ":-1:1:0:0</fader><UDN></UDN>";
setBinaryState(action, argument, value);
}
break;
case CHANNEL_FADER_ENABLED:
argument = "Fader";
if (command.equals(OnOffType.ON)) {
- value = "<BinaryState></BinaryState>" + "<Duration></Duration>" + "<EndAction></EndAction>"
- + "<brightness></brightness>" + "<fader>600:-1:1:0:0</fader>" + "<UDN></UDN>";
+ value = """
+ <BinaryState></BinaryState>\
+ <Duration></Duration>\
+ <EndAction></EndAction>\
+ <brightness></brightness>\
+ <fader>600:-1:1:0:0</fader>\
+ <UDN></UDN>\
+ """;
} else if (command.equals(OnOffType.OFF)) {
- value = "<BinaryState></BinaryState>" + "<Duration></Duration>" + "<EndAction></EndAction>"
- + "<brightness></brightness>" + "<fader>600:-1:0:0:0</fader>" + "<UDN></UDN>";
+ value = """
+ <BinaryState></BinaryState>\
+ <Duration></Duration>\
+ <EndAction></EndAction>\
+ <brightness></brightness>\
+ <fader>600:-1:0:0:0</fader>\
+ <UDN></UDN>\
+ """;
}
setBinaryState(action, argument, value);
break;
}
if (faderSeconds != null && faderEnabled != null) {
if (OnOffType.ON.equals(command)) {
- value = "<BinaryState></BinaryState>" + "<Duration></Duration>" + "<EndAction></EndAction>"
- + "<brightness></brightness>" + "<fader>" + faderSeconds + ":" + timeStamp + ":"
- + faderEnabled + ":0:0</fader>" + "<UDN></UDN>";
+ value = """
+ <BinaryState></BinaryState>\
+ <Duration></Duration>\
+ <EndAction></EndAction>\
+ <brightness></brightness>\
+ <fader>\
+ """ + faderSeconds + ":" + timeStamp + ":" + faderEnabled + ":0:0</fader>"
+ + "<UDN></UDN>";
updateState(CHANNEL_STATE, OnOffType.ON);
} else if (OnOffType.OFF.equals(command)) {
- value = "<BinaryState></BinaryState>" + "<Duration></Duration>" + "<EndAction></EndAction>"
- + "<brightness></brightness>" + "<fader>" + faderSeconds + ":-1:" + faderEnabled
- + ":0:0</fader>" + "<UDN></UDN>";
+ value = """
+ <BinaryState></BinaryState>\
+ <Duration></Duration>\
+ <EndAction></EndAction>\
+ <brightness></brightness>\
+ <fader>\
+ """ + faderSeconds + ":-1:" + faderEnabled + ":0:0</fader>" + "<UDN></UDN>";
}
}
setBinaryState(action, argument, value);
case CHANNEL_NIGHT_MODE_BRIGHTNESS:
action = "ConfigureNightMode";
argument = "NightModeConfiguration";
- if (command instanceof PercentType) {
- int newBrightness = ((PercentType) command).intValue();
+ if (command instanceof PercentType percentCommand) {
+ int newBrightness = percentCommand.intValue();
String newNightModeBrightness = String.valueOf(newBrightness);
value = "<startTime>0</startTime> \\n<nightMode>" + currentNightModeState
+ "</nightMode> \\n<endTime>23400</endTime> \\n<nightModeBrightness>"
updateState(CHANNEL_FADER_COUNT_DOWN_TIME, faderMinutes);
}
if (splitFader[1] != null) {
- State isTimerRunning = splitFader[1].equals("-1") ? OnOffType.OFF : OnOffType.ON;
+ State isTimerRunning = "-1".equals(splitFader[1]) ? OnOffType.OFF : OnOffType.ON;
logger.debug("isTimerRunning '{}' for device '{}' received", isTimerRunning,
getThing().getUID());
updateState(CHANNEL_TIMER_START, isTimerRunning);
}
}
if (splitFader[2] != null) {
- State isFaderEnabled = splitFader[1].equals("0") ? OnOffType.OFF : OnOffType.ON;
+ State isFaderEnabled = "0".equals(splitFader[1]) ? OnOffType.OFF : OnOffType.ON;
logger.debug("isFaderEnabled '{}' for device '{}' received", isFaderEnabled,
getThing().getUID());
updateState(CHANNEL_FADER_ENABLED, isFaderEnabled);
return null;
}
ZonedDateTime zoned = ZonedDateTime.ofInstant(Instant.ofEpochSecond(value), TimeZone.getDefault().toZoneId());
- State dateTimeState = new DateTimeType(zoned);
- return dateTimeState;
+ return new DateTimeType(zoned);
}
public void setBinaryState(String action, String argument, String value) {
}
try {
String soapHeader = "\"urn:Belkin:service:basicevent:1#SetBinaryState\"";
- String content = "<?xml version=\"1.0\"?>"
- + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
- + "<s:Body>" + "<u:" + action + " xmlns:u=\"urn:Belkin:service:basicevent:1\">" + "<" + argument
- + ">" + value + "</" + argument + ">" + "</u:" + action + ">" + "</s:Body>" + "</s:Envelope>";
+ String content = """
+ <?xml version="1.0"?>\
+ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">\
+ <s:Body>\
+ <u:\
+ """
+ + action + " xmlns:u=\"urn:Belkin:service:basicevent:1\">" + "<" + argument + ">" + value + "</"
+ + argument + ">" + "</u:" + action + ">" + "</s:Body>" + "</s:Envelope>";
wemoHttpCaller.executeCall(wemoURL, soapHeader, content);
updateStatus(ThingStatus.ONLINE);
}
try {
String soapHeader = "\"urn:Belkin:service:basicevent:1#SetBinaryState\"";
- String content = "<?xml version=\"1.0\"?>"
- + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
- + "<s:Body>" + "<u:SetBinaryState xmlns:u=\"urn:Belkin:service:basicevent:1\">" + value
- + "</u:SetBinaryState>" + "</s:Body>" + "</s:Envelope>";
+ String content = """
+ <?xml version="1.0"?>\
+ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">\
+ <s:Body>\
+ <u:SetBinaryState xmlns:u="urn:Belkin:service:basicevent:1">\
+ """
+ + value + "</u:SetBinaryState>" + "</s:Body>" + "</s:Envelope>";
wemoHttpCaller.executeCall(wemoURL, soapHeader, content);
updateStatus(ThingStatus.ONLINE);
} catch (Exception e) {
private final Logger logger = LoggerFactory.getLogger(WemoHolmesHandler.class);
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_PURIFIER);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_PURIFIER);
private static final int FILTER_LIFE_DAYS = 330;
private static final int FILTER_LIFE_MINS = FILTER_LIFE_DAYS * 24 * 60;
}
try {
String soapHeader = "\"urn:Belkin:service:deviceevent:1#SetAttributes\"";
- String content = "<?xml version=\"1.0\"?>"
- + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
- + "<s:Body>" + "<u:SetAttributes xmlns:u=\"urn:Belkin:service:deviceevent:1\">"
- + "<attributeList><attribute><name>" + attribute + "</name><value>" + value
+ String content = """
+ <?xml version="1.0"?>\
+ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">\
+ <s:Body>\
+ <u:SetAttributes xmlns:u="urn:Belkin:service:deviceevent:1">\
+ <attributeList><attribute><name>\
+ """
+ + attribute + "</name><value>" + value
+ "</value></attribute></attributeList>" + "</u:SetAttributes>" + "</s:Body>"
+ "</s:Envelope>";
wemoHttpCaller.executeCall(wemoURL, soapHeader, content);
return null;
}
ThingHandler handler = bridge.getHandler();
- if (handler instanceof WemoBridgeHandler) {
- this.wemoBridgeHandler = (WemoBridgeHandler) handler;
+ if (handler instanceof WemoBridgeHandler wemoBridgeHandler) {
+ this.wemoBridgeHandler = wemoBridgeHandler;
} else {
logger.debug("No available bridge handler found for {} bridge {} .", wemoLightID, bridge.getUID());
return null;
switch (channelUID.getId()) {
case CHANNEL_BRIGHTNESS:
capability = "10008";
- if (command instanceof PercentType) {
- int newBrightness = ((PercentType) command).intValue();
+ if (command instanceof PercentType percentCommand) {
+ int newBrightness = percentCommand.intValue();
logger.trace("wemoLight received Value {}", newBrightness);
int value1 = Math.round(newBrightness * 255 / 100);
value = value1 + ":0";
try {
if (capability != null && value != null) {
String soapHeader = "\"urn:Belkin:service:bridge:1#SetDeviceStatus\"";
- String content = "<?xml version=\"1.0\"?>"
- + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
- + "<s:Body>" + "<u:SetDeviceStatus xmlns:u=\"urn:Belkin:service:bridge:1\">"
- + "<DeviceStatusList>"
- + "<?xml version="1.0" encoding="UTF-8"?><DeviceStatus><DeviceID>"
+ String content = """
+ <?xml version="1.0"?>\
+ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">\
+ <s:Body>\
+ <u:SetDeviceStatus xmlns:u="urn:Belkin:service:bridge:1">\
+ <DeviceStatusList>\
+ <?xml version="1.0" encoding="UTF-8"?><DeviceStatus><DeviceID>\
+ """
+ wemoLightID
+ "</DeviceID><IsGroupAction>NO</IsGroupAction><CapabilityID>"
+ capability + "</CapabilityID><CapabilityValue>" + value
}
try {
String soapHeader = "\"urn:Belkin:service:bridge:1#GetDeviceStatus\"";
- String content = "<?xml version=\"1.0\"?>"
- + "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
- + "<s:Body>" + "<u:GetDeviceStatus xmlns:u=\"urn:Belkin:service:bridge:1\">" + "<DeviceIDs>"
+ String content = """
+ <?xml version="1.0"?>\
+ <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">\
+ <s:Body>\
+ <u:GetDeviceStatus xmlns:u="urn:Belkin:service:bridge:1">\
+ <DeviceIDs>\
+ """
+ wemoLightID + "</DeviceIDs>" + "</u:GetDeviceStatus>" + "</s:Body>" + "</s:Envelope>";
String wemoCallResponse = wemoHttpCaller.executeCall(wemoURL, soapHeader, content);
updateState(CHANNEL_STATE, binaryState);
}
if (splitResponse[1] != null) {
- String splitBrightness[] = splitResponse[1].split(":");
+ String[] splitBrightness = splitResponse[1].split(":");
if (splitBrightness[0] != null) {
int newBrightnessValue = Integer.valueOf(splitBrightness[0]);
int newBrightness = Math.round(newBrightnessValue * 100 / 255);
updateState(CHANNEL_STATE, binaryState);
break;
case "10008":
- String splitValue[] = newValue.split(":");
+ String[] splitValue = newValue.split(":");
if (splitValue[0] != null) {
int newBrightnessValue = Integer.valueOf(splitValue[0]);
int newBrightness = Math.round(newBrightnessValue * 100 / 255);
import static org.openhab.binding.wemo.internal.WemoUtil.*;
import java.io.StringReader;
-import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
private final Logger logger = LoggerFactory.getLogger(WemoMakerHandler.class);
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_MAKER);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_MAKER);
private final Object jobLock = new Object();
*/
package org.openhab.binding.wifiled.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_WIFILED = new ThingTypeUID(BINDING_ID, "wifiled");
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_WIFILED);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_WIFILED);
// List of all Channel IDs
public static final String CHANNEL_POWER = "power";
import static org.openhab.binding.wifiled.internal.WiFiLEDBindingConstants.THING_TYPE_WIFILED;
-import java.util.Collections;
import java.util.Set;
import org.openhab.binding.wifiled.internal.handler.WiFiLEDHandler;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.wifiled")
public class WiFiLEDHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_WIFILED);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_WIFILED);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
} else if (channelUID.getId().equals(WiFiLEDBindingConstants.CHANNEL_WHITE2)) {
handleWhite2Command(command);
} else if (channelUID.getId().equals(WiFiLEDBindingConstants.CHANNEL_PROGRAM)
- && (command instanceof StringType)) {
- driver.setProgram((StringType) command);
+ && (command instanceof StringType stringCommand)) {
+ driver.setProgram(stringCommand);
} else if (channelUID.getId().equals(WiFiLEDBindingConstants.CHANNEL_PROGRAM_SPEED)) {
handleProgramSpeedCommand(command);
}
}
private void handleColorCommand(Command command) throws IOException {
- if (command instanceof HSBType) {
- driver.setColor((HSBType) command);
- } else if (command instanceof PercentType) {
- driver.setBrightness((PercentType) command);
- } else if (command instanceof OnOffType) {
- driver.setPower((OnOffType) command);
- } else if (command instanceof IncreaseDecreaseType) {
- IncreaseDecreaseType increaseDecreaseType = (IncreaseDecreaseType) command;
+ if (command instanceof HSBType hsbCommand) {
+ driver.setColor(hsbCommand);
+ } else if (command instanceof PercentType percentCommand) {
+ driver.setBrightness(percentCommand);
+ } else if (command instanceof OnOffType onOffCommand) {
+ driver.setPower(onOffCommand);
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseType) {
if (increaseDecreaseType.equals(IncreaseDecreaseType.INCREASE)) {
driver.incBrightness(INC_DEC_STEP);
} else {
}
private void handleWhiteCommand(Command command) throws IOException {
- if (command instanceof PercentType) {
- driver.setWhite((PercentType) command);
- } else if (command instanceof OnOffType) {
- OnOffType onOffCommand = (OnOffType) command;
+ if (command instanceof PercentType percentCommand) {
+ driver.setWhite(percentCommand);
+ } else if (command instanceof OnOffType onOffCommand) {
if (onOffCommand.equals(OnOffType.ON)) {
driver.setWhite(PercentType.HUNDRED);
} else {
driver.setWhite(PercentType.ZERO);
}
- } else if (command instanceof IncreaseDecreaseType) {
- IncreaseDecreaseType increaseDecreaseType = (IncreaseDecreaseType) command;
- if (increaseDecreaseType.equals(IncreaseDecreaseType.INCREASE)) {
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ if (increaseDecreaseCommand.equals(IncreaseDecreaseType.INCREASE)) {
driver.incWhite(INC_DEC_STEP);
} else {
driver.decWhite(INC_DEC_STEP);
}
private void handleWhite2Command(Command command) throws IOException {
- if (command instanceof PercentType) {
- driver.setWhite2((PercentType) command);
- } else if (command instanceof OnOffType) {
- OnOffType onOffCommand = (OnOffType) command;
+ if (command instanceof PercentType percentCommand) {
+ driver.setWhite2(percentCommand);
+ } else if (command instanceof OnOffType onOffCommand) {
if (onOffCommand.equals(OnOffType.ON)) {
driver.setWhite2(PercentType.HUNDRED);
} else {
driver.setWhite2(PercentType.ZERO);
}
- } else if (command instanceof IncreaseDecreaseType) {
- IncreaseDecreaseType increaseDecreaseType = (IncreaseDecreaseType) command;
- if (increaseDecreaseType.equals(IncreaseDecreaseType.INCREASE)) {
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ if (increaseDecreaseCommand.equals(IncreaseDecreaseType.INCREASE)) {
driver.incWhite2(INC_DEC_STEP);
} else {
driver.decWhite2(INC_DEC_STEP);
}
private void handleProgramSpeedCommand(Command command) throws IOException {
- if (command instanceof PercentType) {
- driver.setProgramSpeed((PercentType) command);
- } else if (command instanceof OnOffType) {
- OnOffType onOffCommand = (OnOffType) command;
+ if (command instanceof PercentType percentCommand) {
+ driver.setProgramSpeed(percentCommand);
+ } else if (command instanceof OnOffType onOffCommand) {
if (onOffCommand.equals(OnOffType.ON)) {
driver.setProgramSpeed(PercentType.HUNDRED);
} else {
driver.setProgramSpeed(PercentType.ZERO);
}
- } else if (command instanceof IncreaseDecreaseType) {
- IncreaseDecreaseType increaseDecreaseType = (IncreaseDecreaseType) command;
- if (increaseDecreaseType.equals(IncreaseDecreaseType.INCREASE)) {
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ if (increaseDecreaseCommand.equals(IncreaseDecreaseType.INCREASE)) {
driver.incProgramSpeed(INC_DEC_STEP);
} else {
driver.decProgramSpeed(INC_DEC_STEP);
}
private void addWindmillDiscoveryResult(ThingUID bridgeUID, Windmill windmill, int shares) {
- String deviceId = windmill.getName().toLowerCase().replaceAll(" ", "-");
+ String deviceId = windmill.getName().toLowerCase().replace(" ", "-");
ThingUID thingUID = new ThingUID(THING_TYPE_WINDMILL, bridgeUID, deviceId);
thingDiscovered(DiscoveryResultBuilder.create(thingUID) //
@SuppressWarnings("null")
public Reader openDataReader(String fileName) throws FileNotFoundException {
- String packagePath = (DataUtil.class.getPackage().getName()).replaceAll("\\.", "/");
+ String packagePath = (DataUtil.class.getPackage().getName()).replace(".", "/");
String filePath = "src/test/resources/" + packagePath + "/" + fileName;
InputStream inputStream = new FileInputStream(filePath);
public static State getState(ChannelUID channelUID, Data data, Settings settings)
throws WlanThermoUnknownChannelException, WlanThermoInputException {
-
String groupId = requireNonNull(channelUID.getGroupId());
System system = data.getSystem();
Unit<Temperature> unit = "F".equals(system.getUnit()) ? ImperialUnits.FAHRENHEIT : SIUnits.CELSIUS;
}
return false;
case CHANNEL_MIN:
- if (command instanceof QuantityType) {
+ if (command instanceof QuantityType quantityCommand) {
try {
- channel.setMin(requireNonNull(((QuantityType<?>) command).toUnit(unit)).doubleValue());
+ channel.setMin(requireNonNull(quantityCommand.toUnit(unit)).doubleValue());
return true;
} catch (WlanThermoInputException ignore) {
return false;
}
return false;
case CHANNEL_MAX:
- if (command instanceof QuantityType) {
+ if (command instanceof QuantityType quantityCommand) {
try {
- channel.setMax(requireNonNull(((QuantityType<?>) command).toUnit(unit)).doubleValue());
+ channel.setMax(requireNonNull(quantityCommand.toUnit(unit)).doubleValue());
return true;
} catch (WlanThermoInputException ignore) {
return false;
}
return false;
case CHANNEL_COLOR_NAME:
- if (command instanceof StringType) {
- channel.setColor(WlanThermoEsp32Util.toHex(((StringType) command).toString()));
+ if (command instanceof StringType stringCommand) {
+ channel.setColor(WlanThermoEsp32Util.toHex(stringCommand.toString()));
return true;
}
return false;
case CHANNEL_COLOR:
- if (command instanceof HSBType) {
- channel.setColor(WlanThermoUtil.toHex((HSBType) command));
+ if (command instanceof HSBType hsbCommand) {
+ channel.setColor(WlanThermoUtil.toHex(hsbCommand));
return true;
}
return false;
}
case CHANNEL_PITMASTER_STATE:
String state = ((StringType) command).toString();
- if (state.equalsIgnoreCase("off") || state.equalsIgnoreCase("manual")
- || state.equalsIgnoreCase("auto")) {
+ if ("off".equalsIgnoreCase(state) || "manual".equalsIgnoreCase(state)
+ || "auto".equalsIgnoreCase(state)) {
pm.setTyp(state);
return true;
}
case WlanThermoBindingConstants.CHANNEL_PITMASTER_DUTY_CYCLE:
return new DecimalType(pit.getControlOut());
case WlanThermoBindingConstants.CHANNEL_PITMASTER_LID_OPEN:
- return OnOffType.from(pit.getOpenLid().equals("True"));
+ return OnOffType.from("True".equals(pit.getOpenLid()));
case WlanThermoBindingConstants.CHANNEL_PITMASTER_CHANNEL_ID:
return new DecimalType(pit.getCh());
}
}
} else if (channelUID.getId().startsWith(CHANNEL_PITMASTER_1)) {
if (data.getPitmaster() != null && data.getPitmaster().getPm() != null
- && data.getPitmaster().getPm().size() > 0) {
+ && !data.getPitmaster().getPm().isEmpty()) {
Pm pm = data.getPitmaster().getPm().get(0);
switch (channelUID.getIdWithoutGroup()) {
case CHANNEL_PITMASTER_CHANNEL_ID:
}
return false;
case CHANNEL_MIN:
- if (command instanceof QuantityType) {
+ if (command instanceof QuantityType quantityCommand) {
try {
- channel.setMin(requireNonNull(((QuantityType<?>) command).toUnit(unit)).doubleValue());
+ channel.setMin(requireNonNull(quantityCommand.toUnit(unit)).doubleValue());
return true;
} catch (WlanThermoInputException ignore) {
return false;
}
return false;
case CHANNEL_MAX:
- if (command instanceof QuantityType) {
+ if (command instanceof QuantityType quantityCommand) {
try {
- channel.setMax(requireNonNull(((QuantityType<?>) command).toUnit(unit)).doubleValue());
+ channel.setMax(requireNonNull(quantityCommand.toUnit(unit)).doubleValue());
return true;
} catch (WlanThermoInputException ignore) {
return false;
}
return false;
case CHANNEL_COLOR_NAME:
- if (command instanceof StringType) {
- channel.setColor(WlanThermoNanoV1Util.toHex(((StringType) command).toString()));
+ if (command instanceof StringType stringCommand) {
+ channel.setColor(WlanThermoNanoV1Util.toHex(stringCommand.toString()));
return true;
}
return false;
}
} else if (channelUID.getId().startsWith(CHANNEL_PITMASTER_1)) {
if (data.getPitmaster() != null && data.getPitmaster().getPm() != null
- && data.getPitmaster().getPm().size() > 0) {
+ && !data.getPitmaster().getPm().isEmpty()) {
Pm pm = data.getPitmaster().getPm().get(0);
switch (channelUID.getIdWithoutGroup()) {
case CHANNEL_PITMASTER_CHANNEL_ID:
}
case CHANNEL_PITMASTER_STATE:
String state = ((StringType) command).toString();
- if (state.equalsIgnoreCase("off") || state.equalsIgnoreCase("manual")
- || state.equalsIgnoreCase("auto")) {
+ if ("off".equalsIgnoreCase(state) || "manual".equalsIgnoreCase(state)
+ || "auto".equalsIgnoreCase(state)) {
pm.setTyp(state);
return true;
}
public static String getTrigger(ChannelUID channelUID, Data data)
throws WlanThermoUnknownChannelException, WlanThermoInputException {
-
String groupId = requireNonNull(channelUID.getGroupId());
List<Channel> channelList = data.getChannel();
}
public static void savePreset(@Nullable ThingActions actions, int presetNumber) {
- if (actions instanceof WLedActions) {
- ((WLedActions) actions).savePreset(presetNumber, "");
+ if (actions instanceof WLedActions wLedActions) {
+ wLedActions.savePreset(presetNumber, "");
} else {
throw new IllegalArgumentException("Instance is not a WLED class.");
}
}
public static void savePreset(@Nullable ThingActions actions, int presetNumber, String presetName) {
- if (actions instanceof WLedActions) {
- ((WLedActions) actions).savePreset(presetNumber, presetName);
+ if (actions instanceof WLedActions wLedActions) {
+ wLedActions.savePreset(presetNumber, presetName);
} else {
throw new IllegalArgumentException("Instance is not a WLED class.");
}
if (!name.contains("wled")) {
return null;
}
- String address[] = service.getURLs();
+ String[] address = service.getURLs();
if ((address == null) || address.length < 1) {
logger.debug("WLED discovered with empty IP address-{}", service);
return null;
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof WLedBridgeHandler) {
- bridgeHandler = (WLedBridgeHandler) handler;
+ if (handler instanceof WLedBridgeHandler wLedBridgeHandler) {
+ bridgeHandler = wLedBridgeHandler;
bridgeUID = bridgeHandler.getThing().getUID();
}
}
fxOptions.add(new StateOption(Integer.toString(counter++), value));
}
if (handler.config.sortEffects) {
- fxOptions.sort(Comparator.comparing(o -> o.getValue().equals("0") ? "" : o.getLabel()));
+ fxOptions.sort(Comparator.comparing(o -> "0".equals(o.getValue()) ? "" : o.getLabel()));
}
return fxOptions;
}
palleteOptions.add(new StateOption(Integer.toString(counter++), value));
}
if (handler.config.sortPalettes) {
- palleteOptions.sort(Comparator.comparing(o -> o.getValue().equals("0") ? "" : o.getLabel()));
+ palleteOptions.sort(Comparator.comparing(o -> "0".equals(o.getValue()) ? "" : o.getLabel()));
}
return palleteOptions;
}
state.infoResponse = getInfo();
String temp = state.infoResponse.ver;
logger.debug("Firmware for WLED is ver:{}", temp);
- temp = temp.replaceAll("\\.", "");
+ temp = temp.replace(".", "");
if (temp.length() > 4) {
temp = temp.substring(0, 4);
}
case CHANNEL_GLOBAL_BRIGHTNESS:
if (command instanceof OnOffType) {
localApi.setGlobalOn(OnOffType.ON.equals(command));
- } else if (command instanceof PercentType) {
+ } else if (command instanceof PercentType percentCommand) {
if (PercentType.ZERO.equals(command)) {
localApi.setGlobalOn(false);
return;
}
- localApi.setGlobalBrightness((PercentType) command);
+ localApi.setGlobalBrightness(percentCommand);
}
break;
case CHANNEL_SLEEP:
localApi.setSleepMode(command.toString());
break;
case CHANNEL_SLEEP_BRIGHTNESS:
- if (command instanceof PercentType) {
- localApi.setSleepTargetBrightness((PercentType) command);
+ if (command instanceof PercentType percentCommand) {
+ localApi.setSleepTargetBrightness(percentCommand);
}
break;
case CHANNEL_SLEEP_DURATION:
- if (command instanceof QuantityType) {
- QuantityType<?> minutes = ((QuantityType<?>) command).toUnit(Units.MINUTE);
+ if (command instanceof QuantityType quantityCommand) {
+ QuantityType<?> minutes = quantityCommand.toUnit(Units.MINUTE);
if (minutes != null) {
localApi.setSleepDuration(new BigDecimal(minutes.intValue()));
}
- } else if (command instanceof DecimalType) {
- localApi.setSleepDuration(new BigDecimal(((DecimalType) command).intValue()));
+ } else if (command instanceof DecimalType decimalCommand) {
+ localApi.setSleepDuration(new BigDecimal(decimalCommand.intValue()));
}
break;
case CHANNEL_PLAYLISTS:
localApi.setPreset(command.toString());
break;
case CHANNEL_TRANS_TIME:
- if (command instanceof QuantityType) {
- QuantityType<?> seconds = ((QuantityType<?>) command).toUnit(Units.SECOND);
+ if (command instanceof QuantityType quantityCommand) {
+ QuantityType<?> seconds = quantityCommand.toUnit(Units.SECOND);
if (seconds != null) {
localApi.setTransitionTime(new BigDecimal(seconds.multiply(BigDecimal.TEN).intValue()));
}
- } else if (command instanceof DecimalType) {
- localApi.setTransitionTime(
- new BigDecimal(((DecimalType) command).intValue()).multiply(BigDecimal.TEN));
+ } else if (command instanceof DecimalType decimalCommand) {
+ localApi.setTransitionTime(new BigDecimal(decimalCommand.intValue()).multiply(BigDecimal.TEN));
}
break;
case CHANNEL_PRESET_DURATION:// ch removed in firmware 0.13.0 and newer
- if (command instanceof QuantityType) {
- QuantityType<?> seconds = ((QuantityType<?>) command).toUnit(Units.SECOND);
+ if (command instanceof QuantityType quantityCommand) {
+ QuantityType<?> seconds = quantityCommand.toUnit(Units.SECOND);
if (seconds != null) {
BigDecimal bigTemp = new BigDecimal(seconds.intValue()).multiply(new BigDecimal(1000));
localApi.sendGetRequest("/win&PT=" + bigTemp.intValue());
}
- } else if (command instanceof DecimalType) {
- BigDecimal bigTemp = new BigDecimal(((DecimalType) command).intValue())
- .multiply(new BigDecimal(1000));
+ } else if (command instanceof DecimalType decimalCommand) {
+ BigDecimal bigTemp = new BigDecimal(decimalCommand.intValue()).multiply(new BigDecimal(1000));
localApi.sendGetRequest("/win&PT=" + bigTemp.intValue());
}
break;
case CHANNEL_SEGMENT_BRIGHTNESS:
if (command instanceof OnOffType) {
localApi.setMasterOn(OnOffType.ON.equals(command), config.segmentIndex);
- } else if (command instanceof PercentType) {
+ } else if (command instanceof PercentType percentCommand) {
if (PercentType.ZERO.equals(command)) {
localApi.setMasterOn(false, config.segmentIndex);
return;
}
- localApi.setMasterBrightness((PercentType) command, config.segmentIndex);
+ localApi.setMasterBrightness(percentCommand, config.segmentIndex);
}
break;
case CHANNEL_MIRROR:
localApi.setMirror(OnOffType.ON.equals(command), config.segmentIndex);
break;
case CHANNEL_SPACING:
- if (command instanceof DecimalType) {
- localApi.setSpacing(((DecimalType) command).intValue(), config.segmentIndex);
+ if (command instanceof DecimalType decimalCommand) {
+ localApi.setSpacing(decimalCommand.intValue(), config.segmentIndex);
}
break;
case CHANNEL_GROUPING:
- if (command instanceof DecimalType) {
- localApi.setGrouping(((DecimalType) command).intValue(), config.segmentIndex);
+ if (command instanceof DecimalType decimalCommand) {
+ localApi.setGrouping(decimalCommand.intValue(), config.segmentIndex);
}
break;
case CHANNEL_REVERSE:
localApi.setReverse(OnOffType.ON.equals(command), config.segmentIndex);
break;
case CHANNEL_PRIMARY_WHITE:
- if (command instanceof PercentType) {
- localApi.sendGetRequest(
- "/win&W=" + ((PercentType) command).toBigDecimal().multiply(BIG_DECIMAL_2_55));
+ if (command instanceof PercentType percentCommand) {
+ localApi.sendGetRequest("/win&W=" + percentCommand.toBigDecimal().multiply(BIG_DECIMAL_2_55));
}
break;
case CHANNEL_SECONDARY_WHITE:
- if (command instanceof PercentType) {
- localApi.sendGetRequest(
- "/win&W2=" + ((PercentType) command).toBigDecimal().multiply(BIG_DECIMAL_2_55));
+ if (command instanceof PercentType percentCommand) {
+ localApi.sendGetRequest("/win&W2=" + percentCommand.toBigDecimal().multiply(BIG_DECIMAL_2_55));
}
break;
case CHANNEL_MASTER_CONTROLS:
localApi.sendGetRequest("/win&TT=1000&A=0");
}
}
- } else if (command instanceof HSBType) {
- if ((((HSBType) command).getBrightness()).equals(PercentType.ZERO)) {
+ } else if (command instanceof HSBType hsbCommand) {
+ if ((hsbCommand.getBrightness()).equals(PercentType.ZERO)) {
localApi.setMasterOn(false, config.segmentIndex);
return;
}
localApi.setGlobalOn(true);
- primaryColor = (HSBType) command;
+ primaryColor = hsbCommand;
if (primaryColor.getSaturation().intValue() < bridgeHandler.config.saturationThreshold
&& bridgeHandler.hasWhite) {
- localApi.setWhiteOnly((PercentType) command, config.segmentIndex);
+ localApi.setWhiteOnly(hsbCommand, config.segmentIndex);
} else if (primaryColor.getSaturation().intValue() == 32
&& primaryColor.getHue().intValue() == 36 && bridgeHandler.hasWhite) {
- localApi.setWhiteOnly((PercentType) command, config.segmentIndex);
+ localApi.setWhiteOnly(hsbCommand, config.segmentIndex);
} else {
- localApi.setMasterHSB((HSBType) command, config.segmentIndex);
+ localApi.setMasterHSB(hsbCommand, config.segmentIndex);
}
- } else if (command instanceof PercentType) {
- localApi.setMasterBrightness((PercentType) command, config.segmentIndex);
+ } else if (command instanceof PercentType percentCommand) {
+ localApi.setMasterBrightness(percentCommand, config.segmentIndex);
}
return;
case CHANNEL_PRIMARY_COLOR:
- if (command instanceof HSBType) {
- primaryColor = (HSBType) command;
- } else if (command instanceof PercentType) {
- primaryColor = new HSBType(primaryColor.getHue(), primaryColor.getSaturation(),
- ((PercentType) command));
+ if (command instanceof HSBType hsbCommand) {
+ primaryColor = hsbCommand;
+ } else if (command instanceof PercentType percentCommand) {
+ primaryColor = new HSBType(primaryColor.getHue(), primaryColor.getSaturation(), percentCommand);
}
localApi.setPrimaryColor(primaryColor, config.segmentIndex);
return;
case CHANNEL_SECONDARY_COLOR:
- if (command instanceof HSBType) {
- secondaryColor = (HSBType) command;
- } else if (command instanceof PercentType) {
+ if (command instanceof HSBType hsbCommand) {
+ secondaryColor = hsbCommand;
+ } else if (command instanceof PercentType percentCommand) {
secondaryColor = new HSBType(secondaryColor.getHue(), secondaryColor.getSaturation(),
- ((PercentType) command));
+ percentCommand);
}
localApi.setSecondaryColor(secondaryColor, config.segmentIndex);
return;
case CHANNEL_THIRD_COLOR:
- if (command instanceof HSBType) {
- thirdColor = (HSBType) command;
- } else if (command instanceof PercentType) {
- thirdColor = new HSBType(thirdColor.getHue(), thirdColor.getSaturation(),
- ((PercentType) command));
+ if (command instanceof HSBType hsbCommand) {
+ thirdColor = hsbCommand;
+ } else if (command instanceof PercentType percentCommand) {
+ thirdColor = new HSBType(thirdColor.getHue(), thirdColor.getSaturation(), percentCommand);
}
localApi.setTertiaryColor(thirdColor, config.segmentIndex);
return;
logger.trace("Login succeeded but failed to create session {}", loginFailedCounter);
return false;
}
-
} catch (WolfSmartsetCloudException e) {
logger.debug("Error logging on to Wolf Smartset ({}): {}", loginFailedCounter, e.getMessage());
loginFailedCounter++;
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof WolfSmartsetAccountBridgeHandler) {
- this.bridgeHandler = (WolfSmartsetAccountBridgeHandler) handler;
+ if (handler instanceof WolfSmartsetAccountBridgeHandler accountBridgeHandler) {
+ this.bridgeHandler = accountBridgeHandler;
}
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof WolfSmartsetSystemBridgeHandler) {
- this.bridgeHandler = (WolfSmartsetSystemBridgeHandler) handler;
+ if (handler instanceof WolfSmartsetSystemBridgeHandler systemBridgeHandler) {
+ this.bridgeHandler = systemBridgeHandler;
}
}
properties.put(CONFIG_UNIT_ID, unit.menuItemTabViewDTO.bundleId.toString());
var tabName = unit.menuItemTabViewDTO.tabName;
var menuName = unit.subMenuEntryDTO.getName();
- tabName = tabName.isEmpty() || tabName.equalsIgnoreCase("NULL") || menuName.equalsIgnoreCase(tabName) ? ""
+ tabName = tabName.isEmpty() || "NULL".equalsIgnoreCase(tabName) || menuName.equalsIgnoreCase(tabName) ? ""
: "-" + tabName;
return DiscoveryResultBuilder.create(unitUID).withProperties(properties)
import static org.openhab.binding.wolfsmartset.internal.WolfSmartsetBindingConstants.CONFIG_SYSTEM_ID;
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(WolfSmartsetAccountDiscoveryService.class);
+ return Set.of(WolfSmartsetAccountDiscoveryService.class);
}
@Override
var systemConfigs = systemHandlers.values().stream().map(s -> s.getSystemConfig())
.filter(s -> s != null).collect(Collectors.toSet());
- if (systemConfigs != null && systemConfigs.size() > 0) {
+ if (systemConfigs != null && !systemConfigs.isEmpty()) {
var systemStates = api.getSystemState(systemConfigs);
if (systemStates != null) {
for (var systemState : systemStates) {
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.ConcurrentHashMap;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(WolfSmartsetSystemDiscoveryService.class);
+ return Set.of(WolfSmartsetSystemDiscoveryService.class);
}
@Override
active = discoveryService.isBackgroundDiscoveryEnabled();
}
+ @Override
public boolean isActive() {
synchronized (LOCK) {
return this.active;
}
@Deactivate
+ @Override
public void disable() {
errorDetail = "";
active = false;
@Test
void programmaticChannelsAreAddedCorrectlyOnce() {
// Given
- final String queryString = "ID=dfggger&" + "PASSWORD=XXXXXX&" + "humidity=74&" + "AqPM2.5=30&"
- + "windspdmph_avg2m=10&" + "dateutc=2021-02-07%2014:04:03&" + "softwaretype=WH2600%20V2.2.8&"
- + "action=updateraw&" + "realtime=1&" + "rtfreq=5";
+ final String queryString = """
+ ID=dfggger&\
+ PASSWORD=XXXXXX&\
+ humidity=74&\
+ AqPM2.5=30&\
+ windspdmph_avg2m=10&\
+ dateutc=2021-02-07%2014:04:03&\
+ softwaretype=WH2600%20V2.2.8&\
+ action=updateraw&\
+ realtime=1&\
+ rtfreq=5\
+ """;
MetaData.Request request = new MetaData.Request("GET",
new HttpURI("http://localhost" + WundergroundUpdateReceiverServlet.SERVLET_URL + "?" + queryString),
HttpVersion.HTTP_1_1, new HttpFields());
void aRequestWithAnUnregisteredStationidIsAddedToTheQueueOnce()
throws ServletException, NamespaceException, IOException {
// Given
- final String queryString = "ID=dfggger&" + "PASSWORD=XXXXXX&" + "tempf=26.1&" + "humidity=74&" + "dewptf=18.9&"
- + "windchillf=26.1&" + "winddir=14&" + "windspeedmph=1.34&" + "windgustmph=2.46&" + "rainin=0.00&"
- + "dailyrainin=0.00&" + "weeklyrainin=0.00&" + "monthlyrainin=0.08&" + "yearlyrainin=3.06&"
- + "solarradiation=42.24&" + "UV=1&indoortempf=69.3&" + "indoorhumidity=32&" + "baromin=30.39&"
- + "AqNOX=21&" + "lowbatt=1&" + "dateutc=2021-02-07%2014:04:03&" + "softwaretype=WH2600%20V2.2.8&"
- + "action=updateraw&" + "realtime=1&" + "rtfreq=5";
+ final String queryString = """
+ ID=dfggger&\
+ PASSWORD=XXXXXX&\
+ tempf=26.1&\
+ humidity=74&\
+ dewptf=18.9&\
+ windchillf=26.1&\
+ winddir=14&\
+ windspeedmph=1.34&\
+ windgustmph=2.46&\
+ rainin=0.00&\
+ dailyrainin=0.00&\
+ weeklyrainin=0.00&\
+ monthlyrainin=0.08&\
+ yearlyrainin=3.06&\
+ solarradiation=42.24&\
+ UV=1&indoortempf=69.3&\
+ indoorhumidity=32&\
+ baromin=30.39&\
+ AqNOX=21&\
+ lowbatt=1&\
+ dateutc=2021-02-07%2014:04:03&\
+ softwaretype=WH2600%20V2.2.8&\
+ action=updateraw&\
+ realtime=1&\
+ rtfreq=5\
+ """;
WundergroundUpdateReceiverDiscoveryService discoveryService = mock(
WundergroundUpdateReceiverDiscoveryService.class);
WundergroundUpdateReceiverServlet sut = new WundergroundUpdateReceiverServlet(discoveryService);
@Test
void multipleIndexedParametersOfTheSameChanneltypeAreCorrectlyDiscovered() throws IOException {
// Given
- final String queryString = "ID=dfggger&" + "PASSWORD=XXXXXX&" + "temp1f=26.1&" + "humidity=74&" + "temp2f=25.1&"
- + "lowbatt=1&" + "soilmoisture1=78&" + "soilmoisture2=73&" + "dateutc=2021-02-07%2014:04:03&"
- + "softwaretype=WH2600%20V2.2.8&" + "action=updateraw&" + "realtime=1&" + "rtfreq=5";
+ final String queryString = """
+ ID=dfggger&\
+ PASSWORD=XXXXXX&\
+ temp1f=26.1&\
+ humidity=74&\
+ temp2f=25.1&\
+ lowbatt=1&\
+ soilmoisture1=78&\
+ soilmoisture2=73&\
+ dateutc=2021-02-07%2014:04:03&\
+ softwaretype=WH2600%20V2.2.8&\
+ action=updateraw&\
+ realtime=1&\
+ rtfreq=5\
+ """;
MetaData.Request request = new MetaData.Request("GET",
new HttpURI("http://localhost" + WundergroundUpdateReceiverServlet.SERVLET_URL + "?" + queryString),
HttpVersion.HTTP_1_1, new HttpFields());
@Test
void unregisteredChannelsAreAddedOnTheFlyWhenDiscovered() throws IOException {
// Given
- final String firstDeviceQueryString = "ID=dfggger&" + "PASSWORD=XXXXXX&" + "tempf=26.1&" + "humidity=74&"
- + "dateutc=2021-02-07%2014:04:03&" + "softwaretype=WH2600%20V2.2.8&" + "action=updateraw&"
- + "realtime=1&" + "rtfreq=5";
+ final String firstDeviceQueryString = """
+ ID=dfggger&\
+ PASSWORD=XXXXXX&\
+ tempf=26.1&\
+ humidity=74&\
+ dateutc=2021-02-07%2014:04:03&\
+ softwaretype=WH2600%20V2.2.8&\
+ action=updateraw&\
+ realtime=1&\
+ rtfreq=5\
+ """;
MetaData.Request request1 = new MetaData.Request("GET", new HttpURI(
"http://localhost" + WundergroundUpdateReceiverServlet.SERVLET_URL + "?" + firstDeviceQueryString),
HttpVersion.HTTP_1_1, new HttpFields());
assertThat(before, hasItems(expectedBefore));
// When
- final String secondDeviceQueryString = "ID=dfggger&" + "PASSWORD=XXXXXX&" + "lowbatt=1&" + "soilmoisture1=78&"
- + "soilmoisture2=73&" + "solarradiation=42.24&" + "dateutc=2021-02-07%2014:04:03&"
- + "softwaretype=WH2600%20V2.2.8&" + "action=updateraw&" + "realtime=1&" + "rtfreq=5";
+ final String secondDeviceQueryString = """
+ ID=dfggger&\
+ PASSWORD=XXXXXX&\
+ lowbatt=1&\
+ soilmoisture1=78&\
+ soilmoisture2=73&\
+ solarradiation=42.24&\
+ dateutc=2021-02-07%2014:04:03&\
+ softwaretype=WH2600%20V2.2.8&\
+ action=updateraw&\
+ realtime=1&\
+ rtfreq=5\
+ """;
MetaData.Request request = new MetaData.Request("GET", new HttpURI(
"http://localhost" + WundergroundUpdateReceiverServlet.SERVLET_URL + "?" + secondDeviceQueryString),
HttpVersion.HTTP_1_1, new HttpFields());
@Test
void unregisteredChannelsAreNotAddedOnUnmanagedThings() throws IOException {
// Given
- final String firstDeviceQueryString = "ID=dfggger&" + "PASSWORD=XXXXXX&" + "tempf=26.1&" + "humidity=74&"
- + "dateutc=2021-02-07%2014:04:03&" + "softwaretype=WH2600%20V2.2.8&" + "action=updateraw&"
- + "realtime=1&" + "rtfreq=5";
+ final String firstDeviceQueryString = """
+ ID=dfggger&\
+ PASSWORD=XXXXXX&\
+ tempf=26.1&\
+ humidity=74&\
+ dateutc=2021-02-07%2014:04:03&\
+ softwaretype=WH2600%20V2.2.8&\
+ action=updateraw&\
+ realtime=1&\
+ rtfreq=5\
+ """;
MetaData.Request request1 = new MetaData.Request("GET", new HttpURI(
"http://localhost" + WundergroundUpdateReceiverServlet.SERVLET_URL + "?" + firstDeviceQueryString),
HttpVersion.HTTP_1_1, new HttpFields());
assertThat(before, hasItems(expectedBefore));
// When
- final String secondDeviceQueryString = "ID=dfggger&" + "PASSWORD=XXXXXX&" + "lowbatt=1&" + "soilmoisture1=78&"
- + "soilmoisture2=73&" + "solarradiation=42.24&" + "dateutc=2021-02-07%2014:04:03&"
- + "softwaretype=WH2600%20V2.2.8&" + "action=updateraw&" + "realtime=1&" + "rtfreq=5";
+ final String secondDeviceQueryString = """
+ ID=dfggger&\
+ PASSWORD=XXXXXX&\
+ lowbatt=1&\
+ soilmoisture1=78&\
+ soilmoisture2=73&\
+ solarradiation=42.24&\
+ dateutc=2021-02-07%2014:04:03&\
+ softwaretype=WH2600%20V2.2.8&\
+ action=updateraw&\
+ realtime=1&\
+ rtfreq=5\
+ """;
MetaData.Request request = new MetaData.Request("GET", new HttpURI(
"http://localhost" + WundergroundUpdateReceiverServlet.SERVLET_URL + "?" + secondDeviceQueryString),
HttpVersion.HTTP_1_1, new HttpFields());
@Test
void lastQueryTriggerIsMigratedSuccessfully() throws IOException {
// Given
- final String firstDeviceQueryString = "ID=dfggger&" + "PASSWORD=XXXXXX&" + "tempf=26.1&" + "humidity=74&"
- + "dateutc=2021-02-07%2014:04:03&" + "softwaretype=WH2600%20V2.2.8&" + "action=updateraw&"
- + "realtime=1&" + "rtfreq=5";
+ final String firstDeviceQueryString = """
+ ID=dfggger&\
+ PASSWORD=XXXXXX&\
+ tempf=26.1&\
+ humidity=74&\
+ dateutc=2021-02-07%2014:04:03&\
+ softwaretype=WH2600%20V2.2.8&\
+ action=updateraw&\
+ realtime=1&\
+ rtfreq=5\
+ """;
MetaData.Request request1 = new MetaData.Request("GET", new HttpURI(
"http://localhost" + WundergroundUpdateReceiverServlet.SERVLET_URL + "?" + firstDeviceQueryString),
HttpVersion.HTTP_1_1, new HttpFields());
handler.dispose();
handler.initialize();
- final String secondDeviceQueryString = "ID=dfggger&" + "PASSWORD=XXXXXX&" + "lowbatt=1&" + "soilmoisture1=78&"
- + "soilmoisture2=73&" + "solarradiation=42.24&" + "dateutc=2021-02-07%2014:04:03&"
- + "softwaretype=WH2600%20V2.2.8&" + "action=updateraw&" + "realtime=1&" + "rtfreq=5";
+ final String secondDeviceQueryString = """
+ ID=dfggger&\
+ PASSWORD=XXXXXX&\
+ lowbatt=1&\
+ soilmoisture1=78&\
+ soilmoisture2=73&\
+ solarradiation=42.24&\
+ dateutc=2021-02-07%2014:04:03&\
+ softwaretype=WH2600%20V2.2.8&\
+ action=updateraw&\
+ realtime=1&\
+ rtfreq=5\
+ """;
MetaData.Request request = new MetaData.Request("GET", new HttpURI(
"http://localhost" + WundergroundUpdateReceiverServlet.SERVLET_URL + "?" + secondDeviceQueryString),
HttpVersion.HTTP_1_1, new HttpFields());
@Override
public void setThingHandler(ThingHandler handler) {
- if (handler instanceof XmlTVHandler) {
- this.handler = (XmlTVHandler) handler;
+ if (handler instanceof XmlTVHandler tvHandler) {
+ this.handler = tvHandler;
}
}
*/
package org.openhab.binding.xmltv.internal.handler;
-import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.time.Instant;
XMLStreamReader xsr = null;
try {
// This can take some seconds depending upon weight of the XmlTV source file
- xsr = xif.createXMLStreamReader(new FileInputStream(new File(config.filePath)), config.encoding);
+ xsr = xif.createXMLStreamReader(new FileInputStream(config.filePath), config.encoding);
try {
Tv xmlFile = (Tv) unmarshaller.unmarshal(xsr);
// Remove all finished programmes
}
private long iso860DateToEpoch(String date) {
- long epoch = ZonedDateTime.parse(date, XMLTV_DATE_FORMAT).toInstant().toEpochMilli();
- return epoch;
+ return ZonedDateTime.parse(date, XMLTV_DATE_FORMAT).toInstant().toEpochMilli();
}
public List<Icon> getIcons() {
*/
package org.openhab.binding.xmppclient.internal;
-import java.util.Collections;
import java.util.Set;
import org.openhab.binding.xmppclient.internal.handler.XMPPClientHandler;
*/
@Component(configurationPid = "binding.xmppclient", service = ThingHandlerFactory.class)
public class XMPPClientHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .singleton(XMPPClientBindingConstants.BRIDGE_TYPE_XMPP);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set
+ .of(XMPPClientBindingConstants.BRIDGE_TYPE_XMPP);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
import java.io.IOException;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jivesoftware.smack.SmackException;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(XMPPActions.class);
+ return Set.of(XMPPActions.class);
}
@Override
if (distributioninfo != null) {
responseCode = distributioninfo.getResponseCode();
localRole = distributioninfo.getRole();
- if (command.toString().equals("")) {
+ if ("".equals(command.toString())) {
action = "unlink";
groupId = distributioninfo.getGroupId();
} else if (command.toString().contains("***")) {
httpResponse = startDistribution(mclinkSetupServer);
localDefaultAfterMCLink = getThing().getConfiguration()
.get("defaultAfterMCLink").toString();
- httpResponse = setInput(localDefaultAfterMCLink.toString(), zone, this.host);
+ httpResponse = setInput(localDefaultAfterMCLink, zone, this.host);
} else if ("".equals(mclinkSetupServer)) {
// fallback in case client is removed from group by ending group on server side
localDefaultAfterMCLink = getThing().getConfiguration()
.get("defaultAfterMCLink").toString();
- httpResponse = setInput(localDefaultAfterMCLink.toString(), zone, this.host);
+ httpResponse = setInput(localDefaultAfterMCLink, zone, this.host);
}
}
}
JsonObject presetObject = pr.getAsJsonObject();
String text = presetObject.get("text").getAsString();
if (!"".equals(text)) {
- optionsPresets.add(new StateOption(String.valueOf(presetCounter),
- "#" + String.valueOf(presetCounter) + " " + text));
+ optionsPresets.add(
+ new StateOption(String.valueOf(presetCounter), "#" + presetCounter + " " + text));
if (inputText.equals(text)) {
currentPreset = presetCounter;
}
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Locale;
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;
@Override
public Collection<ChannelType> getChannelTypes(@Nullable Locale locale) {
- return Collections.singleton(channelType);
+ return Set.of(channelType);
}
@Override
import static org.openhab.binding.yamahareceiver.internal.YamahaReceiverBindingConstants.*;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Locale;
+import java.util.Set;
import java.util.stream.IntStream;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Override
public Collection<ChannelType> getChannelTypes(@Nullable Locale locale) {
- return Collections.singleton(channelType);
+ return Set.of(channelType);
}
@Override
public static final ThingTypeUID BRIDGE_THING_TYPE = new ThingTypeUID(BINDING_ID, "yamahaAV");
public static final ThingTypeUID ZONE_THING_TYPE = new ThingTypeUID(BINDING_ID, "zone");
- public static final Set<ThingTypeUID> BRIDGE_THING_TYPES_UIDS = Collections.singleton(BRIDGE_THING_TYPE);
- public static final Set<ThingTypeUID> ZONE_THING_TYPES_UIDS = Collections.singleton(ZONE_THING_TYPE);
+ public static final Set<ThingTypeUID> BRIDGE_THING_TYPES_UIDS = Set.of(BRIDGE_THING_TYPE);
+ public static final Set<ThingTypeUID> ZONE_THING_TYPES_UIDS = Set.of(ZONE_THING_TYPE);
// List of channel IDs for zone control (except power which is also a non-zone/bridge channel)
public static final String CHANNEL_POWER = "power";
import static org.openhab.binding.yamahareceiver.internal.YamahaReceiverBindingConstants.Configs.CONFIG_HOST_NAME;
import java.net.URL;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
private final Logger logger = LoggerFactory.getLogger(YamahaDiscoveryParticipant.class);
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(BRIDGE_THING_TYPE);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(BRIDGE_THING_TYPE);
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
import java.io.IOException;
import java.util.Collection;
-import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(ZoneDiscoveryService.class);
+ return Set.of(ZoneDiscoveryService.class);
}
/**
bridgeConfig.getPort());
Optional<String> host = bridgeConfig.getHostWithPort();
- if (!host.isPresent()) {
+ if (host.isEmpty()) {
String msg = "Host or port not set. Double check your thing settings.";
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, msg);
logger.warn(msg);
private boolean isFeatureSupported(Node node, String name) {
String value = getNodeContentOrEmpty(node, name);
- boolean supported = "1".equals(value) || "Available".equals(value);
- return supported;
+ return "1".equals(value) || "Available".equals(value);
}
private <T> void checkFeature(Node node, String name, T value, Set<T> set) {
if (sameMenu) {
if (!selectItem(selectItemName)) {
observer.navigationError("Item '" + selectItemName + "' doesn't exist in menu " + state.menuName
- + " at level " + String.valueOf(state.menuLayer) + ". Available options are: "
- + state.getAllItemLabels());
+ + " at level " + state.menuLayer + ". Available options are: " + state.getAllItemLabels());
}
return;
}
for (String pathElement : pathArr) {
if (!selectItem(pathElement)) {
observer.navigationError("Item '" + pathElement + "' doesn't exist in menu " + state.menuName
- + " at level " + String.valueOf(state.menuLayer) + ". Available options are: "
- + state.getAllItemLabels());
+ + " at level " + state.menuLayer + ". Available options are: " + state.getAllItemLabels());
return;
}
}
int index = findItemOnCurrentPage(name);
if (index > 0) {
- com.send(wrInput(
- "<List_Control><Direct_Sel>Line_" + String.valueOf(index) + "</Direct_Sel></List_Control>"));
+ com.send(wrInput("<List_Control><Direct_Sel>Line_" + index + "</Direct_Sel></List_Control>"));
update();
return true;
}
if (doc.getFirstChild() == null) {
throw new ReceivedMessageParseException("The command '" + cmd + "' failed: " + response);
}
- Node content = XMLUtils.getNode(doc.getFirstChild(), path);
- return content;
+ return XMLUtils.getNode(doc.getFirstChild(), path);
}
/**
public int menuLayer = -1;
public int currentLine = 0;
public int maxLine = -1;
- public String items[] = new String[InputWithNavigationControlXML.MAX_PER_PAGE];
+ public String[] items = new String[InputWithNavigationControlXML.MAX_PER_PAGE];
public String getCurrentItemName() {
if (currentLine < 1 || currentLine > items.length) {
}
switch (channelUID.getId()) {
case CHANNEL_BRIGHTNESS:
- if (command instanceof PercentType) {
- handlePercentMessage((PercentType) command);
- } else if (command instanceof OnOffType) {
- handleOnOffCommand((OnOffType) command);
- } else if (command instanceof IncreaseDecreaseType) {
- handleIncreaseDecreaseBrightnessCommand((IncreaseDecreaseType) command);
+ if (command instanceof PercentType percentCommand) {
+ handlePercentMessage(percentCommand);
+ } else if (command instanceof OnOffType onOffCommand) {
+ handleOnOffCommand(onOffCommand);
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ handleIncreaseDecreaseBrightnessCommand(increaseDecreaseCommand);
}
break;
case CHANNEL_COLOR:
- if (command instanceof HSBType) {
- HSBType hsbCommand = (HSBType) command;
+ if (command instanceof HSBType hsbCommand) {
if (hsbCommand.getBrightness().intValue() == 0) {
handleOnOffCommand(OnOffType.OFF);
} else {
handleHSBCommand(hsbCommand);
}
- } else if (command instanceof PercentType) {
- handlePercentMessage((PercentType) command);
- } else if (command instanceof OnOffType) {
- handleOnOffCommand((OnOffType) command);
- } else if (command instanceof IncreaseDecreaseType) {
- handleIncreaseDecreaseBrightnessCommand((IncreaseDecreaseType) command);
+ } else if (command instanceof PercentType percentCommand) {
+ handlePercentMessage(percentCommand);
+ } else if (command instanceof OnOffType onOffCommand) {
+ handleOnOffCommand(onOffCommand);
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ handleIncreaseDecreaseBrightnessCommand(increaseDecreaseCommand);
}
break;
case CHANNEL_COLOR_TEMPERATURE:
- if (command instanceof PercentType) {
- handleColorTemperatureCommand((PercentType) command);
- } else if (command instanceof IncreaseDecreaseType) {
- handleIncreaseDecreaseBrightnessCommand((IncreaseDecreaseType) command);
+ if (command instanceof PercentType percentCommand) {
+ handleColorTemperatureCommand(percentCommand);
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ handleIncreaseDecreaseBrightnessCommand(increaseDecreaseCommand);
}
break;
case CHANNEL_BACKGROUND_COLOR:
- if (command instanceof HSBType) {
- HSBType hsbCommand = (HSBType) command;
+ if (command instanceof HSBType hsbCommand) {
handleBackgroundHSBCommand(hsbCommand);
- } else if (command instanceof PercentType) {
- handleBackgroundBrightnessPercentMessage((PercentType) command);
- } else if (command instanceof OnOffType) {
- handleBackgroundOnOffCommand((OnOffType) command);
+ } else if (command instanceof PercentType percentCommand) {
+ handleBackgroundBrightnessPercentMessage(percentCommand);
+ } else if (command instanceof OnOffType onOffCommand) {
+ handleBackgroundOnOffCommand(onOffCommand);
}
break;
case CHANNEL_NIGHTLIGHT:
JsonArray status = result.get("result").getAsJsonArray();
// power:
- if (status.get(0).toString().equals("\"off\"")) {
+ if ("\"off\"".equals(status.get(0).toString())) {
mDeviceStatus.setPowerOff(true);
- } else if (status.get(0).toString().equals("\"on\"")) {
+ } else if ("\"on\"".equals(status.get(0).toString())) {
mDeviceStatus.setPowerOff(false);
}
JsonArray status = result.get("result").getAsJsonArray();
// power:
- if (status.get(0).toString().equals("\"off\"")) {
+ if ("\"off\"".equals(status.get(0).toString())) {
mDeviceStatus.setPowerOff(true);
- } else if (status.get(0).toString().equals("\"on\"")) {
+ } else if ("\"on\"".equals(status.get(0).toString())) {
mDeviceStatus.setPowerOff(false);
}
JsonArray status = result.get("result").getAsJsonArray();
// power:
- if (status.get(0).toString().equals("\"off\"")) {
+ if ("\"off\"".equals(status.get(0).toString())) {
mDeviceStatus.setPowerOff(true);
- } else if (status.get(0).toString().equals("\"on\"")) {
+ } else if ("\"on\"".equals(status.get(0).toString())) {
mDeviceStatus.setPowerOff(false);
}
try {
if (message.has("method")) {
String method = message.get("method").toString().replace("\"", "");
- if (method.equals("props")) {// Property notify
+ if ("props".equals(method)) {// Property notify
String params = message.get("params").toString();
JsonObject propsObject = JsonParser.parseString(params).getAsJsonObject();
for (Entry<String, JsonElement> prop : propsObject.entrySet()) {
switch (property) {
case POWER:
- if (prop.getValue().toString().equals("\"off\"")) {
+ if ("\"off\"".equals(prop.getValue().toString())) {
mDeviceStatus.setPowerOff(true);
- } else if (prop.getValue().toString().equals("\"on\"")) {
+ } else if ("\"on\"".equals(prop.getValue().toString())) {
mDeviceStatus.setPowerOff(false);
}
break;
} else if (message.has("id") && message.has("result")) {
// no method, but result : ["ok"]
JsonArray result = message.get("result").getAsJsonArray();
- if (result.get(0).toString().equals("\"ok\"")) {
+ if ("\"ok\"".equals(result.get(0).toString())) {
logger.info("######### this is control command response, don't need to notify status change!");
needNotify = false;
}
JsonArray status = result.get("result").getAsJsonArray();
// power:
- if (status.get(0).toString().equals("\"off\"")) {
+ if ("\"off\"".equals(status.get(0).toString())) {
mDeviceStatus.setPowerOff(true);
- } else if (status.get(0).toString().equals("\"on\"")) {
+ } else if ("\"on\"".equals(status.get(0).toString())) {
mDeviceStatus.setPowerOff(false);
}
JsonArray status = result.get("result").getAsJsonArray();
// power:
- if (status.get(0).toString().equals("\"off\"")) {
+ if ("\"off\"".equals(status.get(0).toString())) {
mDeviceStatus.setPowerOff(true);
- } else if (status.get(0).toString().equals("\"on\"")) {
+ } else if ("\"on\"".equals(status.get(0).toString())) {
mDeviceStatus.setPowerOff(false);
}
JsonArray status = result.get("result").getAsJsonArray();
// power:
- if (status.get(0).toString().equals("\"off\"")) {
+ if ("\"off\"".equals(status.get(0).toString())) {
mDeviceStatus.setPowerOff(true);
- } else if (status.get(0).toString().equals("\"on\"")) {
+ } else if ("\"on\"".equals(status.get(0).toString())) {
mDeviceStatus.setPowerOff(false);
}
device.decreaseCt(action.intDuration());
break;
case background_color:
- if (device instanceof DeviceWithAmbientLight) {
+ if (device instanceof DeviceWithAmbientLight light) {
final String[] split = action.strValue().split(",");
- ((DeviceWithAmbientLight) device).setBackgroundColor(Integer.parseInt(split[0]),
- Integer.parseInt(split[1]), action.intDuration());
+ light.setBackgroundColor(Integer.parseInt(split[0]), Integer.parseInt(split[1]),
+ action.intDuration());
}
break;
case background_brightness:
- if (device instanceof DeviceWithAmbientLight) {
- ((DeviceWithAmbientLight) device).setBackgroundBrightness(action.intValue(),
- action.intDuration());
+ if (device instanceof DeviceWithAmbientLight light) {
+ light.setBackgroundBrightness(action.intValue(), action.intDuration());
}
break;
case background_on:
- if (device instanceof DeviceWithAmbientLight) {
- ((DeviceWithAmbientLight) device).setBackgroundPower(true, action.intDuration());
+ if (device instanceof DeviceWithAmbientLight light) {
+ light.setBackgroundPower(true, action.intDuration());
}
break;
case background_off:
- if (device instanceof DeviceWithAmbientLight) {
- ((DeviceWithAmbientLight) device).setBackgroundPower(false, action.intDuration());
+ if (device instanceof DeviceWithAmbientLight light) {
+ light.setBackgroundPower(false, action.intDuration());
}
break;
case nightlight_off:
- if (device instanceof DeviceWithNightlight) {
- ((DeviceWithNightlight) device).toggleNightlightMode(false);
+ if (device instanceof DeviceWithNightlight nightlight) {
+ nightlight.toggleNightlightMode(false);
}
break;
case nightlight_on:
- if (device instanceof DeviceWithNightlight) {
- ((DeviceWithNightlight) device).toggleNightlightMode(true);
+ if (device instanceof DeviceWithNightlight nightlight) {
+ nightlight.toggleNightlightMode(true);
}
break;
default:
}
public static String getDefaultName(DeviceBase device) {
- if (device.getDeviceModel() != null && !device.getDeviceName().equals("")) {
+ if (device.getDeviceModel() != null && !"".equals(device.getDeviceName())) {
return device.getDeviceName();
}
switch (device.getDeviceType()) {
public static final String BINDING_ID = "yioremote";
// List of all used global variables
- public static enum YioRemoteDockHandleStatus {
+ public enum YioRemoteDockHandleStatus {
UNINITIALIZED_STATE,
AUTHENTICATION_PROCESS,
AUTHENTICATION_FAILED,
CONNECTION_FAILED,
CONNECTION_ESTABLISHED,
COMMUNICATION_ERROR,
- RECONNECTION_PROCESS;
+ RECONNECTION_PROCESS
}
- public static enum YioRemoteMessages {
+ public enum YioRemoteMessages {
IR_SEND,
AUTHENTICATE_MESSAGE,
HEARTBEAT_MESSAGE,
IR_RECEIVER_ON,
- IR_RECEIVER_OFF;
+ IR_RECEIVER_OFF
}
// List of all Thing Type UIDs
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
boolean success = false;
if (message.has("type")) {
- if (message.get("type").toString().equalsIgnoreCase("\"auth_required\"")) {
+ if ("\"auth_required\"".equalsIgnoreCase(message.get("type").toString())) {
success = true;
receivedStatus = "Authentication required";
- } else if (message.get("type").toString().equalsIgnoreCase("\"auth_ok\"")) {
+ } else if ("\"auth_ok\"".equalsIgnoreCase(message.get("type").toString())) {
authenticationOk = true;
success = true;
receivedStatus = "Authentication ok";
- } else if (message.get("type").toString().equalsIgnoreCase("\"dock\"") && message.has("message")) {
- if (message.get("message").toString().equalsIgnoreCase("\"pong\"")) {
+ } else if ("\"dock\"".equalsIgnoreCase(message.get("type").toString()) && message.has("message")) {
+ if ("\"pong\"".equalsIgnoreCase(message.get("message").toString())) {
heartBeat = true;
success = true;
receivedStatus = "Heart beat received";
- } else if (message.get("message").toString().equalsIgnoreCase("\"ir_send\"")) {
- if (message.get("success").toString().equalsIgnoreCase("true")) {
+ } else if ("\"ir_send\"".equalsIgnoreCase(message.get("message").toString())) {
+ if ("true".equalsIgnoreCase(message.get("success").toString())) {
receivedStatus = "Send IR Code successfully";
success = true;
} else {
heartBeat = false;
success = false;
}
- } else if (message.get("command").toString().equalsIgnoreCase("\"ir_receive\"")) {
+ } else if ("\"ir_receive\"".equalsIgnoreCase(message.get("command").toString())) {
receivedStatus = message.get("code").toString().replace("\"", "");
if (receivedStatus.matches("[0-9]?[0-9][;]0[xX][0-9a-fA-F]+[;][0-9]+[;][0-9]")) {
irCodeReceivedHandler.setCode(message.get("code").toString().replace("\"", ""));
}
return result;
} catch (IllegalArgumentException e) {
- JsonObject result = new JsonObject();
- return result;
+ return new JsonObject();
}
}
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(YIOremoteDockActions.class);
+ return Set.of(YIOremoteDockActions.class);
}
@Override
import static org.openhab.binding.yioremote.internal.YIOremoteBindingConstants.THING_TYPE_YIOREMOTEDOCK;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.yioremote", service = ThingHandlerFactory.class)
public class YIOremoteHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_YIOREMOTEDOCK);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_YIOREMOTEDOCK);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof ZmMonitorHandler) {
- this.handler = (ZmMonitorHandler) handler;
+ if (handler instanceof ZmMonitorHandler zmMonitorHandler) {
+ this.handler = zmMonitorHandler;
}
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof ZmBridgeHandler) {
- bridgeHandler = (ZmBridgeHandler) handler;
+ if (handler instanceof ZmBridgeHandler zmBridgeHandler) {
+ bridgeHandler = zmBridgeHandler;
}
}
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(MonitorDiscoveryService.class);
+ return Set.of(MonitorDiscoveryService.class);
}
public boolean isBackgroundDiscoveryEnabled() {
try {
ContentResponse response = request.send();
if (response.getStatus() == HttpStatus.OK_200) {
- RawType image = new RawType(response.getContent(), response.getHeaders().get(HttpHeader.CONTENT_TYPE));
- return image;
+ return new RawType(response.getContent(), response.getHeaders().get(HttpHeader.CONTENT_TYPE));
} else {
errorMsg = String.format("HTTP GET failed: %d, %s", response.getStatus(), response.getReason());
}
import java.time.ZonedDateTime;
import java.util.Collection;
-import java.util.Collections;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
}
break;
case CHANNEL_ENABLE:
- if (command instanceof OnOffType) {
- localHandler.setEnabled(monitorId, (OnOffType) command);
+ if (command instanceof OnOffType onOffCommand) {
+ localHandler.setEnabled(monitorId, onOffCommand);
logger.debug("Monitor {}: Set monitor enable to {}", monitorId, command);
}
break;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(ZmActions.class);
+ return Set.of(ZmActions.class);
}
public String getId() {
.unmodifiableSet(Stream.of(THING_TYPE_DEVICE, THING_TYPE_VIRTUAL_DEVICE).collect(Collectors.toSet()));
// List of ignored devices for Discovery
- public static final Set<String> DISCOVERY_IGNORED_DEVICES = Collections
- .unmodifiableSet(Collections.singleton(("BatteryPolling")));
+ public static final Set<String> DISCOVERY_IGNORED_DEVICES = Collections.unmodifiableSet(Set.of(("BatteryPolling")));
// List of all Channel IDs
public static final String BATTERY_CHANNEL = "battery";
private static State getColorState(@Nullable Color colorSwitchState) {
if (colorSwitchState != null && colorSwitchState.getRed() != null && colorSwitchState.getGreen() != null
&& colorSwitchState.getBlue() != null) {
- HSBType hsbType = HSBType.fromRGB(colorSwitchState.getRed(), colorSwitchState.getGreen(),
- colorSwitchState.getBlue());
-
- return hsbType;
+ return HSBType.fromRGB(colorSwitchState.getRed(), colorSwitchState.getGreen(), colorSwitchState.getBlue());
}
return UnDefType.UNDEF;
if (connection.getResponseCode() == 401) {
ThingUID thingUID = new ThingUID(ZWayBindingConstants.THING_TYPE_BRIDGE,
- ipAddress.replaceAll("\\.", "_"));
+ ipAddress.replace(".", "_"));
// Attention: if is already present as thing in the ThingRegistry
// the configuration for thing will be updated!
ZWaveDevice zwaveDevice = mBridgeHandler.getZWayApi().getZWaveDevice(nodeId);
if (zwaveDevice != null) {
String givenName = "Device " + nodeId;
- if (!zwaveDevice.getData().getGivenName().getValue().equals("")) {
+ if (!"".equals(zwaveDevice.getData().getGivenName().getValue())) {
givenName = zwaveDevice.getData().getGivenName().getValue();
- } else if (!zwaveDevice.getData().getDeviceTypeString().getValue().equals("")) {
+ } else if (!"".equals(zwaveDevice.getData().getDeviceTypeString().getValue())) {
givenName += " - " + zwaveDevice.getData().getDeviceTypeString().getValue();
}
// Add additional information as properties
String vendorString = zwaveDevice.getData().getVendorString().getValue();
- if (!zwaveDevice.getData().getVendorString().getValue().equals("")) {
+ if (!"".equals(zwaveDevice.getData().getVendorString().getValue())) {
givenName += " (" + vendorString + ")";
}
String manufacturerId = zwaveDevice.getData().getManufacturerId().getValue();
updateProperties(properties);
// Update channels
- if (zwaveController.getData().getSecureInclusion().getValue().equals("true")) {
+ if ("true".equals(zwaveController.getData().getSecureInclusion().getValue())) {
updateState(SECURE_INCLUSION_CHANNEL, OnOffType.ON);
} else {
updateState(SECURE_INCLUSION_CHANNEL, OnOffType.OFF);
return null;
}
ThingHandler handler = bridge.getHandler();
- if (handler instanceof ZWayBridgeHandler) {
- return (ZWayBridgeHandler) handler;
+ if (handler instanceof ZWayBridgeHandler bridgeHandler) {
+ return bridgeHandler;
} else {
return null;
}
}
} else if (device instanceof SwitchRGBW) {
// possible commands: on(), off(), exact(red, green, blue)
- if (command instanceof HSBType) {
+ if (command instanceof HSBType hsb) {
logger.debug("Handle command: HSBType");
- HSBType hsb = (HSBType) command;
-
// first set on/off
if (hsb.getBrightness().intValue() > 0) {
- if (device.getMetrics().getLevel().toLowerCase().equals("off")) {
+ if ("off".equals(device.getMetrics().getLevel().toLowerCase())) {
device.on();
}
}
// 2. Check if device information includes further information about sensor type
- if (!device.getProbeType().equals("")) {
+ if (!"".equals(device.getProbeType())) {
if (device instanceof SensorMultilevel) {
switch (device.getProbeType()) {
case PROBE_TYPE_TEMPERATURE:
break;
}
}
- } else if (!device.getMetrics().getProbeTitle().equals("")) {
+ } else if (!"".equals(device.getMetrics().getProbeTitle())) {
if (device instanceof SensorMultilevel) {
switch (device.getMetrics().getProbeTitle()) {
case PROBE_TITLE_CO2_LEVEL:
break;
}
}
- } else if (!device.getMetrics().getIcon().equals("")) {
+ } else if (!"".equals(device.getMetrics().getIcon())) {
if (device instanceof SwitchBinary) {
switch (device.getMetrics().getIcon()) {
case ICON_SWITCH:
// Check command classes (only for ThermostatMode)
ZWaveDevice zwaveDevice = getZWayBridgeHandler().getZWayApi()
.getZWaveDevice(mConfig.getNodeId());
- if (!zwaveDevice.getInstances().get0().getCommandClasses().get64().getName().equals("")) {
+ if (!"".equals(zwaveDevice.getInstances().get0().getCommandClasses().get64().getName())) {
// Load available thermostat modes
Map<Integer, String> modes = zwaveDevice.getInstances().get0().getCommandClasses().get64()
.getThermostatModes();