Java 17 features (T-Z) (#15576)

- add missing @override
- Java style array syntax
- remove redundant modifiers
- always move String constants to left side in comparisons
- simplify lambda expressions and return statements
- use replace instead of replaceAll w/o regex
- instanceof matching and multiline strings
- remove null check before instanceof

Signed-off-by: Holger Friedrich <mail@holger-friedrich.de>
This commit is contained in:
Holger Friedrich 2023-09-21 07:58:53 +02:00 committed by GitHub
parent bf1aa3deb2
commit 1b122a53b9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
277 changed files with 1402 additions and 1298 deletions

View File

@ -93,8 +93,7 @@ public final class AnalogMessage extends Message {
public AnalogValue getAnalogValue(int portNumber) { public AnalogValue getAnalogValue(int portNumber) {
// Get the internal index for portNumber within the message // Get the internal index for portNumber within the message
int idx = (portNumber - 1) % 4; int idx = (portNumber - 1) % 4;
AnalogValue value = new AnalogValue(this.getValue(idx), getMeasureType(idx)); return new AnalogValue(this.getValue(idx), getMeasureType(idx));
return value;
} }
/** /**

View File

@ -26,7 +26,7 @@ import org.openhab.core.types.State;
@NonNullByDefault @NonNullByDefault
public class ApiPageEntry { public class ApiPageEntry {
static enum Type { enum Type {
READ_ONLY_SWITCH(true), READ_ONLY_SWITCH(true),
READ_ONLY_NUMERIC(true), READ_ONLY_NUMERIC(true),
NUMERIC_FORM(false), NUMERIC_FORM(false),

View File

@ -30,7 +30,7 @@ public class ChangerX2Entry {
public static final String NUMBER_MAX = "max"; public static final String NUMBER_MAX = "max";
public static final String NUMBER_STEP = "step"; public static final String NUMBER_STEP = "step";
static enum OptionType { enum OptionType {
NUMBER, NUMBER,
SELECT, SELECT,
} }

View File

@ -73,12 +73,12 @@ public class CapabilitiesSupport {
// iterate over all mode capability elements and build the superset of their inner capabilities // iterate over all mode capability elements and build the superset of their inner capabilities
allCapabilities.forEach(e -> { allCapabilities.forEach(e -> {
if (e != null) { if (e != null) {
light |= e.getLight() != null ? e.getLight().size() > 0 : false; light |= e.getLight() != null ? !e.getLight().isEmpty() : false;
swing |= e.getSwings() != null ? e.getSwings().size() > 0 : false; swing |= e.getSwings() != null ? !e.getSwings().isEmpty() : false;
fanLevel |= e.getFanLevel() != null ? e.getFanLevel().size() > 0 : false; fanLevel |= e.getFanLevel() != null ? !e.getFanLevel().isEmpty() : false;
fanSpeed |= e.getFanSpeeds() != null ? e.getFanSpeeds().size() > 0 : false; fanSpeed |= e.getFanSpeeds() != null ? !e.getFanSpeeds().isEmpty() : false;
verticalSwing |= e.getVerticalSwing() != null ? e.getVerticalSwing().size() > 0 : false; verticalSwing |= e.getVerticalSwing() != null ? !e.getVerticalSwing().isEmpty() : false;
horizontalSwing |= e.getHorizontalSwing() != null ? e.getHorizontalSwing().size() > 0 : false; horizontalSwing |= e.getHorizontalSwing() != null ? !e.getHorizontalSwing().isEmpty() : false;
} }
}); });
} }

View File

@ -36,7 +36,7 @@ public class TadoBindingConstants {
// List of all Channel IDs // List of all Channel IDs
public static final String PROPERTY_HOME_TEMPERATURE_UNIT = "temperatureUnit"; public static final String PROPERTY_HOME_TEMPERATURE_UNIT = "temperatureUnit";
public static enum TemperatureUnit { public enum TemperatureUnit {
CELSIUS, CELSIUS,
FAHRENHEIT FAHRENHEIT
} }
@ -52,7 +52,7 @@ public class TadoBindingConstants {
public static final String CHANNEL_ZONE_HVAC_MODE = "hvacMode"; public static final String CHANNEL_ZONE_HVAC_MODE = "hvacMode";
public static enum HvacMode { public enum HvacMode {
OFF, OFF,
HEAT, HEAT,
COOL, COOL,
@ -69,7 +69,7 @@ public class TadoBindingConstants {
public static final String CHANNEL_ZONE_FAN_SPEED = "fanspeed"; public static final String CHANNEL_ZONE_FAN_SPEED = "fanspeed";
public static enum FanSpeed { public enum FanSpeed {
LOW, LOW,
MIDDLE, MIDDLE,
HIGH, HIGH,
@ -78,7 +78,7 @@ public class TadoBindingConstants {
public static final String CHANNEL_ZONE_FAN_LEVEL = "fanLevel"; public static final String CHANNEL_ZONE_FAN_LEVEL = "fanLevel";
public static enum FanLevel { public enum FanLevel {
SILENT, SILENT,
LEVEL1, LEVEL1,
LEVEL2, LEVEL2,
@ -90,7 +90,7 @@ public class TadoBindingConstants {
public static final String CHANNEL_ZONE_HORIZONTAL_SWING = "horizontalSwing"; public static final String CHANNEL_ZONE_HORIZONTAL_SWING = "horizontalSwing";
public static enum HorizontalSwing { public enum HorizontalSwing {
OFF, OFF,
ON, ON,
LEFT, LEFT,
@ -103,7 +103,7 @@ public class TadoBindingConstants {
public static final String CHANNEL_ZONE_VERTICAL_SWING = "verticalSwing"; public static final String CHANNEL_ZONE_VERTICAL_SWING = "verticalSwing";
public static enum VerticalSwing { public enum VerticalSwing {
OFF, OFF,
ON, ON,
UP, UP,
@ -116,7 +116,7 @@ public class TadoBindingConstants {
public static final String CHANNEL_ZONE_OPERATION_MODE = "operationMode"; public static final String CHANNEL_ZONE_OPERATION_MODE = "operationMode";
public static enum OperationMode { public enum OperationMode {
SCHEDULE, SCHEDULE,
TIMER, TIMER,
MANUAL, MANUAL,
@ -141,7 +141,7 @@ public class TadoBindingConstants {
public static final String PROPERTY_ZONE_NAME = "name"; public static final String PROPERTY_ZONE_NAME = "name";
public static final String PROPERTY_ZONE_TYPE = "type"; public static final String PROPERTY_ZONE_TYPE = "type";
public static enum ZoneType { public enum ZoneType {
HEATING, HEATING,
AIR_CONDITIONING, AIR_CONDITIONING,
HOT_WATER HOT_WATER

View File

@ -221,7 +221,7 @@ public class TadoZoneStateAdapter {
break; break;
} }
return power.getValue().equals("ON"); return "ON".equals(power.getValue());
} }
private static DecimalType toDecimalType(double value) { private static DecimalType toDecimalType(double value) {

View File

@ -226,8 +226,8 @@ public class TadoApiTypeUtils {
@Nullable GenericZoneCapabilities capabilities) { @Nullable GenericZoneCapabilities capabilities) {
AirConditioningCapabilities acCapabilities; AirConditioningCapabilities acCapabilities;
if (capabilities instanceof AirConditioningCapabilities) { if (capabilities instanceof AirConditioningCapabilities conditioningCapabilities) {
acCapabilities = (AirConditioningCapabilities) capabilities; acCapabilities = conditioningCapabilities;
} else { } else {
acCapabilities = new AirConditioningCapabilities(); acCapabilities = new AirConditioningCapabilities();
} }

View File

@ -84,8 +84,7 @@ public class TerminationConditionBuilder {
} }
private OverlayTerminationCondition getDefaultTerminationCondition() throws IOException, ApiException { private OverlayTerminationCondition getDefaultTerminationCondition() throws IOException, ApiException {
OverlayTerminationCondition defaultTerminationCondition = zoneHandler.getDefaultTerminationCondition(); return zoneHandler.getDefaultTerminationCondition();
return defaultTerminationCondition;
} }
private TimerTerminationCondition getCurrentOrDefaultTimerTermination(ZoneStateProvider zoneStateProvider) private TimerTerminationCondition getCurrentOrDefaultTimerTermination(ZoneStateProvider zoneStateProvider)

View File

@ -14,10 +14,7 @@ package org.openhab.binding.tado.internal.handler;
import static org.openhab.binding.tado.internal.TadoBindingConstants.*; import static org.openhab.binding.tado.internal.TadoBindingConstants.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -48,8 +45,8 @@ import org.osgi.service.component.annotations.Reference;
@Component(configurationPid = "binding.tado", service = ThingHandlerFactory.class) @Component(configurationPid = "binding.tado", service = ThingHandlerFactory.class)
public class TadoHandlerFactory extends BaseThingHandlerFactory { public class TadoHandlerFactory extends BaseThingHandlerFactory {
private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_HOME, THING_TYPE_ZONE,
.unmodifiableSet(new HashSet<>(Arrays.asList(THING_TYPE_HOME, THING_TYPE_ZONE, THING_TYPE_MOBILE_DEVICE))); THING_TYPE_MOBILE_DEVICE);
private final Map<ThingUID, ServiceRegistration<?>> discoveryServiceRegs = new HashMap<>(); private final Map<ThingUID, ServiceRegistration<?>> discoveryServiceRegs = new HashMap<>();

View File

@ -179,8 +179,8 @@ public class TadoHomeHandler extends BaseBridgeHandler {
switch (id) { switch (id) {
case TadoBindingConstants.CHANNEL_HOME_PRESENCE_MODE: case TadoBindingConstants.CHANNEL_HOME_PRESENCE_MODE:
HomePresence presence = new HomePresence(); HomePresence presence = new HomePresence();
presence.setHomePresence(command.toFullString().toUpperCase().equals("ON") presence.setHomePresence("ON".equals(command.toFullString().toUpperCase())
|| command.toFullString().toUpperCase().equals("HOME") ? PresenceState.HOME || "HOME".equals(command.toFullString().toUpperCase()) ? PresenceState.HOME
: PresenceState.AWAY); : PresenceState.AWAY);
try { try {
api.updatePresenceLock(homeId, presence); api.updatePresenceLock(homeId, presence);

View File

@ -12,7 +12,6 @@
*/ */
package org.openhab.binding.tankerkoenig.internal; package org.openhab.binding.tankerkoenig.internal;
import java.util.Collections;
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -33,8 +32,8 @@ public class TankerkoenigBindingConstants {
public static final ThingTypeUID THING_TYPE_TANKSTELLE = new ThingTypeUID(BINDING_ID, "station"); 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 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> BRIDGE_THING_TYPES_UIDS = Set.of(BRIDGE_THING_TYPE);
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_TANKSTELLE); public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_TANKSTELLE);
// List of all Channel ids // List of all Channel ids
public static final String CHANNEL_DIESEL = "diesel"; public static final String CHANNEL_DIESEL = "diesel";

View File

@ -53,8 +53,7 @@ public class TankerkoenigHandlerFactory extends BaseThingHandlerFactory {
protected @Nullable ThingHandler createHandler(Thing thing) { protected @Nullable ThingHandler createHandler(Thing thing) {
ThingTypeUID thingTypeUID = thing.getThingTypeUID(); ThingTypeUID thingTypeUID = thing.getThingTypeUID();
if (thingTypeUID.equals(BRIDGE_THING_TYPE)) { if (thingTypeUID.equals(BRIDGE_THING_TYPE)) {
WebserviceHandler handler = new WebserviceHandler((Bridge) thing); return new WebserviceHandler((Bridge) thing);
return handler;
} else if (thingTypeUID.equals(THING_TYPE_TANKSTELLE)) { } else if (thingTypeUID.equals(THING_TYPE_TANKSTELLE)) {
return new StationHandler(thing); return new StationHandler(thing);
} }

View File

@ -84,8 +84,7 @@ public class TapoDiscoveryService extends AbstractDiscoveryService implements Th
@Override @Override
public void setThingHandler(@Nullable ThingHandler handler) { public void setThingHandler(@Nullable ThingHandler handler) {
if (handler instanceof TapoBridgeHandler) { if (handler instanceof TapoBridgeHandler tapoBridge) {
TapoBridgeHandler tapoBridge = (TapoBridgeHandler) handler;
tapoBridge.setDiscoveryService(this); tapoBridge.setDiscoveryService(this);
this.bridge = tapoBridge; this.bridge = tapoBridge;
} }

View File

@ -222,8 +222,7 @@ public class TapoCloudConnector {
httpRequest.content(new StringContentProvider(payload, CONTENT_CHARSET), CONTENT_TYPE_JSON); httpRequest.content(new StringContentProvider(payload, CONTENT_CHARSET), CONTENT_TYPE_JSON);
try { try {
ContentResponse httpResponse = httpRequest.send(); return httpRequest.send();
return httpResponse;
} catch (InterruptedException e) { } catch (InterruptedException e) {
logger.debug("({}) sending request interrupted: {}", uid, e.toString()); logger.debug("({}) sending request interrupted: {}", uid, e.toString());
handleError(new TapoErrorHandler(e)); handleError(new TapoErrorHandler(e));

View File

@ -158,7 +158,7 @@ public class TapoDeviceHttpApi {
String payload = plBuilder.getPayload(); String payload = plBuilder.getPayload();
/* send request (create ) */ /* 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); ContentResponse response = sendRequest(this.deviceURL, payload);
if (response != null && getErrorCode(response) == 0) { if (response != null && getErrorCode(response) == 0) {
String encryptedKey = getKeyFromResponse(response); String encryptedKey = getKeyFromResponse(response);
@ -308,8 +308,7 @@ public class TapoDeviceHttpApi {
httpRequest.content(new StringContentProvider(payload, CONTENT_CHARSET), CONTENT_TYPE_JSON); httpRequest.content(new StringContentProvider(payload, CONTENT_CHARSET), CONTENT_TYPE_JSON);
try { try {
ContentResponse httpResponse = httpRequest.send(); return httpRequest.send();
return httpResponse;
} catch (InterruptedException e) { } catch (InterruptedException e) {
logger.debug("({}) sending request interrupted: {}", uid, e.toString()); logger.debug("({}) sending request interrupted: {}", uid, e.toString());
handleError(new TapoErrorHandler(e)); handleError(new TapoErrorHandler(e));

View File

@ -13,7 +13,7 @@
package org.openhab.binding.tapocontrol.internal.device; package org.openhab.binding.tapocontrol.internal.device;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Set;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -114,7 +114,7 @@ public class TapoBridgeHandler extends BaseBridgeHandler {
*/ */
@Override @Override
public Collection<Class<? extends ThingHandlerService>> getServices() { public Collection<Class<? extends ThingHandlerService>> getServices() {
return Collections.singleton(TapoDiscoveryService.class); return Set.of(TapoDiscoveryService.class);
} }
/** /**

View File

@ -140,7 +140,7 @@ public abstract class TapoDevice extends BaseThingHandler {
TapoErrorHandler configErr = new TapoErrorHandler(); TapoErrorHandler configErr = new TapoErrorHandler();
/* check bridge */ /* check bridge */
if (bridge == null || !(bridge instanceof TapoBridgeHandler)) { if (!(bridge instanceof TapoBridgeHandler)) {
configErr.raiseError(ERR_CONFIG_NO_BRIDGE); configErr.raiseError(ERR_CONFIG_NO_BRIDGE);
return configErr; return configErr;
} }

View File

@ -76,24 +76,24 @@ public class TapoLightStrip extends TapoDevice {
refreshInfo = true; refreshInfo = true;
break; break;
case CHANNEL_BRIGHTNESS: case CHANNEL_BRIGHTNESS:
if (command instanceof PercentType) { if (command instanceof PercentType percentCommand) {
Float percent = ((PercentType) command).floatValue(); Float percent = percentCommand.floatValue();
setBrightness(percent.intValue()); // 0..100% = 0..100 setBrightness(percent.intValue()); // 0..100% = 0..100
refreshInfo = true; refreshInfo = true;
} else if (command instanceof DecimalType) { } else if (command instanceof DecimalType decimalCommand) {
setBrightness(((DecimalType) command).intValue()); setBrightness(decimalCommand.intValue());
refreshInfo = true; refreshInfo = true;
} }
break; break;
case CHANNEL_COLOR_TEMP: case CHANNEL_COLOR_TEMP:
if (command instanceof DecimalType) { if (command instanceof DecimalType decimalCommand) {
setColorTemp(((DecimalType) command).intValue()); setColorTemp(decimalCommand.intValue());
refreshInfo = true; refreshInfo = true;
} }
break; break;
case CHANNEL_COLOR: case CHANNEL_COLOR:
if (command instanceof HSBType) { if (command instanceof HSBType hsbCommand) {
setColor((HSBType) command); setColor(hsbCommand);
refreshInfo = true; refreshInfo = true;
} }
break; break;
@ -163,11 +163,11 @@ public class TapoLightStrip extends TapoDevice {
TapoLightEffect lightEffect = deviceInfo.getLightEffect(); TapoLightEffect lightEffect = deviceInfo.getLightEffect();
switch (channel) { switch (channel) {
case CHANNEL_FX_BRIGHTNESS: case CHANNEL_FX_BRIGHTNESS:
if (command instanceof PercentType) { if (command instanceof PercentType percentCommand) {
Float percent = ((PercentType) command).floatValue(); Float percent = percentCommand.floatValue();
lightEffect.setBrightness(percent.intValue()); // 0..100% = 0..100 lightEffect.setBrightness(percent.intValue()); // 0..100% = 0..100
} else if (command instanceof DecimalType) { } else if (command instanceof DecimalType decimalCommand) {
lightEffect.setBrightness(((DecimalType) command).intValue()); lightEffect.setBrightness(decimalCommand.intValue());
} }
break; break;
case CHANNEL_FX_COLORS: case CHANNEL_FX_COLORS:

View File

@ -71,24 +71,24 @@ public class TapoSmartBulb extends TapoDevice {
refreshInfo = true; refreshInfo = true;
break; break;
case CHANNEL_BRIGHTNESS: case CHANNEL_BRIGHTNESS:
if (command instanceof PercentType) { if (command instanceof PercentType percentCommand) {
Float percent = ((PercentType) command).floatValue(); Float percent = percentCommand.floatValue();
setBrightness(percent.intValue()); // 0..100% = 0..100 setBrightness(percent.intValue()); // 0..100% = 0..100
refreshInfo = true; refreshInfo = true;
} else if (command instanceof DecimalType) { } else if (command instanceof DecimalType decimalCommand) {
setBrightness(((DecimalType) command).intValue()); setBrightness(decimalCommand.intValue());
refreshInfo = true; refreshInfo = true;
} }
break; break;
case CHANNEL_COLOR_TEMP: case CHANNEL_COLOR_TEMP:
if (command instanceof DecimalType) { if (command instanceof DecimalType decimalCommand) {
setColorTemp(((DecimalType) command).intValue()); setColorTemp(decimalCommand.intValue());
refreshInfo = true; refreshInfo = true;
} }
break; break;
case CHANNEL_COLOR: case CHANNEL_COLOR:
if (command instanceof HSBType) { if (command instanceof HSBType hsbCommand) {
setColor((HSBType) command); setColor(hsbCommand);
refreshInfo = true; refreshInfo = true;
} }
break; break;

View File

@ -70,24 +70,24 @@ public class TapoUniversalDevice extends TapoDevice {
refreshInfo = true; refreshInfo = true;
break; break;
case CHANNEL_BRIGHTNESS: case CHANNEL_BRIGHTNESS:
if (command instanceof PercentType) { if (command instanceof PercentType percentCommand) {
Float percent = ((PercentType) command).floatValue(); Float percent = percentCommand.floatValue();
setBrightness(percent.intValue()); // 0..100% = 0..100 setBrightness(percent.intValue()); // 0..100% = 0..100
refreshInfo = true; refreshInfo = true;
} else if (command instanceof DecimalType) { } else if (command instanceof DecimalType decimalCommand) {
setBrightness(((DecimalType) command).intValue()); setBrightness(decimalCommand.intValue());
refreshInfo = true; refreshInfo = true;
} }
break; break;
case CHANNEL_COLOR_TEMP: case CHANNEL_COLOR_TEMP:
if (command instanceof DecimalType) { if (command instanceof DecimalType decimalCommand) {
setColorTemp(((DecimalType) command).intValue()); setColorTemp(decimalCommand.intValue());
refreshInfo = true; refreshInfo = true;
} }
break; break;
case CHANNEL_COLOR: case CHANNEL_COLOR:
if (command instanceof HSBType) { if (command instanceof HSBType hsbCommand) {
setColor((HSBType) command); setColor(hsbCommand);
refreshInfo = true; refreshInfo = true;
} }
break; break;
@ -173,6 +173,7 @@ public class TapoUniversalDevice extends TapoDevice {
* *
* @param responseBody * @param responseBody
*/ */
@Override
public void responsePasstrough(String responseBody) { public void responsePasstrough(String responseBody) {
logger.debug("({}) received response {}", uid, responseBody); logger.debug("({}) received response {}", uid, responseBody);
publishState(getChannelID(CHANNEL_GROUP_DEBUG, CHANNEL_RESPONSE), getStringType(responseBody)); publishState(getChannelID(CHANNEL_GROUP_DEBUG, CHANNEL_RESPONSE), getStringType(responseBody));
@ -224,6 +225,7 @@ public class TapoUniversalDevice extends TapoDevice {
* @param channelID String channelID * @param channelID String channelID
* @return String channel-name * @return String channel-name
*/ */
@Override
protected String getChannelFromID(ChannelUID channelID) { protected String getChannelFromID(ChannelUID channelID) {
String channel = channelID.getIdWithoutGroup(); String channel = channelID.getIdWithoutGroup();
channel = channel.replace(CHANNEL_GROUP_ACTUATOR + "#", ""); channel = channel.replace(CHANNEL_GROUP_ACTUATOR + "#", "");

View File

@ -44,10 +44,10 @@ public class PayloadBuilder {
* @param value parameter value (typeOf Bool,Number or String) * @param value parameter value (typeOf Bool,Number or String)
*/ */
public void addParameter(String name, Object value) { public void addParameter(String name, Object value) {
if (value instanceof Boolean) { if (value instanceof Boolean bool) {
this.parameters.addProperty(name, (Boolean) value); this.parameters.addProperty(name, bool);
} else if (value instanceof Number) { } else if (value instanceof Number number) {
this.parameters.addProperty(name, (Number) value); this.parameters.addProperty(name, number);
} else { } else {
this.parameters.addProperty(name, value.toString()); this.parameters.addProperty(name, value.toString());
} }

View File

@ -82,8 +82,7 @@ public class TapoUtils {
*/ */
public static String formatMac(String mac, char newDivisionChar) { public static String formatMac(String mac, char newDivisionChar) {
String unformatedMac = unformatMac(mac); String unformatedMac = unformatMac(mac);
String formatedMac = unformatedMac.replaceAll("(.{2})", "$1" + newDivisionChar).substring(0, 17); return unformatedMac.replaceAll("(.{2})", "$1" + newDivisionChar).substring(0, 17);
return formatedMac;
} }
/** /**

View File

@ -34,7 +34,7 @@ public class TapoLightEffect {
private Boolean custom = false; private Boolean custom = false;
private Integer brightness = 0; private Integer brightness = 0;
private Integer[] colorTempRange = { 9000, 9000 }; // :[9000,9000] private Integer[] colorTempRange = { 9000, 9000 }; // :[9000,9000]
private Color displayColors[] = { Color.WHITE }; private Color[] displayColors = { Color.WHITE };
private JsonObject jsonObject = new JsonObject(); private JsonObject jsonObject = new JsonObject();

View File

@ -84,8 +84,7 @@ public class TapoDiscoveryService extends AbstractDiscoveryService implements Th
@Override @Override
public void setThingHandler(@Nullable ThingHandler handler) { public void setThingHandler(@Nullable ThingHandler handler) {
if (handler instanceof TapoBridgeHandler) { if (handler instanceof TapoBridgeHandler tapoBridge) {
TapoBridgeHandler tapoBridge = (TapoBridgeHandler) handler;
tapoBridge.setDiscoveryService(this); tapoBridge.setDiscoveryService(this);
this.bridge = tapoBridge; this.bridge = tapoBridge;
} }

View File

@ -13,7 +13,7 @@
package org.openhab.binding.tapocontrol.internal.device; package org.openhab.binding.tapocontrol.internal.device;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Set;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -116,7 +116,7 @@ public class TapoBridgeHandler extends BaseBridgeHandler {
*/ */
@Override @Override
public Collection<Class<? extends ThingHandlerService>> getServices() { public Collection<Class<? extends ThingHandlerService>> getServices() {
return Collections.singleton(TapoDiscoveryService.class); return Set.of(TapoDiscoveryService.class);
} }
/** /**

View File

@ -70,24 +70,24 @@ public class TapoUniversalDevice extends TapoDevice {
refreshInfo = true; refreshInfo = true;
break; break;
case CHANNEL_BRIGHTNESS: case CHANNEL_BRIGHTNESS:
if (command instanceof PercentType) { if (command instanceof PercentType percentCommand) {
Float percent = ((PercentType) command).floatValue(); Float percent = percentCommand.floatValue();
setBrightness(percent.intValue()); // 0..100% = 0..100 setBrightness(percent.intValue()); // 0..100% = 0..100
refreshInfo = true; refreshInfo = true;
} else if (command instanceof DecimalType) { } else if (command instanceof DecimalType decimalCommand) {
setBrightness(((DecimalType) command).intValue()); setBrightness(decimalCommand.intValue());
refreshInfo = true; refreshInfo = true;
} }
break; break;
case CHANNEL_COLOR_TEMP: case CHANNEL_COLOR_TEMP:
if (command instanceof DecimalType) { if (command instanceof DecimalType decimalCommand) {
setColorTemp(((DecimalType) command).intValue()); setColorTemp(decimalCommand.intValue());
refreshInfo = true; refreshInfo = true;
} }
break; break;
case CHANNEL_COLOR: case CHANNEL_COLOR:
if (command instanceof HSBType) { if (command instanceof HSBType hsbCommand) {
setColor((HSBType) command); setColor(hsbCommand);
refreshInfo = true; refreshInfo = true;
} }
break; break;
@ -173,6 +173,7 @@ public class TapoUniversalDevice extends TapoDevice {
* *
* @param responseBody * @param responseBody
*/ */
@Override
public void responsePasstrough(String responseBody) { public void responsePasstrough(String responseBody) {
logger.info("({}) received response {}", uid, responseBody); logger.info("({}) received response {}", uid, responseBody);
publishState(getChannelID(CHANNEL_GROUP_DEBUG, CHANNEL_RESPONSE), getStringType(responseBody)); publishState(getChannelID(CHANNEL_GROUP_DEBUG, CHANNEL_RESPONSE), getStringType(responseBody));
@ -224,6 +225,7 @@ public class TapoUniversalDevice extends TapoDevice {
* @param channelID String channelID * @param channelID String channelID
* @return String channel-name * @return String channel-name
*/ */
@Override
protected String getChannelFromID(ChannelUID channelID) { protected String getChannelFromID(ChannelUID channelID) {
String channel = channelID.getIdWithoutGroup(); String channel = channelID.getIdWithoutGroup();
channel = channel.replace(CHANNEL_GROUP_ACTUATOR + "#", ""); channel = channel.replace(CHANNEL_GROUP_ACTUATOR + "#", "");

View File

@ -34,7 +34,7 @@ public class TapoLightEffect {
private Integer custom = 0; private Integer custom = 0;
private Integer brightness = 0; private Integer brightness = 0;
private Integer[] colorTempRange = { 9000, 9000 }; // :[9000,9000] private Integer[] colorTempRange = { 9000, 9000 }; // :[9000,9000]
private Color displayColors[] = { Color.WHITE }; private Color[] displayColors = { Color.WHITE };
private JsonObject jsonObject = new JsonObject(); private JsonObject jsonObject = new JsonObject();

View File

@ -22,12 +22,12 @@ import java.time.ZonedDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -473,7 +473,7 @@ public class TelegramHandler extends BaseThingHandler {
@Override @Override
public Collection<Class<? extends ThingHandlerService>> getServices() { public Collection<Class<? extends ThingHandlerService>> getServices() {
return Collections.singleton(TelegramActions.class); return Set.of(TelegramActions.class);
} }
/** /**

View File

@ -14,7 +14,6 @@ package org.openhab.binding.telegram.internal;
import static org.openhab.binding.telegram.internal.TelegramBindingConstants.TELEGRAM_THING; import static org.openhab.binding.telegram.internal.TelegramBindingConstants.TELEGRAM_THING;
import java.util.Collections;
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -40,7 +39,7 @@ import org.osgi.service.component.annotations.Reference;
@Component(configurationPid = "binding.telegram", service = ThingHandlerFactory.class) @Component(configurationPid = "binding.telegram", service = ThingHandlerFactory.class)
public class TelegramHandlerFactory extends BaseThingHandlerFactory { 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; private final HttpClient httpClient;

View File

@ -672,11 +672,11 @@ public class TelegramActions implements ThingActions {
public static boolean sendTelegramAnswer(ThingActions actions, @Nullable String chatId, @Nullable String replyId, public static boolean sendTelegramAnswer(ThingActions actions, @Nullable String chatId, @Nullable String replyId,
@Nullable String message) { @Nullable String message) {
if (actions instanceof TelegramActions) { if (actions instanceof TelegramActions telegramActions) {
if (chatId == null) { if (chatId == null) {
return false; return false;
} }
return ((TelegramActions) actions).sendTelegramAnswer(Long.valueOf(chatId), replyId, message); return telegramActions.sendTelegramAnswer(Long.valueOf(chatId), replyId, message);
} else { } else {
throw new IllegalArgumentException("Actions is not an instance of TelegramActions"); throw new IllegalArgumentException("Actions is not an instance of TelegramActions");
} }
@ -689,11 +689,11 @@ public class TelegramActions implements ThingActions {
public static boolean sendTelegramAnswer(ThingActions actions, @Nullable String chatId, @Nullable String callbackId, public static boolean sendTelegramAnswer(ThingActions actions, @Nullable String chatId, @Nullable String callbackId,
@Nullable String messageId, @Nullable String message) { @Nullable String messageId, @Nullable String message) {
if (actions instanceof TelegramActions) { if (actions instanceof TelegramActions telegramActions) {
if (chatId == null) { if (chatId == null) {
return false; return false;
} }
return ((TelegramActions) actions).sendTelegramAnswer(Long.valueOf(chatId), callbackId, return telegramActions.sendTelegramAnswer(Long.valueOf(chatId), callbackId,
messageId != null ? Long.parseLong(messageId) : null, message); messageId != null ? Long.parseLong(messageId) : null, message);
} else { } else {
throw new IllegalArgumentException("Actions is not an instance of TelegramActions"); throw new IllegalArgumentException("Actions is not an instance of TelegramActions");

View File

@ -187,8 +187,8 @@ public class TeleinfoDiscoveryService extends AbstractDiscoveryService
@Override @Override
public void setThingHandler(@Nullable ThingHandler handler) { public void setThingHandler(@Nullable ThingHandler handler) {
if (handler instanceof TeleinfoAbstractControllerHandler) { if (handler instanceof TeleinfoAbstractControllerHandler teleinfoAbstractControllerHandler) {
controllerHandler = (TeleinfoAbstractControllerHandler) handler; controllerHandler = teleinfoAbstractControllerHandler;
} }
} }

View File

@ -13,7 +13,6 @@
package org.openhab.binding.teleinfo.internal.handler; package org.openhab.binding.teleinfo.internal.handler;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.Set; import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.CopyOnWriteArraySet;
@ -52,6 +51,6 @@ public abstract class TeleinfoAbstractControllerHandler extends BaseBridgeHandle
@Override @Override
public Collection<Class<? extends ThingHandlerService>> getServices() { public Collection<Class<? extends ThingHandlerService>> getServices() {
return Collections.singleton(TeleinfoDiscoveryService.class); return Set.of(TeleinfoDiscoveryService.class);
} }
} }

View File

@ -120,8 +120,8 @@ public class TellstickHandlerFactory extends BaseThingHandlerFactory {
@Override @Override
protected void removeHandler(ThingHandler thingHandler) { protected void removeHandler(ThingHandler thingHandler) {
if (thingHandler instanceof TelldusBridgeHandler) { if (thingHandler instanceof TelldusBridgeHandler telldusBridgeHandler) {
unregisterDeviceDiscoveryService((TelldusBridgeHandler) thingHandler); unregisterDeviceDiscoveryService(telldusBridgeHandler);
} }
} }
} }

View File

@ -156,10 +156,10 @@ public class TelldusCoreDeviceController implements DeviceChangeListener, Sensor
turnOn(device); turnOn(device);
} else if (command == OnOffType.OFF) { } else if (command == OnOffType.OFF) {
turnOff(device); turnOff(device);
} else if (command instanceof PercentType) { } else if (command instanceof PercentType percentCommand) {
dim(device, (PercentType) command); dim(device, percentCommand);
} else if (command instanceof IncreaseDecreaseType) { } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
increaseDecrease(device, ((IncreaseDecreaseType) command)); increaseDecrease(device, increaseDecreaseCommand);
} }
} else if (device instanceof SwitchableDevice) { } else if (device instanceof SwitchableDevice) {
if (command == OnOffType.ON) { if (command == OnOffType.ON) {
@ -198,29 +198,29 @@ public class TelldusCoreDeviceController implements DeviceChangeListener, Sensor
double value = command.doubleValue(); double value = command.doubleValue();
// 0 means OFF and 100 means ON // 0 means OFF and 100 means ON
if (value == 0 && dev instanceof SwitchableDevice) { if (value == 0 && dev instanceof SwitchableDevice device) {
((SwitchableDevice) dev).off(); device.off();
} else if (value == 100 && dev instanceof SwitchableDevice) { } else if (value == 100 && dev instanceof SwitchableDevice device) {
((SwitchableDevice) dev).on(); device.on();
} else if (dev instanceof DimmableDevice) { } else if (dev instanceof DimmableDevice device) {
long tdVal = Math.round((value / 100) * 255); long tdVal = Math.round((value / 100) * 255);
((DimmableDevice) dev).dim((int) tdVal); device.dim((int) tdVal);
} else { } else {
throw new TelldusBindingException("Cannot send DIM to " + dev); throw new TelldusBindingException("Cannot send DIM to " + dev);
} }
} }
private void turnOff(Device dev) throws TellstickException { private void turnOff(Device dev) throws TellstickException {
if (dev instanceof SwitchableDevice) { if (dev instanceof SwitchableDevice device) {
((SwitchableDevice) dev).off(); device.off();
} else { } else {
throw new TelldusBindingException("Cannot send OFF to " + dev); throw new TelldusBindingException("Cannot send OFF to " + dev);
} }
} }
private void turnOn(Device dev) throws TellstickException { private void turnOn(Device dev) throws TellstickException {
if (dev instanceof SwitchableDevice) { if (dev instanceof SwitchableDevice device) {
((SwitchableDevice) dev).on(); device.on();
} else { } else {
throw new TelldusBindingException("Cannot send ON to " + dev); throw new TelldusBindingException("Cannot send ON to " + dev);
} }

View File

@ -135,16 +135,16 @@ public class TellstickDiscoveryService extends AbstractDiscoveryService implemen
} else if (device instanceof SwitchableDevice) { } else if (device instanceof SwitchableDevice) {
thingUID = new ThingUID(TellstickBindingConstants.SWITCH_THING_TYPE, bridge.getUID(), thingUID = new ThingUID(TellstickBindingConstants.SWITCH_THING_TYPE, bridge.getUID(),
device.getUUId()); device.getUUId());
} else if (device instanceof TellstickNetDevice) { } else if (device instanceof TellstickNetDevice netDevice) {
if ((((TellstickNetDevice) device).getMethods() & JNA.CLibrary.TELLSTICK_DIM) > 0) { if ((netDevice.getMethods() & JNA.CLibrary.TELLSTICK_DIM) > 0) {
thingUID = new ThingUID(TellstickBindingConstants.DIMMER_THING_TYPE, bridge.getUID(), thingUID = new ThingUID(TellstickBindingConstants.DIMMER_THING_TYPE, bridge.getUID(),
device.getUUId()); device.getUUId());
} else { } else {
thingUID = new ThingUID(TellstickBindingConstants.SWITCH_THING_TYPE, bridge.getUID(), thingUID = new ThingUID(TellstickBindingConstants.SWITCH_THING_TYPE, bridge.getUID(),
device.getUUId()); device.getUUId());
} }
} else if (device instanceof TellstickLocalDeviceDTO) { } else if (device instanceof TellstickLocalDeviceDTO localDevice) {
if ((((TellstickLocalDeviceDTO) device).getMethods() & JNA.CLibrary.TELLSTICK_DIM) > 0) { if ((localDevice.getMethods() & JNA.CLibrary.TELLSTICK_DIM) > 0) {
thingUID = new ThingUID(TellstickBindingConstants.DIMMER_THING_TYPE, bridge.getUID(), thingUID = new ThingUID(TellstickBindingConstants.DIMMER_THING_TYPE, bridge.getUID(),
device.getUUId()); device.getUUId());
} else { } else {
@ -162,8 +162,7 @@ public class TellstickDiscoveryService extends AbstractDiscoveryService implemen
private ThingTypeUID findSensorType(Device device) { private ThingTypeUID findSensorType(Device device) {
logger.debug("Device: {}", device); logger.debug("Device: {}", device);
ThingTypeUID sensorThingId; ThingTypeUID sensorThingId;
if (device instanceof TellstickSensor) { if (device instanceof TellstickSensor sensor) {
TellstickSensor sensor = (TellstickSensor) device;
logger.debug("Sensor: {}", device); logger.debug("Sensor: {}", device);
if (sensor.getData(DataType.WINDAVERAGE) != null || sensor.getData(DataType.WINDGUST) != null if (sensor.getData(DataType.WINDAVERAGE) != null || sensor.getData(DataType.WINDGUST) != null
|| sensor.getData(DataType.WINDDIRECTION) != null) { || sensor.getData(DataType.WINDDIRECTION) != null) {
@ -173,8 +172,7 @@ public class TellstickDiscoveryService extends AbstractDiscoveryService implemen
} else { } else {
sensorThingId = TellstickBindingConstants.SENSOR_THING_TYPE; sensorThingId = TellstickBindingConstants.SENSOR_THING_TYPE;
} }
} else if (device instanceof TellstickNetSensor) { } else if (device instanceof TellstickNetSensor sensor) {
TellstickNetSensor sensor = (TellstickNetSensor) device;
if (sensor.isSensorOfType(LiveDataType.WINDAVERAGE) || sensor.isSensorOfType(LiveDataType.WINDDIRECTION) if (sensor.isSensorOfType(LiveDataType.WINDAVERAGE) || sensor.isSensorOfType(LiveDataType.WINDDIRECTION)
|| sensor.isSensorOfType(LiveDataType.WINDGUST)) { || sensor.isSensorOfType(LiveDataType.WINDGUST)) {
sensorThingId = TellstickBindingConstants.WINDSENSOR_THING_TYPE; sensorThingId = TellstickBindingConstants.WINDSENSOR_THING_TYPE;

View File

@ -241,29 +241,29 @@ public class TelldusDevicesHandler extends BaseThingHandler implements DeviceSta
} }
private boolean isSensor() { 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.RAINSENSOR_THING_TYPE)
|| getThing().getThingTypeUID().equals(TellstickBindingConstants.WINDSENSOR_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) { private void updateSensorStates(Device dev) {
if (dev instanceof TellstickSensor) { if (dev instanceof TellstickSensor sensor) {
updateStatus(ThingStatus.ONLINE); updateStatus(ThingStatus.ONLINE);
for (DataType type : ((TellstickSensor) dev).getData().keySet()) { for (DataType type : sensor.getData().keySet()) {
updateSensorDataState(type, ((TellstickSensor) dev).getData(type)); updateSensorDataState(type, sensor.getData(type));
} }
} else if (dev instanceof TellstickNetSensor) { } else if (dev instanceof TellstickNetSensor netSensor) {
if (((TellstickNetSensor) dev).getOnline()) { if (netSensor.getOnline()) {
updateStatus(ThingStatus.ONLINE); updateStatus(ThingStatus.ONLINE);
} else { } else {
updateStatus(ThingStatus.OFFLINE); updateStatus(ThingStatus.OFFLINE);
} }
for (DataTypeValue type : ((TellstickNetSensor) dev).getData()) { for (DataTypeValue type : netSensor.getData()) {
updateSensorDataState(type); updateSensorDataState(type);
} }
} else if (dev instanceof TellstickLocalSensorDTO) { } else if (dev instanceof TellstickLocalSensorDTO localSensor) {
for (LocalDataTypeValueDTO type : ((TellstickLocalSensorDTO) dev).getData()) { for (LocalDataTypeValueDTO type : localSensor.getData()) {
updateSensorDataState(type); updateSensorDataState(type);
} }
} }
@ -283,14 +283,11 @@ public class TelldusDevicesHandler extends BaseThingHandler implements DeviceSta
if (device.getUUId().equals(deviceId)) { if (device.getUUId().equals(deviceId)) {
if (event instanceof TellstickDeviceEvent) { if (event instanceof TellstickDeviceEvent) {
updateDeviceState(device); updateDeviceState(device);
} else if (event instanceof TellstickNetSensorEvent) { } else if (event instanceof TellstickNetSensorEvent sensorevent) {
TellstickNetSensorEvent sensorevent = (TellstickNetSensorEvent) event;
updateSensorDataState(sensorevent.getDataTypeValue()); updateSensorDataState(sensorevent.getDataTypeValue());
} else if (event instanceof TellstickLocalSensorEventDTO) { } else if (event instanceof TellstickLocalSensorEventDTO sensorevent) {
TellstickLocalSensorEventDTO sensorevent = (TellstickLocalSensorEventDTO) event;
updateSensorDataState(sensorevent.getDataTypeValue()); updateSensorDataState(sensorevent.getDataTypeValue());
} else if (event instanceof TellstickSensorEvent) { } else if (event instanceof TellstickSensorEvent sensorevent) {
TellstickSensorEvent sensorevent = (TellstickSensorEvent) event;
updateSensorDataState(sensorevent.getDataType(), sensorevent.getData()); updateSensorDataState(sensorevent.getDataType(), sensorevent.getData());
} else { } else {
logger.debug("Unhandled Device {}.", device.getDeviceType()); logger.debug("Unhandled Device {}.", device.getDeviceType());
@ -356,7 +353,7 @@ public class TelldusDevicesHandler extends BaseThingHandler implements DeviceSta
new QuantityType<>(new BigDecimal(dataType.getValue()), WIND_SPEED_UNIT_MS)); new QuantityType<>(new BigDecimal(dataType.getValue()), WIND_SPEED_UNIT_MS));
break; break;
case WATT: 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)); updateState(ampereChannel, new QuantityType<>(new BigDecimal(dataType.getValue()), ELECTRIC_UNIT));
} else { } else {
updateState(wattChannel, new QuantityType<>(new BigDecimal(dataType.getValue()), POWER_UNIT)); updateState(wattChannel, new QuantityType<>(new BigDecimal(dataType.getValue()), POWER_UNIT));

View File

@ -129,10 +129,10 @@ public class TelldusLiveDeviceController implements DeviceChangeListener, Sensor
turnOn(device); turnOn(device);
} else if (command == OnOffType.OFF) { } else if (command == OnOffType.OFF) {
turnOff(device); turnOff(device);
} else if (command instanceof PercentType) { } else if (command instanceof PercentType percentCommand) {
dim(device, (PercentType) command); dim(device, percentCommand);
} else if (command instanceof IncreaseDecreaseType) { } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
increaseDecrease(device, ((IncreaseDecreaseType) command)); increaseDecrease(device, increaseDecreaseCommand);
} }
} else if (device instanceof SwitchableDevice) { } else if (device instanceof SwitchableDevice) {
if (command == OnOffType.ON) { if (command == OnOffType.ON) {
@ -172,22 +172,21 @@ public class TelldusLiveDeviceController implements DeviceChangeListener, Sensor
turnOff(dev); turnOff(dev);
} else if (value == 100 && dev instanceof TellstickNetDevice) { } else if (value == 100 && dev instanceof TellstickNetDevice) {
turnOn(dev); turnOn(dev);
} else if (dev instanceof TellstickNetDevice } else if (dev instanceof TellstickNetDevice device && (device.getMethods() & JNA.CLibrary.TELLSTICK_DIM) > 0) {
&& (((TellstickNetDevice) dev).getMethods() & JNA.CLibrary.TELLSTICK_DIM) > 0) {
long tdVal = Math.round((value / 100) * 255); long tdVal = Math.round((value / 100) * 255);
TelldusLiveResponse response = callRestMethod(String.format(HTTP_TELLDUS_DEVICE_DIM, dev.getId(), tdVal), TelldusLiveResponse response = callRestMethod(String.format(HTTP_TELLDUS_DEVICE_DIM, dev.getId(), tdVal),
TelldusLiveResponse.class); TelldusLiveResponse.class);
handleResponse((TellstickNetDevice) dev, response); handleResponse(device, response);
} else { } else {
throw new TelldusBindingException("Cannot send DIM to " + dev); throw new TelldusBindingException("Cannot send DIM to " + dev);
} }
} }
private void turnOff(Device dev) throws TellstickException { 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 response = callRestMethod(String.format(HTTP_TELLDUS_DEVICE_TURNOFF, dev.getId()),
TelldusLiveResponse.class); TelldusLiveResponse.class);
handleResponse((TellstickNetDevice) dev, response); handleResponse(device, response);
} else { } else {
throw new TelldusBindingException("Cannot send OFF to " + dev); throw new TelldusBindingException("Cannot send OFF to " + dev);
} }
@ -197,21 +196,21 @@ public class TelldusLiveDeviceController implements DeviceChangeListener, Sensor
if (response == null || (response.status == null && response.error == null)) { if (response == null || (response.status == null && response.error == null)) {
throw new TelldusBindingException("No response " + response); throw new TelldusBindingException("No response " + response);
} else if (response.error != null) { } 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.setOnline(false);
device.setUpdated(true); device.setUpdated(true);
} }
throw new TelldusBindingException("Error " + response.error); 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); throw new TelldusBindingException("Response " + response.status);
} }
} }
private void turnOn(Device dev) throws TellstickException { 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 response = callRestMethod(String.format(HTTP_TELLDUS_DEVICE_TURNON, dev.getId()),
TelldusLiveResponse.class); TelldusLiveResponse.class);
handleResponse((TellstickNetDevice) dev, response); handleResponse(device, response);
} else { } else {
throw new TelldusBindingException("Cannot send ON to " + dev); throw new TelldusBindingException("Cannot send ON to " + dev);
} }

View File

@ -90,10 +90,10 @@ public class TelldusLocalDeviceController implements DeviceChangeListener, Senso
turnOn(device); turnOn(device);
} else if (command == OnOffType.OFF) { } else if (command == OnOffType.OFF) {
turnOff(device); turnOff(device);
} else if (command instanceof PercentType) { } else if (command instanceof PercentType percentCommand) {
dim(device, (PercentType) command); dim(device, percentCommand);
} else if (command instanceof IncreaseDecreaseType) { } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
increaseDecrease(device, ((IncreaseDecreaseType) command)); increaseDecrease(device, increaseDecreaseCommand);
} }
} else if (device instanceof SwitchableDevice) { } else if (device instanceof SwitchableDevice) {
if (command == OnOffType.ON) { if (command == OnOffType.ON) {
@ -137,22 +137,22 @@ public class TelldusLocalDeviceController implements DeviceChangeListener, Senso
turnOff(dev); turnOff(dev);
} else if (value == 100 && dev instanceof TellstickLocalDeviceDTO) { } else if (value == 100 && dev instanceof TellstickLocalDeviceDTO) {
turnOn(dev); turnOn(dev);
} else if (dev instanceof TellstickLocalDeviceDTO } else if (dev instanceof TellstickLocalDeviceDTO device
&& (((TellstickLocalDeviceDTO) dev).getMethods() & JNA.CLibrary.TELLSTICK_DIM) > 0) { && (device.getMethods() & JNA.CLibrary.TELLSTICK_DIM) > 0) {
long tdVal = Math.round((value / 100) * 255); long tdVal = Math.round((value / 100) * 255);
TelldusLocalResponseDTO response = callRestMethod( TelldusLocalResponseDTO response = callRestMethod(
String.format(HTTP_LOCAL_API_DEVICE_DIM, dev.getId(), tdVal), TelldusLocalResponseDTO.class); String.format(HTTP_LOCAL_API_DEVICE_DIM, dev.getId(), tdVal), TelldusLocalResponseDTO.class);
handleResponse((TellstickLocalDeviceDTO) dev, response); handleResponse(device, response);
} else { } else {
throw new TelldusBindingException("Cannot send DIM to " + dev); throw new TelldusBindingException("Cannot send DIM to " + dev);
} }
} }
private void turnOff(Device dev) throws TellstickException, InterruptedException { 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 response = callRestMethod(String.format(HTTP_LOCAL_API_DEVICE_TURNOFF, dev.getId()),
TelldusLocalResponseDTO.class); TelldusLocalResponseDTO.class);
handleResponse((TellstickLocalDeviceDTO) dev, response); handleResponse(device, response);
} else { } else {
throw new TelldusBindingException("Cannot send OFF to " + dev); throw new TelldusBindingException("Cannot send OFF to " + dev);
} }
@ -165,16 +165,16 @@ public class TelldusLocalDeviceController implements DeviceChangeListener, Senso
} else if (response.getError() != null) { } else if (response.getError() != null) {
device.setUpdated(true); device.setUpdated(true);
throw new TelldusBindingException("Error " + response.getError()); 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()); throw new TelldusBindingException("Response " + response.getStatus());
} }
} }
private void turnOn(Device dev) throws TellstickException, InterruptedException { 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 response = callRestMethod(String.format(HTTP_LOCAL_DEVICE_TURNON, dev.getId()),
TelldusLocalResponseDTO.class); TelldusLocalResponseDTO.class);
handleResponse((TellstickLocalDeviceDTO) dev, response); handleResponse(device, response);
} else { } else {
throw new TelldusBindingException("Cannot send ON to " + dev); throw new TelldusBindingException("Cannot send ON to " + dev);
} }

View File

@ -964,7 +964,7 @@ public class TeslaChannelSelectorProxy {
VEHICLE_NAME("vehicle_name", "name", StringType.class, true) { VEHICLE_NAME("vehicle_name", "name", StringType.class, true) {
@Override @Override
public State getState(String s, TeslaChannelSelectorProxy proxy, Map<String, String> properties) { 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) { VALET_MODE("valet_mode", "valetmode", OnOffType.class, false) {

View File

@ -18,7 +18,6 @@ import java.time.Instant;
import java.time.ZoneId; import java.time.ZoneId;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ -472,6 +471,6 @@ public class TeslaAccountHandler extends BaseBridgeHandler {
@Override @Override
public Collection<Class<? extends ThingHandlerService>> getServices() { public Collection<Class<? extends ThingHandlerService>> getServices() {
return Collections.singletonList(TeslaVehicleDiscoveryService.class); return List.of(TeslaVehicleDiscoveryService.class);
} }
} }

View File

@ -256,8 +256,8 @@ public class TeslaVehicleHandler extends BaseThingHandler {
try { try {
switch (selector) { switch (selector) {
case CHARGE_LIMIT_SOC: { case CHARGE_LIMIT_SOC: {
if (command instanceof PercentType) { if (command instanceof PercentType percentCommand) {
setChargeLimit(((PercentType) command).intValue()); setChargeLimit(percentCommand.intValue());
} else if (command instanceof OnOffType && command == OnOffType.ON) { } else if (command instanceof OnOffType && command == OnOffType.ON) {
setChargeLimit(100); setChargeLimit(100);
} else if (command instanceof OnOffType && command == OnOffType.OFF) { } else if (command instanceof OnOffType && command == OnOffType.OFF) {
@ -273,11 +273,11 @@ public class TeslaVehicleHandler extends BaseThingHandler {
} }
case CHARGE_AMPS: case CHARGE_AMPS:
Integer amps = null; Integer amps = null;
if (command instanceof DecimalType) { if (command instanceof DecimalType decimalCommand) {
amps = ((DecimalType) command).intValue(); amps = decimalCommand.intValue();
} }
if (command instanceof QuantityType<?>) { if (command instanceof QuantityType<?> quantityCommand) {
QuantityType<?> qamps = ((QuantityType<?>) command).toUnit(Units.AMPERE); QuantityType<?> qamps = quantityCommand.toUnit(Units.AMPERE);
if (qamps != null) { if (qamps != null) {
amps = qamps.intValue(); amps = qamps.intValue();
} }
@ -324,8 +324,8 @@ public class TeslaVehicleHandler extends BaseThingHandler {
break; break;
} }
case CHARGE_TO_MAX: { case CHARGE_TO_MAX: {
if (command instanceof OnOffType) { if (command instanceof OnOffType onOffCommand) {
if (((OnOffType) command) == OnOffType.ON) { if (onOffCommand == OnOffType.ON) {
setMaxRangeCharging(true); setMaxRangeCharging(true);
} else { } else {
setMaxRangeCharging(false); setMaxRangeCharging(false);
@ -334,8 +334,8 @@ public class TeslaVehicleHandler extends BaseThingHandler {
break; break;
} }
case CHARGE: { case CHARGE: {
if (command instanceof OnOffType) { if (command instanceof OnOffType onOffCommand) {
if (((OnOffType) command) == OnOffType.ON) { if (onOffCommand == OnOffType.ON) {
charge(true); charge(true);
} else { } else {
charge(false); charge(false);
@ -344,32 +344,32 @@ public class TeslaVehicleHandler extends BaseThingHandler {
break; break;
} }
case FLASH: { case FLASH: {
if (command instanceof OnOffType) { if (command instanceof OnOffType onOffCommand) {
if (((OnOffType) command) == OnOffType.ON) { if (onOffCommand == OnOffType.ON) {
flashLights(); flashLights();
} }
} }
break; break;
} }
case HONK_HORN: { case HONK_HORN: {
if (command instanceof OnOffType) { if (command instanceof OnOffType onOffCommand) {
if (((OnOffType) command) == OnOffType.ON) { if (onOffCommand == OnOffType.ON) {
honkHorn(); honkHorn();
} }
} }
break; break;
} }
case CHARGEPORT: { case CHARGEPORT: {
if (command instanceof OnOffType) { if (command instanceof OnOffType onOffCommand) {
if (((OnOffType) command) == OnOffType.ON) { if (onOffCommand == OnOffType.ON) {
openChargePort(); openChargePort();
} }
} }
break; break;
} }
case DOOR_LOCK: { case DOOR_LOCK: {
if (command instanceof OnOffType) { if (command instanceof OnOffType onOffCommand) {
if (((OnOffType) command) == OnOffType.ON) { if (onOffCommand == OnOffType.ON) {
lockDoors(true); lockDoors(true);
} else { } else {
lockDoors(false); lockDoors(false);
@ -378,8 +378,8 @@ public class TeslaVehicleHandler extends BaseThingHandler {
break; break;
} }
case AUTO_COND: { case AUTO_COND: {
if (command instanceof OnOffType) { if (command instanceof OnOffType onOffCommand) {
if (((OnOffType) command) == OnOffType.ON) { if (onOffCommand == OnOffType.ON) {
autoConditioning(true); autoConditioning(true);
} else { } else {
autoConditioning(false); autoConditioning(false);
@ -388,24 +388,24 @@ public class TeslaVehicleHandler extends BaseThingHandler {
break; break;
} }
case WAKEUP: { case WAKEUP: {
if (command instanceof OnOffType) { if (command instanceof OnOffType onOffCommand) {
if (((OnOffType) command) == OnOffType.ON) { if (onOffCommand == OnOffType.ON) {
wakeUp(); wakeUp();
} }
} }
break; break;
} }
case FT: { case FT: {
if (command instanceof OnOffType) { if (command instanceof OnOffType onOffCommand) {
if (((OnOffType) command) == OnOffType.ON) { if (onOffCommand == OnOffType.ON) {
openFrunk(); openFrunk();
} }
} }
break; break;
} }
case RT: { case RT: {
if (command instanceof OnOffType) { if (command instanceof OnOffType onOffCommand) {
if (((OnOffType) command) == OnOffType.ON) { if (onOffCommand == OnOffType.ON) {
if (vehicleState.rt == 0) { if (vehicleState.rt == 0) {
openTrunk(); openTrunk();
} }
@ -416,9 +416,9 @@ public class TeslaVehicleHandler extends BaseThingHandler {
break; break;
} }
case VALET_MODE: { case VALET_MODE: {
if (command instanceof OnOffType) { if (command instanceof OnOffType onOffCommand) {
int valetpin = ((BigDecimal) getConfig().get(VALETPIN)).intValue(); int valetpin = ((BigDecimal) getConfig().get(VALETPIN)).intValue();
if (((OnOffType) command) == OnOffType.ON) { if (onOffCommand == OnOffType.ON) {
setValetMode(true, valetpin); setValetMode(true, valetpin);
} else { } else {
setValetMode(false, valetpin); setValetMode(false, valetpin);
@ -427,16 +427,16 @@ public class TeslaVehicleHandler extends BaseThingHandler {
break; break;
} }
case RESET_VALET_PIN: { case RESET_VALET_PIN: {
if (command instanceof OnOffType) { if (command instanceof OnOffType onOffCommand) {
if (((OnOffType) command) == OnOffType.ON) { if (onOffCommand == OnOffType.ON) {
resetValetPin(); resetValetPin();
} }
} }
break; break;
} }
case STEERINGWHEEL_HEATER: { case STEERINGWHEEL_HEATER: {
if (command instanceof OnOffType) { if (command instanceof OnOffType onOffCommand) {
boolean commandBooleanValue = ((OnOffType) command) == OnOffType.ON ? true : false; boolean commandBooleanValue = onOffCommand == OnOffType.ON ? true : false;
setSteeringWheelHeater(commandBooleanValue); setSteeringWheelHeater(commandBooleanValue);
} }
break; break;
@ -1025,7 +1025,7 @@ public class TeslaVehicleHandler extends BaseThingHandler {
case "data:update": case "data:update":
logger.debug("Event : Received an update: '{}'", event.value); 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 currentTimeStamp = Long.parseLong(vals[0]);
long systemTimeStamp = System.currentTimeMillis(); long systemTimeStamp = System.currentTimeMillis();
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {

View File

@ -26,7 +26,7 @@ public class Vehicle {
public String option_codes; public String option_codes;
public String vehicle_id; public String vehicle_id;
public String vin; public String vin;
public String tokens[]; public String[] tokens;
public String state; public String state;
public boolean remote_start_enabled; public boolean remote_start_enabled;
public boolean calendar_enabled; public boolean calendar_enabled;

View File

@ -26,7 +26,7 @@ public class VehicleData {
public String option_codes; public String option_codes;
public String vehicle_id; public String vehicle_id;
public String vin; public String vin;
public String tokens[]; public String[] tokens;
public String state; public String state;
public boolean remote_start_enabled; public boolean remote_start_enabled;
public boolean calendar_enabled; public boolean calendar_enabled;

View File

@ -14,7 +14,6 @@ package org.openhab.binding.tivo.internal;
import static org.openhab.binding.tivo.internal.TiVoBindingConstants.THING_TYPE_TIVO; import static org.openhab.binding.tivo.internal.TiVoBindingConstants.THING_TYPE_TIVO;
import java.util.Collections;
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -39,7 +38,7 @@ import org.osgi.service.component.annotations.Component;
@NonNullByDefault @NonNullByDefault
@Component(configurationPid = "binding.tivo", service = ThingHandlerFactory.class) @Component(configurationPid = "binding.tivo", service = ThingHandlerFactory.class)
public class TiVoHandlerFactory extends BaseThingHandlerFactory { 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 @Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) { public boolean supportsThingType(ThingTypeUID thingTypeUID) {

View File

@ -15,7 +15,6 @@ package org.openhab.binding.tivo.internal.discovery;
import static org.openhab.binding.tivo.internal.TiVoBindingConstants.*; import static org.openhab.binding.tivo.internal.TiVoBindingConstants.*;
import java.net.InetAddress; import java.net.InetAddress;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -48,7 +47,7 @@ public class TiVoDiscoveryParticipant implements MDNSDiscoveryParticipant {
@Override @Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() { public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
return Collections.singleton(THING_TYPE_TIVO); return Set.of(THING_TYPE_TIVO);
} }
@Override @Override

View File

@ -73,7 +73,7 @@ public class TiVoHandler extends BaseThingHandler {
// Handles the commands from the various TiVo channel objects // Handles the commands from the various TiVo channel objects
logger.debug("handleCommand '{}', parameter: {}", channelUID, command); 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.", logger.debug("handleCommand '{}' device is not initialized yet, command '{}' will be ignored.",
getThing().getUID(), channelUID + " " + command); getThing().getUID(), channelUID + " " + command);
return; return;
@ -122,7 +122,7 @@ public class TiVoHandler extends BaseThingHandler {
private void sendCommand(String commandKeyword, String commandParameter, TivoStatusData currentStatus) private void sendCommand(String commandKeyword, String commandParameter, TivoStatusData currentStatus)
throws InterruptedException { throws InterruptedException {
if (!tivoConnection.isPresent()) { if (tivoConnection.isEmpty()) {
return; return;
} }
@ -299,8 +299,7 @@ public class TiVoHandler extends BaseThingHandler {
} }
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
logger.warn("TiVo'{}' unable to parse channel integer, value sent was: '{}'", getThing().getUID(), logger.warn("TiVo'{}' unable to parse channel integer, value sent was: '{}'", getThing().getUID(), command);
command.toString());
} }
return tmpStatus; return tmpStatus;
} }

View File

@ -78,7 +78,7 @@ public class TivoStatusData {
UNKNOWN, UNKNOWN,
OFFLINE, OFFLINE,
STANDBY, STANDBY,
ONLINE; ONLINE
} }
/** /**

View File

@ -124,7 +124,7 @@ public class TivoStatusProvider {
} }
for (int i = 1; i <= repeatCount; i++) { for (int i = 1; i <= repeatCount; i++) {
// Send the command // Send the command
streamWriter.println(tivoCommand.toString() + "\r"); streamWriter.println(tivoCommand + "\r");
if (streamWriter.checkError()) { if (streamWriter.checkError()) {
logger.debug("TiVo '{}' - called cmdTivoSend and encountered an IO error", logger.debug("TiVo '{}' - called cmdTivoSend and encountered an IO error",
tivoConfigData.getCfgIdentifier()); tivoConfigData.getCfgIdentifier());

View File

@ -57,8 +57,7 @@ public class TouchWandAlarmSensorHandler extends TouchWandBaseUnitHandler {
@Override @Override
void updateTouchWandUnitState(TouchWandUnitData unitData) { void updateTouchWandUnitState(TouchWandUnitData unitData) {
if (unitData instanceof TouchWandUnitDataAlarmSensor) { if (unitData instanceof TouchWandUnitDataAlarmSensor sensor) {
TouchWandUnitDataAlarmSensor sensor = (TouchWandUnitDataAlarmSensor) unitData;
if (isFirstUpdateTouchWandUnitState) { if (isFirstUpdateTouchWandUnitState) {
removeUnsupportedChannels(sensor); removeUnsupportedChannels(sensor);
isFirstUpdateTouchWandUnitState = false; isFirstUpdateTouchWandUnitState = false;

View File

@ -42,21 +42,21 @@ public class TouchWandBSensorHandler extends TouchWandBaseUnitHandler {
@Override @Override
void updateTouchWandUnitState(TouchWandUnitData unitData) { void updateTouchWandUnitState(TouchWandUnitData unitData) {
if (unitData instanceof TouchWandBSensorUnitData) { if (unitData instanceof TouchWandBSensorUnitData bSensorUnitData) {
if (isFirstUpdateTouchWandUnitState) { if (isFirstUpdateTouchWandUnitState) {
removeUnsupportedChannels((TouchWandBSensorUnitData) unitData); removeUnsupportedChannels(bSensorUnitData);
isFirstUpdateTouchWandUnitState = false; isFirstUpdateTouchWandUnitState = false;
} }
String sensorSubType = ((TouchWandBSensorUnitData) unitData).getIdData().getSubType(); String sensorSubType = bSensorUnitData.getIdData().getSubType();
switch (sensorSubType) { switch (sensorSubType) {
case BSENSOR_SUBTYPE_DOORWINDOW: case BSENSOR_SUBTYPE_DOORWINDOW:
updateChannelDoorWindow((TouchWandBSensorUnitData) unitData); updateChannelDoorWindow(bSensorUnitData);
break; break;
case BSENSOR_SUBTYPE_MOTION: case BSENSOR_SUBTYPE_MOTION:
updateChannelMotion((TouchWandBSensorUnitData) unitData); updateChannelMotion(bSensorUnitData);
break; break;
case BSENSOR_SUBTYPE_SMOKE: case BSENSOR_SUBTYPE_SMOKE:
updateChannelSmoke((TouchWandBSensorUnitData) unitData); updateChannelSmoke(bSensorUnitData);
break; break;
default: default:
} }

View File

@ -137,7 +137,7 @@ public abstract class TouchWandBaseUnitHandler extends BaseThingHandler implemen
@Override @Override
public void onItemStatusUpdate(TouchWandUnitData unitData) { public void onItemStatusUpdate(TouchWandUnitData unitData) {
if (unitData.getStatus().equals("ALIVE")) { if ("ALIVE".equals(unitData.getStatus())) {
updateStatus(ThingStatus.ONLINE); updateStatus(ThingStatus.ONLINE);
} else { } else {
// updateStatus(ThingStatus.OFFLINE); // comment - OFFLINE status is not accurate at the moment // updateStatus(ThingStatus.OFFLINE); // comment - OFFLINE status is not accurate at the moment

View File

@ -15,7 +15,6 @@ package org.openhab.binding.touchwand.internal;
import static org.openhab.binding.touchwand.internal.TouchWandBindingConstants.THING_TYPE_BRIDGE; import static org.openhab.binding.touchwand.internal.TouchWandBindingConstants.THING_TYPE_BRIDGE;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -45,7 +44,7 @@ import org.slf4j.LoggerFactory;
*/ */
@NonNullByDefault @NonNullByDefault
public class TouchWandBridgeHandler extends BaseBridgeHandler implements TouchWandUnitStatusUpdateListener { 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 final Logger logger = LoggerFactory.getLogger(TouchWandBridgeHandler.class);
private boolean addSecondaryUnits; private boolean addSecondaryUnits;
private @Nullable TouchWandWebSockets touchWandWebSockets; private @Nullable TouchWandWebSockets touchWandWebSockets;
@ -138,6 +137,6 @@ public class TouchWandBridgeHandler extends BaseBridgeHandler implements TouchWa
@Override @Override
public Collection<Class<? extends ThingHandlerService>> getServices() { public Collection<Class<? extends ThingHandlerService>> getServices() {
return Collections.singleton(TouchWandUnitDiscoveryService.class); return Set.of(TouchWandUnitDiscoveryService.class);
} }
} }

View File

@ -39,8 +39,8 @@ public class TouchWandDimmerHandler extends TouchWandBaseUnitHandler {
void touchWandUnitHandleCommand(Command command) { void touchWandUnitHandleCommand(Command command) {
TouchWandBridgeHandler touchWandBridgeHandler = bridgeHandler; TouchWandBridgeHandler touchWandBridgeHandler = bridgeHandler;
if (touchWandBridgeHandler != null) { if (touchWandBridgeHandler != null) {
if (command instanceof OnOffType) { if (command instanceof OnOffType onOffCommand) {
touchWandBridgeHandler.touchWandClient.cmdSwitchOnOff(unitId, (OnOffType) command); touchWandBridgeHandler.touchWandClient.cmdSwitchOnOff(unitId, onOffCommand);
} else { } else {
touchWandBridgeHandler.touchWandClient.cmdDimmerPosition(unitId, command.toString()); touchWandBridgeHandler.touchWandClient.cmdDimmerPosition(unitId, command.toString());
} }
@ -49,8 +49,8 @@ public class TouchWandDimmerHandler extends TouchWandBaseUnitHandler {
@Override @Override
void updateTouchWandUnitState(TouchWandUnitData unitData) { void updateTouchWandUnitState(TouchWandUnitData unitData) {
if (unitData instanceof TouchWandShutterSwitchUnitData) { if (unitData instanceof TouchWandShutterSwitchUnitData shutterSwitchUnitData) {
int status = ((TouchWandShutterSwitchUnitData) unitData).getCurrStatus(); int status = shutterSwitchUnitData.getCurrStatus();
PercentType state = PercentType.ZERO; PercentType state = PercentType.ZERO;
int convertStatus = status; int convertStatus = status;
state = new PercentType(convertStatus); state = new PercentType(convertStatus);

View File

@ -203,8 +203,7 @@ public class TouchWandRestClient {
} }
private String buildUrl(String command) { private String buildUrl(String command) {
String url = "http://" + touchWandIpAddr + ":" + touchWandPort + COMMAND_MAP.get(command); return "http://" + touchWandIpAddr + ":" + touchWandPort + COMMAND_MAP.get(command);
return url;
} }
private synchronized String sendCommand(String command, HttpMethod method, String content) { private synchronized String sendCommand(String command, HttpMethod method, String content) {

View File

@ -59,8 +59,8 @@ public class TouchWandShutterHandler extends TouchWandBaseUnitHandler {
@Override @Override
void updateTouchWandUnitState(TouchWandUnitData unitData) { void updateTouchWandUnitState(TouchWandUnitData unitData) {
if (unitData instanceof TouchWandShutterSwitchUnitData) { if (unitData instanceof TouchWandShutterSwitchUnitData shutterSwitchUnitData) {
int status = ((TouchWandShutterSwitchUnitData) unitData).getCurrStatus(); int status = shutterSwitchUnitData.getCurrStatus();
PercentType state = PercentType.ZERO; PercentType state = PercentType.ZERO;
int convertStatus = 100 - status; int convertStatus = 100 - status;
state = new PercentType(convertStatus); state = new PercentType(convertStatus);

View File

@ -37,9 +37,9 @@ public class TouchWandSwitchHandler extends TouchWandBaseUnitHandler {
@Override @Override
void updateTouchWandUnitState(TouchWandUnitData unitData) { void updateTouchWandUnitState(TouchWandUnitData unitData) {
if (unitData instanceof TouchWandShutterSwitchUnitData) { if (unitData instanceof TouchWandShutterSwitchUnitData shutterSwitchUnitData) {
OnOffType state; OnOffType state;
int status = ((TouchWandShutterSwitchUnitData) unitData).getCurrStatus(); int status = shutterSwitchUnitData.getCurrStatus();
String sStatus = Integer.toString(status); String sStatus = Integer.toString(status);
if (sStatus.equals(SWITCH_STATUS_OFF)) { if (sStatus.equals(SWITCH_STATUS_OFF)) {
@ -58,10 +58,10 @@ public class TouchWandSwitchHandler extends TouchWandBaseUnitHandler {
@Override @Override
void touchWandUnitHandleCommand(Command command) { void touchWandUnitHandleCommand(Command command) {
if (command instanceof OnOffType) { if (command instanceof OnOffType onOffCommand) {
TouchWandBridgeHandler touchWandBridgeHandler = bridgeHandler; TouchWandBridgeHandler touchWandBridgeHandler = bridgeHandler;
if (touchWandBridgeHandler != null) { if (touchWandBridgeHandler != null) {
touchWandBridgeHandler.touchWandClient.cmdSwitchOnOff(unitId, (OnOffType) command); touchWandBridgeHandler.touchWandClient.cmdSwitchOnOff(unitId, onOffCommand);
} }
} }
} }

View File

@ -40,8 +40,7 @@ public class TouchWandThermostatHandler extends TouchWandBaseUnitHandler {
@Override @Override
void updateTouchWandUnitState(TouchWandUnitData unitData) { void updateTouchWandUnitState(TouchWandUnitData unitData) {
if (unitData instanceof TouchWandThermostatUnitData) { if (unitData instanceof TouchWandThermostatUnitData thermostat) {
TouchWandThermostatUnitData thermostat = (TouchWandThermostatUnitData) unitData;
updateThermostatState(thermostat); updateThermostatState(thermostat);
updateTargetTemperature(thermostat); updateTargetTemperature(thermostat);
updateRoomTemperature(thermostat); updateRoomTemperature(thermostat);
@ -56,12 +55,12 @@ public class TouchWandThermostatHandler extends TouchWandBaseUnitHandler {
void touchWandUnitHandleCommand(Command command) { void touchWandUnitHandleCommand(Command command) {
TouchWandBridgeHandler touchWandBridgeHandler = bridgeHandler; TouchWandBridgeHandler touchWandBridgeHandler = bridgeHandler;
if (touchWandBridgeHandler != null) { if (touchWandBridgeHandler != null) {
if (command instanceof OnOffType) { if (command instanceof OnOffType onOffCommand) {
touchWandBridgeHandler.touchWandClient.cmdThermostatOnOff(unitId, (OnOffType) command); touchWandBridgeHandler.touchWandClient.cmdThermostatOnOff(unitId, onOffCommand);
return; return;
} }
if (command instanceof QuantityType) { if (command instanceof QuantityType quantityCommand) {
final QuantityType<?> value = ((QuantityType<?>) command).toUnit(SIUnits.CELSIUS); final QuantityType<?> value = quantityCommand.toUnit(SIUnits.CELSIUS);
String targetTemperature = String.valueOf(value.intValue()); String targetTemperature = String.valueOf(value.intValue());
touchWandBridgeHandler.touchWandClient.cmdThermostatTargetTemperature(unitId, targetTemperature); touchWandBridgeHandler.touchWandClient.cmdThermostatTargetTemperature(unitId, targetTemperature);
return; return;

View File

@ -48,8 +48,8 @@ public class TouchWandWallControllerHandler extends TouchWandBaseUnitHandler {
@Override @Override
void updateTouchWandUnitState(TouchWandUnitData unitData) { void updateTouchWandUnitState(TouchWandUnitData unitData) {
if (unitData instanceof TouchWandUnitDataWallController) { if (unitData instanceof TouchWandUnitDataWallController unitDataWallController) {
Csc status = ((TouchWandUnitDataWallController) unitData).getCurrStatus(); Csc status = unitDataWallController.getCurrStatus();
long ts = status.getTs(); long ts = status.getTs();
long timeDiff = ts - timeLastEventMs; long timeDiff = ts - timeLastEventMs;
if ((timeDiff) > ADJACENT_EVENT_FILTER_TIME_MILLISEC) { if ((timeDiff) > ADJACENT_EVENT_FILTER_TIME_MILLISEC) {

View File

@ -79,7 +79,7 @@ public class TouchWandWebSockets {
public void connect() { public void connect() {
try { try {
uri = new URI("ws://" + controllerAddress + ":" + String.valueOf(port) + WS_ENDPOINT_TOUCHWAND); uri = new URI("ws://" + controllerAddress + ":" + port + WS_ENDPOINT_TOUCHWAND);
} catch (URISyntaxException e) { } catch (URISyntaxException e) {
logger.warn("URI not valid {} message {}", uri, e.getMessage()); logger.warn("URI not valid {} message {}", uri, e.getMessage());
return; return;
@ -152,12 +152,12 @@ public class TouchWandWebSockets {
TouchWandUnitData touchWandUnit; TouchWandUnitData touchWandUnit;
try { try {
JsonObject unitObj = JsonParser.parseString(msg).getAsJsonObject(); 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) { if (!eventUnitChanged) {
return; return;
} }
touchWandUnit = TouchWandUnitFromJson.parseResponse(unitObj.get("unit").getAsJsonObject()); 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()); logger.debug("UNIT_CHANGED unit status not ALIVE : {}", touchWandUnit.getStatus());
} }
boolean supportedUnitType = Arrays.asList(SUPPORTED_TOUCHWAND_TYPES).contains(touchWandUnit.getType()); boolean supportedUnitType = Arrays.asList(SUPPORTED_TOUCHWAND_TYPES).contains(touchWandUnit.getType());

View File

@ -91,7 +91,7 @@ public class TouchWandControllerDiscoveryService extends AbstractDiscoveryServic
} }
private void addDeviceDiscoveryResult(String label, String ip) { private void addDeviceDiscoveryResult(String label, String ip) {
String id = ip.replaceAll("\\.", ""); String id = ip.replace(".", "");
ThingUID thingUID = new ThingUID(THING_TYPE_BRIDGE, id); ThingUID thingUID = new ThingUID(THING_TYPE_BRIDGE, id);
Map<String, Object> properties = new HashMap<>(); Map<String, Object> properties = new HashMap<>();
properties.put("label", label); properties.put("label", label);
@ -138,7 +138,7 @@ public class TouchWandControllerDiscoveryService extends AbstractDiscoveryServic
String sentence = new String(dgram.getData(), 0, dgram.getLength(), StandardCharsets.US_ASCII); String sentence = new String(dgram.getData(), 0, dgram.getLength(), StandardCharsets.US_ASCII);
JsonObject bridge = JsonParser.parseString(sentence).getAsJsonObject();// JsonObject bridge = JsonParser.parseString(sentence).getAsJsonObject();//
String name = bridge.get("name").getAsString(); 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(), logger.debug("Received Datagram from {}:{} on Port {} message {}", address.getHostAddress(),
dgram.getPort(), mySocket.getLocalPort(), sentence); dgram.getPort(), mySocket.getLocalPort(), sentence);
} }

View File

@ -191,8 +191,8 @@ public class TouchWandUnitDiscoveryService extends AbstractDiscoveryService impl
@Override @Override
public void setThingHandler(@NonNullByDefault({}) ThingHandler handler) { public void setThingHandler(@NonNullByDefault({}) ThingHandler handler) {
if (handler instanceof TouchWandBridgeHandler) { if (handler instanceof TouchWandBridgeHandler touchWandBridgeHandler) {
touchWandBridgeHandler = (TouchWandBridgeHandler) handler; this.touchWandBridgeHandler = touchWandBridgeHandler;
} }
} }

View File

@ -69,7 +69,7 @@ public class AlarmSensorUnitDataDeserializer implements JsonDeserializer<TouchWa
for (Entry<String, JsonElement> entry : currentStatusObj.entrySet()) { for (Entry<String, JsonElement> entry : currentStatusObj.entrySet()) {
String key = entry.getKey(); 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]; String keyName = splits[0];
int index = 0; int index = 0;

View File

@ -70,12 +70,12 @@ public class BulbDevice extends SmartHomeDevice {
final int transitionPeriod = configuration.transitionPeriod; final int transitionPeriod = configuration.transitionPeriod;
final HasErrorResponse response; final HasErrorResponse response;
if (command instanceof OnOffType && CHANNELS_BULB_SWITCH.contains(channelId)) { if (command instanceof OnOffType onOffCommand && CHANNELS_BULB_SWITCH.contains(channelId)) {
response = handleOnOffType(channelId, (OnOffType) command, transitionPeriod); response = handleOnOffType(channelId, onOffCommand, transitionPeriod);
} else if (command instanceof HSBType && CHANNEL_COLOR.equals(channelId)) { } else if (command instanceof HSBType hsbCommand && CHANNEL_COLOR.equals(channelId)) {
response = handleHSBType(channelId, (HSBType) command, transitionPeriod); response = handleHSBType(channelId, hsbCommand, transitionPeriod);
} else if (command instanceof DecimalType) { } else if (command instanceof DecimalType decimalCommand) {
response = handleDecimalType(channelId, (DecimalType) command, transitionPeriod); response = handleDecimalType(channelId, decimalCommand, transitionPeriod);
} else { } else {
return false; return false;
} }

View File

@ -56,11 +56,9 @@ public class DimmerDevice extends SwitchDevice {
private boolean handleBrightnessChannel(ChannelUID channelUid, Command command) throws IOException { private boolean handleBrightnessChannel(ChannelUID channelUid, Command command) throws IOException {
HasErrorResponse response = null; HasErrorResponse response = null;
if (command instanceof OnOffType) { if (command instanceof OnOffType onOffCommand) {
response = setOnOffState(channelUid, (OnOffType) command); response = setOnOffState(channelUid, onOffCommand);
} else if (command instanceof PercentType) { } else if (command instanceof PercentType percentCommand) {
PercentType percentCommand = (PercentType) command;
// Don't send value 0 as brightness value as it will give an error from the device. // Don't send value 0 as brightness value as it will give an error from the device.
if (percentCommand.intValue() > 0) { if (percentCommand.intValue() > 0) {
response = commands.setDimmerBrightnessResponse( response = commands.setDimmerBrightnessResponse(

View File

@ -41,7 +41,7 @@ public class SwitchDevice extends SmartHomeDevice {
@Override @Override
public boolean handleCommand(ChannelUID channelUid, Command command) throws IOException { 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);
} }
/** /**

View File

@ -58,8 +58,8 @@ public class TPLinkSmartHomeActions implements ThingActions, ThingHandlerService
@Override @Override
public void setThingHandler(final ThingHandler handler) { public void setThingHandler(final ThingHandler handler) {
if (handler instanceof SmartHomeHandler) { if (handler instanceof SmartHomeHandler smartHomeHandler) {
this.handler = (SmartHomeHandler) handler; this.handler = smartHomeHandler;
} }
} }

View File

@ -122,7 +122,7 @@ public class FritzboxActions implements ThingActions {
Optional<SCPDServiceType> scpdService = scpdUtil.getDevice("") Optional<SCPDServiceType> scpdService = scpdUtil.getDevice("")
.flatMap(deviceType -> deviceType.getServiceList().stream().filter( .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()); .findFirst());
if (scpdService.isEmpty()) { if (scpdService.isEmpty()) {
logger.warn("Could not get service."); logger.warn("Could not get service.");

View File

@ -53,8 +53,8 @@ public class Tr064DiscoveryService extends AbstractDiscoveryService implements T
@Override @Override
public void setThingHandler(ThingHandler thingHandler) { public void setThingHandler(ThingHandler thingHandler) {
if (thingHandler instanceof Tr064RootHandler) { if (thingHandler instanceof Tr064RootHandler tr064RootHandler) {
this.bridgeHandler = (Tr064RootHandler) thingHandler; this.bridgeHandler = tr064RootHandler;
} }
} }

View File

@ -111,8 +111,8 @@ public class Tr064HandlerFactory extends BaseThingHandlerFactory {
@Override @Override
protected void removeHandler(ThingHandler thingHandler) { protected void removeHandler(ThingHandler thingHandler) {
if (thingHandler instanceof Tr064RootHandler) { if (thingHandler instanceof Tr064RootHandler tr064RootHandler) {
phonebookProfileFactory.unregisterPhonebookProvider((Tr064RootHandler) thingHandler); phonebookProfileFactory.unregisterPhonebookProvider(tr064RootHandler);
} }
} }
} }

View File

@ -242,7 +242,7 @@ public class Tr064RootHandler extends BaseBridgeHandler implements PhonebookProv
SCPDDeviceType device = scpdUtil.getDevice("") SCPDDeviceType device = scpdUtil.getDevice("")
.orElseThrow(() -> new SCPDException("Root device not found")); .orElseThrow(() -> new SCPDException("Root device not found"));
SCPDServiceType deviceService = device.getServiceList().stream() 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( .findFirst().orElseThrow(() -> new SCPDException(
"service 'urn:DeviceInfo-com:serviceId:DeviceInfo1' not found")); "service 'urn:DeviceInfo-com:serviceId:DeviceInfo1' not found"));
@ -282,7 +282,7 @@ public class Tr064RootHandler extends BaseBridgeHandler implements PhonebookProv
SCPDActionType getInfoAction = scpdUtil.getService(deviceService.getServiceId()) SCPDActionType getInfoAction = scpdUtil.getService(deviceService.getServiceId())
.orElseThrow(() -> new SCPDException( .orElseThrow(() -> new SCPDException(
"Could not get service definition for 'urn:DeviceInfo-com:serviceId:DeviceInfo1'")) "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")); .orElseThrow(() -> new SCPDException("Action 'GetInfo' not found"));
SOAPMessage soapResponse1 = soapConnector SOAPMessage soapResponse1 = soapConnector
.doSOAPRequest(new SOAPRequest(deviceService, getInfoAction.getName())); .doSOAPRequest(new SOAPRequest(deviceService, getInfoAction.getName()));

View File

@ -98,17 +98,17 @@ public class PhonebookProfile implements StateProfile {
phonebookName = UIDUtils.decode(phonebookParams[1]); phonebookName = UIDUtils.decode(phonebookParams[1]);
} }
if (matchCountParam != null) { if (matchCountParam != null) {
if (matchCountParam instanceof BigDecimal) { if (matchCountParam instanceof BigDecimal bigDecimal) {
matchCount = ((BigDecimal) matchCountParam).intValue(); matchCount = bigDecimal.intValue();
} else if (matchCountParam instanceof String) { } else if (matchCountParam instanceof String string) {
matchCount = Integer.parseInt((String) matchCountParam); matchCount = Integer.parseInt(string);
} }
} }
if (phoneNumberIndexParam != null) { if (phoneNumberIndexParam != null) {
if (phoneNumberIndexParam instanceof BigDecimal) { if (phoneNumberIndexParam instanceof BigDecimal bigDecimal) {
phoneNumberIndex = ((BigDecimal) phoneNumberIndexParam).intValue(); phoneNumberIndex = bigDecimal.intValue();
} else if (phoneNumberIndexParam instanceof String) { } else if (phoneNumberIndexParam instanceof String string) {
phoneNumberIndex = Integer.parseInt((String) phoneNumberIndexParam); phoneNumberIndex = Integer.parseInt(string);
} }
} }
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {

View File

@ -153,8 +153,8 @@ public class SOAPConnector {
return soapMessage; return soapMessage;
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
Throwable cause = e.getCause(); Throwable cause = e.getCause();
if (cause instanceof Tr064CommunicationException) { if (cause instanceof Tr064CommunicationException tr064CommunicationException) {
throw (Tr064CommunicationException) cause; throw tr064CommunicationException;
} else { } else {
throw e; throw e;
} }

View File

@ -78,9 +78,8 @@ public class SOAPValueConverter {
// we don't have data to send // we don't have data to send
return Optional.of(""); return Optional.of("");
} }
if (command instanceof QuantityType) { if (command instanceof QuantityType quantityCommand) {
QuantityType<?> value = (unit.isEmpty()) ? ((QuantityType<?>) command) QuantityType<?> value = (unit.isEmpty()) ? quantityCommand : quantityCommand.toUnit(unit);
: ((QuantityType<?>) command).toUnit(unit);
if (value == null) { if (value == null) {
logger.warn("Could not convert {} to unit {}", command, unit); logger.warn("Could not convert {} to unit {}", command, unit);
return Optional.empty(); return Optional.empty();
@ -95,8 +94,8 @@ public class SOAPValueConverter {
default -> { default -> {
} }
} }
} else if (command instanceof DecimalType) { } else if (command instanceof DecimalType decimalCommand) {
BigDecimal value = ((DecimalType) command).toBigDecimal(); BigDecimal value = decimalCommand.toBigDecimal();
switch (dataType) { switch (dataType) {
case "ui1", "ui2" -> { case "ui1", "ui2" -> {
return Optional.of(String.valueOf(value.shortValue())); return Optional.of(String.valueOf(value.shortValue()));
@ -139,7 +138,7 @@ public class SOAPValueConverter {
// map rawValue to State // map rawValue to State
switch (dataType) { switch (dataType) {
case "boolean" -> { case "boolean" -> {
return rawValue.equals("0") ? OnOffType.OFF : OnOffType.ON; return "0".equals(rawValue) ? OnOffType.OFF : OnOffType.ON;
} }
case "string" -> { case "string" -> {
return new StringType(rawValue); return new StringType(rawValue);
@ -170,8 +169,8 @@ public class SOAPValueConverter {
Method method = SOAPValueConverter.class.getDeclaredMethod(postProcessor, State.class, Method method = SOAPValueConverter.class.getDeclaredMethod(postProcessor, State.class,
Tr064ChannelConfig.class); Tr064ChannelConfig.class);
Object o = method.invoke(this, state, channelConfig); Object o = method.invoke(this, state, channelConfig);
if (o instanceof State) { if (o instanceof State stateInstance) {
return (State) o; return stateInstance;
} }
} catch (NoSuchMethodException | IllegalAccessException e) { } catch (NoSuchMethodException | IllegalAccessException e) {
logger.warn("Postprocessor {} not found, this most likely is a programming error", postProcessor, e); logger.warn("Postprocessor {} not found, this most likely is a programming error", postProcessor, e);

View File

@ -281,10 +281,10 @@ public class Util {
// get parameters by reflection from thing config // get parameters by reflection from thing config
Field paramField = thingConfig.getClass().getField(parameter.getThingParameter()); Field paramField = thingConfig.getClass().getField(parameter.getThingParameter());
Object rawFieldValue = paramField.get(thingConfig); Object rawFieldValue = paramField.get(thingConfig);
if ((rawFieldValue instanceof List<?>)) { if ((rawFieldValue instanceof List<?> list)) {
((List<?>) rawFieldValue).forEach(obj -> { list.forEach(obj -> {
if (obj instanceof String) { if (obj instanceof String string) {
parameters.add((String) obj); parameters.add(string);
} }
}); });
} }

View File

@ -52,9 +52,9 @@ public class TradfriBindingConstants {
.unmodifiableSet(Stream.of(THING_TYPE_DIMMABLE_LIGHT, THING_TYPE_COLOR_TEMP_LIGHT, THING_TYPE_COLOR_LIGHT) .unmodifiableSet(Stream.of(THING_TYPE_DIMMABLE_LIGHT, THING_TYPE_COLOR_TEMP_LIGHT, THING_TYPE_COLOR_LIGHT)
.collect(Collectors.toSet())); .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); public static final Set<ThingTypeUID> SUPPORTED_AIR_PURIFIER_TYPES_UIDS = Set.of(THING_TYPE_AIR_PURIFIER);
@ -70,7 +70,7 @@ public class TradfriBindingConstants {
.unmodifiableSet(Stream.of(THING_TYPE_DIMMER, THING_TYPE_REMOTE_CONTROL, .unmodifiableSet(Stream.of(THING_TYPE_DIMMER, THING_TYPE_REMOTE_CONTROL,
THING_TYPE_OPEN_CLOSE_REMOTE_CONTROL, THING_TYPE_MOTION_SENSOR).collect(Collectors.toSet())); 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 public static final Set<ThingTypeUID> SUPPORTED_DEVICE_TYPES_UIDS = Collections.unmodifiableSet(Stream
.of(SUPPORTED_LIGHT_TYPES_UIDS.stream(), SUPPORTED_CONTROLLER_TYPES_UIDS.stream(), .of(SUPPORTED_LIGHT_TYPES_UIDS.stream(), SUPPORTED_CONTROLLER_TYPES_UIDS.stream(),

View File

@ -86,8 +86,8 @@ public class TradfriDiscoveryService extends AbstractDiscoveryService
@Override @Override
public void setThingHandler(@Nullable ThingHandler handler) { public void setThingHandler(@Nullable ThingHandler handler) {
if (handler instanceof TradfriGatewayHandler) { if (handler instanceof TradfriGatewayHandler gatewayHandler) {
this.handler = (TradfriGatewayHandler) handler; this.handler = gatewayHandler;
} }
} }

View File

@ -75,8 +75,8 @@ public class TradfriAirPurifierHandler extends TradfriThingHandler {
} }
private void handleFanModeCommand(Command command) { private void handleFanModeCommand(Command command) {
if (command instanceof Number) { if (command instanceof Number numberCommand) {
set(new TradfriAirPurifierData().setFanMode((Number) command).getJsonString()); set(new TradfriAirPurifierData().setFanMode(numberCommand).getJsonString());
} else { } else {
logger.debug("Cannot handle command '{}' of type {} for channel '{}'", command, command.getClass(), logger.debug("Cannot handle command '{}' of type {} for channel '{}'", command, command.getClass(),
CHANNEL_FAN_MODE); CHANNEL_FAN_MODE);
@ -84,8 +84,8 @@ public class TradfriAirPurifierHandler extends TradfriThingHandler {
} }
private void handleDisableLed(Command command) { private void handleDisableLed(Command command) {
if (command instanceof OnOffType) { if (command instanceof OnOffType onOffCommand) {
set(new TradfriAirPurifierData().setDisableLed((OnOffType) command).getJsonString()); set(new TradfriAirPurifierData().setDisableLed(onOffCommand).getJsonString());
} else { } else {
logger.debug("Cannot handle command '{}' of type {} for channel '{}'", command, command.getClass(), logger.debug("Cannot handle command '{}' of type {} for channel '{}'", command, command.getClass(),
CHANNEL_DISABLE_LED); CHANNEL_DISABLE_LED);
@ -93,8 +93,8 @@ public class TradfriAirPurifierHandler extends TradfriThingHandler {
} }
private void handleLockButton(Command command) { private void handleLockButton(Command command) {
if (command instanceof OnOffType) { if (command instanceof OnOffType onOffCommand) {
set(new TradfriAirPurifierData().setLockPhysicalButton((OnOffType) command).getJsonString()); set(new TradfriAirPurifierData().setLockPhysicalButton(onOffCommand).getJsonString());
} else { } else {
logger.debug("Cannot handle command '{}' of type {} for channel '{}'", command, command.getClass(), logger.debug("Cannot handle command '{}' of type {} for channel '{}'", command, command.getClass(),
CHANNEL_DISABLE_LED); CHANNEL_DISABLE_LED);

View File

@ -108,8 +108,8 @@ public class TradfriBlindHandler extends TradfriThingHandler {
} }
private void handlePositionCommand(Command command) { private void handlePositionCommand(Command command) {
if (command instanceof PercentType) { if (command instanceof PercentType percentCommand) {
setPosition((PercentType) command); setPosition(percentCommand);
} else if (command instanceof StopMoveType) { } else if (command instanceof StopMoveType) {
if (StopMoveType.STOP.equals(command)) { if (StopMoveType.STOP.equals(command)) {
triggerStop(); triggerStop();

View File

@ -18,7 +18,6 @@ import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.Objects; import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
@ -137,7 +136,7 @@ public class TradfriGatewayHandler extends BaseBridgeHandler implements CoapCall
@Override @Override
public Collection<Class<? extends ThingHandlerService>> getServices() { public Collection<Class<? extends ThingHandlerService>> getServices() {
return Collections.singleton(TradfriDiscoveryService.class); return Set.of(TradfriDiscoveryService.class);
} }
private void establishConnection() { private void establishConnection() {

View File

@ -154,10 +154,10 @@ public class TradfriLightHandler extends TradfriThingHandler {
} }
private void handleBrightnessCommand(Command command) { private void handleBrightnessCommand(Command command) {
if (command instanceof PercentType) { if (command instanceof PercentType percentCommand) {
setBrightness((PercentType) command); setBrightness(percentCommand);
} else if (command instanceof OnOffType) { } else if (command instanceof OnOffType onOffCommand) {
setState(((OnOffType) command)); setState(onOffCommand);
} else if (command instanceof IncreaseDecreaseType) { } else if (command instanceof IncreaseDecreaseType) {
final TradfriLightData state = this.state; final TradfriLightData state = this.state;
if (state != null && state.getBrightness() != null) { if (state != null && state.getBrightness() != null) {
@ -177,8 +177,8 @@ public class TradfriLightHandler extends TradfriThingHandler {
} }
private void handleColorTemperatureCommand(Command command) { private void handleColorTemperatureCommand(Command command) {
if (command instanceof PercentType) { if (command instanceof PercentType percentCommand) {
setColorTemperature((PercentType) command); setColorTemperature(percentCommand);
} else if (command instanceof IncreaseDecreaseType) { } else if (command instanceof IncreaseDecreaseType) {
final TradfriLightData state = this.state; final TradfriLightData state = this.state;
if (state != null && state.getColorTemperature() != null) { if (state != null && state.getColorTemperature() != null) {
@ -198,13 +198,13 @@ public class TradfriLightHandler extends TradfriThingHandler {
} }
private void handleColorCommand(Command command) { private void handleColorCommand(Command command) {
if (command instanceof HSBType) { if (command instanceof HSBType hsbCommand) {
setColor((HSBType) command); setColor(hsbCommand);
setBrightness(((HSBType) command).getBrightness()); setBrightness(hsbCommand.getBrightness());
} else if (command instanceof OnOffType) { } else if (command instanceof OnOffType onOffCommand) {
setState(((OnOffType) command)); setState(onOffCommand);
} else if (command instanceof PercentType) { } else if (command instanceof PercentType percentCommand) {
setBrightness((PercentType) command); setBrightness(percentCommand);
} else if (command instanceof IncreaseDecreaseType) { } else if (command instanceof IncreaseDecreaseType) {
final TradfriLightData state = this.state; final TradfriLightData state = this.state;
// increase or decrease only the brightness, but keep color // increase or decrease only the brightness, but keep color

View File

@ -75,8 +75,8 @@ public class TradfriPlugHandler extends TradfriThingHandler {
switch (channelUID.getId()) { switch (channelUID.getId()) {
case CHANNEL_POWER: case CHANNEL_POWER:
if (command instanceof OnOffType) { if (command instanceof OnOffType onOffCommand) {
setState(((OnOffType) command)); setState(onOffCommand);
} else { } else {
logger.debug("Cannot handle command '{}' for channel '{}'", command, CHANNEL_POWER); logger.debug("Cannot handle command '{}' for channel '{}'", command, CHANNEL_POWER);
} }

View File

@ -135,8 +135,8 @@ public class TradfriAirPurifierData extends TradfriDeviceData {
public @Nullable State getAirQualityRating() { public @Nullable State getAirQualityRating() {
State pm25State = getAirQualityPM25(); State pm25State = getAirQualityPM25();
if (pm25State != null) { if (pm25State != null) {
if (pm25State instanceof Number) { if (pm25State instanceof Number number) {
int pm25Value = ((Number) pm25State).intValue(); int pm25Value = number.intValue();
int qualityRating = 1; int qualityRating = 1;
if (pm25Value >= AIR_PURIFIER_AIR_QUALITY_BAD) { if (pm25Value >= AIR_PURIFIER_AIR_QUALITY_BAD) {

View File

@ -21,7 +21,7 @@ import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.List;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -82,7 +82,7 @@ public class TwitterHandler extends BaseThingHandler {
// creates list of available Actions // creates list of available Actions
@Override @Override
public Collection<Class<? extends ThingHandlerService>> getServices() { public Collection<Class<? extends ThingHandlerService>> getServices() {
return Collections.singletonList(TwitterActions.class); return List.of(TwitterActions.class);
} }
@Override @Override
@ -118,7 +118,7 @@ public class TwitterHandler extends BaseThingHandler {
Twitter localClient = client; Twitter localClient = client;
if (localClient != null) { if (localClient != null) {
ResponseList<Status> statuses = localClient.getUserTimeline(); ResponseList<Status> statuses = localClient.getUserTimeline();
if (statuses.size() > 0) { if (!statuses.isEmpty()) {
updateState(CHANNEL_LASTTWEET, StringType.valueOf(statuses.get(0).getText())); updateState(CHANNEL_LASTTWEET, StringType.valueOf(statuses.get(0).getText()));
} else { } else {
logger.debug("No Statuses Found"); logger.debug("No Statuses Found");

View File

@ -112,8 +112,8 @@ public class TwitterActions implements ThingActions {
@Override @Override
public void setThingHandler(@Nullable ThingHandler handler) { public void setThingHandler(@Nullable ThingHandler handler) {
if (handler instanceof TwitterHandler) { if (handler instanceof TwitterHandler twitterHandler) {
this.handler = (TwitterHandler) handler; this.handler = twitterHandler;
} }
} }

View File

@ -259,8 +259,8 @@ public class UniFiSiteActions implements ThingActions {
@Override @Override
public void setThingHandler(ThingHandler handler) { public void setThingHandler(ThingHandler handler) {
if (handler instanceof UniFiSiteThingHandler) { if (handler instanceof UniFiSiteThingHandler siteThingHandler) {
this.handler = (UniFiSiteThingHandler) handler; this.handler = siteThingHandler;
} }
} }

View File

@ -206,13 +206,13 @@ class UniFiControllerRequest<T> {
} else if (cause instanceof SSLException) { } else if (cause instanceof SSLException) {
// cannot establish ssl connection // cannot establish ssl connection
throw new UniFiSSLException(cause); throw new UniFiSSLException(cause);
} else if (cause instanceof HttpResponseException } else if (cause instanceof HttpResponseException httpResponseException
&& ((HttpResponseException) cause).getResponse() instanceof ContentResponse) { && httpResponseException.getResponse() instanceof ContentResponse) {
// the UniFi controller violates the HTTP protocol // the UniFi controller violates the HTTP protocol
// - it returns 401 UNAUTHORIZED without the WWW-Authenticate response header // - it returns 401 UNAUTHORIZED without the WWW-Authenticate response header
// - this causes an ExecutionException to be thrown // - this causes an ExecutionException to be thrown
// - we unwrap the response from the exception for proper handling of the 401 status code // - we unwrap the response from the exception for proper handling of the 401 status code
response = ((HttpResponseException) cause).getResponse(); response = httpResponseException.getResponse();
} else { } else {
// catch all // catch all
throw new UniFiException(cause); throw new UniFiException(cause);

View File

@ -107,8 +107,10 @@ public class UniFiVoucher implements HasId {
@Override @Override
public String toString() { public String toString() {
return String.format( 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, id, code, createTime, duration, quota, used, qosUsageQuota, qosRateMaxUp, qosRateMaxDown, qosOverwrite,
note, status, getSite()); note, status, getSite());
} }

View File

@ -245,13 +245,13 @@ public class UniFiClientThingHandler extends UniFiBaseThingHandler<UniFiClient,
default: default:
// mgb: additional wired client channels // mgb: additional wired client channels
if (client.isWired() && (client instanceof UniFiWiredClient)) { if (client.isWired() && (client instanceof UniFiWiredClient wiredClient)) {
state = getWiredChannelState((UniFiWiredClient) client, channelId, state); state = getWiredChannelState(wiredClient, channelId, state);
} }
// mgb: additional wireless client channels // mgb: additional wireless client channels
else if (client.isWireless() && (client instanceof UniFiWirelessClient)) { else if (client.isWireless() && (client instanceof UniFiWirelessClient wirelessClient)) {
state = getWirelessChannelState((UniFiWirelessClient) client, channelId, state); state = getWirelessChannelState(wirelessClient, channelId, state);
} }
break; break;
} }

View File

@ -199,8 +199,8 @@ public class UniFiControllerThingHandler extends BaseBridgeHandler {
getThing().getThings().forEach((thing) -> { getThing().getThings().forEach((thing) -> {
final ThingHandler handler = thing.getHandler(); final ThingHandler handler = thing.getHandler();
if (handler instanceof UniFiBaseThingHandler) { if (handler instanceof UniFiBaseThingHandler baseThingHandler) {
((UniFiBaseThingHandler<?, ?>) handler).refresh(); baseThingHandler.refresh();
} }
}); });
} }

View File

@ -15,7 +15,7 @@ package org.openhab.binding.unifi.internal.handler;
import static org.openhab.binding.unifi.internal.UniFiBindingConstants.*; import static org.openhab.binding.unifi.internal.UniFiBindingConstants.*;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Set;
import java.util.function.Predicate; import java.util.function.Predicate;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -134,6 +134,6 @@ public class UniFiSiteThingHandler extends UniFiBaseThingHandler<UniFiSite, UniF
@Override @Override
public Collection<Class<? extends ThingHandlerService>> getServices() { public Collection<Class<? extends ThingHandlerService>> getServices() {
return Collections.singleton(UniFiSiteActions.class); return Set.of(UniFiSiteActions.class);
} }
} }

View File

@ -76,8 +76,8 @@ public class UniFiThingDiscoveryService extends AbstractDiscoveryService
@Override @Override
public void setThingHandler(final ThingHandler handler) { public void setThingHandler(final ThingHandler handler) {
if (handler instanceof UniFiControllerThingHandler) { if (handler instanceof UniFiControllerThingHandler controllerThingHandler) {
bridgeHandler = (UniFiControllerThingHandler) handler; bridgeHandler = controllerThingHandler;
} }
} }

View File

@ -135,8 +135,8 @@ public class UniFiWlanThingHandler extends UniFiBaseThingHandler<UniFiWlan, UniF
return UnDefType.UNDEF; return UnDefType.UNDEF;
} else { } else {
return new DecimalType(site.getCache().countClients(site, return new DecimalType(site.getCache().countClients(site,
c -> c instanceof UniFiWirelessClient c -> c instanceof UniFiWirelessClient wirelessClient
&& (wlan.getName() != null && wlan.getName().equals(((UniFiWirelessClient) c).getEssid())) && (wlan.getName() != null && wlan.getName().equals(wirelessClient.getEssid()))
&& filter.test(c))); && filter.test(c)));
} }
} }

View File

@ -12,7 +12,6 @@
*/ */
package org.openhab.binding.unifiedremote.internal; package org.openhab.binding.unifiedremote.internal;
import java.util.Collections;
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -31,8 +30,7 @@ public class UnifiedRemoteBindingConstants {
// List of all Thing Type UIDs // List of all Thing Type UIDs
public static final ThingTypeUID THING_TYPE_UNIFIED_REMOTE_SERVER = new ThingTypeUID(BINDING_ID, "server"); public static final ThingTypeUID THING_TYPE_UNIFIED_REMOTE_SERVER = new ThingTypeUID(BINDING_ID, "server");
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_UNIFIED_REMOTE_SERVER);
.singleton(THING_TYPE_UNIFIED_REMOTE_SERVER);
// List of all Channel ids // List of all Channel ids
public static final String MOUSE_CHANNEL = "mouse-move"; public static final String MOUSE_CHANNEL = "mouse-move";

View File

@ -87,16 +87,14 @@ public class UPBController {
} }
public void deviceAdded(final ThingHandler childHandler, final Thing childThing) { public void deviceAdded(final ThingHandler childHandler, final Thing childThing) {
if (childHandler instanceof UPBThingHandler) { if (childHandler instanceof UPBThingHandler upbThingHandler) {
final UPBThingHandler hnd = (UPBThingHandler) childHandler; things.put(mkAddr(upbThingHandler.getNetworkId(), upbThingHandler.getUnitId()), upbThingHandler);
things.put(mkAddr(hnd.getNetworkId(), hnd.getUnitId()), hnd);
} }
} }
public void deviceRemoved(final ThingHandler childHandler, final Thing childThing) { public void deviceRemoved(final ThingHandler childHandler, final Thing childThing) {
if (childHandler instanceof UPBThingHandler) { if (childHandler instanceof UPBThingHandler upbThingHandler) {
final UPBThingHandler hnd = (UPBThingHandler) childHandler; things.remove(mkAddr(upbThingHandler.getNetworkId(), upbThingHandler.getUnitId()), upbThingHandler);
things.remove(mkAddr(hnd.getNetworkId(), hnd.getUnitId()), hnd);
} }
} }

View File

@ -144,8 +144,8 @@ public class UPBThingHandler extends BaseThingHandler {
message = MessageBuilder.forCommand(ACTIVATE); message = MessageBuilder.forCommand(ACTIVATE);
} else if (cmd == OnOffType.OFF) { } else if (cmd == OnOffType.OFF) {
message = MessageBuilder.forCommand(DEACTIVATE); message = MessageBuilder.forCommand(DEACTIVATE);
} else if (cmd instanceof PercentType) { } else if (cmd instanceof PercentType percentCommand) {
message = MessageBuilder.forCommand(GOTO).args(((PercentType) cmd).byteValue()); message = MessageBuilder.forCommand(GOTO).args(percentCommand.byteValue());
} else if (cmd == RefreshType.REFRESH) { } else if (cmd == RefreshType.REFRESH) {
refreshDeviceState(); refreshDeviceState();
return; return;

View File

@ -52,8 +52,7 @@ public class UpnpDynamicCommandDescriptionProvider implements DynamicCommandDesc
@Override @Override
public @Nullable CommandDescription getCommandDescription(Channel channel, public @Nullable CommandDescription getCommandDescription(Channel channel,
@Nullable CommandDescription originalCommandDescription, @Nullable Locale locale) { @Nullable CommandDescription originalCommandDescription, @Nullable Locale locale) {
CommandDescription description = descriptions.get(channel.getUID()); return descriptions.get(channel.getUID());
return description;
} }
@Deactivate @Deactivate

View File

@ -52,8 +52,7 @@ public class UpnpDynamicStateDescriptionProvider implements DynamicStateDescript
@Override @Override
public @Nullable StateDescription getStateDescription(Channel channel, public @Nullable StateDescription getStateDescription(Channel channel,
@Nullable StateDescription originalStateDescription, @Nullable Locale locale) { @Nullable StateDescription originalStateDescription, @Nullable Locale locale) {
StateDescription description = descriptions.get(channel.getUID()); return descriptions.get(channel.getUID());
return description;
} }
@Deactivate @Deactivate

View File

@ -333,7 +333,7 @@ public abstract class UpnpHandler extends BaseThingHandler implements UpnpIOPart
* Invoke ConnectionComplete on UPnP Connection Manager. * Invoke ConnectionComplete on UPnP Connection Manager.
*/ */
protected void connectionComplete() { 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); invokeAction(CONNECTION_MANAGER, "ConnectionComplete", inputs);
} }
@ -367,7 +367,7 @@ public abstract class UpnpHandler extends BaseThingHandler implements UpnpIOPart
isRcsIdSet = new CompletableFuture<Boolean>(); isRcsIdSet = new CompletableFuture<Boolean>();
// ConnectionID will default to 0 if not set through prepareForConnection method // 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); invokeAction(CONNECTION_MANAGER, "GetCurrentConnectionInfo", inputs);
} }

View File

@ -19,7 +19,6 @@ import java.nio.charset.StandardCharsets;
import java.time.Instant; import java.time.Instant;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
@ -317,7 +316,7 @@ public class UpnpRendererHandler extends UpnpHandler {
// received // 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); invokeAction(AV_TRANSPORT, "Stop", inputs);
} }
@ -353,7 +352,7 @@ public class UpnpRendererHandler extends UpnpHandler {
* Invoke Pause on UPnP AV Transport. * Invoke Pause on UPnP AV Transport.
*/ */
protected void pause() { 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); invokeAction(AV_TRANSPORT, "Pause", inputs);
} }
@ -362,7 +361,7 @@ public class UpnpRendererHandler extends UpnpHandler {
* Invoke Next on UPnP AV Transport. * Invoke Next on UPnP AV Transport.
*/ */
protected void next() { 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); invokeAction(AV_TRANSPORT, "Next", inputs);
} }
@ -371,7 +370,7 @@ public class UpnpRendererHandler extends UpnpHandler {
* Invoke Previous on UPnP AV Transport. * Invoke Previous on UPnP AV Transport.
*/ */
protected void previous() { 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); invokeAction(AV_TRANSPORT, "Previous", inputs);
} }
@ -456,7 +455,7 @@ public class UpnpRendererHandler extends UpnpHandler {
* Result is received in {@link #onValueReceived}. * Result is received in {@link #onValueReceived}.
*/ */
protected void getTransportState() { 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); invokeAction(AV_TRANSPORT, "GetTransportInfo", inputs);
} }
@ -466,7 +465,7 @@ public class UpnpRendererHandler extends UpnpHandler {
* Result is received in {@link #onValueReceived}. * Result is received in {@link #onValueReceived}.
*/ */
protected void getPositionInfo() { 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); invokeAction(AV_TRANSPORT, "GetPositionInfo", inputs);
} }
@ -476,7 +475,7 @@ public class UpnpRendererHandler extends UpnpHandler {
* Result is received in {@link #onValueReceived}. * Result is received in {@link #onValueReceived}.
*/ */
protected void getMediaInfo() { 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); invokeAction(AV_TRANSPORT, "smarthome:audio stream http://icecast.vrtcdn.be/stubru_tijdloze-high.mp3", inputs);
} }
@ -696,24 +695,24 @@ public class UpnpRendererHandler extends UpnpHandler {
private void handleCommandVolume(Command command, String id) { private void handleCommandVolume(Command command, String id) {
if (command instanceof RefreshType) { if (command instanceof RefreshType) {
getVolume("volume".equals(id) ? UPNP_MASTER : id.replace("volume", "")); getVolume("volume".equals(id) ? UPNP_MASTER : id.replace("volume", ""));
} else if (command instanceof PercentType) { } else if (command instanceof PercentType percentCommand) {
setVolume("volume".equals(id) ? UPNP_MASTER : id.replace("volume", ""), (PercentType) command); setVolume("volume".equals(id) ? UPNP_MASTER : id.replace("volume", ""), percentCommand);
} }
} }
private void handleCommandMute(Command command, String id) { private void handleCommandMute(Command command, String id) {
if (command instanceof RefreshType) { if (command instanceof RefreshType) {
getMute("mute".equals(id) ? UPNP_MASTER : id.replace("mute", "")); getMute("mute".equals(id) ? UPNP_MASTER : id.replace("mute", ""));
} else if (command instanceof OnOffType) { } else if (command instanceof OnOffType onOffCommand) {
setMute("mute".equals(id) ? UPNP_MASTER : id.replace("mute", ""), (OnOffType) command); setMute("mute".equals(id) ? UPNP_MASTER : id.replace("mute", ""), onOffCommand);
} }
} }
private void handleCommandLoudness(Command command, String id) { private void handleCommandLoudness(Command command, String id) {
if (command instanceof RefreshType) { if (command instanceof RefreshType) {
getLoudness("loudness".equals(id) ? UPNP_MASTER : id.replace("loudness", "")); getLoudness("loudness".equals(id) ? UPNP_MASTER : id.replace("loudness", ""));
} else if (command instanceof OnOffType) { } else if (command instanceof OnOffType onOffCommand) {
setLoudness("loudness".equals(id) ? UPNP_MASTER : id.replace("loudness", ""), (OnOffType) command); setLoudness("loudness".equals(id) ? UPNP_MASTER : id.replace("loudness", ""), onOffCommand);
} }
} }
@ -884,8 +883,8 @@ public class UpnpRendererHandler extends UpnpHandler {
private void handleCommandTrackPosition(ChannelUID channelUID, Command command) { private void handleCommandTrackPosition(ChannelUID channelUID, Command command) {
if (command instanceof RefreshType) { if (command instanceof RefreshType) {
updateState(channelUID, new QuantityType<>(trackPosition, Units.SECOND)); updateState(channelUID, new QuantityType<>(trackPosition, Units.SECOND));
} else if (command instanceof QuantityType<?>) { } else if (command instanceof QuantityType<?> quantityCommand) {
QuantityType<?> position = ((QuantityType<?>) command).toUnit(Units.SECOND); QuantityType<?> position = quantityCommand.toUnit(Units.SECOND);
if (position != null) { if (position != null) {
int pos = Integer.min(trackDuration, position.intValue()); int pos = Integer.min(trackDuration, position.intValue());
seek(String.format("%02d:%02d:%02d", pos / 3600, (pos % 3600) / 60, pos % 60)); seek(String.format("%02d:%02d:%02d", pos / 3600, (pos % 3600) / 60, pos % 60));
@ -897,8 +896,8 @@ public class UpnpRendererHandler extends UpnpHandler {
if (command instanceof RefreshType) { if (command instanceof RefreshType) {
int relPosition = (trackDuration != 0) ? (trackPosition * 100) / trackDuration : 0; int relPosition = (trackDuration != 0) ? (trackPosition * 100) / trackDuration : 0;
updateState(channelUID, new PercentType(relPosition)); updateState(channelUID, new PercentType(relPosition));
} else if (command instanceof PercentType) { } else if (command instanceof PercentType percentCommand) {
int pos = ((PercentType) command).intValue() * trackDuration / 100; int pos = percentCommand.intValue() * trackDuration / 100;
seek(String.format("%02d:%02d:%02d", pos / 3600, (pos % 3600) / 60, pos % 60)); seek(String.format("%02d:%02d:%02d", pos / 3600, (pos % 3600) / 60, pos % 60));
} }
} }

View File

@ -321,8 +321,8 @@ public class UpnpServerHandler extends UpnpHandler {
private void handleCommandUpnpRenderer(ChannelUID channelUID, Command command) { private void handleCommandUpnpRenderer(ChannelUID channelUID, Command command) {
UpnpRendererHandler renderer = null; UpnpRendererHandler renderer = null;
UpnpRendererHandler previousRenderer = currentRendererHandler; UpnpRendererHandler previousRenderer = currentRendererHandler;
if (command instanceof StringType) { if (command instanceof StringType stringCommand) {
renderer = (upnpRenderers.get(((StringType) command).toString())); renderer = (upnpRenderers.get(stringCommand.toString()));
currentRendererHandler = renderer; currentRendererHandler = renderer;
if (config.filter) { if (config.filter) {
// only refresh title list if filtering by renderer capabilities // only refresh title list if filtering by renderer capabilities

Some files were not shown because too many files have changed in this diff Show More