}
try {
- URI requestURI = new URI(HttpScheme.HTTP.asString(), (String) null, address, port, path, query,
- (String) null);
- return requestURI;
+ return new URI(HttpScheme.HTTP.asString(), (String) null, address, port, path, query, (String) null);
} catch (URISyntaxException var8) {
LOGGER.warn("URI could not be parsed with path {}", path);
throw new NanoleafException("Wrong URI format for API request");
}
} catch (ExecutionException ee) {
Throwable cause = ee.getCause();
- if (cause != null && cause instanceof HttpResponseException
- && ((HttpResponseException) cause).getResponse().getStatus() == HttpStatus.UNAUTHORIZED_401) {
+ if (cause instanceof HttpResponseException httpResponseException
+ && httpResponseException.getResponse().getStatus() == HttpStatus.UNAUTHORIZED_401) {
LOGGER.debug("OpenAPI request unauthorized. Invalid authorization token.");
throw new NanoleafUnauthorizedException("Invalid authorization token");
} else {
thingRegistry.getAll().forEach(thing -> {
if (thing.getUID().getBindingId().equals(NanoleafBindingConstants.BINDING_ID)) {
ThingHandler handler = thing.getHandler();
- if (handler instanceof NanoleafControllerHandler) {
- NanoleafControllerHandler nanoleafControllerHandler = (NanoleafControllerHandler) handler;
+ if (handler instanceof NanoleafControllerHandler nanoleafControllerHandler) {
if (!handler.getThing().isEnabled()) {
console.println(
"The following Nanoleaf is NOT enabled as a Thing. Enable it first to view its layout.");
Thing thing = thingRegistry.get(new ThingUID(uid));
if (thing != null) {
ThingHandler handler = thing.getHandler();
- if (handler instanceof NanoleafControllerHandler) {
- NanoleafControllerHandler nanoleafControllerHandler = (NanoleafControllerHandler) handler;
+ if (handler instanceof NanoleafControllerHandler nanoleafControllerHandler) {
String layout = nanoleafControllerHandler.getLayout();
console.println(layout);
} else {
- console.println("Thing with UID '" + uid.toString()
- + "' is not an initialized Nanoleaf controller.");
+ console.println(
+ "Thing with UID '" + uid + "' is not an initialized Nanoleaf controller.");
}
} else {
- console.println("Thing with UID '" + uid.toString() + "' does not exist.");
+ console.println("Thing with UID '" + uid + "' does not exist.");
}
} else {
printUsage(console);
MODEL_ID_LIGHTPANELS.equals(modelId) ? API_MIN_FW_VER_LIGHTPANELS : API_MIN_FW_VER_CANVAS);
}
- final DiscoveryResult result = DiscoveryResultBuilder.create(uid).withThingType(getThingType(service))
- .withProperties(properties).withLabel(service.getName()).withRepresentationProperty(CONFIG_ADDRESS)
- .build();
- return result;
+ return DiscoveryResultBuilder.create(uid).withThingType(getThingType(service)).withProperties(properties)
+ .withLabel(service.getName()).withRepresentationProperty(CONFIG_ADDRESS).build();
}
@Override
Bridge bridge = getBridge();
if (bridge != null) {
ThingHandler handler = bridge.getHandler();
- if (handler instanceof NanoleafControllerHandler) {
- ((NanoleafControllerHandler) handler).getColorInformation().unregisterChangeListener(getPanelID());
+ if (handler instanceof NanoleafControllerHandler controllerHandler) {
+ controllerHandler.getColorInformation().unregisterChangeListener(getPanelID());
}
}
Bridge bridge = getBridge();
if (bridge != null) {
ThingHandler handler = bridge.getHandler();
- if (handler instanceof NanoleafControllerHandler) {
- ((NanoleafControllerHandler) handler).getColorInformation().registerChangeListener(getPanelID(), this);
+ if (handler instanceof NanoleafControllerHandler controllerHandler) {
+ controllerHandler.getColorInformation().registerChangeListener(getPanelID(), this);
}
}
}
logger.debug("currentPanelColor: {}", currentPanelColor);
HSBType newPanelColor = new HSBType();
- if (command instanceof HSBType) {
- newPanelColor = (HSBType) command;
+ if (command instanceof HSBType hsbCommand) {
+ newPanelColor = hsbCommand;
} else if (command instanceof OnOffType) {
if (OnOffType.ON.equals(command)) {
newPanelColor = new HSBType(currentPanelColor.getHue(), currentPanelColor.getSaturation(),
newPanelColor = new HSBType(currentPanelColor.getHue(), currentPanelColor.getSaturation(),
MIN_PANEL_BRIGHTNESS);
}
- } else if (command instanceof PercentType) {
- PercentType brightness = new PercentType(
- Math.max(MIN_PANEL_BRIGHTNESS.intValue(), ((PercentType) command).intValue()));
+ } else if (command instanceof PercentType type) {
+ PercentType brightness = new PercentType(Math.max(MIN_PANEL_BRIGHTNESS.intValue(), type.intValue()));
newPanelColor = new HSBType(currentPanelColor.getHue(), currentPanelColor.getSaturation(), brightness);
} else if (command instanceof IncreaseDecreaseType) {
int brightness = currentPanelColor.getBrightness().intValue();
Object panelId = getThing().getConfiguration().get(CONFIG_PANEL_ID);
if (panelId instanceof Integer) {
return (Integer) panelId;
- } else if (panelId instanceof Number) {
- return ((Number) panelId).intValue();
+ } else if (panelId instanceof Number numberValue) {
+ return numberValue.intValue();
} else {
// Fall back to parsing string representation of panel if it is not returning an integer
String stringPanelId = panelId.toString();
Bridge bridge = getBridge();
if (bridge != null) {
ThingHandler handler = bridge.getHandler();
- if (handler instanceof NanoleafControllerHandler) {
- ((NanoleafControllerHandler) handler).getColorInformation().setPanelColor(panelId, color);
+ if (handler instanceof NanoleafControllerHandler controllerHandler) {
+ controllerHandler.getColorInformation().setPanelColor(panelId, color);
} else {
logger.debug("Couldn't find handler for panel {}", panelId);
}
TRIANGLE,
HEXAGON,
CORNER,
- LINE;
+ LINE
}
private static ImagePoint2D toPictureLayout(Point2D original, int imageHeight, ImagePoint2D min,
double rotationRadians) {
Point2D rotated = original.rotate(rotationRadians);
- ImagePoint2D translated = new ImagePoint2D(
- NanoleafBindingConstants.LAYOUT_BORDER_WIDTH + rotated.getX() - min.getX(),
+ return new ImagePoint2D(NanoleafBindingConstants.LAYOUT_BORDER_WIDTH + rotated.getX() - min.getX(),
imageHeight - NanoleafBindingConstants.LAYOUT_BORDER_WIDTH - rotated.getY() + min.getY());
- return translated;
}
private static List<ImagePoint2D> toPictureLayout(List<Point2D> originals, int imageHeight, ImagePoint2D min,
return new byte[] {};
}
- ImagePoint2D size[] = findSize(positionDatums, rotationRadians);
+ ImagePoint2D[] size = findSize(positionDatums, rotationRadians);
final ImagePoint2D min = size[0];
final ImagePoint2D max = size[1];
}
public void setState(IntegerState value) {
- if (value instanceof Brightness) {
- this.setBrightness((Brightness) value);
- } else if (value instanceof Hue) {
- this.setHue((Hue) value);
- } else if (value instanceof Sat) {
- this.setSaturation((Sat) value);
- } else if (value instanceof Ct) {
- this.setColorTemperature((Ct) value);
+ if (value instanceof Brightness brightnessState) {
+ this.setBrightness(brightnessState);
+ } else if (value instanceof Hue hueState) {
+ this.setHue(hueState);
+ } else if (value instanceof Sat satState) {
+ this.setSaturation(satState);
+ } else if (value instanceof Ct ctState) {
+ this.setColorTemperature(ctState);
}
}
public void setState(BooleanState value) {
- if (value instanceof On) {
- this.setOn((On) value);
+ if (value instanceof On onState) {
+ this.setOn(onState);
}
}
}
}
private class TestPanelState implements PanelState {
- private final HSBType testColors[] = { HSBType.fromRGB(160, 120, 40), HSBType.fromRGB(80, 60, 20),
+ private final HSBType[] testColors = { HSBType.fromRGB(160, 120, 40), HSBType.fromRGB(80, 60, 20),
HSBType.fromRGB(120, 90, 30), HSBType.fromRGB(200, 150, 60) };
@Override
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPE_UIDS = Collections
.unmodifiableSet(Stream.of(BRIDGE_TYPE_NEATOACCOUNT, THING_TYPE_VACUUMCLEANER).collect(Collectors.toSet()));
- public static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPE_UIDS = Collections
- .singleton(THING_TYPE_VACUUMCLEANER);
+ public static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPE_UIDS = Set.of(THING_TYPE_VACUUMCLEANER);
private Map<ThingUID, ServiceRegistration<DiscoveryService>> discoveryServiceRegistrations = new HashMap<>();
return HttpUtil.executeUrl("POST",
"https://nucleo.neatocloud.com:4443/vendors/neato/robots/" + this.serialNumber + "/messages",
headers, stream, "text/html; charset=ISO-8859-1", 20000);
-
} catch (IOException | NoSuchAlgorithmException | InvalidKeyException e) {
throw new NeatoCommunicationException(e);
}
import java.net.InetAddress;
import java.net.UnknownHostException;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@Override
public Set<@Nullable ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(BRIDGE_TYPE_BRAIN);
+ return Set.of(BRIDGE_TYPE_BRAIN);
}
@Override
package org.openhab.binding.neeo.internal.discovery;
import java.io.IOException;
-import java.util.Collections;
import java.util.Objects;
import java.util.Set;
private final Logger logger = LoggerFactory.getLogger(NeeoDeviceDiscoveryService.class);
/** The device thing type we support */
- private static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPES_UIDS = Collections
- .singleton(NeeoConstants.THING_TYPE_DEVICE);
+ private static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPES_UIDS = Set.of(NeeoConstants.THING_TYPE_DEVICE);
/** The timeout (in seconds) for searching the room */
private static final int SEARCH_TIME = 10;
package org.openhab.binding.neeo.internal.discovery;
import java.io.IOException;
-import java.util.Collections;
import java.util.Objects;
import java.util.Set;
private final Logger logger = LoggerFactory.getLogger(NeeoRoomDiscoveryService.class);
/** The room bridge type we support */
- private static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPES_UIDS = Collections
- .singleton(NeeoConstants.BRIDGE_TYPE_ROOM);
+ private static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPES_UIDS = Set.of(NeeoConstants.BRIDGE_TYPE_ROOM);
/** The timeout (in seconds) for searching the brain */
private static final int SEARCH_TIME = 10;
final Bridge parent = getBridge();
if (parent != null) {
final BridgeHandler handler = parent.getHandler();
- if (handler instanceof NeeoRoomHandler) {
- return ((NeeoRoomHandler) handler);
+ if (handler instanceof NeeoRoomHandler roomHandler) {
+ return roomHandler;
}
}
return null;
final Bridge parent = getBridge();
if (parent != null) {
final BridgeHandler handler = parent.getHandler();
- if (handler instanceof NeeoBrainHandler) {
- return ((NeeoBrainHandler) handler);
+ if (handler instanceof NeeoBrainHandler brainHandler) {
+ return brainHandler;
}
}
return null;
Objects.requireNonNull(jsonElement, "jsonElement cannot be null");
Objects.requireNonNull(context, "context cannot be null");
- if (jsonElement instanceof JsonObject) {
+ if (jsonElement instanceof JsonObject jsonObject) {
final List<NeeoDevice> scenarios = new ArrayList<>();
- for (Map.Entry<String, JsonElement> entry : ((JsonObject) jsonElement).entrySet()) {
+ for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
final NeeoDevice device = context.deserialize(entry.getValue(), NeeoDevice.class);
scenarios.add(device);
}
Objects.requireNonNull(jsonElement, "jsonElement cannot be null");
Objects.requireNonNull(context, "context cannot be null");
- if (jsonElement instanceof JsonObject) {
+ if (jsonElement instanceof JsonObject jsonObject) {
final List<NeeoMacro> scenarios = new ArrayList<>();
- for (Map.Entry<String, JsonElement> entry : ((JsonObject) jsonElement).entrySet()) {
+ for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
final NeeoMacro macro = context.deserialize(entry.getValue(), NeeoMacro.class);
scenarios.add(macro);
}
Objects.requireNonNull(jsonElement, "jsonElement cannot be null");
Objects.requireNonNull(context, "context cannot be null");
- if (jsonElement instanceof JsonObject) {
+ if (jsonElement instanceof JsonObject jsonObject) {
final List<NeeoRecipe> recipes = new ArrayList<>();
- for (Map.Entry<String, JsonElement> entry : ((JsonObject) jsonElement).entrySet()) {
+ for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
final NeeoRecipe recipe = context.deserialize(entry.getValue(), NeeoRecipe.class);
recipes.add(recipe);
}
@Nullable JsonDeserializationContext context) throws JsonParseException {
Objects.requireNonNull(jsonElement, "jsonElement cannot be null");
Objects.requireNonNull(context, "context cannot be null");
- if (jsonElement instanceof JsonObject) {
+ if (jsonElement instanceof JsonObject jsonObject) {
final List<NeeoRoom> recipes = new ArrayList<>();
- for (Map.Entry<String, JsonElement> entry : ((JsonObject) jsonElement).entrySet()) {
+ for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
final NeeoRoom room = context.deserialize(entry.getValue(), NeeoRoom.class);
recipes.add(room);
}
@Nullable JsonDeserializationContext context) throws JsonParseException {
Objects.requireNonNull(jsonElement, "jsonElement cannot be null");
Objects.requireNonNull(context, "context cannot be null");
- if (jsonElement instanceof JsonObject) {
+ if (jsonElement instanceof JsonObject jsonObject) {
final List<NeeoScenario> scenarios = new ArrayList<>();
- for (Map.Entry<String, JsonElement> entry : ((JsonObject) jsonElement).entrySet()) {
+ for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
final NeeoScenario scenario = context.deserialize(entry.getValue(), NeeoScenario.class);
scenarios.add(scenario);
}
import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingStatusDetail;
import org.openhab.core.thing.binding.BaseThingHandler;
-import org.openhab.core.thing.binding.BridgeHandler;
import org.openhab.core.types.Command;
import org.openhab.core.types.RefreshType;
import org.openhab.core.types.State;
if (channel != null) {
Configuration config = channel.getConfiguration();
Object holdOnlineState = config.get(PARAM_HOLD_ONLINE_STATE);
- if (holdOnlineState != null && (holdOnlineState instanceof Boolean)
- && ((Boolean) holdOnlineState).booleanValue()) {
+ if (holdOnlineState instanceof Boolean booleanValue && booleanValue.booleanValue()) {
/*
* the Configuration Parameter "holdOnlineState" is True so do NOT send a
* state update to OpenHAB
protected @Nullable NeoHubHandler getNeoHub() {
@Nullable
Bridge b;
- @Nullable
- BridgeHandler h;
- if ((b = getBridge()) != null && (h = b.getHandler()) != null && h instanceof NeoHubHandler) {
- return (NeoHubHandler) h;
+ if ((b = getBridge()) != null && (b.getHandler() instanceof NeoHubHandler neoHubHandler)) {
+ return neoHubHandler;
}
return null;
/*
* enumerator for results of method calls
*/
- public static enum NeoHubReturnResult {
+ public enum NeoHubReturnResult {
SUCCEEDED,
ERR_COMMUNICATION,
ERR_INITIALIZATION
package org.openhab.binding.neohub.internal;
import java.net.Inet4Address;
-import java.util.Collections;
import java.util.Set;
import javax.jmdns.ServiceInfo;
private String getIpAddressIfValidNeoHub(ServiceInfo serviceInfo) {
if (serviceInfo.getName().contains(HEATMISER_NEO_HUB)) {
for (Inet4Address ipAddr : serviceInfo.getInet4Addresses()) {
- String ipStr = ipAddr.getHostAddress();
- return ipStr;
+ return ipAddr.getHostAddress();
}
}
return "";
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(NeoHubBindingConstants.THING_TYPE_NEOHUB);
+ return Set.of(NeoHubBindingConstants.THING_TYPE_NEOHUB);
}
@Override
String ipStr = getIpAddressIfValidNeoHub(serviceInfo);
if (!ipStr.isEmpty()) {
ThingUID thingUID = new ThingUID(NeoHubBindingConstants.THING_TYPE_NEOHUB, ipStr.replace('.', '_'));
- DiscoveryResult hub = DiscoveryResultBuilder.create(thingUID)
- .withProperty(NeoHubConfiguration.HOST_NAME, ipStr)
+ return DiscoveryResultBuilder.create(thingUID).withProperty(NeoHubConfiguration.HOST_NAME, ipStr)
.withRepresentationProperty(NeoHubConfiguration.HOST_NAME).withLabel("NeoHub (" + ipStr + ")")
.build();
- return hub;
}
return null;
}
for (AbstractRecord deviceRecord : deviceRecords) {
// the record came from the legacy API (deviceType included)
- if (deviceRecord instanceof InfoRecord) {
- deviceType = ((InfoRecord) deviceRecord).getDeviceType();
+ if (deviceRecord instanceof InfoRecord infoRecord) {
+ deviceType = infoRecord.getDeviceType();
publishDevice(deviceRecord, deviceType);
continue;
}
// the record came from the new API (deviceType NOT included)
- if (deviceRecord instanceof LiveDataRecord) {
+ if (deviceRecord instanceof LiveDataRecord liveDataRecord) {
if (engineerData == null) {
break;
}
- String deviceName = ((LiveDataRecord) deviceRecord).getDeviceName();
+ String deviceName = liveDataRecord.getDeviceName();
// exclude repeater nodes from being discovered
if (MATCHER_HEATMISER_REPEATER.matcher(deviceName).matches()) {
continue;
// check if we also need to discard and update systemData
NeoHubReadDcbResponse systemData = this.systemData;
if (systemData != null) {
- if (deviceData instanceof NeoHubLiveDeviceData) {
+ if (deviceData instanceof NeoHubLiveDeviceData liveDeviceData) {
/*
* note: time-stamps are measured in seconds from 1970-01-01T00:00:00Z
*
* new API: discard systemData if its time-stamp is older than the system
* time-stamp on the hub
*/
- if (systemData.timeStamp < ((NeoHubLiveDeviceData) deviceData).getTimestampSystem()) {
+ if (systemData.timeStamp < liveDeviceData.getTimestampSystem()) {
this.systemData = null;
}
} else {
List<Thing> children = getThing().getThings();
for (Thing child : children) {
ThingHandler device = child.getHandler();
- if (device instanceof NeoBaseHandler) {
- ((NeoBaseHandler) device).toBaseSendPollResponse(deviceData);
+ if (device instanceof NeoBaseHandler neoBaseHandler) {
+ neoBaseHandler.toBaseSendPollResponse(deviceData);
}
}
import static org.openhab.binding.neohub.internal.NeoHubBindingConstants.*;
-import java.util.Arrays;
-import java.util.Collections;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;
@Component(configurationPid = "binding.neohub", service = ThingHandlerFactory.class)
public class NeoHubHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .unmodifiableSet(new HashSet<>(Arrays.asList(THING_TYPE_NEOHUB, THING_TYPE_NEOSTAT, THING_TYPE_NEOPLUG,
- THING_TYPE_NEOCONTACT, THING_TYPE_NEOTEMPERATURESENSOR)));
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_NEOHUB, THING_TYPE_NEOSTAT,
+ THING_TYPE_NEOPLUG, THING_TYPE_NEOCONTACT, THING_TYPE_NEOTEMPERATURESENSOR);
private final WebSocketFactory webSocketFactory;
private final Map<ThingUID, ServiceRegistration<?>> discoServices = new HashMap<>();
protected @Nullable ThingHandler createHandler(Thing thing) {
ThingTypeUID thingTypeUID = thing.getThingTypeUID();
- if ((thingTypeUID.equals(THING_TYPE_NEOHUB)) && (thing instanceof Bridge)) {
- NeoHubHandler handler = new NeoHubHandler((Bridge) thing, webSocketFactory);
+ if ((thingTypeUID.equals(THING_TYPE_NEOHUB)) && (thing instanceof Bridge bridge)) {
+ NeoHubHandler handler = new NeoHubHandler(bridge, webSocketFactory);
createDiscoveryService(handler);
return handler;
}
@Override
protected synchronized void removeHandler(ThingHandler handler) {
- if (handler instanceof NeoHubHandler) {
- destroyDiscoveryService((NeoHubHandler) handler);
+ if (handler instanceof NeoHubHandler neoHubHandler) {
+ destroyDiscoveryService(neoHubHandler);
}
}
protected String toNeoHubBuildCommandString(String channelId, Command command) {
NeoBaseConfiguration config = this.config;
if (config != null) {
- if (command instanceof OnOffType && channelId.equals(CHAN_PLUG_OUTPUT_STATE)) {
- return String.format(CMD_CODE_TIMER, ((OnOffType) command).toString(), config.deviceNameInHub);
+ if (command instanceof OnOffType onOffCommand && channelId.equals(CHAN_PLUG_OUTPUT_STATE)) {
+ return String.format(CMD_CODE_TIMER, onOffCommand.toString(), config.deviceNameInHub);
}
- if (command instanceof OnOffType && channelId.equals(CHAN_PLUG_AUTO_MODE)) {
- return String.format(CMD_CODE_MANUAL, invert((OnOffType) command).toString(), config.deviceNameInHub);
+ if (command instanceof OnOffType onOffCommand && channelId.equals(CHAN_PLUG_AUTO_MODE)) {
+ return String.format(CMD_CODE_MANUAL, invert(onOffCommand).toString(), config.deviceNameInHub);
}
}
return "";
protected String toNeoHubBuildCommandString(String channelId, Command command) {
NeoBaseConfiguration config = this.config;
if (config != null) {
- if (command instanceof QuantityType<?> && channelId.equals(CHAN_TARGET_TEMP)) {
+ if (command instanceof QuantityType<?> quantityCommand && channelId.equals(CHAN_TARGET_TEMP)) {
Command doCommand = command;
- QuantityType<?> temp = ((QuantityType<?>) command).toUnit(getTemperatureUnit());
+ QuantityType<?> temp = quantityCommand.toUnit(getTemperatureUnit());
if (temp != null) {
doCommand = temp;
}
config.deviceNameInHub);
}
- if (command instanceof OnOffType && channelId.equals(CHAN_OCC_MODE_PRESENT)) {
- return String.format(CMD_CODE_AWAY, invert((OnOffType) command).toString(), config.deviceNameInHub);
+ if (command instanceof OnOffType onOffCommand && channelId.equals(CHAN_OCC_MODE_PRESENT)) {
+ return String.format(CMD_CODE_AWAY, invert(onOffCommand).toString(), config.deviceNameInHub);
}
}
return "";
jsonElement = JsonParser.parseString(load("dcb_celsius"));
assertTrue(jsonElement.isJsonObject());
- assertTrue(((JsonObject) jsonElement).keySet().size() > 0);
+ assertTrue(!((JsonObject) jsonElement).keySet().isEmpty());
jsonElement = JsonParser.parseString(load("live_data"));
assertTrue(jsonElement.isJsonObject());
- assertTrue(((JsonObject) jsonElement).keySet().size() > 0);
+ assertTrue(!((JsonObject) jsonElement).keySet().isEmpty());
jsonElement = JsonParser.parseString(load("engineers"));
assertTrue(jsonElement.isJsonObject());
- assertTrue(((JsonObject) jsonElement).keySet().size() > 0);
+ assertTrue(!((JsonObject) jsonElement).keySet().isEmpty());
jsonElement = JsonParser.parseString(load("info_new"));
assertTrue(jsonElement.isJsonObject());
- assertTrue(((JsonObject) jsonElement).keySet().size() > 0);
+ assertTrue(!((JsonObject) jsonElement).keySet().isEmpty());
jsonElement = JsonParser.parseString(load("info_old"));
assertTrue(jsonElement.isJsonObject());
- assertTrue(((JsonObject) jsonElement).keySet().size() > 0);
+ assertTrue(!((JsonObject) jsonElement).keySet().isEmpty());
jsonElement = JsonParser.parseString(load("system"));
assertTrue(jsonElement.isJsonObject());
- assertTrue(((JsonObject) jsonElement).keySet().size() > 0);
+ assertTrue(!((JsonObject) jsonElement).keySet().isEmpty());
jsonElement = JsonParser.parseString(load("info_sensors_closed"));
assertTrue(jsonElement.isJsonObject());
- assertTrue(((JsonObject) jsonElement).keySet().size() > 0);
+ assertTrue(!((JsonObject) jsonElement).keySet().isEmpty());
}
}
listeners.remove(listener);
if (listeners.isEmpty()) {
subscriptionListeners.remove(subscriptionId);
- scheduler.getQueue().removeIf(runnable -> runnable instanceof Subscriber
- && ((Subscriber) runnable).subscriptionId.equals(subscriptionId));
+ scheduler.getQueue().removeIf(
+ runnable -> runnable instanceof Subscriber s && s.subscriptionId.equals(subscriptionId));
}
}
}
@Override
public void setThingHandler(ThingHandler handler) {
- if (handler instanceof SDMAccountHandler) {
- accountHandler = (SDMAccountHandler) handler;
+ if (handler instanceof SDMAccountHandler sdmAccountHandler) {
+ accountHandler = sdmAccountHandler;
}
}
*/
public SDMSetFanTimerRequest(SDMFanTimerMode timerMode, Duration duration) {
super("sdm.devices.commands.Fan.SetTimer", entry("timerMode", timerMode.name()),
- entry("duration", String.valueOf(duration.toSeconds()) + "s"));
+ entry("duration", duration.toSeconds() + "s"));
}
}
public enum SDMTemperatureScale {
CELSIUS,
- FAHRENHEIT;
+ FAHRENHEIT
}
/**
delayedRefresh();
}
} else if (CHANNEL_FAN_TIMER_MODE.equals(channelUID.getId())) {
- if (command instanceof OnOffType) {
- if ((OnOffType) command == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
executeDeviceCommand(new SDMSetFanTimerRequest(SDMFanTimerMode.ON, getFanTimerDuration()));
} else {
executeDeviceCommand(new SDMSetFanTimerRequest(SDMFanTimerMode.OFF));
delayedRefresh();
}
} else if (CHANNEL_FAN_TIMER_TIMEOUT.equals(channelUID.getId())) {
- if (command instanceof DateTimeType) {
- Duration duration = Duration.between(ZonedDateTime.now(),
- ((DateTimeType) command).getZonedDateTime());
+ if (command instanceof DateTimeType dateTimeCommand) {
+ Duration duration = Duration.between(ZonedDateTime.now(), dateTimeCommand.getZonedDateTime());
executeDeviceCommand(new SDMSetFanTimerRequest(SDMFanTimerMode.ON, duration));
delayedRefresh();
}
if (channel != null) {
Configuration configuration = channel.getConfiguration();
Object fanTimerDuration = configuration.get(SDMBindingConstants.CONFIG_PROPERTY_FAN_TIMER_DURATION);
- if (fanTimerDuration instanceof BigDecimal) {
- seconds = ((BigDecimal) fanTimerDuration).longValue();
+ if (fanTimerDuration instanceof BigDecimal decimalValue) {
+ seconds = decimalValue.longValue();
}
}
public class SDMDataUtil {
public static Reader openDataReader(String fileName) throws FileNotFoundException {
- String packagePath = (SDMDataUtil.class.getPackage().getName()).replaceAll("\\.", "/");
+ String packagePath = (SDMDataUtil.class.getPackage().getName()).replace(".", "/");
String filePath = "src/test/resources/" + packagePath + "/" + fileName;
InputStream inputStream = new FileInputStream(filePath);
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof CommonInterface) {
- CommonInterface commonHandler = (CommonInterface) handler;
+ if (handler instanceof CommonInterface commonHandler) {
this.handler = commonHandler;
}
}
@Nullable String payload, @Nullable String contentType) throws NetatmoException {
URI uri = uriBuilder.build();
T response = apiBridge.executeUri(uri, method, clazz, payload, contentType, 3);
- if (response instanceof ApiResponse.Ok && ((ApiResponse.Ok) response).failed()) {
+ if (response instanceof ApiResponse.Ok apiResponseOk && apiResponseOk.failed()) {
throw new NetatmoException("Command failed : %s for uri : %s", response.getStatus(), uri.toString());
}
return response;
throws NetatmoException {
UriBuilder uriBuilder = getApiUriBuilder(SUB_PATH_GET_STATION, PARAM_DEVICE_ID, deviceId, //
PARAM_FAVORITES, getFavorites);
- StationDataResponse response = get(uriBuilder, StationDataResponse.class);
- return response;
+ return get(uriBuilder, StationDataResponse.class);
}
/**
this.minValue = minValue;
this.maxValue = maxValue;
this.unit = unit;
- String[] splitter = Double.valueOf(precision).toString().split("\\.");
+ String[] splitter = Double.toString(precision).split("\\.");
if (splitter.length > 1) {
int dec = Integer.parseInt(splitter[1]);
this.scale = dec > 0 ? Integer.toString(dec).length() : 0;
public static final int THERM_MAX_SETPOINT = 30;
// Token scopes
- public static enum Scope {
+ public enum Scope {
@SerializedName("read_station")
READ_STATION,
@SerializedName("read_thermostat")
ACCESS_DOORBELL,
@SerializedName("read_carbonmonoxidedetector")
READ_CARBONMONOXIDEDETECTOR,
- UNKNOWN;
+ UNKNOWN
}
private static final Scope[] SMOKE_SCOPES = { Scope.READ_SMOKEDETECTOR };
private static final Scope[] DOORBELL_SCOPES = { Scope.READ_DOORBELL, Scope.WRITE_DOORBELL, Scope.ACCESS_DOORBELL };
private static final Scope[] PRESENCE_SCOPES = { Scope.READ_PRESENCE, Scope.WRITE_PRESENCE, Scope.ACCESS_PRESENCE };
- public static enum FeatureArea {
+ public enum FeatureArea {
AIR_CARE(AIR_CARE_SCOPES),
WEATHER(WEATHER_SCOPES),
ENERGY(THERMOSTAT_SCOPES),
static final int[] RADIO_SIGNAL_LEVELS = new int[] { 90, 80, 70, 60 }; // Resp : low, medium, high, full
// Thermostat definitions
- public static enum SetpointMode {
+ public enum SetpointMode {
@SerializedName("program")
PROGRAM("program"),
@SerializedName("away")
}
}
- public static enum ThermostatZoneType {
+ public enum ThermostatZoneType {
@SerializedName("0")
DAY("0"),
@SerializedName("1")
OFF,
@SerializedName("auto")
AUTO,
- UNKNOWN;
+ UNKNOWN
}
public enum EventCategory {
ANIMAL,
@SerializedName("vehicle")
VEHICLE,
- UNKNOWN;
+ UNKNOWN
}
public enum TrendDescription {
STABLE,
@SerializedName("down")
DOWN,
- UNKNOWN;
+ UNKNOWN
}
public enum VideoStatus {
AVAILABLE,
@SerializedName("deleted")
DELETED,
- UNKNOWN;
+ UNKNOWN
}
public enum SdCardStatus {
SD_CARD_INCOMPATIBLE_SPEED,
@SerializedName("7")
SD_CARD_INSUFFICIENT_SPACE,
- UNKNOWN;
+ UNKNOWN
}
public enum AlimentationStatus {
ALIM_INCORRECT_POWER,
@SerializedName("2")
ALIM_CORRECT_POWER,
- UNKNOWN;
+ UNKNOWN
}
public enum SirenStatus {
@SerializedName("40")
JSON_GIVEN_HAS_AN_INVALID_ENCODING,
@SerializedName("41")
- DEVICE_IS_UNREACHABLE;
+ DEVICE_IS_UNREACHABLE
}
}
this.console = console;
for (Thing thing : thingRegistry.getAll()) {
ThingHandler thingHandler = thing.getHandler();
- if (thingHandler instanceof ApiBridgeHandler) {
+ if (thingHandler instanceof ApiBridgeHandler bridgeHandler) {
console.println("Account bridge: " + thing.getLabel());
- ((ApiBridgeHandler) thingHandler).identifyAllModulesAndApplyAction(this::printThing);
+ bridgeHandler.identifyAllModulesAndApplyAction(this::printThing);
}
}
} else {
throws JsonParseException {
ParameterizedType parameterized = (ParameterizedType) clazz;
Type[] typeArguments = parameterized.getActualTypeArguments();
- if (typeArguments.length > 0 && json instanceof JsonArray) {
+ if (typeArguments.length > 0 && json instanceof JsonArray jsonArray) {
Type objectType = typeArguments[0];
NAObjectMap<NAObject> result = new NAObjectMap<>();
- ((JsonArray) json).forEach(item -> {
+ jsonArray.forEach(item -> {
result.put(context.deserialize(item, objectType));
});
return result;
@Override
public void setThingHandler(ThingHandler handler) {
- if (handler instanceof ApiBridgeHandler) {
- this.handler = (ApiBridgeHandler) handler;
+ if (handler instanceof ApiBridgeHandler bridgeHandler) {
+ this.handler = bridgeHandler;
}
}
default List<CommonInterface> getActiveChildren() {
Thing thing = getThing();
- if (thing instanceof Bridge) {
- return ((Bridge) thing).getThings().stream().filter(Thing::isEnabled)
+ if (thing instanceof Bridge bridge) {
+ return bridge.getThings().stream().filter(Thing::isEnabled)
.filter(th -> th.getStatusInfo().getStatusDetail() != ThingStatusDetail.BRIDGE_OFFLINE)
.map(Thing::getHandler).filter(Objects::nonNull).map(CommonInterface.class::cast).toList();
}
}
default void setNewData(NAObject newData) {
- if (newData instanceof NAThing) {
- NAThing thingData = (NAThing) newData;
+ if (newData instanceof NAThing thingData) {
if (getId().equals(thingData.getBridge())) {
getActiveChildren().stream().filter(child -> child.getId().equals(thingData.getId())).findFirst()
.ifPresent(child -> child.setNewData(thingData));
MeasureClass.AS_SET.stream().filter(mc -> mc.apiDescriptor.equals(descriptor))
.reduce((first, second) -> second)
.ifPresent(mc -> measures.put(channel.getUID().getIdWithoutGroup(),
- result instanceof ZonedDateTime ? toDateTimeType((ZonedDateTime) result)
+ result instanceof ZonedDateTime zonedDateTime ? toDateTimeType(zonedDateTime)
: result instanceof Double ? toQuantityType((Double) result, mc)
: UnDefType.UNDEF));
} catch (NetatmoException e) {
protected @Nullable State internalGetProperty(String channelId, NAThing naThing, Configuration config) {
int percent = -1;
BatteryState batteryState = BatteryState.UNKNOWN;
- if (naThing instanceof Module) {
- percent = ((Module) naThing).getBatteryPercent();
- batteryState = ((Module) naThing).getBatteryState();
- } else if (naThing instanceof HomeStatusModule) {
- percent = ((HomeStatusModule) naThing).getBatteryState().level;
- batteryState = ((HomeStatusModule) naThing).getBatteryState();
+ if (naThing instanceof Module module) {
+ percent = module.getBatteryPercent();
+ batteryState = module.getBatteryState();
+ } else if (naThing instanceof HomeStatusModule homeStatusModule) {
+ percent = homeStatusModule.getBatteryState().level;
+ batteryState = homeStatusModule.getBatteryState();
} else {
return null;
}
@Override
protected @Nullable State internalGetProperty(String channelId, NAThing naThing, Configuration config) {
- if (naThing instanceof HomeStatusModule) {
- HomeStatusModule camera = (HomeStatusModule) naThing;
+ if (naThing instanceof HomeStatusModule camera) {
boolean isMonitoring = OnOffType.ON.equals(camera.getMonitoring());
switch (channelId) {
case CHANNEL_MONITORING:
State result = null;
if (channelGroups.isEmpty() || (groupId != null && channelGroups.contains(groupId))) {
NAObject localData = data;
- if (localData instanceof HomeEvent) {
- result = internalGetHomeEvent(channelId, groupId, (HomeEvent) localData);
+ if (localData instanceof HomeEvent homeEvent) {
+ result = internalGetHomeEvent(channelId, groupId, homeEvent);
if (result != null) {
return result;
}
}
- if (localData instanceof Event) {
- result = internalGetEvent(channelId, (Event) localData);
+ if (localData instanceof Event event) {
+ result = internalGetEvent(channelId, event);
if (result != null) {
return result;
}
}
- if (localData instanceof NAThing) {
- NAThing naThing = (NAThing) localData;
+ if (localData instanceof NAThing naThing) {
result = internalGetProperty(channelId, naThing, config);
if (result != null) {
return result;
@Override
protected @Nullable State internalGetProperty(String channelId, NAThing naThing, Configuration config) {
- if (naThing instanceof HomeStatusModule) {
- HomeStatusModule doorTag = (HomeStatusModule) naThing;
+ if (naThing instanceof HomeStatusModule doorTag) {
if (CHANNEL_STATUS.equalsIgnoreCase(channelId)) {
return doorTag.getStatus().map(status -> (State) OpenClosedType.valueOf(status.toUpperCase()))
.orElse(UnDefType.UNDEF);
@Override
public void setNewData(@Nullable NAObject data) {
- if (data instanceof Event) {
- Event event = (Event) data;
+ if (data instanceof Event event) {
if (!event.getEventType().validFor(moduleType)) {
return;
}
protected @Nullable State internalGetProperty(String channelId, NAThing naThing, Configuration config) {
if (CHANNEL_VALUE.equals(channelId)) {
State point = UnDefType.UNDEF;
- if (naThing instanceof Home) {
- point = ((Home) naThing).getLocation();
- } else if (naThing instanceof Device) {
- point = ((Device) naThing).getPlace().map(place -> place.getLocation()).orElse(point);
+ if (naThing instanceof Home home) {
+ point = home.getLocation();
+ } else if (naThing instanceof Device device) {
+ point = device.getPlace().map(place -> place.getLocation()).orElse(point);
}
return point;
}
@Override
protected @Nullable State internalGetProperty(String channelId, NAThing naThing, Configuration config) {
- if (naThing instanceof HomeDataPerson) {
- HomeDataPerson person = (HomeDataPerson) naThing;
+ if (naThing instanceof HomeDataPerson person) {
switch (channelId) {
case CHANNEL_PERSON_AVATAR_URL:
return toStringType(person.getUrl().orElse(null));
return toRawType(person.getUrl().orElse(null));
}
}
- if (naThing instanceof HomeStatusPerson) {
- HomeStatusPerson person = (HomeStatusPerson) naThing;
+ if (naThing instanceof HomeStatusPerson person) {
switch (channelId) {
case CHANNEL_PERSON_AT_HOME:
return OnOffType.from(person.atHome());
@Override
protected @Nullable State internalGetObject(String channelId, NAObject naObject) {
- if (naObject instanceof Room) {
- Room room = (Room) naObject;
+ if (naObject instanceof Room room) {
switch (channelId) {
case CHANNEL_ROOM_WINDOW_OPEN:
return room.hasOpenedWindows();
@Override
protected @Nullable State internalGetObject(String channelId, NAObject naObject) {
- if (naObject instanceof Room) {
- Room room = (Room) naObject;
+ if (naObject instanceof Room room) {
switch (channelId) {
case CHANNEL_SETPOINT_MODE:
return toStringType(room.getSetpointMode().name());
@Override
protected @Nullable State internalGetProperty(String channelId, NAThing naThing, Configuration config) {
- return (naThing instanceof HomeStatusModule && CHANNEL_THERM_RELAY.equals(channelId))
- ? ((HomeStatusModule) naThing).getBoilerStatus()
+ return (naThing instanceof HomeStatusModule homeStatusModule && CHANNEL_THERM_RELAY.equals(channelId))
+ ? homeStatusModule.getBoilerStatus()
: null;
}
}
public static @Nullable QuantityType<?> commandToQuantity(Command command, MeasureClass measureClass) {
Measure measureDef = measureClass.measureDefinition;
- if (command instanceof QuantityType<?>) {
- return ((QuantityType<?>) command).toUnit(measureDef.unit);
+ if (command instanceof QuantityType<?> quantityCommand) {
+ return quantityCommand.toUnit(measureDef.unit);
}
try {
double value = Double.parseDouble(command.toString());
@Test
public void testWebHookEvent() throws NetatmoException {
- String event = "{" + " \"user_id\": \"5c810xxxxxxx45f4\"," + " \"snapshot_id\": \"5d19bxxxxxx6380342\","
- + " \"snapshot_key\": \"f0134210ff83fxxxxxxxf770090a423d9a5\","
- + " \"snapshot_url\": \"https://netatmocameraimage.blob.core.windows.net/production/5d1xxxa5\","
- + " \"event_type\": \"movement\"," + " \"camera_id\": \"70:exxxxxdd:a7\","
- + " \"device_id\": \"70:exxxxdd:a7\"," + " \"home_id\": \"5c5d79xxxx08cd594\","
- + " \"home_name\": \"Boulogne Billan.\"," + " \"event_id\": \"5d19baae369359e896380341\","
- + " \"message\": \"Boulogne Billan: Movement detected by Indoor Camera\","
- + " \"push_type\": \"NACamera-movement\"" + "}";
+ String event = """
+ {\
+ "user_id": "5c810xxxxxxx45f4",\
+ "snapshot_id": "5d19bxxxxxx6380342",\
+ "snapshot_key": "f0134210ff83fxxxxxxxf770090a423d9a5",\
+ "snapshot_url": "https://netatmocameraimage.blob.core.windows.net/production/5d1xxxa5",\
+ "event_type": "movement",\
+ "camera_id": "70:exxxxxdd:a7",\
+ "device_id": "70:exxxxdd:a7",\
+ "home_id": "5c5d79xxxx08cd594",\
+ "home_name": "Boulogne Billan.",\
+ "event_id": "5d19baae369359e896380341",\
+ "message": "Boulogne Billan: Movement detected by Indoor Camera",\
+ "push_type": "NACamera-movement"\
+ }\
+ """;
WebhookEvent object = gson.deserialize(WebhookEvent.class, event);
assertEquals(object.getEventType(), EventType.MOVEMENT);
}
@Test
public void testDashboardData() throws NetatmoException {
- String dashboard = "{time_utc:1623160336,Temperature:22.1,CO2:511,"
- + "Humidity:66,Noise:36,Pressure:1026.1,AbsolutePressure:1009.3,"
- + "min_temp:20,max_temp:22.4,date_max_temp:1623147932,"
- + "Sdate_min_temp:1623125249,pressure_trend:\"nonexistent\",temp_trend:\"stable\"}";
+ String dashboard = """
+ {time_utc:1623160336,Temperature:22.1,CO2:511,\
+ Humidity:66,Noise:36,Pressure:1026.1,AbsolutePressure:1009.3,\
+ min_temp:20,max_temp:22.4,date_max_temp:1623147932,\
+ Sdate_min_temp:1623125249,pressure_trend:"nonexistent",temp_trend:"stable"}\
+ """;
Dashboard object = gson.deserialize(Dashboard.class, dashboard);
assertEquals(511, object.getCo2(), 0);
assertEquals(TrendDescription.UNKNOWN, object.getPressureTrend());
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof NetworkHandler) {
- this.handler = (NetworkHandler) handler;
+ if (handler instanceof NetworkHandler networkHandler) {
+ this.handler = networkHandler;
}
}
public static ThingUID createServiceUID(String ip, int tcpPort) {
// uid must not contains dots
- return new ThingUID(SERVICE_DEVICE, ip.replace('.', '_') + "_" + String.valueOf(tcpPort));
+ return new ThingUID(SERVICE_DEVICE, ip.replace('.', '_') + "_" + tcpPort);
}
/**
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.Collection;
-import java.util.Collections;
+import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.TimeZone;
import org.eclipse.jdt.annotation.NonNullByDefault;
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "No port configured!");
return;
}
- presenceDetection.setServicePorts(Collections.singleton(port));
+ presenceDetection.setServicePorts(Set.of(port));
} else {
// It does not harm to send an additional UDP packet to a device,
// therefore we assume all ping devices are iOS devices. If this
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singletonList(NetworkActions.class);
+ return List.of(NetworkActions.class);
}
public void sendWakeOnLanPacketViaIp() {
return IpPingMethodEnum.JAVA_PING;
} else {
os = os.toLowerCase();
- if (os.indexOf("win") >= 0) {
+ if (os.contains("win")) {
method = IpPingMethodEnum.WINDOWS_PING;
- } else if (os.indexOf("mac") >= 0) {
+ } else if (os.contains("mac")) {
method = IpPingMethodEnum.MAC_OS_PING;
- } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") >= 0) {
+ } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
method = IpPingMethodEnum.IPUTILS_LINUX_PING;
} else {
// We cannot estimate the command line for any other operating system and just return false
import java.io.IOException;
import java.net.UnknownHostException;
-import java.util.Collections;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
@BeforeEach
public void setUp() throws UnknownHostException {
// Mock an interface
- when(networkUtils.getInterfaceNames()).thenReturn(Collections.singleton("TESTinterface"));
+ when(networkUtils.getInterfaceNames()).thenReturn(Set.of("TESTinterface"));
doReturn(ArpPingUtilEnum.IPUTILS_ARPING).when(networkUtils).determineNativeARPpingMethod(anyString());
doReturn(IpPingMethodEnum.WINDOWS_PING).when(networkUtils).determinePingMethod();
subject.setTimeout(300);
subject.setUseDhcpSniffing(false);
subject.setIOSDevice(true);
- subject.setServicePorts(Collections.singleton(1010));
+ subject.setServicePorts(Set.of(1010));
subject.setUseArpPing(true, "arping", ArpPingUtilEnum.IPUTILS_ARPING);
subject.setUseIcmpPing(true);
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
-import java.util.Collections;
+import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
// TCP device
when(value.isPingReachable()).thenReturn(false);
when(value.isTCPServiceReachable()).thenReturn(true);
- when(value.getReachableTCPports()).thenReturn(Collections.singletonList(1010));
+ when(value.getReachableTCPports()).thenReturn(List.of(1010));
d.partialDetectionResult(value);
verify(listener).thingDiscovered(any(), result.capture());
DiscoveryResult dresult = result.getValue();
@Override
public void setThingHandler(@Nullable final ThingHandler handler) {
- if (handler instanceof NUTHandler) {
+ if (handler instanceof NUTHandler nutHandler) {
this.handler = handler;
- ((NUTHandler) handler).setChannelTypeProvider(this);
+ nutHandler.setChannelTypeProvider(this);
}
}
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(NUTChannelTypeProvider.class);
+ return Set.of(NUTChannelTypeProvider.class);
}
public void setChannelTypeProvider(final NUTChannelTypeProvider channelTypeProvider) {
import static org.openhab.binding.networkupstools.internal.NUTBindingConstants.THING_TYPE_UPS;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.networkupstools", service = ThingHandlerFactory.class)
public class NUTHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_UPS);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_UPS);
@Override
public boolean supportsThingType(final ThingTypeUID thingTypeUID) {
int b;
// wait first byte (blocking)
if ((b = in.read()) > -1) {
- byte d[] = new byte[] { (byte) b };
+ byte[] d = new byte[] { (byte) b };
os.write(d);
// read rest of the available bytes
logger.debug("Read queue: {}, Write queue: {}", readQueue.size(), writeQueue.size());
}
Thread.sleep(800);
-
} catch (InterruptedException e) {
}
}
public void sendDatagram(NibeHeatPumpMessage msg) throws NibeHeatPumpException {
logger.debug("Sending request: {}", msg.toHexString());
- byte data[] = msg.decodeMessage();
+ byte[] data = msg.decodeMessage();
int port = -1;
if (msg instanceof ModbusWriteRequestMessage) {
if (command instanceof DecimalType || command instanceof QuantityType || command instanceof StringType) {
BigDecimal v;
- if (command instanceof DecimalType) {
- v = ((DecimalType) command).toBigDecimal();
- } else if (command instanceof QuantityType) {
- v = ((QuantityType) command).toBigDecimal();
+ if (command instanceof DecimalType decimalCommand) {
+ v = decimalCommand.toBigDecimal();
+ } else if (command instanceof QuantityType quantityCommand) {
+ v = quantityCommand.toBigDecimal();
} else {
v = new BigDecimal(command.toString());
}
updateStatus(ThingStatus.ONLINE);
- if (msg instanceof ModbusReadResponseMessage) {
- handleReadResponseMessage((ModbusReadResponseMessage) msg);
- } else if (msg instanceof ModbusWriteResponseMessage) {
- handleWriteResponseMessage((ModbusWriteResponseMessage) msg);
- } else if (msg instanceof ModbusDataReadOutMessage) {
- handleDataReadOutMessage((ModbusDataReadOutMessage) msg);
+ if (msg instanceof ModbusReadResponseMessage readResponseMessage) {
+ handleReadResponseMessage(readResponseMessage);
+ } else if (msg instanceof ModbusWriteResponseMessage writeResponseMessage) {
+ handleWriteResponseMessage(writeResponseMessage);
+ } else if (msg instanceof ModbusDataReadOutMessage dataReadOutMessage) {
+ handleDataReadOutMessage(dataReadOutMessage);
} else {
logger.debug("Received unknown message: {}", msg.toString());
}
logger.trace("Value did not change, ignoring update");
} else {
final String channelPrefix = (variableInfo.type == Type.SETTING ? "setting#" : "sensor#");
- final String channelId = channelPrefix + String.valueOf(coilAddress);
+ final String channelId = channelPrefix + coilAddress;
final String acceptedItemType = thing.getChannel(channelId).getAcceptedItemType();
logger.trace("AcceptedItemType for channel {} = {}", channelId, acceptedItemType);
//@formatter:off
final String strTestData =
// RMU40 message, acknowledge should be send
- "5C001962189600E1010200000000800000000000020914340001000005B8"
- // RMU40 message, CRC failure, negative acknowledge should be send
- + "5C001962189600E1010200000000800000000000020914340001000005B9"
- // MODBUS40 write request
- + "5C00206B004B"
- // nonsense
- + "3EAABB"
- // MODBUS40 read request
- + "5C0020690049"
- // nonsense
- + "F0561939F6"
- // MODBUS40 data read out, acknowledge should be send
- + "5C00206850449C9600489C88014C9C2D014E9CCF004D9CE0014F9C3200509C0400519C8201529C6B02569C3E00C9AF000001A8F600FDA77E02FAA90F0098A9DC27FFFF0000A0A93A04FFFF00009CA9FD19FFFF000081"
- // nonsense
- + "F0349823"
- // MODBUS40 data read out, CRC failure, negative acknowledge should be send
- + "5C00206850449C9600489C88014C9C2D014E9CCF004D9CE0014F9C3200509C0400519C8201529C6B02569C3E00C9AF000001A8F600FDA77E02FAA90F0098A9DC27FFFF0000A0A93A04FFFF00009CA9FD19FFFF000080"
- // RMU40 message, acknowledge should be send
- + "5C001962189600DF01020000000080000000000002091434000100000586"
- // nonsense
- + "123490"
- // unknown RMU40 message, acknowledge should be send
- + "5C0019600079"
- // MODBUS40 data read out, special len, acknowledge should be send
- + "5C00206851449C2500489CFC004C9CF1004E9CC7014D9C0B024F9C2500509C3300519C0B01529C5C5C01569C3100C9AF000001A80C01FDA716FAFAA9070098A91B1BFFFF0000A0A9CA02FFFF00009CA99212FFFF0000BE"
- // MODBUS40 data read out, special len, acknowledge should be send
- + "5C00206852449C2500489CFE004C9CF2004E9CD4014D9CFB014F9C2500509C3700519C0D01529C5C5C01569C3200C9AF000001A80C01FDA712FAFAA9070098A95C5C1BFFFF0000A0A9D102FFFF00009CA9B412FFFF00007F"
- // MODBUS40 data read out, special checksum, acknowledge should be send
- + "5C00206850449C2600489CF6004C9CF1004E9CD6014D9C0C024F9C4500509C3F00519CF100529C0401569CD500C9AF000001A80C01FDA799FAFAA9020098A91A1BFFFF0000A0A9CA02FFFF00009CA99212FFFF0000C5"
- // 16-bit address (e.g. model F2120 heatpumps), acknowledge should be send
- + "5C41C9F7007F";
+ """
+ 5C001962189600E1010200000000800000000000020914340001000005B8\
+ 5C001962189600E1010200000000800000000000020914340001000005B9\
+ 5C00206B004B\
+ 3EAABB\
+ 5C0020690049\
+ F0561939F6\
+ 5C00206850449C9600489C88014C9C2D014E9CCF004D9CE0014F9C3200509C0400519C8201529C6B02569C3E00C9AF000001A8F600FDA77E02FAA90F0098A9DC27FFFF0000A0A93A04FFFF00009CA9FD19FFFF000081\
+ F0349823\
+ 5C00206850449C9600489C88014C9C2D014E9CCF004D9CE0014F9C3200509C0400519C8201529C6B02569C3E00C9AF000001A8F600FDA77E02FAA90F0098A9DC27FFFF0000A0A93A04FFFF00009CA9FD19FFFF000080\
+ 5C001962189600DF01020000000080000000000002091434000100000586\
+ 123490\
+ 5C0019600079\
+ 5C00206851449C2500489CFC004C9CF1004E9CC7014D9C0B024F9C2500509C3300519C0B01529C5C5C01569C3100C9AF000001A80C01FDA716FAFAA9070098A91B1BFFFF0000A0A9CA02FFFF00009CA99212FFFF0000BE\
+ 5C00206852449C2500489CFE004C9CF2004E9CD4014D9CFB014F9C2500509C3700519C0D01529C5C5C01569C3200C9AF000001A80C01FDA712FAFAA9070098A95C5C1BFFFF0000A0A9D102FFFF00009CA9B412FFFF00007F\
+ 5C00206850449C2600489CF6004C9CF1004E9CD6014D9C0C024F9C4500509C3F00519CF100529C0401569CD500C9AF000001A80C01FDA799FAFAA9020098A91A1BFFFF0000A0A9CA02FFFF00009CA99212FFFF0000C5\
+ 5C41C9F7007F\
+ """;
//@formatter:on
// create byte data from hex string
private String extractValue(Command command) {
// this is necessary because we must not send the unit to the nibe backend
- if (command instanceof QuantityType<?>) {
- return String.valueOf(((QuantityType<?>) command).doubleValue());
- } else if (command instanceof OnOffType) {
- return ChannelUtil.mapValue(channel, (OnOffType) command);
+ if (command instanceof QuantityType<?> quantityCommand) {
+ return String.valueOf(quantityCommand.doubleValue());
+ } else if (command instanceof OnOffType onOffCommand) {
+ return ChannelUtil.mapValue(channel, onOffCommand);
} else {
return command.toString();
}
import static org.openhab.binding.nikobus.internal.NikobusBindingConstants.*;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
private @Nullable NikobusPcLinkHandler bridgeHandler;
public NikobusDiscoveryService() throws IllegalArgumentException {
- super(Collections.singleton(THING_TYPE_PUSH_BUTTON), 0);
+ super(Set.of(THING_TYPE_PUSH_BUTTON), 0);
}
@Override
@Override
public void setThingHandler(ThingHandler handler) {
- if (handler instanceof NikobusPcLinkHandler) {
- bridgeHandler = (NikobusPcLinkHandler) handler;
+ if (handler instanceof NikobusPcLinkHandler pcLinkHandler) {
+ bridgeHandler = pcLinkHandler;
}
}
@Override
protected int valueFromCommand(String channelId, Command command) {
- if (command instanceof PercentType) {
- return Math.round(((PercentType) command).floatValue() / 100f * 255f);
+ if (command instanceof PercentType percentCommand) {
+ return Math.round(percentCommand.floatValue() / 100f * 255f);
}
return super.valueFromCommand(channelId, command);
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(NikobusDiscoveryService.class);
+ return Set.of(NikobusDiscoveryService.class);
}
private void processReceivedValue(byte value) {
}
ThingHandler thingHandler = thing.getHandler();
- if (thingHandler instanceof NikobusModuleHandler) {
- return (NikobusModuleHandler) thingHandler;
+ if (thingHandler instanceof NikobusModuleHandler nikobusModuleHandler) {
+ return nikobusModuleHandler;
}
return null;
}
}
SwitchModuleGroup getGroup() {
- if (getSegment(2).equals("1")) {
+ if ("1".equals(getSegment(2))) {
return FIRST;
}
- if (getSegment(2).equals("2")) {
+ if ("2".equals(getSegment(2))) {
return SECOND;
}
throw new IllegalArgumentException("Unexpected group found " + getSegment(2));
@Override
protected int valueFromCommand(String channelId, Command command) {
Optional<PositionEstimator> positionEstimator = getPositionEstimator(channelId);
- if (command instanceof DecimalType) {
- return positionEstimator.map(estimator -> {
- return estimator.processSetPosition(((DecimalType) command).intValue());
- }).orElseThrow(() -> {
- throw new IllegalArgumentException(
- "Received position request but no estimation configured for channel " + channelId);
- });
+ if (command instanceof DecimalType decimalCommand) {
+ return positionEstimator.map(estimator -> estimator.processSetPosition(decimalCommand.intValue()))
+ .orElseThrow(() -> {
+ throw new IllegalArgumentException(
+ "Received position request but no estimation configured for channel " + channelId);
+ });
}
int result = convertCommandToValue(channelId, command);
positionEstimator.ifPresent(PositionEstimator::cancelStopMovement);
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof NikoHomeControlBridgeHandler) {
- this.handler = (NikoHomeControlBridgeHandler) handler;
+ if (handler instanceof NikoHomeControlBridgeHandler homeControlBridgeHandler) {
+ this.handler = homeControlBridgeHandler;
bridgeUID = handler.getThing().getUID();
}
}
return;
}
- if (command instanceof OnOffType) {
- OnOffType s = (OnOffType) command;
- if (OnOffType.OFF.equals(s)) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (OnOffType.OFF.equals(onOffCommand)) {
nhcAction.execute(NHCOFF);
} else {
nhcAction.execute(NHCON);
return;
}
- if (command instanceof OnOffType) {
- OnOffType s = (OnOffType) command;
- if (OnOffType.OFF.equals(s)) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (OnOffType.OFF.equals(onOffCommand)) {
nhcAction.execute(NHCOFF);
} else {
nhcAction.execute(NHCON);
}
- } else if (command instanceof IncreaseDecreaseType) {
- IncreaseDecreaseType s = (IncreaseDecreaseType) command;
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
int currentValue = nhcAction.getState();
int newValue;
- if (IncreaseDecreaseType.INCREASE.equals(s)) {
+ if (IncreaseDecreaseType.INCREASE.equals(increaseDecreaseCommand)) {
newValue = currentValue + stepValue;
// round down to step multiple
newValue = newValue - newValue % stepValue;
nhcAction.execute(Integer.toString(newValue));
}
}
- } else if (command instanceof PercentType) {
- PercentType p = (PercentType) command;
- if (PercentType.ZERO.equals(p)) {
+ } else if (command instanceof PercentType percentCommand) {
+ if (PercentType.ZERO.equals(percentCommand)) {
nhcAction.execute(NHCOFF);
} else {
- nhcAction.execute(Integer.toString(p.intValue()));
+ nhcAction.execute(Integer.toString(percentCommand.intValue()));
}
}
}
return;
}
- if (command instanceof UpDownType) {
- UpDownType s = (UpDownType) command;
- if (UpDownType.UP.equals(s)) {
+ if (command instanceof UpDownType upDownCommand) {
+ if (UpDownType.UP.equals(upDownCommand)) {
nhcAction.execute(!invert ? NHCUP : NHCDOWN);
} else {
nhcAction.execute(!invert ? NHCDOWN : NHCUP);
}
} else if (command instanceof StopMoveType) {
nhcAction.execute(NHCSTOP);
- } else if (command instanceof PercentType) {
- PercentType p = (PercentType) command;
- nhcAction.execute(!invert ? Integer.toString(100 - p.intValue()) : Integer.toString(p.intValue()));
+ } else if (command instanceof PercentType percentCommand) {
+ nhcAction.execute(!invert ? Integer.toString(100 - percentCommand.intValue())
+ : Integer.toString(percentCommand.intValue()));
}
}
properties.put("timeToClose", String.valueOf(nhcAction.getCloseTime()));
}
- if (nhcAction instanceof NhcAction2) {
- NhcAction2 action = (NhcAction2) nhcAction;
+ if (nhcAction instanceof NhcAction2 action) {
properties.put(PROPERTY_DEVICE_TYPE, action.getDeviceType());
properties.put(PROPERTY_DEVICE_TECHNOLOGY, action.getDeviceTechnology());
properties.put(PROPERTY_DEVICE_MODEL, action.getDeviceModel());
private void updateProperties(NhcEnergyMeter nhcEnergyMeter) {
Map<String, String> properties = new HashMap<>();
- if (nhcEnergyMeter instanceof NhcEnergyMeter2) {
- NhcEnergyMeter2 energyMeter = (NhcEnergyMeter2) nhcEnergyMeter;
+ if (nhcEnergyMeter instanceof NhcEnergyMeter2 energyMeter) {
properties.put(PROPERTY_DEVICE_TYPE, energyMeter.getDeviceType());
properties.put(PROPERTY_DEVICE_TECHNOLOGY, energyMeter.getDeviceTechnology());
properties.put(PROPERTY_DEVICE_MODEL, energyMeter.getDeviceModel());
updateStatus(ThingStatus.ONLINE);
break;
case CHANNEL_MODE:
- if (command instanceof DecimalType) {
- nhcThermostat.executeMode(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ nhcThermostat.executeMode(decimalCommand.intValue());
}
updateStatus(ThingStatus.ONLINE);
break;
if (time <= 0) {
time = overruleTime;
}
- if (command instanceof QuantityType<?>) {
- QuantityType<?> setpoint = ((QuantityType<?>) command).toUnit(CELSIUS);
+ if (command instanceof QuantityType<?> quantityCommand) {
+ QuantityType<?> setpoint = quantityCommand.toUnit(CELSIUS);
if (setpoint != null) {
nhcThermostat.executeOverrule(Math.round(setpoint.floatValue() * 10), time);
}
- } else if (command instanceof DecimalType) {
- BigDecimal setpoint = ((DecimalType) command).toBigDecimal();
+ } else if (command instanceof DecimalType decimalCommand) {
+ BigDecimal setpoint = decimalCommand.toBigDecimal();
nhcThermostat.executeOverrule(Math.round(setpoint.floatValue() * 10), time);
}
updateStatus(ThingStatus.ONLINE);
break;
case CHANNEL_OVERRULETIME:
- if (command instanceof DecimalType) {
- int overruletime = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ int overruletime = decimalCommand.intValue();
int overrule = nhcThermostat.getOverrule();
if (overruletime <= 0) {
overruletime = 0;
private void updateProperties(NhcThermostat nhcThermostat) {
Map<String, String> properties = new HashMap<>();
- if (nhcThermostat instanceof NhcThermostat2) {
- NhcThermostat2 thermostat = (NhcThermostat2) nhcThermostat;
+ if (nhcThermostat instanceof NhcThermostat2 thermostat) {
properties.put(PROPERTY_DEVICE_TYPE, thermostat.getDeviceType());
properties.put(PROPERTY_DEVICE_TECHNOLOGY, thermostat.getDeviceTechnology());
properties.put(PROPERTY_DEVICE_MODEL, thermostat.getDeviceModel());
public class NikoHomeControlConstants {
// Action types abstracted from NhcI and NhcII action types
- public static enum ActionType {
+ public enum ActionType {
TRIGGER,
RELAY,
DIMMER,
private MqttMessageSubscriber messageSubscriber;
private MqttConnectionObserver connectionObserver;
- private TrustManager trustManagers[];
+ private TrustManager[] trustManagers;
private String clientId;
private volatile String cocoAddress = "";
if (CHANNEL_HUB_ACTIVE_OVERRIDE_NAME.equals(channelUID.getId())) {
if (ht != null && h != null) {
- if (command instanceof StringType) {
- StringType strCommand = (StringType) command;
- logger.debug("Changing override for hub {} to {}", channelUID, strCommand);
+ if (command instanceof StringType stringCommand) {
+ logger.debug("Changing override for hub {} to {}", channelUID, stringCommand);
try {
- OverrideMode mode = OverrideMode.getByName(strCommand.toFullString());
+ OverrideMode mode = OverrideMode.getByName(stringCommand.toFullString());
ht.getConnection().setOverride(h, mode);
} catch (NoboCommunicationException nce) {
logger.debug("Failed setting override mode", nce);
@Override
protected void removeHandler(ThingHandler thingHandler) {
- if (thingHandler instanceof NoboHubBridgeHandler) {
- unregisterDiscoveryService((NoboHubBridgeHandler) thingHandler);
+ if (thingHandler instanceof NoboHubBridgeHandler bridgeHandler) {
+ unregisterDiscoveryService(bridgeHandler);
}
}
if (CHANNEL_ZONE_COMFORT_TEMPERATURE.equals(channelUID.getId())) {
Zone zone = getZone();
if (zone != null) {
- if (command instanceof DecimalType) {
- DecimalType comfortTemp = (DecimalType) command;
+ if (command instanceof DecimalType comfortTemp) {
logger.debug("Set comfort temp for zone {} to {}", zone.getName(), comfortTemp.doubleValue());
zone.setComfortTemperature(comfortTemp.intValue());
sendCommand(zone.generateCommandString("U00"));
if (CHANNEL_ZONE_ECO_TEMPERATURE.equals(channelUID.getId())) {
Zone zone = getZone();
if (zone != null) {
- if (command instanceof DecimalType) {
- DecimalType ecoTemp = (DecimalType) command;
+ if (command instanceof DecimalType ecoTemp) {
logger.debug("Set eco temp for zone {} to {}", zone.getName(), ecoTemp.doubleValue());
zone.setEcoTemperature(ecoTemp.intValue());
sendCommand(zone.generateCommandString("U00"));
if (CHANNEL_ZONE_ACTIVE_WEEK_PROFILE.equals(channelUID.getId())) {
Zone zone = getZone();
if (zone != null) {
- if (command instanceof DecimalType) {
- DecimalType weekProfileId = (DecimalType) command;
+ if (command instanceof DecimalType weekProfileId) {
logger.debug("Set week profile for zone {} to {}", zone.getName(), weekProfileId);
zone.setWeekProfile(weekProfileId.intValue());
sendCommand(zone.generateCommandString("U00"));
@Override
public void setThingHandler(ThingHandler thingHandler) {
- if (thingHandler instanceof NoboHubBridgeHandler) {
- this.hubBridgeHandler = (NoboHubBridgeHandler) thingHandler;
+ if (thingHandler instanceof NoboHubBridgeHandler bridgeHandler) {
+ this.hubBridgeHandler = bridgeHandler;
}
}
}
public static Hub fromH05(String h05) throws NoboDataException {
- String parts[] = h05.split(" ", 8);
+ String[] parts = h05.split(" ", 8);
if (parts.length != 8) {
throw new NoboDataException(
}
public static Temperature fromY02(String y02) throws NoboDataException {
- String parts[] = y02.split(" ", 3);
+ String[] parts = y02.split(" ", 3);
if (parts.length != 3) {
throw new NoboDataException(
String.format("Unexpected number of parts from hub on Y02 call: %d", parts.length));
}
public static Zone fromH01(String h01) throws NoboDataException {
- String parts[] = h01.split(" ", 8);
+ String[] parts = h01.split(" ", 8);
if (parts.length != 8) {
throw new NoboDataException(
import static org.openhab.binding.novafinedust.internal.NovaFineDustBindingConstants.THING_TYPE_SDS011;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.novafinedust", service = ThingHandlerFactory.class)
public class NovaFineDustHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_SDS011);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_SDS011);
private final SerialPortManager serialPortManager;
*/
public void initialize(WorkMode mode, Duration interval)
throws PortInUseException, TooManyListenersException, IOException, UnsupportedCommOperationException {
-
logger.trace("Initializing with mode={}, interval={}", mode, interval);
SerialPort localSerialPort = portId.open(thingHandler.getThing().getUID().toString(), 2000);
private boolean doRead() throws IOException {
SensorReply reply = readReply();
logger.trace("doRead(): Read reply={}", reply);
- if (reply instanceof SensorMeasuredDataReply) {
- SensorMeasuredDataReply sensorData = (SensorMeasuredDataReply) reply;
+ if (reply instanceof SensorMeasuredDataReply sensorData) {
logger.trace("We received sensor data");
if (sensorData.isValidData()) {
logger.trace("Sensor data is valid => updating channels");
* @return firmware of the sensor formatted as YY-MM-DD
*/
public String getFirmware() {
- String firmware = year + "-" + month + "-" + day;
- return firmware;
+ return year + "-" + month + "-" + day;
}
@Override
*/
package org.openhab.binding.ntp.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
public static final String PROPERTY_DATE_TIME_FORMAT = "DateTimeFormat";
public static final String PROPERTY_NTP_SERVER_PORT = "serverPort";
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_NTP);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_NTP);
}
public void unregisterHandler(Thing thing) {
super.unregisterHandler(thing);
ThingHandler handler = thing.getHandler();
- if (handler instanceof NukiBridgeHandler) {
- nukiApiServlet.remove((NukiBridgeHandler) handler);
+ if (handler instanceof NukiBridgeHandler bridgeHandler) {
+ nukiApiServlet.remove(bridgeHandler);
}
}
*/
package org.openhab.binding.nuki.internal.constants;
-import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public static final ThingTypeUID THING_TYPE_SMARTLOCK = new ThingTypeUID(BINDING_ID, "smartlock");
public static final ThingTypeUID THING_TYPE_OPENER = new ThingTypeUID(BINDING_ID, "opener");
- public static final Set<ThingTypeUID> THING_TYPE_BRIDGE_UIDS = Collections.singleton(THING_TYPE_BRIDGE);
- public static final Set<ThingTypeUID> THING_TYPE_SMARTLOCK_UIDS = Collections.singleton(THING_TYPE_SMARTLOCK);
- public static final Set<ThingTypeUID> THING_TYPE_OPENER_UIDS = Collections.singleton(THING_TYPE_OPENER);
+ public static final Set<ThingTypeUID> THING_TYPE_BRIDGE_UIDS = Set.of(THING_TYPE_BRIDGE);
+ public static final Set<ThingTypeUID> THING_TYPE_SMARTLOCK_UIDS = Set.of(THING_TYPE_SMARTLOCK);
+ public static final Set<ThingTypeUID> THING_TYPE_OPENER_UIDS = Set.of(THING_TYPE_OPENER);
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Stream
.of(THING_TYPE_BRIDGE_UIDS, THING_TYPE_SMARTLOCK_UIDS, THING_TYPE_OPENER_UIDS).flatMap(Set::stream)
private NukiBaseResponse handleException(Exception e) {
if (e instanceof ExecutionException) {
Throwable cause = e.getCause();
- if (cause instanceof HttpResponseException) {
- HttpResponseException causeException = (HttpResponseException) cause;
+ if (cause instanceof HttpResponseException causeException) {
int status = causeException.getResponse().getStatus();
String reason = causeException.getResponse().getReason();
logger.debug("HTTP Response Exception! Status[{}] - Reason[{}]! Check your API Token!", status, reason);
*/
package org.openhab.binding.nuki.internal.discovery;
-import java.util.Collections;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jetty.client.HttpClient;
@Activate
public NukiBridgeDiscoveryService(@Reference final HttpClientFactory httpClientFactory,
@Reference final ThingRegistry thingRegistry) {
- super(Collections.singleton(NukiBindingConstants.THING_TYPE_BRIDGE), 30, false);
+ super(Set.of(NukiBindingConstants.THING_TYPE_BRIDGE), 30, false);
this.httpClient = httpClientFactory.getCommonHttpClient();
this.thingRegistry = thingRegistry;
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof NukiBridgeHandler) {
- bridge = (NukiBridgeHandler) handler;
+ if (handler instanceof NukiBridgeHandler bridgeHandler) {
+ bridge = bridgeHandler;
}
}
}
private void initializeHandler(@Nullable ThingHandler handler, @Nullable ThingStatus bridgeStatus) {
- if (handler instanceof NukiBridgeHandler && bridgeStatus != null) {
- NukiBridgeHandler bridgeHandler = (NukiBridgeHandler) handler;
+ if (handler instanceof NukiBridgeHandler bridgeHandler && bridgeStatus != null) {
if (bridgeStatus == ThingStatus.ONLINE) {
this.nukiHttpClient = bridgeHandler.getNukiHttpClient();
withHttpClient(client -> {
}
}
+ @Override
protected void triggerChannel(String channelId, String event) {
Channel channel = thing.getChannel(channelId);
if (channel != null) {
Bridge bridge = getBridge();
if (bridge != null) {
BridgeHandler bridgeHandler = bridge.getHandler();
- if (bridgeHandler instanceof NukiBridgeHandler) {
- scheduler.execute(() -> handler.accept((NukiBridgeHandler) bridgeHandler));
+ if (bridgeHandler instanceof NukiBridgeHandler nukiBridgeHandler) {
+ scheduler.execute(() -> handler.accept(nukiBridgeHandler));
}
}
}
import java.util.Collection;
import java.util.Collections;
import java.util.List;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(NukiDeviceDiscoveryService.class);
+ return Set.of(NukiDeviceDiscoveryService.class);
}
private synchronized void initializeHandler() {
public void checkBridgeOnline() {
logger.debug("checkBridgeOnline():bridgeIp[{}] status[{}]", this.config.ip, getThing().getStatus());
if (getThing().getStatus().equals(ThingStatus.ONLINE)) {
-
withHttpClient(client -> {
logger.debug("Requesting BridgeInfo to ensure Bridge[{}] is online.", this.config.ip);
BridgeInfoResponse bridgeInfoResponse = client.getBridgeInfo();
protected boolean doHandleCommand(ChannelUID channelUID, Command command) {
switch (channelUID.getId()) {
case NukiBindingConstants.CHANNEL_OPENER_STATE:
- if (command instanceof DecimalType) {
- OpenerAction action = OpenerAction.fromAction(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ OpenerAction action = OpenerAction.fromAction(decimalCommand.intValue());
if (action != null) {
return withHttpClient(client -> {
BridgeLockActionResponse response = client.getOpenerAction(configuration.nukiId, action);
}
break;
case NukiBindingConstants.CHANNEL_SMARTLOCK_STATE:
- if (command instanceof DecimalType) {
- DecimalType cmd = (DecimalType) command;
- SmartLockAction action = SmartLockAction.fromAction(cmd.intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ SmartLockAction action = SmartLockAction.fromAction(decimalCommand.intValue());
if (action != null) {
withHttpClient(client -> {
BridgeLockActionResponse bridgeLockActionResponse = client
import static org.openhab.binding.nuvo.internal.NuvoBindingConstants.*;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.nuvo", service = ThingHandlerFactory.class)
public class NuvoHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_AMP);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_AMP);
private final SerialPortManager serialPortManager;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
-import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
// Also add any openHAB NuvoNet source favorites to the list
for (int src = 1; src <= MAX_SRC; src++) {
- NuvoEnum source = NuvoEnum.valueOf(SOURCE + String.valueOf(src));
+ NuvoEnum source = NuvoEnum.valueOf(SOURCE + src);
String[] favorites = favoriteMap.get(source);
if (favorites != null) {
for (int fav = 0; fav < favorites.length; fav++) {
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singletonList(NuvoThingActions.class);
+ return List.of(NuvoThingActions.class);
}
public void handleRawCommand(String command) {
}
break;
case CHANNEL_TYPE_SOURCE:
- if (command instanceof DecimalType) {
- int value = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ int value = decimalCommand.intValue();
if (value >= 1 && value <= MAX_SRC) {
logger.debug("Got source command {} zone {}", value, target);
connector.sendCommand(target, NuvoCommand.SOURCE, String.valueOf(value));
}
break;
case CHANNEL_TYPE_FAVORITE:
- if (command instanceof DecimalType) {
- int value = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ int value = decimalCommand.intValue();
if (value >= 1 && value <= MAX_FAV) {
logger.debug("Got favorite command {} zone {}", value, target);
connector.sendCommand(target, NuvoCommand.FAVORITE, String.valueOf(value));
}
break;
case CHANNEL_TYPE_VOLUME:
- if (command instanceof PercentType) {
+ if (command instanceof PercentType percentCommand) {
int value = (MAX_VOLUME
- - (int) Math.round(
- ((PercentType) command).doubleValue() / 100.0 * (MAX_VOLUME - MIN_VOLUME))
+ - (int) Math.round(percentCommand.doubleValue() / 100.0 * (MAX_VOLUME - MIN_VOLUME))
+ MIN_VOLUME);
logger.debug("Got volume command {} zone {}", value, target);
connector.sendCommand(target, NuvoCommand.VOLUME, String.valueOf(value));
}
break;
case CHANNEL_TYPE_TREBLE:
- if (command instanceof DecimalType) {
- int value = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ int value = decimalCommand.intValue();
if (value >= MIN_EQ && value <= MAX_EQ) {
// device can only accept even values
if (value % 2 == 1) {
}
break;
case CHANNEL_TYPE_BASS:
- if (command instanceof DecimalType) {
- int value = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ int value = decimalCommand.intValue();
if (value >= MIN_EQ && value <= MAX_EQ) {
if (value % 2 == 1) {
value++;
}
break;
case CHANNEL_TYPE_BALANCE:
- if (command instanceof DecimalType) {
- int value = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ int value = decimalCommand.intValue();
if (value >= MIN_EQ && value <= MAX_EQ) {
if (value % 2 == 1) {
value++;
import static org.openhab.binding.nzwateralerts.internal.NZWaterAlertsBindingConstants.*;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
public class NZWaterAlertsHandlerFactory extends BaseThingHandlerFactory {
private final HttpClient httpClient;
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_WATERALERT);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_WATERALERT);
@Activate
public NZWaterAlertsHandlerFactory(final @Reference HttpClientFactory httpClientFactory) {
}
}
}
-
}
} catch (IOException e) {
logger.debug("An exception occurred while quering host {}:{} : '{}'", config.ipAddress,
SerialOceanicBindingConfiguration config = getConfigAs(SerialOceanicBindingConfiguration.class);
if (serialPort == null && config.port != null) {
-
SerialPortIdentifier portIdentifier = serialPortManager.getIdentifier(config.port);
if (portIdentifier == null) {
}
long timeStamp = System.currentTimeMillis();
- while (lastLineReceived.equals("")) {
+ while ("".equals(lastLineReceived)) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
@Override
protected @Nullable ThingHandler createHandler(Thing thing) {
if (SUPPORTED_THING_TYPES_UIDS.contains(thing.getThingTypeUID())) {
- OJCloudHandler handler = new OJCloudHandler((Bridge) thing, httpClient);
- return handler;
+ return new OJCloudHandler((Bridge) thing, httpClient);
}
return null;
}
}
private void updateManualSetpoint(Command command) {
- if (command instanceof QuantityType<?>) {
- getCurrentThermostat().manualModeSetpoint = (int) (((QuantityType<?>) command).floatValue() * 100);
+ if (command instanceof QuantityType<?> quantityCommand) {
+ getCurrentThermostat().manualModeSetpoint = (int) (quantityCommand.floatValue() * 100);
} else {
logger.warn("Unable to set value {}", command);
}
}
private void updateBoostEndTime(Command command) {
- if (command instanceof DateTimeType) {
- getCurrentThermostat().boostEndTime = Date.from(((DateTimeType) command).getZonedDateTime().toInstant());
+ if (command instanceof DateTimeType dateTimeCommand) {
+ getCurrentThermostat().boostEndTime = Date.from(dateTimeCommand.getZonedDateTime().toInstant());
} else {
logger.warn("Unable to set value {}", command);
}
}
private void updateComfortEndTime(Command command) {
- if (command instanceof DateTimeType) {
+ if (command instanceof DateTimeType dateTimeCommand) {
getCurrentThermostat().comfortEndTime = Objects
- .requireNonNull(Date.from(((DateTimeType) command).getZonedDateTime().toInstant()));
+ .requireNonNull(Date.from(dateTimeCommand.getZonedDateTime().toInstant()));
} else {
logger.warn("Unable to set value {}", command);
}
}
private void updateComfortSetpoint(Command command) {
- if (command instanceof QuantityType<?>) {
- getCurrentThermostat().comfortSetpoint = (int) (((QuantityType<?>) command).floatValue() * 100);
+ if (command instanceof QuantityType<?> quantityCommand) {
+ getCurrentThermostat().comfortSetpoint = (int) (quantityCommand.floatValue() * 100);
} else {
logger.warn("Unable to set value {}", command);
}
}
private void updateVacationBeginDay(Command command) {
- if (command instanceof DateTimeType) {
+ if (command instanceof DateTimeType dateTimeCommand) {
getCurrentThermostat().vacationBeginDay = Date
- .from(((DateTimeType) command).getZonedDateTime().toInstant().truncatedTo(ChronoUnit.DAYS));
+ .from(dateTimeCommand.getZonedDateTime().toInstant().truncatedTo(ChronoUnit.DAYS));
} else {
logger.warn("Unable to set value {}", command);
}
}
private void updateVacationEndDay(Command command) {
- if (command instanceof DateTimeType) {
+ if (command instanceof DateTimeType dateTimeCommand) {
getCurrentThermostat().vacationEndDay = Date
- .from(((DateTimeType) command).getZonedDateTime().toInstant().truncatedTo(ChronoUnit.DAYS));
+ .from(dateTimeCommand.getZonedDateTime().toInstant().truncatedTo(ChronoUnit.DAYS));
} else {
logger.warn("Unable to set value {}", command);
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof OJCloudHandler) {
- final OJCloudHandler bridgeHandler = (OJCloudHandler) handler;
+ if (handler instanceof OJCloudHandler bridgeHandler) {
this.bridgeHandler = bridgeHandler;
bridgeHandler.setDiscoveryService(this);
}
}
private Request createRequest() {
- Request request = httpClient.newRequest(config.getRestApiUrl() + "/Group/GroupContents")
- .param("sessionid", sessionId).param("apiKey", config.apiKey).method(HttpMethod.GET);
- return request;
+ return httpClient.newRequest(config.getRestApiUrl() + "/Group/GroupContents").param("sessionid", sessionId)
+ .param("apiKey", config.apiKey).method(HttpMethod.GET);
}
private void initializationDone(String responseBody) {
if (result.getResponse().getStatus() == 200) {
PostSignInResponseModel signInModel = Objects
.requireNonNull(gson.fromJson(getContentAsString(), PostSignInResponseModel.class));
- if (signInModel.errorCode != 0 || signInModel.sessionId.equals("")) {
+ if (signInModel.errorCode != 0 || "".equals(signInModel.sessionId)) {
unauthorized.run();
return;
}
import static org.openhab.binding.omnikinverter.internal.OmnikInverterBindingConstants.THING_TYPE_OMNIK;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.omnikinverter", service = ThingHandlerFactory.class)
public class OmnikInverterHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_OMNIK);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_OMNIK);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof OmnilinkBridgeHandler) {
- this.handler = (OmnilinkBridgeHandler) handler;
+ if (handler instanceof OmnilinkBridgeHandler bridgeHandler) {
+ this.handler = bridgeHandler;
}
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof OmnilinkBridgeHandler) {
- bridgeHandler = (OmnilinkBridgeHandler) handler;
+ if (handler instanceof OmnilinkBridgeHandler omnilinkBridgeHandler) {
+ bridgeHandler = omnilinkBridgeHandler;
}
}
protected abstract EnumSet<AreaAlarm> getAlarms();
private void handleKeypadEmergency(ChannelUID channelUID, Command command) {
- if (command instanceof DecimalType) {
+ if (command instanceof DecimalType decimalCommand) {
try {
final OmnilinkBridgeHandler bridge = getOmnilinkBridgeHandler();
if (bridge != null) {
- bridge.activateKeypadEmergency(thingID, ((DecimalType) command).intValue());
+ bridge.activateKeypadEmergency(thingID, decimalCommand.intValue());
} else {
logger.debug("Received null bridge while sending Keypad Emergency command!");
}
if (command instanceof RefreshType) {
updateState(CHANNEL_AUDIO_SOURCE_POLLING,
OnOffType.from((scheduledPolling != null && !scheduledPolling.isDone())));
- } else if (command instanceof OnOffType) {
- handlePolling(channelUID, (OnOffType) command);
+ } else if (command instanceof OnOffType onOffCommand) {
+ handlePolling(channelUID, onOffCommand);
} else {
logger.debug("Invalid command: {}, must be RefreshType or OnOffType", command);
}
}
break;
case CHANNEL_AUDIO_ZONE_VOLUME:
- if (command instanceof PercentType) {
- sendOmnilinkCommand(CommandMessage.CMD_AUDIO_ZONE_SET_VOLUME, ((PercentType) command).intValue(),
- thingID);
+ if (command instanceof PercentType percentCommand) {
+ sendOmnilinkCommand(CommandMessage.CMD_AUDIO_ZONE_SET_VOLUME, percentCommand.intValue(), thingID);
} else {
logger.debug("Invalid command: {}, must be PercentType", command);
}
break;
case CHANNEL_AUDIO_ZONE_SOURCE:
- if (command instanceof DecimalType) {
- sendOmnilinkCommand(CommandMessage.CMD_AUDIO_ZONE_SET_SOURCE, ((DecimalType) command).intValue(),
- thingID);
+ if (command instanceof DecimalType decimalCommand) {
+ sendOmnilinkCommand(CommandMessage.CMD_AUDIO_ZONE_SET_SOURCE, decimalCommand.intValue(), thingID);
} else {
logger.debug("Invalid command: {}, must be DecimalType", command);
}
break;
case CHANNEL_AUDIO_ZONE_CONTROL:
- if (command instanceof PlayPauseType) {
- handlePlayPauseCommand(channelUID, (PlayPauseType) command);
- } else if (command instanceof NextPreviousType) {
- handleNextPreviousCommand(channelUID, (NextPreviousType) command);
+ if (command instanceof PlayPauseType playPauseCommand) {
+ handlePlayPauseCommand(channelUID, playPauseCommand);
+ } else if (command instanceof NextPreviousType nextPreviousCommand) {
+ handleNextPreviousCommand(channelUID, nextPreviousCommand);
} else {
logger.debug("Invalid command: {}, must be PlayPauseType or NextPreviousType", command);
}
switch (channelUID.getId()) {
case CHANNEL_CONSOLE_ENABLE_DISABLE_BEEPER:
- if (command instanceof StringType) {
+ if (command instanceof StringType stringCommand) {
sendOmnilinkCommand(CommandMessage.CMD_CONSOLE_ENABLE_DISABLE_BEEPER,
- ((StringType) command).equals(StringType.valueOf("OFF")) ? 0 : 1, thingID);
+ stringCommand.equals(StringType.valueOf("OFF")) ? 0 : 1, thingID);
} else {
logger.debug("Invalid command: {}, must be StringType", command);
}
break;
case CHANNEL_CONSOLE_BEEP:
- if (command instanceof DecimalType) {
- sendOmnilinkCommand(CommandMessage.CMD_CONSOLE_BEEP, ((DecimalType) command).intValue(), thingID);
+ if (command instanceof DecimalType decimalCommand) {
+ sendOmnilinkCommand(CommandMessage.CMD_CONSOLE_BEEP, decimalCommand.intValue(), thingID);
} else {
logger.debug("Invalid command: {}, must be DecimalType", command);
}
switch (channelUID.getId()) {
case CHANNEL_CONSOLE_ENABLE_DISABLE_BEEPER:
- if (command instanceof StringType) {
+ if (command instanceof StringType stringCommand) {
try {
sendOmnilinkCommand(CommandMessage.CMD_CONSOLE_ENABLE_DISABLE_BEEPER,
- ((StringType) command).equals(StringType.valueOf("OFF")) ? 0 : 1, 0);
+ stringCommand.equals(StringType.valueOf("OFF")) ? 0 : 1, 0);
updateState(CHANNEL_CONSOLE_ENABLE_DISABLE_BEEPER, UnDefType.UNDEF);
} catch (NumberFormatException | OmniInvalidResponseException | OmniUnknownMessageTypeException
| BridgeOfflineException e) {
}
break;
case CHANNEL_CONSOLE_BEEP:
- if (command instanceof DecimalType) {
+ if (command instanceof DecimalType decimalCommand) {
try {
- sendOmnilinkCommand(CommandMessage.CMD_CONSOLE_BEEP, ((DecimalType) command).intValue(), 0);
+ sendOmnilinkCommand(CommandMessage.CMD_CONSOLE_BEEP, decimalCommand.intValue(), 0);
updateState(CHANNEL_CONSOLE_BEEP, UnDefType.UNDEF);
} catch (NumberFormatException | OmniInvalidResponseException | OmniUnknownMessageTypeException
| BridgeOfflineException e) {
if (objectStatus != null) {
Status[] statuses = objectStatus.getStatuses();
for (Status status : statuses) {
- if (status instanceof ExtendedUnitStatus) {
- ExtendedUnitStatus unitStatus = (ExtendedUnitStatus) status;
+ if (status instanceof ExtendedUnitStatus unitStatus) {
int unitNumber = unitStatus.getNumber();
logger.debug("Received status update for Unit: {}, status: {}", unitNumber, unitStatus);
Optional<Thing> theThing = getUnitThing(unitNumber);
theThing.map(Thing::getHandler)
.ifPresent(theHandler -> ((UnitHandler) theHandler).handleStatus(unitStatus));
- } else if (status instanceof ExtendedZoneStatus) {
- ExtendedZoneStatus zoneStatus = (ExtendedZoneStatus) status;
+ } else if (status instanceof ExtendedZoneStatus zoneStatus) {
int zoneNumber = zoneStatus.getNumber();
logger.debug("Received status update for Zone: {}, status: {}", zoneNumber, zoneStatus);
Optional<Thing> theThing = getChildThing(THING_TYPE_ZONE, zoneNumber);
theThing.map(Thing::getHandler)
.ifPresent(theHandler -> ((ZoneHandler) theHandler).handleStatus(zoneStatus));
- } else if (status instanceof ExtendedAreaStatus) {
- ExtendedAreaStatus areaStatus = (ExtendedAreaStatus) status;
+ } else if (status instanceof ExtendedAreaStatus areaStatus) {
int areaNumber = areaStatus.getNumber();
logger.debug("Received status update for Area: {}, status: {}", areaNumber, areaStatus);
theThing.map(Thing::getHandler)
.ifPresent(theHandler -> ((AbstractAreaHandler) theHandler).handleStatus(areaStatus));
});
- } else if (status instanceof ExtendedAccessControlReaderLockStatus) {
- ExtendedAccessControlReaderLockStatus lockStatus = (ExtendedAccessControlReaderLockStatus) status;
+ } else if (status instanceof ExtendedAccessControlReaderLockStatus lockStatus) {
int lockNumber = lockStatus.getNumber();
logger.debug("Received status update for Lock: {}, status: {}", lockNumber, lockStatus);
Optional<Thing> theThing = getChildThing(THING_TYPE_LOCK, lockNumber);
theThing.map(Thing::getHandler)
.ifPresent(theHandler -> ((LockHandler) theHandler).handleStatus(lockStatus));
- } else if (status instanceof ExtendedThermostatStatus) {
- ExtendedThermostatStatus thermostatStatus = (ExtendedThermostatStatus) status;
+ } else if (status instanceof ExtendedThermostatStatus thermostatStatus) {
int thermostatNumber = thermostatStatus.getNumber();
logger.debug("Received status update for Thermostat: {}, status: {}", thermostatNumber,
Optional<Thing> theThing = getChildThing(THING_TYPE_THERMOSTAT, thermostatNumber);
theThing.map(Thing::getHandler)
.ifPresent(theHandler -> ((ThermostatHandler) theHandler).handleStatus(thermostatStatus));
- } else if (status instanceof ExtendedAudioZoneStatus) {
- ExtendedAudioZoneStatus audioZoneStatus = (ExtendedAudioZoneStatus) status;
+ } else if (status instanceof ExtendedAudioZoneStatus audioZoneStatus) {
int audioZoneNumber = audioZoneStatus.getNumber();
logger.debug("Received status update for Audio Zone: {}, status: {}", audioZoneNumber,
Optional<Thing> theThing = getChildThing(THING_TYPE_AUDIO_ZONE, audioZoneNumber);
theThing.map(Thing::getHandler)
.ifPresent(theHandler -> ((AudioZoneHandler) theHandler).handleStatus(audioZoneStatus));
- } else if (status instanceof ExtendedAuxSensorStatus) {
- ExtendedAuxSensorStatus auxSensorStatus = (ExtendedAuxSensorStatus) status;
+ } else if (status instanceof ExtendedAuxSensorStatus auxSensorStatus) {
int auxSensorNumber = auxSensorStatus.getNumber();
// Aux Sensors can be either temperature or humidity, need to check both.
}
if (bridgeHandler != null) {
temperatureFormat = bridgeHandler.getTemperatureFormat();
- if (!temperatureFormat.isPresent()) {
+ if (temperatureFormat.isEmpty()) {
logger.warn("Receieved null temperature format!");
return;
}
}
if (bridgeHandler != null) {
temperatureFormat = bridgeHandler.getTemperatureFormat();
- if (!temperatureFormat.isPresent()) {
+ if (temperatureFormat.isEmpty()) {
logger.warn("Receieved null temperature format!");
return;
}
switch (channelUID.getId()) {
case CHANNEL_UNIT_LEVEL:
case CHANNEL_UNIT_SWITCH:
- if (command instanceof OnOffType) {
- handleOnOff(channelUID, (OnOffType) command);
+ if (command instanceof OnOffType onOffCommand) {
+ handleOnOff(channelUID, onOffCommand);
} else {
logger.debug("Invalid command: {}, must be OnOffType", command);
}
case CHANNEL_UNIT_OFF_FOR_MINUTES:
case CHANNEL_UNIT_ON_FOR_HOURS:
case CHANNEL_UNIT_OFF_FOR_HOURS:
- if (command instanceof DecimalType) {
- handleUnitDuration(channelUID, (DecimalType) command);
+ if (command instanceof DecimalType decimalCommand) {
+ handleUnitDuration(channelUID, decimalCommand);
} else {
logger.debug("Invalid command: {}, must be DecimalType", command);
}
private void handleUnitLevel(ChannelUID channelUID, Command command) {
logger.debug("handleUnitLevel called for channel: {}, command: {}", channelUID, command);
- if (command instanceof PercentType) {
- handlePercent(channelUID, (PercentType) command);
- } else if (command instanceof IncreaseDecreaseType) {
- handleIncreaseDecrease(channelUID, (IncreaseDecreaseType) command);
+ if (command instanceof PercentType percentCommand) {
+ handlePercent(channelUID, percentCommand);
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ handleIncreaseDecrease(channelUID, increaseDecreaseCommand);
} else {
// Only handle percent or increase/decrease.
super.handleCommand(channelUID, command);
switch (channelUID.getId()) {
case CHANNEL_FLAG_VALUE:
- if (command instanceof DecimalType) {
- sendOmnilinkCommand(CommandMessage.CMD_UNIT_SET_COUNTER, ((DecimalType) command).intValue(),
- thingID);
+ if (command instanceof DecimalType decimalCommand) {
+ sendOmnilinkCommand(CommandMessage.CMD_UNIT_SET_COUNTER, decimalCommand.intValue(), thingID);
} else {
logger.debug("Invalid command: {}, must be DecimalType", command);
}
break;
case CHANNEL_FLAG_SWITCH:
- if (command instanceof OnOffType) {
- handleOnOff(channelUID, (OnOffType) command);
+ if (command instanceof OnOffType onOffCommand) {
+ handleOnOff(channelUID, onOffCommand);
} else {
logger.debug("Invalid command: {}, must be OnOffType", command);
}
case CHANNEL_ROOM_SCENE_B:
case CHANNEL_ROOM_SCENE_C:
case CHANNEL_ROOM_SCENE_D:
- if (command instanceof OnOffType) {
- handleRoomScene(channelUID, (OnOffType) command);
+ if (command instanceof OnOffType onOffCommand) {
+ handleRoomScene(channelUID, onOffCommand);
} else {
logger.debug("Invalid command: {}, must be OnOffType", command);
}
break;
case CHANNEL_ROOM_SWITCH:
- if (command instanceof OnOffType) {
- super.handleOnOff(channelUID, (OnOffType) command);
+ if (command instanceof OnOffType onOffCommand) {
+ super.handleOnOff(channelUID, onOffCommand);
} else {
logger.debug("Invalid command: {}, must be OnOffType", command);
}
break;
case CHANNEL_ROOM_STATE:
- if (command instanceof DecimalType) {
- handleRoomState(channelUID, (DecimalType) command);
+ if (command instanceof DecimalType decimalCommand) {
+ handleRoomState(channelUID, decimalCommand);
} else {
logger.debug("Invalid command: {}, must be DecimalType", command);
}
Channel channel = callback.getThing().getChannel(CHANNEL_DIGITAL6);
if (channel != null) {
BAE091xPIOConfiguration channelConfig = channel.getConfiguration().as(BAE091xPIOConfiguration.class);
- piocRegister.set(PIOC_DD, channelConfig.mode.equals("output"));
+ piocRegister.set(PIOC_DD, "output".equals(channelConfig.mode));
switch (channelConfig.pulldevice) {
case "pullup" -> {
piocRegister.set(PIOC_PE);
List<State> states = bridgeHandler.readDecimalTypeArray(sensorId, counterParameter);
if (states.size() != 2) {
- throw new OwException("Expected exactly two values, got " + String.valueOf(states.size()));
+ throw new OwException("Expected exactly two values, got " + states.size());
} else {
callback.postUpdate(CHANNEL_COUNTER + "0", states.get(0));
callback.postUpdate(CHANNEL_COUNTER + "1", states.get(1));
if (enabledChannels.contains(CHANNEL_CURRENT)) {
if (currentSensorType == CurrentSensorType.IBUTTONLINK) {
State current = bridgeHandler.readDecimalType(sensorId, voltageParameter);
- if (current instanceof DecimalType) {
- double currentDouble = ((DecimalType) current).doubleValue();
+ if (current instanceof DecimalType decimalCommand) {
+ double currentDouble = decimalCommand.doubleValue();
if (currentDouble >= 0.1 || currentDouble <= 3.78) {
current = new QuantityType<>(currentDouble * 5.163 + 0.483, Units.AMPERE);
}
switch (lightSensorType) {
case ELABNET_V2:
State light = bridgeHandler.readDecimalType(sensorId, currentParamater);
- if (light instanceof DecimalType) {
+ if (light instanceof DecimalType decimalCommand) {
light = new QuantityType<>(
- Math.round(Math.pow(10, ((DecimalType) light).doubleValue() / 47 * 1000)),
- Units.LUX);
+ Math.round(Math.pow(10, decimalCommand.doubleValue() / 47 * 1000)), Units.LUX);
callback.postUpdate(CHANNEL_LIGHT, light);
}
break;
case ELABNET_V1:
light = bridgeHandler.readDecimalType(sensorId, currentParamater);
- if (light instanceof DecimalType) {
- light = new QuantityType<>(Math.round(Math
- .exp(1.059 * Math.log(1000000 * ((DecimalType) light).doubleValue() / (4096 * 390))
- + 4.518)
+ if (light instanceof DecimalType decimalCommand) {
+ light = new QuantityType<>(Math.round(Math.exp(
+ 1.059 * Math.log(1000000 * decimalCommand.doubleValue() / (4096 * 390)) + 4.518)
* 20000), Units.LUX);
callback.postUpdate(CHANNEL_LIGHT, light);
}
@Override
public void setThingHandler(ThingHandler thingHandler) {
- if (thingHandler instanceof OwserverBridgeHandler) {
- this.bridgeHandler = (OwserverBridgeHandler) thingHandler;
+ if (thingHandler instanceof OwserverBridgeHandler serverBridgeHandler) {
+ this.bridgeHandler = serverBridgeHandler;
}
}
import static org.openhab.binding.onewire.internal.OwBindingConstants.*;
import java.nio.charset.StandardCharsets;
-import java.util.Collections;
import java.util.Map;
import java.util.Set;
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_EDS_ENV);
public static final Set<OwSensorType> SUPPORTED_SENSOR_TYPES = Set.of(OwSensorType.EDS0064, OwSensorType.EDS0065,
OwSensorType.EDS0066, OwSensorType.EDS0067, OwSensorType.EDS0068);
- private static final Set<String> REQUIRED_PROPERTIES = Collections.singleton(PROPERTY_HW_REVISION);
+ private static final Set<String> REQUIRED_PROPERTIES = Set.of(PROPERTY_HW_REVISION);
public EDSSensorThingHandler(Thing thing, OwDynamicStateDescriptionProvider dynamicStateDescriptionProvider) {
super(thing, dynamicStateDescriptionProvider, SUPPORTED_SENSOR_TYPES, REQUIRED_PROPERTIES);
properties.put(PROPERTY_MODELID, sensorType.name());
properties.put(PROPERTY_VENDOR, "Embedded Data Systems");
- properties.put(PROPERTY_HW_REVISION, String.valueOf(fwRevision));
+ properties.put(PROPERTY_HW_REVISION, fwRevision);
updateProperties(properties);
}
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
-import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
*/
@NonNullByDefault
public class OwserverBridgeHandler extends BaseBridgeHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_OWSERVER);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_OWSERVER);
private final Logger logger = LoggerFactory.getLogger(OwserverBridgeHandler.class);
protected boolean refreshable = false;
State value;
try {
synchronized (owserverConnection) {
- if (channelConfig.acceptedItemType.equals("String")) {
+ if ("String".equals(channelConfig.acceptedItemType)) {
value = new StringType(owserverConnection.readString(channelConfig.path));
- } else if (channelConfig.acceptedItemType.equals("Number")) {
+ } else if ("Number".equals(channelConfig.acceptedItemType)) {
value = owserverConnection.readDecimalType(channelConfig.path);
} else {
logger.debug("mismatched configuration, itemType unknown for channel {}",
} else {
returnPacket = read(false);
}
- } while (returnPacket.isPingPacket() || !(returnPacket.hasPayload() == payloadExpected));
+ } while (returnPacket.isPingPacket() || returnPacket.hasPayload() != payloadExpected);
} catch (OwException e) {
logger.debug("failed requesting {}->{} [{}]", requestPacket, returnPacket, e.getMessage());
protected int packetSize = 0;
protected int payloadOffset = 0;
- protected byte payload[] = new byte[0];
+ protected byte[] payload = new byte[0];
/**
* constructor for new packet
return;
}
- Mockito.doAnswer(answer -> {
- return OwSensorType.DS2401;
- }).when(secondBridgeHandler).getType(any());
+ Mockito.doAnswer(answer -> OwSensorType.DS2401).when(secondBridgeHandler).getType(any());
thingHandler.initialize();
return;
}
- Mockito.doAnswer(answer -> {
- return OwSensorType.DS18B20;
- }).when(secondBridgeHandler).getType(any());
+ Mockito.doAnswer(answer -> OwSensorType.DS18B20).when(secondBridgeHandler).getType(any());
thingHandler.initialize();
waitForAssert(() -> assertEquals(ThingStatus.UNKNOWN, thingHandler.getThing().getStatusInfo().getStatus()));
return;
}
- Mockito.doAnswer(answer -> {
- return OwSensorType.DS2408;
- }).when(secondBridgeHandler).getType(any());
+ Mockito.doAnswer(answer -> OwSensorType.DS2408).when(secondBridgeHandler).getType(any());
thingHandler.initialize();
waitForAssert(() -> assertEquals(ThingStatus.UNKNOWN, thingHandler.getThing().getStatusInfo().getStatus()));
initializeHandlerMocks();
- Mockito.doAnswer(answer -> {
- return new OwPageBuffer("EDS0065 ".getBytes());
- }).when(secondBridgeHandler).readPages(any());
+ Mockito.doAnswer(answer -> new OwPageBuffer("EDS0065 ".getBytes())).when(secondBridgeHandler).readPages(any());
}
@Test
initializeHandlerMocks();
- Mockito.doAnswer(answer -> {
- return OwSensorType.DS2438;
- }).when(secondBridgeHandler).getType(any());
+ Mockito.doAnswer(answer -> OwSensorType.DS2438).when(secondBridgeHandler).getType(any());
Mockito.doAnswer(answer -> {
OwPageBuffer pageBuffer = new OwPageBuffer(8);
import static org.openhab.binding.onewiregpio.internal.OneWireGPIOBindingConstants.THING_TYPE;
-import java.util.Collections;
import java.util.Set;
import org.openhab.binding.onewiregpio.internal.handler.OneWireGPIOHandler;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.onewiregpio")
public class OneWireGPIOHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof OnkyoHandler) {
- this.handler = (OnkyoHandler) handler;
+ if (handler instanceof OnkyoHandler onkyoHandler) {
+ this.handler = onkyoHandler;
}
}
ZONE3_SOURCE_SET("SL3", "%02X"),
ZONE3_SOURCE("SL3", "");
- public static enum Zone {
+ public enum Zone {
MAIN,
ZONE1,
ZONE2,
// version
final byte versionChar = stream.readByte();
if (versionChar != 1) {
- throw new EiscpException("Unsupported version " + String.valueOf(versionChar));
+ throw new EiscpException("Unsupported version " + versionChar);
}
// skip 3 reserved bytes
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
handleVolumeSet(EiscpCommand.Zone.ZONE1, volumeLevelZone1, command);
break;
case CHANNEL_INPUT:
- if (command instanceof DecimalType) {
- selectInput(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ selectInput(decimalCommand.intValue());
} else if (command.equals(RefreshType.REFRESH)) {
sendCommand(EiscpCommand.SOURCE_QUERY);
}
} else if (command instanceof StringType) {
val = String.format(valTemplate, command);
- } else if (command instanceof DecimalType) {
- val = String.format(valTemplate, ((DecimalType) command).intValue());
+ } else if (command instanceof DecimalType decimalCommand) {
+ val = String.format(valTemplate, decimalCommand.intValue());
- } else if (command instanceof PercentType) {
- val = String.format(valTemplate, ((DecimalType) command).intValue());
+ } else if (command instanceof PercentType percentCommand) {
+ val = String.format(valTemplate, percentCommand.intValue());
} else {
val = valTemplate;
}
}
private void handleVolumeSet(EiscpCommand.Zone zone, final State currentValue, final Command command) {
- if (command instanceof PercentType) {
- sendCommand(EiscpCommand.getCommandForZone(zone, EiscpCommand.VOLUME_SET),
- downScaleVolume((PercentType) command));
+ if (command instanceof PercentType percentCommand) {
+ sendCommand(EiscpCommand.getCommandForZone(zone, EiscpCommand.VOLUME_SET), downScaleVolume(percentCommand));
} else if (command.equals(IncreaseDecreaseType.INCREASE)) {
- if (currentValue instanceof PercentType) {
- if (((DecimalType) currentValue).intValue() < configuration.volumeLimit) {
+ if (currentValue instanceof PercentType percentCommand) {
+ if (percentCommand.intValue() < configuration.volumeLimit) {
sendCommand(EiscpCommand.getCommandForZone(zone, EiscpCommand.VOLUME_UP));
} else {
logger.info("Volume level is limited to {}, ignore volume up command.", configuration.volumeLimit);
}
private State handleReceivedVolume(State volume) {
- if (volume instanceof DecimalType) {
- return upScaleVolume(((DecimalType) volume));
+ if (volume instanceof DecimalType decimalCommand) {
+ return upScaleVolume(decimalCommand);
}
return volume;
}
}
public PercentType getVolume() throws IOException {
- if (volumeLevelZone1 instanceof PercentType) {
- return (PercentType) volumeLevelZone1;
+ if (volumeLevelZone1 instanceof PercentType percentCommand) {
+ return percentCommand;
}
throw new IOException();
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singletonList(OnkyoThingActions.class);
+ return List.of(OnkyoThingActions.class);
}
}
}
protected void handlePlayUri(Command command) {
- if (command != null && command instanceof StringType) {
+ if (command instanceof StringType) {
try {
playMedia(command.toString());
*/
package org.openhab.binding.opengarage.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
public static final String CHANNEL_OG_VEHICLE = "vehicle"; // now deprecated
public static final String CHANNEL_OG_VEHICLE_STATUS = "vehicle-status";
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(OPENGARAGE_THING);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(OPENGARAGE_THING);
}
public List<StateOption> stations = new ArrayList<>();
public static class JsResponse {
- public int sn[] = new int[8];
+ public int[] sn = new int[8];
public int nstations = 8;
}
InetAddress currentIP = InetAddress.getByAddress(ByteBuffer.allocate(4).putInt(i).array());
// Try to reach each IP with a timeout of 500ms which is enough for local network
if (currentIP.isReachable(500)) {
- String host = currentIP.getHostAddress().toString();
+ String host = currentIP.getHostAddress();
logger.debug("Unknown device was found at: {}", host);
discoverySearchPool.execute(new OpenSprinklerDiscoveryJob(this, host));
}
sb.append(String.format("%02x", b & 0xff));
}
- String digest = sb.toString();
-
- return digest;
+ return sb.toString();
} catch (Exception exp) {
// Instead of null we return the unhashed password.
return unhashed;
}
for (DataItem dataItem : dataItems) {
- if (dataItem instanceof TspFhbSizeDataItem) {
+ if (dataItem instanceof TspFhbSizeDataItem sizeDataItem) {
logger.debug("Received TSP or FHB size message {} ({})", message.getID(), dataItem.getSubject());
- verifyTspFhbChannels(((TspFhbSizeDataItem) dataItem).getValueId(),
- message.getUInt(dataItem.getByteType()));
+ verifyTspFhbChannels(sizeDataItem.getValueId(), message.getUInt(dataItem.getByteType()));
} else {
String channelId = dataItem.getChannelId(message);
GatewayCommand gatewayCommand = null;
- if (command instanceof OnOffType) {
- OnOffType onOff = (OnOffType) command;
- gatewayCommand = GatewayCommand.parse(code, onOff == OnOffType.ON ? "1" : "0");
+ if (command instanceof OnOffType onOffCommand) {
+ gatewayCommand = GatewayCommand.parse(code, onOffCommand == OnOffType.ON ? "1" : "0");
}
- if (command instanceof QuantityType<?>) {
- QuantityType<?> quantityType = ((QuantityType<?>) command).toUnit(SIUnits.CELSIUS);
+ if (command instanceof QuantityType<?> quantityCommand) {
+ QuantityType<?> quantityType = quantityCommand.toUnit(SIUnits.CELSIUS);
if (quantityType != null) {
double value = quantityType.doubleValue();
sendCommand(gatewayCommand);
if (GatewayCommandCode.CONTROLSETPOINT.equals(code)) {
- if (gatewayCommand.getMessage().equals("0.0")) {
+ if ("0.0".equals(gatewayCommand.getMessage())) {
updateState(OpenThermGatewayBindingConstants.CHANNEL_OVERRIDE_CENTRAL_HEATING_WATER_SETPOINT,
UnDefType.UNDEF);
}
updateState(OpenThermGatewayBindingConstants.CHANNEL_OVERRIDE_CENTRAL_HEATING_ENABLED,
- OnOffType.from(!gatewayCommand.getMessage().equals("0.0")));
+ OnOffType.from(!"0.0".equals(gatewayCommand.getMessage())));
} else if (GatewayCommandCode.CONTROLSETPOINT2.equals(code)) {
- if (gatewayCommand.getMessage().equals("0.0")) {
+ if ("0.0".equals(gatewayCommand.getMessage())) {
updateState(OpenThermGatewayBindingConstants.CHANNEL_OVERRIDE_CENTRAL_HEATING2_WATER_SETPOINT,
UnDefType.UNDEF);
}
updateState(OpenThermGatewayBindingConstants.CHANNEL_OVERRIDE_CENTRAL_HEATING2_ENABLED,
- OnOffType.from(!gatewayCommand.getMessage().equals("0.0")));
+ OnOffType.from(!"0.0".equals(gatewayCommand.getMessage())));
}
}
}
@SerializedName("st5")
V, // Fitzpatrick Skin Type V
@SerializedName("st6")
- VI;// Fitzpatrick Skin Type VI
+ VI// Fitzpatrick Skin Type VI
}
private double uv;
// legacy delegate methods
public static void virtualPress(@Nullable ThingActions actions, @Nullable String press, int button) {
- if (actions instanceof OpenWebNetCENActions) {
- ((OpenWebNetCENActions) actions).virtualPress(press, button);
+ if (actions instanceof OpenWebNetCENActions openWebNetCENActions) {
+ openWebNetCENActions.virtualPress(press, button);
} else {
throw new IllegalArgumentException("Instance is not an OpenWebNetCENActions class.");
}
package org.openhab.binding.openwebnet.internal.discovery;
import java.util.Arrays;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(OpenWebNetBindingConstants.THING_TYPE_BUS_GATEWAY);
+ return Set.of(OpenWebNetBindingConstants.THING_TYPE_BUS_GATEWAY);
}
@Override
whereConfig, properties.get(OpenWebNetBindingConstants.CONFIG_PROPERTY_STANDALONE));
}
- if (w instanceof WhereZigBee && WhereZigBee.UNIT_02.equals(((WhereZigBee) w).getUnit())) {
+ if (w instanceof WhereZigBee whereZigBee && WhereZigBee.UNIT_02.equals(whereZigBee.getUnit())) {
logger.debug("UNIT=02 found (WHERE={}) -> will remove previous result if exists", w);
thingRemoved(thingUID); // remove previously discovered thing
// re-create thingUID with new type
thingTypeUID = OpenWebNetBindingConstants.THING_TYPE_ZB_ON_OFF_SWITCH_2UNITS;
thingLabel = OpenWebNetBindingConstants.THING_LABEL_ZB_ON_OFF_SWITCH_2UNITS;
thingUID = new ThingUID(thingTypeUID, bridgeUID, tId);
- whereConfig = ((WhereZigBee) w).valueWithUnit(WhereZigBee.UNIT_ALL); // replace unit '02' with '00'
+ whereConfig = whereZigBee.valueWithUnit(WhereZigBee.UNIT_ALL); // replace unit '02' with '00'
logger.debug("UNIT=02, switching type from {} to {}",
OpenWebNetBindingConstants.THING_TYPE_ZB_ON_OFF_SWITCH,
OpenWebNetBindingConstants.THING_TYPE_ZB_ON_OFF_SWITCH_2UNITS);
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof OpenWebNetBridgeHandler) {
+ if (handler instanceof OpenWebNetBridgeHandler openWebNetBridgeHandler) {
logger.debug("attaching {} to handler {} ", this, handler);
- bridgeHandler = (OpenWebNetBridgeHandler) handler;
+ bridgeHandler = openWebNetBridgeHandler;
bridgeHandler.deviceDiscoveryService = this;
bridgeUID = bridgeHandler.getThing().getUID();
}
*/
package org.openhab.binding.openwebnet.internal.discovery;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
*/
@Activate
public UsbGatewayDiscoveryService(final @Reference SerialPortManager spm) {
- super(Collections.singleton(OpenWebNetBindingConstants.THING_TYPE_ZB_GATEWAY), DISCOVERY_TIMEOUT_SECONDS,
- false);
+ super(Set.of(OpenWebNetBindingConstants.THING_TYPE_ZB_GATEWAY), DISCOVERY_TIMEOUT_SECONDS, false);
// Obtain the serial port manager service using an OSGi reference
serialPortManager = spm;
}
if (shutterRunConfig == null) {
shutterRunConfig = AUTO_CALIBRATION;
logger.debug("shutterRun null --> default to AUTO");
- } else if (shutterRunConfig instanceof String) {
- if (AUTO_CALIBRATION.equalsIgnoreCase(((String) shutterRunConfig))) {
+ } else if (shutterRunConfig instanceof String stringValue) {
+ if (AUTO_CALIBRATION.equalsIgnoreCase(stringValue)) {
logger.debug("shutterRun set to AUTO via configuration");
shutterRun = SHUTTER_RUN_UNDEFINED; // reset shutterRun
} else { // try to parse int>=1000
- int shutterRunInt = Integer.parseInt((String) shutterRunConfig);
+ int shutterRunInt = Integer.parseInt(stringValue);
if (shutterRunInt < 1000) {
throw new NumberFormatException();
}
} else {
send(Automation.requestMoveDown(w.value()));
}
- } else if (command instanceof PercentType) {
- handlePercentCommand((PercentType) command, w.value());
+ } else if (command instanceof PercentType percentCommand) {
+ handlePercentCommand(percentCommand, w.value());
}
}
} else {
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(OpenWebNetDeviceDiscoveryService.class);
+ return Set.of(OpenWebNetDeviceDiscoveryService.class);
}
/**
return; // we ignore ACKS/NACKS
}
// GATEWAY MANAGEMENT
- if (msg instanceof GatewayMgmt) {
- GatewayMgmt gwMsg = (GatewayMgmt) msg;
+ if (msg instanceof GatewayMgmt gwMsg) {
if (dateTimeSynch && GatewayMgmt.DimGatewayMgmt.DATETIME.equals(gwMsg.getDim())) {
checkDateTimeDiff(gwMsg);
}
logger.warn("received onConnected() but gateway is null");
return;
}
- if (gw instanceof USBGateway) {
+ if (gw instanceof USBGateway usbGateway) {
logger.info("---- CONNECTED to Zigbee USB gateway bridge '{}' (serialPort: {})", thing.getUID(),
- ((USBGateway) gw).getSerialPortName());
+ usbGateway.getSerialPortName());
} else {
logger.info("---- CONNECTED to BUS gateway bridge '{}' ({}:{})", thing.getUID(),
((BUSGateway) gw).getHost(), ((BUSGateway) gw).getPort());
*/
public String normalizeWhere(Where where) {
String str = where.value();
- if (where instanceof WhereZigBee) {
- str = ((WhereZigBee) where).valueWithUnit(WhereZigBee.UNIT_ALL); // 76543210X#9 --> 765432100#9
+ if (where instanceof WhereZigBee whereZigBee) {
+ str = whereZigBee.valueWithUnit(WhereZigBee.UNIT_ALL); // 76543210X#9 --> 765432100#9
} else {
if (str.indexOf("#4#") == -1) { // skip APL#4#bus case
if (str.indexOf('#') == 0) { // Thermo central unit (#0) or zone via central unit (#Z, Z=[1-99]) --> Z,
*/
private void handleBrightnessCommand(Command command) {
logger.debug("handleBrightnessCommand() command={}", command);
- if (command instanceof PercentType) {
- dimLightTo(((PercentType) command).intValue(), command);
+ if (command instanceof PercentType percentCommand) {
+ dimLightTo(percentCommand.intValue(), command);
} else if (command instanceof IncreaseDecreaseType) {
if (IncreaseDecreaseType.INCREASE.equals(command)) {
dimLightTo(brightness + 10, command);
import java.util.Arrays;
import java.util.Collection;
-import java.util.Collections;
import java.util.Optional;
import java.util.Scanner;
import java.util.Set;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(OpenWebNetCENActions.class);
+ return Set.of(OpenWebNetCENActions.class);
}
@Override
import static org.openhab.binding.oppo.internal.OppoBindingConstants.*;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@NonNullByDefault
@Component(configurationPid = "binding.oppo", service = ThingHandlerFactory.class)
public class OppoHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_PLAYER);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_PLAYER);
private final SerialPortManager serialPortManager;
ThingTypeUID thingTypeUID = thing.getThingTypeUID();
if (SUPPORTED_THING_TYPES_UIDS.contains(thingTypeUID)) {
- OppoHandler handler = new OppoHandler(thing, stateDescriptionProvider, serialPortManager);
-
- return handler;
+ return new OppoHandler(thing, stateDescriptionProvider, serialPortManager);
}
return null;
}
@NonNullByDefault
@Component(service = DiscoveryService.class, configurationPid = "discovery.oppo")
public class OppoDiscoveryService extends AbstractDiscoveryService {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_PLAYER);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_PLAYER);
private final Logger logger = LoggerFactory.getLogger(OppoDiscoveryService.class);
}
break;
case CHANNEL_SOURCE:
- if (command instanceof DecimalType) {
- int value = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ int value = decimalCommand.intValue();
connector.sendCommand(OppoCommand.SET_INPUT_SOURCE, String.valueOf(value));
}
break;
}
break;
case CHANNEL_SUB_SHIFT:
- if (command instanceof DecimalType) {
- int value = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ int value = decimalCommand.intValue();
connector.sendCommand(OppoCommand.SET_SUBTITLE_SHIFT, String.valueOf(value));
}
break;
case CHANNEL_OSD_POSITION:
- if (command instanceof DecimalType) {
- int value = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ int value = decimalCommand.intValue();
connector.sendCommand(OppoCommand.SET_OSD_POSITION, String.valueOf(value));
}
break;
if (model == MODEL83 || model == MODEL103 || model == MODEL105) {
hdmiModeOptions.add(new StateOption("AUTO", "Auto"));
hdmiModeOptions.add(new StateOption("SRC", "Source Direct"));
- if (!(model == MODEL83)) {
+ if (model != MODEL83) {
hdmiModeOptions.add(new StateOption("4K2K", "4K*2K"));
}
hdmiModeOptions.add(new StateOption("1080P", "1080P"));
import static org.openhab.binding.orbitbhyve.internal.OrbitBhyveBindingConstants.THING_TYPE_SPRINKLER;
-import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Override
public void setThingHandler(@Nullable ThingHandler thingHandler) {
- if (thingHandler instanceof OrbitBhyveBridgeHandler) {
- bridgeHandler = (OrbitBhyveBridgeHandler) thingHandler;
+ if (thingHandler instanceof OrbitBhyveBridgeHandler bridgeHandler) {
+ this.bridgeHandler = bridgeHandler;
}
}
@Override
public Set<ThingTypeUID> getSupportedThingTypes() {
- return Collections.singleton(THING_TYPE_SPRINKLER);
+ return Set.of(THING_TYPE_SPRINKLER);
}
}
import java.util.Collections;
import java.util.Date;
import java.util.List;
+import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(OrbitBhyveDiscoveryService.class);
+ return Set.of(OrbitBhyveDiscoveryService.class);
}
@Override
if (logger.isTraceEnabled()) {
logger.trace("Device response: {}", response.getContentAsString());
}
- OrbitBhyveDevice device = gson.fromJson(response.getContentAsString(), OrbitBhyveDevice.class);
- return device;
+ return gson.fromJson(response.getContentAsString(), OrbitBhyveDevice.class);
} else {
logger.debug("Returned status: {}", response.getStatus());
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
if (th.isEnabled()) {
String deviceId = th.getUID().getId();
ThingHandler handler = th.getHandler();
- if (handler instanceof OrbitBhyveSprinklerHandler) {
+ if (handler instanceof OrbitBhyveSprinklerHandler sprinklerHandler) {
for (OrbitBhyveDevice device : devices) {
if (deviceId.equals(th.getUID().getId())) {
- updateDeviceStatus(device, (OrbitBhyveSprinklerHandler) handler);
+ updateDeviceStatus(device, sprinklerHandler);
}
}
}
for (Thing th : getThing().getThings()) {
if (deviceId.equals(th.getUID().getId())) {
ThingHandler handler = th.getHandler();
- if (handler instanceof OrbitBhyveSprinklerHandler) {
+ if (handler instanceof OrbitBhyveSprinklerHandler sprinklerHandler) {
OrbitBhyveDevice device = getDevice(deviceId);
- updateDeviceStatus(device, (OrbitBhyveSprinklerHandler) handler);
+ updateDeviceStatus(device, sprinklerHandler);
}
}
}
for (Thing th : getThing().getThings()) {
if (program.getDeviceId().equals(th.getUID().getId())) {
ThingHandler handler = th.getHandler();
- if (handler instanceof OrbitBhyveSprinklerHandler) {
- ((OrbitBhyveSprinklerHandler) handler).updateProgram(program);
+ if (handler instanceof OrbitBhyveSprinklerHandler sprinklerHandler) {
+ sprinklerHandler.updateProgram(program);
}
}
}
handler.stopWatering(deviceId);
return;
}
- if (CHANNEL_WATERING_TIME.equals(channelUID.getId()) && command instanceof QuantityType) {
- final QuantityType<?> value = ((QuantityType<?>) command).toUnit(Units.MINUTE);
+ if (CHANNEL_WATERING_TIME.equals(channelUID.getId()) && command instanceof QuantityType quantityCommand) {
+ final QuantityType<?> value = quantityCommand.toUnit(Units.MINUTE);
if (value != null) {
wateringTime = value.intValue();
}
import static org.openhab.binding.orvibo.internal.OrviboBindingConstants.THING_TYPE_S20;
-import java.util.Collections;
import java.util.Set;
import org.openhab.binding.orvibo.internal.handler.S20Handler;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.orvibo")
public class OrviboHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_S20);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_S20);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
package org.openhab.binding.orvibo.internal.discovery;
import java.net.SocketException;
-import java.util.Collections;
import java.util.Map;
import java.util.Set;
}
private static Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(OrviboBindingConstants.THING_TYPE_S20);
+ return Set.of(OrviboBindingConstants.THING_TYPE_S20);
}
@Override
}
private ThingUID getUID(Socket socket) {
- ThingUID thingUID = new ThingUID(OrviboBindingConstants.THING_TYPE_S20, socket.getDeviceId());
- return thingUID;
+ return new ThingUID(OrviboBindingConstants.THING_TYPE_S20, socket.getDeviceId());
}
private void doThingDiscovered(Socket socket) {
}
private byte[] generateInitializationRequest(byte[] initializationMessage, byte[] pcPassword) {
- byte[] message7 = new byte[] {
+ return new byte[] {
// Initialization command
0x00,
// Checksum
0x00 };
- return message7;
}
@Override
// UGLY - this is the handling of ghost packet which appears after the logon sequence
// Read ghost packet affter 300ms then continue with normal flow
communicator.getScheduler().schedule(() -> {
- if (communicator instanceof GenericCommunicator) {
+ if (communicator instanceof GenericCommunicator genericCommunicator) {
try {
- GenericCommunicator genCommunicator = (GenericCommunicator) communicator;
byte[] value = new byte[256];
- int packetLength = genCommunicator.getRx().read(value);
+ int packetLength = genericCommunicator.getRx().read(value);
logger.debug("Reading ghost packet with length={}", packetLength);
ParadoxUtil.printPacket("Reading ghost packet", value);
} catch (IOException e) {
@Override
protected void runPhase(IParadoxInitialLoginCommunicator communicator, Object... args) {
- if (communicator instanceof IParadoxCommunicator) {
- IParadoxCommunicator comm = (IParadoxCommunicator) communicator;
+ if (communicator instanceof IParadoxCommunicator comm) {
comm.initializeData();
}
nextState().runPhase(communicator);
byteArray[i] = (byte) (keyBytes[i] & 0xFF);
}
- byte[] expandedArray = ParadoxUtil.extendArray(byteArray, KEY_ARRAY_LENGTH);
- return expandedArray;
+ return ParadoxUtil.extendArray(byteArray, KEY_ARRAY_LENGTH);
}
private void expandKey(byte[] input) {
private void discoverZones(List<Zone> zones) {
zones.stream().forEach(zone -> {
- String thingId = zone.getLabel().replaceAll(" ", "_");
+ String thingId = zone.getLabel().replace(" ", "_");
String label = zone.getLabel();
ThingUID bridgeUid = ip150BridgeHandler.getThing().getUID();
return null;
}
- Partition partition = partitions.get(index);
- return partition;
+ return partitions.get(index);
}
}
return null;
}
- Zone zone = zones.get(index);
- return zone;
+ return zones.get(index);
}
private ParadoxIP150BridgeHandler getBridgeHandler() {
for (byte[] array : arrays) {
outputStream.write(array);
}
- byte[] byteArray = outputStream.toByteArray();
- return byteArray;
+ return outputStream.toByteArray();
} catch (IOException e) {
LOGGER.warn("Exception merging arrays:", e);
return new byte[0];
@Override
public void run() {
logger.debug("parser thread started");
- byte buf[] = new byte[40];
+ byte[] buf = new byte[40];
int c;
int chksum, i, length;
Thing thing;
return;
}
- if (command instanceof OnOffType) {
- boolean state = ((OnOffType) command) == OnOffType.ON;
+ if (command instanceof OnOffType onOffCommand) {
+ boolean state = onOffCommand == OnOffType.ON;
switch (channelUID.getId()) {
case EASYTOUCH_POOL:
circuitSwitch(18, state);
break;
}
- } else if (command instanceof DecimalType) {
- int sp = ((DecimalType) command).intValue();
+ } else if (command instanceof DecimalType decimalCommand) {
+ int sp = decimalCommand.intValue();
switch (channelUID.getId()) {
case EASYTOUCH_SPASETPOINT:
throw new IllegalStateException("cannot open serial port!");
}
- if (cp instanceof SerialPort) {
- port = (SerialPort) cp;
+ if (cp instanceof SerialPort serialPort) {
+ port = serialPort;
} else {
throw new IllegalStateException("unknown port type");
}
String thingID = StringUtils.padLeft(Integer.toBinaryString(moduleAddr & 0xFF).trim(), 5, "0");
thingID = new StringBuilder(thingID).reverse().toString();
- ThingUID thingUID = new ThingUID(thingTypeUID, thingID);
-
- return thingUID;
+ return new ThingUID(thingTypeUID, thingID);
}
/**
private final BlockingQueue<QueueObject> sendQueue = new LinkedBlockingQueue<>();
private final ScheduledThreadPoolExecutor threadPoolExecutor = new ScheduledThreadPoolExecutor(3);
- private final byte emLedOutputState[] = new byte[32];
- private final byte amOutputState[] = new byte[32];
- private final byte dmOutputState[] = new byte[32];
+ private final byte[] emLedOutputState = new byte[32];
+ private final byte[] amOutputState = new byte[32];
+ private final byte[] dmOutputState = new byte[32];
private final List<Byte> modules = new ArrayList<>();
private void sendDim(byte moduleAddress, byte channel, Command command, short dimTime) {
byte module = (byte) (moduleAddress | 0xA0);
- byte[] cmd = new byte[(command instanceof PercentType && !(((PercentType) command).byteValue() == 0)) ? 3 : 1];
+ byte[] cmd = new byte[(command instanceof PercentType percentCommand && percentCommand.byteValue() != 0) ? 3
+ : 1];
cmd[0] = (byte) (channel << 5);
}
ThingHandler handler = bridge.getHandler();
- if (handler instanceof PHCBridgeHandler) {
- bridgeHandler = (PHCBridgeHandler) handler;
+ if (handler instanceof PHCBridgeHandler phcBridgeHandler) {
+ bridgeHandler = phcBridgeHandler;
} else {
logger.debug("No available bridge handler for {}.", bridge.getUID());
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
-import java.util.Collections;
+import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
callback.versionReceived(version);
} else if (line.startsWith("{\"status\":")) {
// currently unused
- } else if (line.equals("1")) {
+ } else if ("1".equals(line)) {
throw new IOException("Connection to pilight lost");
} else {
final @Nullable Status status = inputMapper.readValue(line, Status.class);
- callback.statusReceived(Collections.singletonList(status));
+ callback.statusReceived(List.of(status));
}
}
private static final int AUTODISCOVERY_SEARCH_TIME_SEC = 5;
private static final int AUTODISCOVERY_BACKGROUND_SEARCH_INTERVAL_SEC = 60 * 10;
- private static final String SSDP_DISCOVERY_REQUEST_MESSAGE = "M-SEARCH * HTTP/1.1\r\n"
- + "Host:239.255.255.250:1900\r\n" + "ST:urn:schemas-upnp-org:service:pilight:1\r\n"
- + "Man:\"ssdp:discover\"\r\n" + "MX:3\r\n\r\n";
+ private static final String SSDP_DISCOVERY_REQUEST_MESSAGE = """
+ M-SEARCH * HTTP/1.1
+ Host:239.255.255.250:1900
+ ST:urn:schemas-upnp-org:service:pilight:1
+ Man:"ssdp:discover"
+ MX:3
+
+ """;
public static final String SSDP_MULTICAST_ADDRESS = "239.255.255.250";
public static final int SSDP_PORT = 1900;
public static final int SSDP_WAIT_TIMEOUT = 2000; // in milliseconds
}
public static Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(PilightBindingConstants.THING_TYPE_BRIDGE);
+ return Set.of(PilightBindingConstants.THING_TYPE_BRIDGE);
}
@Override
@Override
public void setThingHandler(final ThingHandler handler) {
- if (handler instanceof PilightBridgeHandler) {
- this.pilightBridgeHandler = (PilightBridgeHandler) handler;
- final @Nullable PilightBridgeHandler pilightBridgeHandler = this.pilightBridgeHandler;
- if (pilightBridgeHandler != null) {
- bridgeUID = pilightBridgeHandler.getThing().getUID();
- }
+ if (handler instanceof PilightBridgeHandler pilightBridgeHandler) {
+ this.pilightBridgeHandler = pilightBridgeHandler;
+ bridgeUID = pilightBridgeHandler.getThing().getUID();
}
}
if (bridge != null) {
@Nullable
BridgeHandler handler = bridge.getHandler();
- if (handler instanceof PilightBridgeHandler) {
- return (PilightBridgeHandler) handler;
+ if (handler instanceof PilightBridgeHandler bridgeHandler) {
+ return bridgeHandler;
}
}
return null;
package org.openhab.binding.pilight.internal.handler;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
+import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
if (!DeviceType.SERVER.equals(type)) {
for (Thing thing : getThing().getThings()) {
final @Nullable ThingHandler handler = thing.getHandler();
- if (handler instanceof PilightBaseHandler) {
- ((PilightBaseHandler) handler).updateFromStatusIfMatches(status);
+ if (handler instanceof PilightBaseHandler baseHandler) {
+ baseHandler.updateFromStatusIfMatches(status);
}
}
}
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(PilightDeviceDiscoveryService.class);
+ return Set.of(PilightDeviceDiscoveryService.class);
}
/**
private void processConfig(Config config) {
for (Thing thing : getThing().getThings()) {
final @Nullable ThingHandler handler = thing.getHandler();
- if (handler instanceof PilightBaseHandler) {
- ((PilightBaseHandler) handler).updateFromConfigIfMatches(config);
+ if (handler instanceof PilightBaseHandler baseHandler) {
+ baseHandler.updateFromConfigIfMatches(config);
}
}
if (command instanceof OnOffType) {
code.setState(command.equals(OnOffType.ON) ? Code.STATE_ON : Code.STATE_OFF);
- } else if (command instanceof PercentType) {
- setDimmerValue((PercentType) command, code);
+ } else if (command instanceof PercentType percentCommand) {
+ setDimmerValue(percentCommand, code);
} else {
logger.warn("Only OnOffType and PercentType are supported by a dimmer.");
return null;
* @return
*/
public static SimpleCommand getIpControlCommand(SimpleCommandType command) {
- SimpleCommand result = new SimpleCommand(command);
- return result;
+ return new SimpleCommand(command);
}
/**
* @return
*/
public static SimpleCommand getIpControlCommand(SimpleCommandType command, int zone) {
- SimpleCommand result = new SimpleCommand(command, zone);
- return result;
+ return new SimpleCommand(command, zone);
}
/**
* @return
*/
public static ParameterizedCommand getIpControlCommand(ParameterizedCommandType command) {
- ParameterizedCommand result = new ParameterizedCommand(command);
- return result;
+ return new ParameterizedCommand(command);
}
/**
* @return
*/
public static ParameterizedCommand getIpControlCommand(ParameterizedCommandType command, int zone) {
- ParameterizedCommand result = new ParameterizedCommand(command, zone);
- return result;
+ return new ParameterizedCommand(command, zone);
}
/**
MCACC_MEMORY_CHANGE_CYCLIC("0MC"),
MCACC_MEMORY_QUERY("?MC");
- private String zoneCommands[];
+ private String[] zoneCommands;
private SimpleCommandType(String... command) {
this.zoneCommands = command;
commandToSend = RequestResponseFactory.getIpControlCommand(SimpleCommandType.VOLUME_DOWN, zone);
} else if (command == IncreaseDecreaseType.INCREASE) {
commandToSend = RequestResponseFactory.getIpControlCommand(SimpleCommandType.VOLUME_UP, zone);
- } else if (command instanceof PercentType) {
+ } else if (command instanceof PercentType percentCommand) {
String ipControlVolume = VolumeConverter
- .convertFromPercentToIpControlVolume(((PercentType) command).doubleValue(), zone);
+ .convertFromPercentToIpControlVolume(percentCommand.doubleValue(), zone);
commandToSend = RequestResponseFactory.getIpControlCommand(ParameterizedCommandType.VOLUME_SET, zone)
.setParameter(ipControlVolume);
- } else if (command instanceof DecimalType) {
- String ipControlVolume = VolumeConverter
- .convertFromDbToIpControlVolume(((DecimalType) command).doubleValue(), zone);
+ } else if (command instanceof DecimalType decimalCommand) {
+ String ipControlVolume = VolumeConverter.convertFromDbToIpControlVolume(decimalCommand.doubleValue(),
+ zone);
commandToSend = RequestResponseFactory.getIpControlCommand(ParameterizedCommandType.VOLUME_SET, zone)
.setParameter(ipControlVolume);
} else {
commandToSend = RequestResponseFactory.getIpControlCommand(SimpleCommandType.INPUT_CHANGE_CYCLIC, zone);
} else if (command == IncreaseDecreaseType.DECREASE) {
commandToSend = RequestResponseFactory.getIpControlCommand(SimpleCommandType.INPUT_CHANGE_REVERSE, zone);
- } else if (command instanceof StringType) {
- String inputSourceValue = ((StringType) command).toString();
+ } else if (command instanceof StringType stringCommand) {
+ String inputSourceValue = stringCommand.toString();
commandToSend = RequestResponseFactory.getIpControlCommand(ParameterizedCommandType.INPUT_CHANNEL_SET, zone)
.setParameter(inputSourceValue);
} else {
if (command == IncreaseDecreaseType.INCREASE) {
commandToSend = RequestResponseFactory.getIpControlCommand(SimpleCommandType.LISTENING_MODE_CHANGE_CYCLIC,
zone);
- } else if (command instanceof StringType) {
- String listeningModeValue = ((StringType) command).toString();
+ } else if (command instanceof StringType stringCommand) {
+ String listeningModeValue = stringCommand.toString();
commandToSend = RequestResponseFactory
.getIpControlCommand(ParameterizedCommandType.LISTENING_MODE_SET, zone)
.setParameter(listeningModeValue);
if (command == IncreaseDecreaseType.INCREASE) {
commandToSend = RequestResponseFactory.getIpControlCommand(SimpleCommandType.MCACC_MEMORY_CHANGE_CYCLIC);
- } else if (command instanceof StringType) {
- String MCACCMemoryValue = ((StringType) command).toString();
+ } else if (command instanceof StringType stringCommand) {
+ String MCACCMemoryValue = stringCommand.toString();
commandToSend = RequestResponseFactory.getIpControlCommand(ParameterizedCommandType.MCACC_MEMORY_SET)
.setParameter(MCACCMemoryValue);
} else {
int expiresIn = Integer.parseInt(responseJson.get("expires_in").toString());
setTokenExpiryDate(TimeUnit.SECONDS.toNanos(expiresIn));
- setAuthToken(responseJson.get(AUTH_TOKEN).toString().replaceAll("\"", ""));
+ setAuthToken(responseJson.get(AUTH_TOKEN).toString().replace("\"", ""));
updateStatus(ThingStatus.ONLINE);
return;
*/
package org.openhab.binding.pixometer.internal;
-import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public static final ThingTypeUID THING_TYPE_GASMETER = new ThingTypeUID(BINDING_ID, "gasmeter");
public static final ThingTypeUID THING_TYPE_WATERMETER = new ThingTypeUID(BINDING_ID, "watermeter");
- 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 = Stream
.of(THING_TYPE_ENERGYMETER, THING_TYPE_GASMETER, THING_TYPE_WATERMETER).collect(Collectors.toSet());
* @return The wanted string without unnecessary quotation marks
*/
private String getStringFromJson(JsonObject data, String key) {
- return data.get(key).toString().replaceAll("\"", "");
+ return data.get(key).toString().replace("\"", "");
}
/**
* @return returns true if null values have been found, false otherwise
*/
private boolean checkStringForNullValues(String s) {
- return (s == null || s.isEmpty() || s.equals("null"));
+ return (s == null || s.isEmpty() || "null".equals(s));
}
}
if (command == RefreshType.REFRESH) {
StringType input = new StringType(device.getInputStatus().getResult().getValue());
updateState(PJLinkDeviceBindingConstants.CHANNEL_INPUT, input);
- } else if (command instanceof StringType) {
+ } else if (command instanceof StringType stringCommand) {
logger.trace("Received input command {}", command);
- Input input = new Input(((StringType) command).toString());
+ Input input = new Input(stringCommand.toString());
device.setInput(input);
} else {
logger.debug("Received unknown channel command {}", command);
import static org.openhab.binding.pjlinkdevice.internal.PJLinkDeviceBindingConstants.THING_TYPE_PJLINK;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.pjlinkdevice", service = { ThingHandlerFactory.class })
public class PJLinkDeviceHandlerFactory extends BaseThingHandlerFactory {
private InputChannelStateDescriptionProvider stateDescriptionProvider;
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_PJLINK);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_PJLINK);
@Activate
public PJLinkDeviceHandlerFactory(@Reference InputChannelStateDescriptionProvider provider) {
} else {
try {
authenticate(rawHeader.substring("PJLINK 1 ".length()));
- } catch (AuthenticationException e) {
- // propagate AuthenticationException
- throw e;
} catch (ResponseException e) {
// maybe only the test command is broken on the device
// as long as we don't get an AuthenticationException, we'll just ignore it for now
String response = null;
while ((response = getReader().readLine()) != null && preprocessResponse(response).isEmpty()) {
logger.debug("Got empty string response for request '{}' from {}, waiting for another line", response,
- fullCommand.replaceAll("\r", "\\\\r"));
+ fullCommand.replace("\r", "\\\\r"));
}
if (response == null) {
- throw new ResponseException(MessageFormat.format("Response to request ''{0}'' was null",
- fullCommand.replaceAll("\r", "\\\\r")));
+ throw new ResponseException(
+ MessageFormat.format("Response to request ''{0}'' was null", fullCommand.replace("\r", "\\\\r")));
}
if (logger.isDebugEnabled()) {
logger.debug("Got response '{}' ({}) for request '{}' from {}", response,
- Arrays.toString(response.getBytes()), fullCommand.replaceAll("\r", "\\\\r"), ipAddress);
+ Arrays.toString(response.getBytes()), fullCommand.replace("\r", "\\\\r"), ipAddress);
}
return preprocessResponse(response);
}
} catch (CacheException e) {
// try to unwrap RuntimeException thrown in ExpiringCache
Throwable cause = e.getCause();
- if (cause instanceof ResponseException) {
- throw (ResponseException) cause;
+ if (cause instanceof ResponseException responseException) {
+ throw responseException;
}
- if (cause instanceof IOException) {
- throw (IOException) cause;
+ if (cause instanceof IOException ioException) {
+ throw ioException;
}
- if (cause instanceof AuthenticationException) {
- throw (AuthenticationException) cause;
+ if (cause instanceof AuthenticationException authenticationException) {
+ throw authenticationException;
}
throw e;
}
Matcher matcher = RESPONSE_PARSING_PATTERN.matcher(responseWithoutPrefix);
while (matcher.find()) {
int lampHours = Integer.parseInt(matcher.group("hours"));
- boolean active = matcher.group("active").equals("1");
+ boolean active = "1".equals(matcher.group("active"));
result.add(new LampState(active, lampHours));
}
return result;
public static ThingUID createServiceUID(String ip, int tcpPort) {
// uid must not contains dots
- return new ThingUID(PJLinkDeviceBindingConstants.THING_TYPE_PJLINK,
- ip.replace('.', '_') + "_" + String.valueOf(tcpPort));
+ return new ThingUID(PJLinkDeviceBindingConstants.THING_TYPE_PJLINK, ip.replace('.', '_') + "_" + tcpPort);
}
protected abstract void checkAddress(InetAddress ip, int tcpPort, int timeout);
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.UnknownHostException;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@NonNullByDefault
public class DiscoveryParticipantClass1 extends AbstractDiscoveryParticipant {
public DiscoveryParticipantClass1() throws IllegalArgumentException {
- super(Collections.singleton(PJLinkDeviceBindingConstants.THING_TYPE_PJLINK), 60, true);
+ super(Set.of(PJLinkDeviceBindingConstants.THING_TYPE_PJLINK), 60, true);
logger.trace("PJLinkProjectorDiscoveryParticipant constructor");
}
private void wakeMethod(DatagramPacket srchPacket, DatagramPacket receivePacket, DatagramPacket wakePacket,
int triesLeft) {
- try (DatagramSocket searchSocket = new DatagramSocket(); DatagramSocket wakeSocket = new DatagramSocket();) {
+ try (DatagramSocket searchSocket = new DatagramSocket(); DatagramSocket wakeSocket = new DatagramSocket()) {
wakeSocket.setBroadcast(true);
searchSocket.setBroadcast(true);
searchSocket.setSoTimeout(1000);
private final Logger logger = LoggerFactory.getLogger(PS4Crypto.class);
// Public key is from ps4-waker (https://github.com/dhleong/ps4-waker)
- private static final String PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----"
- + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxfAO/MDk5ovZpp7xlG9J"
- + "JKc4Sg4ztAz+BbOt6Gbhub02tF9bryklpTIyzM0v817pwQ3TCoigpxEcWdTykhDL"
- + "cGhAbcp6E7Xh8aHEsqgtQ/c+wY1zIl3fU//uddlB1XuipXthDv6emXsyyU/tJWqc"
- + "zy9HCJncLJeYo7MJvf2TE9nnlVm1x4flmD0k1zrvb3MONqoZbKb/TQVuVhBv7SM+"
- + "U5PSi3diXIx1Nnj4vQ8clRNUJ5X1tT9XfVmKQS1J513XNZ0uYHYRDzQYujpLWucu"
- + "ob7v50wCpUm3iKP1fYCixMP6xFm0jPYz1YQaMV35VkYwc40qgk3av0PDS+1G0dCm" + "swIDAQAB"
- + "-----END PUBLIC KEY-----";
+ private static final String PUBLIC_KEY = """
+ -----BEGIN PUBLIC KEY-----\
+ MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxfAO/MDk5ovZpp7xlG9J\
+ JKc4Sg4ztAz+BbOt6Gbhub02tF9bryklpTIyzM0v817pwQ3TCoigpxEcWdTykhDL\
+ cGhAbcp6E7Xh8aHEsqgtQ/c+wY1zIl3fU//uddlB1XuipXthDv6emXsyyU/tJWqc\
+ zy9HCJncLJeYo7MJvf2TE9nnlVm1x4flmD0k1zrvb3MONqoZbKb/TQVuVhBv7SM+\
+ U5PSi3diXIx1Nnj4vQ8clRNUJ5X1tT9XfVmKQS1J513XNZ0uYHYRDzQYujpLWucu\
+ ob7v50wCpUm3iKP1fYCixMP6xFm0jPYz1YQaMV35VkYwc40qgk3av0PDS+1G0dCm\
+ swIDAQAB\
+ -----END PUBLIC KEY-----\
+ """;
private final byte[] remoteSeed = new byte[16];
private final byte[] randomSeed = new byte[16];
if (command instanceof RefreshType) {
refreshFromState(channelUID);
} else {
- if (command instanceof StringType) {
+ if (command instanceof StringType stringCommand) {
switch (channelUID.getId()) {
case CHANNEL_APPLICATION_ID:
- if (!currentApplicationId.equals(((StringType) command).toString())) {
- updateApplicationTitleid(((StringType) command).toString());
+ if (!currentApplicationId.equals(stringCommand.toString())) {
+ updateApplicationTitleid(stringCommand.toString());
startApplication(currentApplicationId);
}
break;
case CHANNEL_OSK_TEXT:
- setOSKText(((StringType) command).toString());
+ setOSKText(stringCommand.toString());
break;
case CHANNEL_SEND_KEY:
int ps4Key = 0;
- switch (((StringType) command).toString()) {
+ switch (stringCommand.toString()) {
case SEND_KEY_UP:
ps4Key = PS4_KEY_UP;
break;
default:
break;
}
- } else if (command instanceof OnOffType) {
- OnOffType onOff = (OnOffType) command;
+ } else if (command instanceof OnOffType onOffCommand) {
switch (channelUID.getId()) {
case CHANNEL_POWER:
- if (currentPower != onOff) {
- currentPower = onOff;
+ if (currentPower != onOffCommand) {
+ currentPower = onOffCommand;
if (currentPower.equals(OnOffType.ON)) {
turnOnPS4();
} else if (currentPower.equals(OnOffType.OFF)) {
break;
case CHANNEL_CONNECT:
boolean connected = socketChannelHandler != null && socketChannelHandler.isChannelOpen();
- if (connected && onOff.equals(OnOffType.OFF)) {
+ if (connected && onOffCommand.equals(OnOffType.OFF)) {
sendByeBye();
- } else if (!connected && onOff.equals(OnOffType.ON)) {
+ } else if (!connected && onOffCommand.equals(OnOffType.ON)) {
scheduler.execute(() -> login());
}
break;
properties.put(Thing.PROPERTY_HARDWARE_VERSION, hwVersion);
properties.put(Thing.PROPERTY_FIRMWARE_VERSION, formatPS4Version(systemVersion));
properties.put(Thing.PROPERTY_MAC_ADDRESS, hostIdToMacAddress(hostId));
- ThingUID uid = hostType.equalsIgnoreCase("PS5") ? new ThingUID(THING_TYPE_PS5, hostId)
+ ThingUID uid = "PS5".equalsIgnoreCase(hostType) ? new ThingUID(THING_TYPE_PS5, hostId)
: new ThingUID(THING_TYPE_PS4, hostId);
DiscoveryResult result = DiscoveryResultBuilder.create(uid).withProperties(properties).withLabel(hostName)
hwVersion = PS4HW_CUH1000;
break;
case "bc60a7": // Ethernet
- if (ethId.equals("7b")) {
+ if ("7b".equals(ethId)) {
hwVersion = PS4HW_CUH2000;
}
- if (ethId.equals("8f")) {
+ if ("8f".equals(ethId)) {
hwVersion = PS4HW_CUH7000;
}
break;
break;
case "40490f": // WiFi
case "5c9656": // WiFi
- if (ethId.equals("07")) {
+ if ("07".equals(ethId)) {
hwVersion = PS4HW_CUH2000;
}
- if (ethId.equals("da")) {
+ if ("da".equals(ethId)) {
hwVersion = PS4HW_CUH7000;
}
break;
// read first portion directly to data
result = super.ReadArea(Area, DBNumber, Start, packet, WordLength, Data);
while ((result == 0) && (offset < Amount)) {
- byte buffer[] = new byte[Math.min(Amount - offset, packet)];
+ byte[] buffer = new byte[Math.min(Amount - offset, packet)];
result = super.ReadArea(Area, DBNumber, offset, buffer.length, WordLength, buffer);
System.arraycopy(buffer, 0, Data, offset, buffer.length);
offset = offset + buffer.length;
@Override
protected @Nullable ThingHandler createHandler(Thing thing) {
- if (THING_TYPE_DEVICE.equals(thing.getThingTypeUID()) && (thing instanceof Bridge)) {
- return new PLCBridgeHandler((Bridge) thing);
+ if (THING_TYPE_DEVICE.equals(thing.getThingTypeUID()) && (thing instanceof Bridge bridge)) {
+ return new PLCBridgeHandler(bridge);
} else if (THING_TYPE_ANALOG.equals(thing.getThingTypeUID())) {
return new PLCAnalogHandler(thing);
} else if (THING_TYPE_DIGITAL.equals(thing.getThingTypeUID())) {
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Arrays;
-import java.util.Collections;
import java.util.Enumeration;
import java.util.Set;
import java.util.TreeSet;
public class PLCDiscoveryService extends AbstractDiscoveryService {
private final Logger logger = LoggerFactory.getLogger(PLCDiscoveryService.class);
- private static final Set<ThingTypeUID> THING_TYPES_UIDS = Collections.singleton(THING_TYPE_DEVICE);
+ private static final Set<ThingTypeUID> THING_TYPES_UIDS = Set.of(THING_TYPE_DEVICE);
private static final String LOGO_HOST = "address";
private static final int LOGO_PORT = 102;
@NonNullByDefault
public class PLCAnalogHandler extends PLCCommonHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_ANALOG);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_ANALOG);
private final Logger logger = LoggerFactory.getLogger(PLCAnalogHandler.class);
private AtomicReference<PLCAnalogConfiguration> config = new AtomicReference<>();
} else {
logger.debug("Can not read data from LOGO!: {}.", S7Client.ErrorText(result));
}
- } else if (command instanceof DecimalType) {
+ } else if (command instanceof DecimalType decimalCommand) {
byte[] buffer = new byte[2];
String type = channel.getAcceptedItemType();
if (ANALOG_ITEM.equalsIgnoreCase(type)) {
- S7.SetShortAt(buffer, 0, ((DecimalType) command).intValue());
+ S7.SetShortAt(buffer, 0, decimalCommand.intValue());
} else {
logger.debug("Channel {} will not accept {} items.", channelUID, type);
}
cBuilder.withType(new ChannelTypeUID(BINDING_ID, type.toLowerCase()));
cBuilder.withLabel(name);
cBuilder.withDescription("Analog " + text + " block " + name);
- cBuilder.withProperties(Collections.singletonMap(BLOCK_PROPERTY, name));
+ cBuilder.withProperties(Map.of(BLOCK_PROPERTY, name));
tBuilder.withChannel(cBuilder.build());
setOldValue(name, null);
}
import java.time.DateTimeException;
import java.time.ZonedDateTime;
import java.util.Arrays;
-import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@NonNullByDefault
public class PLCBridgeHandler extends BaseBridgeHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_DEVICE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_DEVICE);
private final Logger logger = LoggerFactory.getLogger(PLCBridgeHandler.class);
@Override
public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
super.childHandlerInitialized(childHandler, childThing);
- if (childHandler instanceof PLCCommonHandler) {
- PLCCommonHandler handler = (PLCCommonHandler) childHandler;
+ if (childHandler instanceof PLCCommonHandler plcCommonHandler) {
synchronized (handlers) {
- if (!handlers.contains(handler)) {
- handlers.add(handler);
+ if (!handlers.contains(plcCommonHandler)) {
+ handlers.add(plcCommonHandler);
}
}
}
@Override
public void childHandlerDisposed(ThingHandler childHandler, Thing childThing) {
- if (childHandler instanceof PLCCommonHandler) {
- PLCCommonHandler handler = (PLCCommonHandler) childHandler;
+ if (childHandler instanceof PLCCommonHandler plcCommonHandler) {
synchronized (handlers) {
- if (handlers.contains(handler)) {
- handlers.remove(handler);
+ if (handlers.contains(plcCommonHandler)) {
+ handlers.remove(plcCommonHandler);
}
}
}
Bridge bridge = getBridge();
if (bridge != null) {
BridgeHandler handler = bridge.getHandler();
- if ((handler != null) && (handler instanceof PLCBridgeHandler)) {
- return (PLCBridgeHandler) handler;
+ if (handler instanceof PLCBridgeHandler bridgeHandler) {
+ return bridgeHandler;
}
}
return null;
import static org.openhab.binding.plclogo.internal.PLCLogoBindingConstants.*;
import java.time.ZonedDateTime;
-import java.util.Collections;
import java.util.List;
+import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
@NonNullByDefault
public class PLCDateTimeHandler extends PLCCommonHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_DATETIME);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_DATETIME);
private final Logger logger = LoggerFactory.getLogger(PLCDateTimeHandler.class);
private AtomicReference<PLCDateTimeConfiguration> config = new AtomicReference<>();
} else {
logger.debug("Can not read data from LOGO!: {}.", S7Client.ErrorText(result));
}
- } else if (command instanceof DateTimeType) {
+ } else if (command instanceof DateTimeType dateTimeCommand) {
byte[] buffer = new byte[2];
String type = channel.getAcceptedItemType();
if (DATE_TIME_ITEM.equalsIgnoreCase(type)) {
- ZonedDateTime datetime = ((DateTimeType) command).getZonedDateTime();
+ ZonedDateTime datetime = dateTimeCommand.getZonedDateTime();
if ("Time".equalsIgnoreCase(channelUID.getId())) {
buffer[0] = S7.ByteToBCD(datetime.getHour());
buffer[1] = S7.ByteToBCD(datetime.getMinute());
cBuilder.withType(new ChannelTypeUID(BINDING_ID, type.toLowerCase()));
cBuilder.withLabel(name);
cBuilder.withDescription(text + " block parameter " + name);
- cBuilder.withProperties(Collections.singletonMap(BLOCK_PROPERTY, name));
+ cBuilder.withProperties(Map.of(BLOCK_PROPERTY, name));
tBuilder.withChannel(cBuilder.build());
cBuilder = ChannelBuilder.create(new ChannelUID(thing.getUID(), VALUE_CHANNEL), ANALOG_ITEM);
cBuilder.withType(new ChannelTypeUID(BINDING_ID, ANALOG_ITEM.toLowerCase()));
cBuilder.withLabel(name);
cBuilder.withDescription(text + " block parameter " + name);
- cBuilder.withProperties(Collections.singletonMap(BLOCK_PROPERTY, name));
+ cBuilder.withProperties(Map.of(BLOCK_PROPERTY, name));
tBuilder.withChannel(cBuilder.build());
setOldValue(name, null);
@NonNullByDefault
public class PLCDigitalHandler extends PLCCommonHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_DIGITAL);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_DIGITAL);
private final Logger logger = LoggerFactory.getLogger(PLCDigitalHandler.class);
private AtomicReference<PLCDigitalConfiguration> config = new AtomicReference<>();
protected void updateState(ChannelUID channelUID, State state) {
super.updateState(channelUID, state);
DecimalType value = state.as(DecimalType.class);
- if (state instanceof OpenClosedType) {
- OpenClosedType type = (OpenClosedType) state;
- value = new DecimalType(type == OpenClosedType.CLOSED ? 1 : 0);
+ if (state instanceof OpenClosedType openClosedState) {
+ value = new DecimalType(openClosedState == OpenClosedType.CLOSED ? 1 : 0);
}
Channel channel = thing.getChannel(channelUID.getId());
cBuilder.withType(new ChannelTypeUID(BINDING_ID, type.toLowerCase()));
cBuilder.withLabel(name);
cBuilder.withDescription("Digital " + text + " block " + name);
- cBuilder.withProperties(Collections.singletonMap(BLOCK_PROPERTY, name));
+ cBuilder.withProperties(Map.of(BLOCK_PROPERTY, name));
tBuilder.withChannel(cBuilder.build());
setOldValue(name, null);
}
import static org.openhab.binding.plclogo.internal.PLCLogoBindingConstants.*;
-import java.util.Collections;
import java.util.List;
+import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
@NonNullByDefault
public class PLCMemoryHandler extends PLCCommonHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_MEMORY);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_MEMORY);
private final Logger logger = LoggerFactory.getLogger(PLCMemoryHandler.class);
private AtomicReference<PLCMemoryConfiguration> config = new AtomicReference<>();
} else {
logger.debug("Can not read data from LOGO!: {}.", S7Client.ErrorText(result));
}
- } else if (command instanceof DecimalType) {
+ } else if (command instanceof DecimalType decimalCommand) {
int length = MEMORY_BYTE.equalsIgnoreCase(kind) ? 1 : 2;
byte[] buffer = new byte[MEMORY_DWORD.equalsIgnoreCase(kind) ? 4 : length];
if (ANALOG_ITEM.equalsIgnoreCase(type) && MEMORY_BYTE.equalsIgnoreCase(kind)) {
- buffer[0] = ((DecimalType) command).byteValue();
+ buffer[0] = decimalCommand.byteValue();
} else if (ANALOG_ITEM.equalsIgnoreCase(type) && MEMORY_WORD.equalsIgnoreCase(kind)) {
- S7.SetShortAt(buffer, 0, ((DecimalType) command).intValue());
+ S7.SetShortAt(buffer, 0, decimalCommand.intValue());
} else if (ANALOG_ITEM.equalsIgnoreCase(type) && MEMORY_DWORD.equalsIgnoreCase(kind)) {
- S7.SetDIntAt(buffer, 0, ((DecimalType) command).intValue());
+ S7.SetDIntAt(buffer, 0, decimalCommand.intValue());
} else {
logger.debug("Channel {} will not accept {} items.", channelUID, type);
}
if (result != 0) {
logger.debug("Can not write data to LOGO!: {}.", S7Client.ErrorText(result));
}
- } else if (command instanceof OnOffType) {
+ } else if (command instanceof OnOffType onOffCommand) {
byte[] buffer = new byte[1];
if (DIGITAL_OUTPUT_ITEM.equalsIgnoreCase(type) && MEMORY_BYTE.equalsIgnoreCase(kind)) {
- S7.SetBitAt(buffer, 0, 0, ((OnOffType) command) == OnOffType.ON);
+ S7.SetBitAt(buffer, 0, 0, onOffCommand == OnOffType.ON);
} else {
logger.debug("Channel {} will not accept {} items.", channelUID, type);
}
cBuilder.withType(new ChannelTypeUID(BINDING_ID, type.toLowerCase()));
cBuilder.withLabel(name);
cBuilder.withDescription(text + " in/output block " + name);
- cBuilder.withProperties(Collections.singletonMap(BLOCK_PROPERTY, name));
+ cBuilder.withProperties(Map.of(BLOCK_PROPERTY, name));
tBuilder.withChannel(cBuilder.build());
setOldValue(name, null);
import static org.openhab.binding.plclogo.internal.PLCLogoBindingConstants.*;
-import java.util.Collections;
import java.util.List;
+import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
@NonNullByDefault
public class PLCPulseHandler extends PLCCommonHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_PULSE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_PULSE);
private final Logger logger = LoggerFactory.getLogger(PLCPulseHandler.class);
private AtomicReference<PLCPulseConfiguration> config = new AtomicReference<>();
protected void updateState(ChannelUID channelUID, State state) {
super.updateState(channelUID, state);
DecimalType value = state.as(DecimalType.class);
- if (state instanceof OpenClosedType) {
- OpenClosedType type = (OpenClosedType) state;
- value = new DecimalType(type == OpenClosedType.CLOSED ? 1 : 0);
+ if (state instanceof OpenClosedType openClosedState) {
+ value = new DecimalType(openClosedState == OpenClosedType.CLOSED ? 1 : 0);
}
setOldValue(channelUID.getId(), value);
cBuilder.withType(new ChannelTypeUID(BINDING_ID, bType.toLowerCase()));
cBuilder.withLabel(bName);
cBuilder.withDescription("Control block " + bName);
- cBuilder.withProperties(Collections.singletonMap(BLOCK_PROPERTY, bName));
+ cBuilder.withProperties(Map.of(BLOCK_PROPERTY, bName));
tBuilder.withChannel(cBuilder.build());
setOldValue(STATE_CHANNEL, null);
cBuilder.withType(new ChannelTypeUID(BINDING_ID, oType.toLowerCase()));
cBuilder.withLabel(oName);
cBuilder.withDescription("Observed block " + oName);
- cBuilder.withProperties(Collections.singletonMap(BLOCK_PROPERTY, oName));
+ cBuilder.withProperties(Map.of(BLOCK_PROPERTY, oName));
tBuilder.withChannel(cBuilder.build());
setOldValue(OBSERVE_CHANNEL, null);
*/
public @Nullable MediaContainer getSessionData() {
try {
- String url = "https://" + host + ":" + String.valueOf(port) + "/status/sessions" + "?X-Plex-Token=" + token;
+ String url = "https://" + host + ":" + port + "/status/sessions" + "?X-Plex-Token=" + token;
logger.debug("Getting session data '{}'", url);
- MediaContainer mediaContainer = getFromXml(doHttpRequest("GET", url, getClientHeaders(), false),
- MediaContainer.class);
- return mediaContainer;
+ return getFromXml(doHttpRequest("GET", url, getClientHeaders(), false), MediaContainer.class);
} catch (IOException | InterruptedException | TimeoutException | ExecutionException e) {
logger.debug("An exception occurred while polling the PLEX Server: '{}'", e.getMessage());
return null;
* @return the completed url that will be usable
*/
public String getURL(String url) {
- String artURL = scheme + "://" + host + ":" + String.valueOf(port + url + "?X-Plex-Token=" + token);
- return artURL;
+ return scheme + "://" + host + ":" + port + url + "?X-Plex-Token=" + token;
}
/**
NotificationContainer notification = gson.fromJson(msg, NotificationContainer.class);
if (notification != null) {
PlexUpdateListener listenerLocal = listener;
- if (listenerLocal != null && notification.getNotificationContainer().getType().equals("playing")) {
+ if (listenerLocal != null && "playing".equals(notification.getNotificationContainer().getType())) {
listenerLocal.onItemStatusUpdate(
notification.getNotificationContainer().getPlaySessionStateNotification().get(0)
.getSessionKey(),
if (commandPath != null) {
try {
- String url = "https://" + host + ":" + String.valueOf(port) + commandPath;
+ String url = "https://" + host + ":" + port + commandPath;
Properties headers = getClientHeaders();
headers.put("X-Plex-Target-Client-Identifier", playerID);
doHttpRequest("GET", url, headers, false);
// configured, update
// it
tmpMeta.setArt(plexAPIConnector.getURL(tmpMeta.getArt()));
- if (tmpMeta.getType().equals("episode")) {
+ if ("episode".equals(tmpMeta.getType())) {
tmpMeta.setThumb(plexAPIConnector.getURL(tmpMeta.getGrandparentThumb()));
tmpMeta.setTitle(tmpMeta.getGrandparentTitle() + " : " + tmpMeta.getTitle());
- } else if (tmpMeta.getType().equals("track")) {
+ } else if ("track".equals(tmpMeta.getType())) {
tmpMeta.setThumb(plexAPIConnector.getURL(tmpMeta.getThumb()));
tmpMeta.setTitle(tmpMeta.getGrandparentTitle() + " - " + tmpMeta.getParentTitle() + " - "
+ tmpMeta.getTitle());
}
refreshAllPlayers();
} catch (Exception e) {
- updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, String
- .format("An exception occurred while polling the PLEX Server: '%s'", e.getMessage()).toString());
+ updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
+ String.format("An exception occurred while polling the PLEX Server: '%s'", e.getMessage()));
}
};
*/
private void parseAndQueue(ByteBuffer readBuffer) {
String response = new String(readBuffer.array(), 0, readBuffer.limit());
- response = response.replaceAll("\r", "").replaceAll("\n", "");
+ response = response.replace("\r", "").replace("\n", "");
Matcher matcher = RESPONSE_PATTERN.matcher(response);
try {
Message message = messageFactory.createMessage(messageType, sequenceNumber, payload);
- if (message instanceof AcknowledgementMessage
- && !((AcknowledgementMessage) message).isExtended()) {
+ if (message instanceof AcknowledgementMessage acknowledgementMessage
+ && !acknowledgementMessage.isExtended()) {
logger.debug("Adding to acknowledgedQueue: {}", message);
- context.getAcknowledgedQueue().put((AcknowledgementMessage) message);
+ context.getAcknowledgedQueue().put(acknowledgementMessage);
} else {
logger.debug("Adding to receivedQueue: {}", message);
context.getReceivedQueue().put(message);
@Override
public void setThingHandler(ThingHandler handler) {
- if (handler instanceof PlugwiseStickHandler) {
- stickHandler = (PlugwiseStickHandler) handler;
+ if (handler instanceof PlugwiseStickHandler plugwiseStickHandler) {
+ stickHandler = plugwiseStickHandler;
stickHandler.addStickStatusListener(this);
}
}
public void handleCommand(ChannelUID channelUID, Command command) {
logger.debug("Handling command '{}' for {} ({}) channel '{}'", command, deviceType, macAddress,
channelUID.getId());
- if (CHANNEL_STATE.equals(channelUID.getId()) && (command instanceof OnOffType)) {
+ if (CHANNEL_STATE.equals(channelUID.getId()) && (command instanceof OnOffType onOffCommand)) {
if (configuration.getPowerStateChanging() == PowerStateChanging.COMMAND_SWITCHING) {
- OnOffType onOff = (OnOffType) command;
- pendingPowerStateChange = new PendingPowerStateChange(onOff);
- handleOnOffCommand(onOff);
+ pendingPowerStateChange = new PendingPowerStateChange(onOffCommand);
+ handleOnOffCommand(onOffCommand);
} else {
OnOffType onOff = configuration.getPowerStateChanging() == PowerStateChanging.ALWAYS_ON ? OnOffType.ON
: OnOffType.OFF;
if (matcher.matches()) {
macAddress = new MACAddress(matcher.group(1));
portMask = Integer.parseInt(matcher.group(2));
- powerState = (matcher.group(3).equals("01"));
+ powerState = ("01".equals(matcher.group(3)));
} else {
throw new PlugwisePayloadMismatchException(BROADCAST_GROUP_SWITCH_RESPONSE, PAYLOAD_PATTERN, payload);
}
month = Integer.parseInt(matcher.group(3), 16);
minutes = Integer.parseInt(matcher.group(4), 16);
logAddress = (Integer.parseInt(matcher.group(5), 16) - 278528) / 32;
- powerState = (matcher.group(6).equals("01"));
+ powerState = ("01".equals(matcher.group(6)));
hertz = Integer.parseInt(matcher.group(7), 16);
hardwareVersion = matcher.group(8).substring(0, 4) + "-" + matcher.group(8).substring(4, 8) + "-"
+ matcher.group(8).substring(8, 12);
DomainObjects domainObjects = executeRequest(request);
this.gatewayUpdateDateTime = ZonedDateTime.parse(request.getServerDateTime(), PlugwiseHAController.FORMAT);
int size = 0;
- if (!(domainObjects.getAppliances() == null)) {
+ if (domainObjects.getAppliances() != null) {
size = domainObjects.getAppliances().size();
}
this.logger.debug("Found {} Plugwise Home Automation appliance(s)", size);
DomainObjects domainObjects = executeRequest(request);
this.gatewayUpdateDateTime = ZonedDateTime.parse(request.getServerDateTime(), PlugwiseHAController.FORMAT);
int size = 0;
- if (!(domainObjects.getLocations() == null)) {
+ if (domainObjects.getLocations() != null) {
size = domainObjects.getLocations().size();
}
this.logger.debug("Found {} Plugwise Home Automation Zone(s)", size);
}
try {
- ZonedDateTime dateTime = ZonedDateTime.parse(str, DateTimeConverter.FORMAT);
- return dateTime;
+ return ZonedDateTime.parse(str, DateTimeConverter.FORMAT);
} catch (DateTimeParseException e) {
logger.debug("Invalid datetime format in {}", str);
return null;
return upperBound;
}
+ @Override
public ZonedDateTime getUpdatedDate() {
return updatedDate;
}
public boolean isBatteryOperated() {
if (this.zigbeeNode instanceof ZigBeeNode) {
- return this.zigbeeNode.getPowerSource().equals("battery") && this.getBatteryLevel().isPresent();
+ return "battery".equals(this.zigbeeNode.getPowerSource()) && this.getBatteryLevel().isPresent();
} else {
return false;
}
return measurementDate;
}
+ @Override
public ZonedDateTime getUpdatedDate() {
return updatedDate;
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof PlugwiseHABridgeHandler) {
- bridgeHandler = (PlugwiseHABridgeHandler) handler;
+ if (handler instanceof PlugwiseHABridgeHandler bridgeHandler) {
+ this.bridgeHandler = bridgeHandler;
}
}
@Override
protected @Nullable Appliance getEntity(PlugwiseHAController controller) throws PlugwiseHAException {
PlugwiseHAThingConfig config = getPlugwiseThingConfig();
- Appliance appliance = controller.getAppliance(config.getId());
-
- return appliance;
+ return controller.getAppliance(config.getId());
}
@Override
switch (channelID) {
case APPLIANCE_LOCK_CHANNEL:
- if (command instanceof OnOffType) {
+ if (command instanceof OnOffType onOffCommand) {
try {
controller.setRelay(entity, (command == OnOffType.ON));
} catch (PlugwiseHAException e) {
- logger.warn("Unable to switch relay lock {} for appliance '{}'", (State) command,
+ logger.warn("Unable to switch relay lock {} for appliance '{}'", onOffCommand,
entity.getName());
}
}
break;
case APPLIANCE_OFFSET_CHANNEL:
- if (command instanceof QuantityType) {
+ if (command instanceof QuantityType quantityCommand) {
Unit<Temperature> unit = entity.getOffsetTemperatureUnit().orElse(UNIT_CELSIUS).equals(UNIT_CELSIUS)
? SIUnits.CELSIUS
: ImperialUnits.FAHRENHEIT;
- QuantityType<?> state = ((QuantityType<?>) command).toUnit(unit);
+ QuantityType<?> state = quantityCommand.toUnit(unit);
if (state != null) {
try {
}
break;
case APPLIANCE_POWER_CHANNEL:
- if (command instanceof OnOffType) {
+ if (command instanceof OnOffType onOffCommand) {
try {
controller.setRelay(entity, command == OnOffType.ON);
} catch (PlugwiseHAException e) {
- logger.warn("Unable to switch relay {} for appliance '{}'", (State) command, entity.getName());
+ logger.warn("Unable to switch relay {} for appliance '{}'", onOffCommand, entity.getName());
}
}
break;
case APPLIANCE_SETPOINT_CHANNEL:
- if (command instanceof QuantityType) {
+ if (command instanceof QuantityType quantityCommand) {
Unit<Temperature> unit = entity.getSetpointTemperatureUnit().orElse(UNIT_CELSIUS)
.equals(UNIT_CELSIUS) ? SIUnits.CELSIUS : ImperialUnits.FAHRENHEIT;
- QuantityType<?> state = ((QuantityType<?>) command).toUnit(unit);
+ QuantityType<?> state = quantityCommand.toUnit(unit);
if (state != null) {
try {
import static org.openhab.core.thing.ThingStatusDetail.*;
import java.util.Collection;
-import java.util.Collections;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(PlugwiseHADiscoveryService.class);
+ return Set.of(PlugwiseHADiscoveryService.class);
}
@Override
@Override
protected @Nullable Location getEntity(PlugwiseHAController controller) throws PlugwiseHAException {
PlugwiseHAThingConfig config = getPlugwiseThingConfig();
- Location location = controller.getLocation(config.getId());
-
- return location;
+ return controller.getLocation(config.getId());
}
@Override
if (controller != null) {
switch (channelID) {
case ZONE_COOLING_CHANNEL:
- if (command instanceof OnOffType) {
+ if (command instanceof OnOffType onOffCommand) {
try {
controller.setAllowCooling(entity, command == OnOffType.ON);
} catch (PlugwiseHAException e) {
- logger.warn("Unable to switch allow cooling {} for zone '{}'", (State) command,
+ logger.warn("Unable to switch allow cooling {} for zone '{}'", onOffCommand,
entity.getName());
}
}
break;
case ZONE_SETPOINT_CHANNEL:
- if (command instanceof QuantityType) {
+ if (command instanceof QuantityType quantityCommand) {
Unit<Temperature> unit = entity.getSetpointTemperatureUnit().orElse(UNIT_CELSIUS)
.equals(UNIT_CELSIUS) ? SIUnits.CELSIUS : ImperialUnits.FAHRENHEIT;
- QuantityType<?> state = ((QuantityType<?>) command).toUnit(unit);
+ QuantityType<?> state = quantityCommand.toUnit(unit);
if (state != null) {
try {
controller.setLocationThermostat(entity, state.doubleValue());
}
break;
case ZONE_PREHEAT_CHANNEL:
- if (command instanceof OnOffType) {
+ if (command instanceof OnOffType onOffCommand) {
try {
controller.setPreHeating(entity, command == OnOffType.ON);
} catch (PlugwiseHAException e) {
- logger.warn("Unable to switch zone pre heating {} for zone '{}'", (State) command,
+ logger.warn("Unable to switch zone pre heating {} for zone '{}'", onOffCommand,
entity.getName());
}
}
break;
case ZONE_REGULATION_CHANNEL:
- if (command instanceof StringType) {
+ if (command instanceof StringType stringCommand) {
try {
controller.setRegulationControl(entity, command.toString());
} catch (PlugwiseHAException e) {
- logger.warn("Unable to switch regulation control {} for zone '{}'", (State) command,
+ logger.warn("Unable to switch regulation control {} for zone '{}'", stringCommand,
entity.getName());
}
}
break;
case ZONE_PRESETSCENE_CHANNEL:
- if (command instanceof StringType) {
+ if (command instanceof StringType stringCommand) {
try {
controller.setPresetScene(entity, command.toString());
} catch (PlugwiseHAException e) {
- logger.warn("Unable to switch preset scene {} for zone '{}'", (State) command,
+ logger.warn("Unable to switch preset scene {} for zone '{}'", stringCommand,
entity.getName());
}
}
PowermaxBridgeHandler handler = null;
if (thing != null) {
thingHandler = thing.getHandler();
- if (thingHandler instanceof PowermaxBridgeHandler) {
- handler = (PowermaxBridgeHandler) thingHandler;
+ if (thingHandler instanceof PowermaxBridgeHandler bridgeHandler) {
+ handler = bridgeHandler;
}
}
if (thing == null) {
@Override
public void setThingHandler(ThingHandler handler) {
- if (handler instanceof PowermaxBridgeHandler) {
- bridgeHandler = (PowermaxBridgeHandler) handler;
+ if (handler instanceof PowermaxBridgeHandler powermaxBridgeHandler) {
+ bridgeHandler = powermaxBridgeHandler;
}
}
for (Thing thing : handler.getThing().getThings()) {
ThingHandler thingHandler = thing.getHandler();
if (thing.getThingTypeUID().equals(PowermaxBindingConstants.THING_TYPE_ZONE)
- && thingHandler instanceof PowermaxThingHandler) {
- PowermaxZoneConfiguration config = ((PowermaxThingHandler) thingHandler).getZoneConfiguration();
+ && thingHandler instanceof PowermaxThingHandler powermaxThingHandler) {
+ PowermaxZoneConfiguration config = powermaxThingHandler.getZoneConfiguration();
if (config.zoneNumber == zoneNumber) {
return;
}
for (Thing thing : handler.getThing().getThings()) {
ThingHandler thingHandler = thing.getHandler();
if (thing.getThingTypeUID().equals(PowermaxBindingConstants.THING_TYPE_X10)
- && thingHandler instanceof PowermaxThingHandler) {
- PowermaxX10Configuration config = ((PowermaxThingHandler) thingHandler).getX10Configuration();
+ && thingHandler instanceof PowermaxThingHandler powermaxThingHandler) {
+ PowermaxX10Configuration config = powermaxThingHandler.getX10Configuration();
if (config.deviceNumber == deviceNumber) {
return;
}
import static org.openhab.binding.powermax.internal.PowermaxBindingConstants.*;
import java.util.Collection;
-import java.util.Collections;
import java.util.EventObject;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(PowermaxDiscoveryService.class);
+ return Set.of(PowermaxDiscoveryService.class);
}
public @Nullable PowermaxState getCurrentState() {
continue;
}
ThingHandler thingHandler = thing.getHandler();
- if (thingHandler instanceof PowermaxThingHandler) {
- PowermaxThingHandler handler = (PowermaxThingHandler) thingHandler;
+ if (thingHandler instanceof PowermaxThingHandler powermaxThingHandler) {
if (thing.getThingTypeUID().equals(THING_TYPE_ZONE)) {
// All of the zone state objects will have the same list of values.
// The use of getZone(1) here is just to get any PowermaxZoneState
for (Value<?> value : state.getZone(1).getValues()) {
String channelId = value.getChannel();
if ((channel == null) || channel.equals(channelId)) {
- handler.updateChannelFromAlarmState(channelId, state);
+ powermaxThingHandler.updateChannelFromAlarmState(channelId, state);
}
}
} else if (thing.getThingTypeUID().equals(THING_TYPE_X10)) {
if ((channel == null) || channel.equals(X10_STATUS)) {
- handler.updateChannelFromAlarmState(X10_STATUS, state);
+ powermaxThingHandler.updateChannelFromAlarmState(X10_STATUS, state);
}
}
}
// System events
- public static enum PowermaxSysEventType {
+ public enum PowermaxSysEventType {
NONE,
ALARM,
SILENT_ALARM,
RESTORE,
GENERAL_RESTORE,
CANCEL,
- RESET;
+ RESET
}
public static class PowermaxSysEvent {
} else if (zoneEType == 0x05) {
// Violated (Motion)
PowermaxZoneSettings zone = panelSettings.getZoneSettings(eventZone);
- if ((zone != null) && zone.getSensorType().equalsIgnoreCase("unknown")) {
+ if ((zone != null) && "unknown".equalsIgnoreCase(zone.getSensorType())) {
zone.setSensorType(PowermaxSensorType.MOTION_SENSOR_1.getLabel());
}
updatedState.getZone(eventZone).tripped.setValue(true);
// the sensor type always triggers an alarm
// or the system is armed away
// or the system is armed home and the zone is not interior(-follow)
- boolean armed = (!zone.getType().equalsIgnoreCase("Non-Alarm")
+ boolean armed = (!"Non-Alarm".equalsIgnoreCase(zone.getType())
&& (zone.isAlwaysInAlarm() || (mode == PowermaxArmMode.ARMED_AWAY.getCode())
|| ((mode == PowermaxArmMode.ARMED_HOME.getCode())
- && !zone.getType().equalsIgnoreCase("Interior-Follow")
- && !zone.getType().equalsIgnoreCase("Interior"))));
+ && !"Interior-Follow".equalsIgnoreCase(zone.getType())
+ && !"Interior".equalsIgnoreCase(zone.getType()))));
updatedState.getZone(i).armed.setValue(armed);
}
});
public StringValue lastMessage = new StringValue(this, ZONE_LAST_MESSAGE);
public DateTimeValue lastMessageTime = new DateTimeValue(this, ZONE_LAST_MESSAGE_TIME);
- public DynamicValue<Boolean> locked = new DynamicValue<>(this, LOCKED, () -> {
- return armed.getValue();
- }, () -> {
+ public DynamicValue<Boolean> locked = new DynamicValue<>(this, LOCKED, () -> armed.getValue(), () -> {
Boolean isArmed = armed.getValue();
if (isArmed == null) {
return UnDefType.NULL;
import static org.openhab.binding.prowl.internal.ProwlBindingConstants.*;
import java.util.Collection;
-import java.util.Collections;
+import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singletonList(ProwlActions.class);
+ return List.of(ProwlActions.class);
}
public void pushNotification(@Nullable String event, @Nullable String description) {
public static void pushNotification(@Nullable ThingActions actions, @Nullable String event,
@Nullable String description, int priority) {
- if (actions instanceof ProwlActions) {
- ((ProwlActions) actions).pushNotification(event, description, priority);
+ if (actions instanceof ProwlActions prowlActions) {
+ prowlActions.pushNotification(event, description, priority);
} else {
throw new IllegalArgumentException("Instance is not a ProwlActions class.");
}
import static org.openhab.binding.publictransportswitzerland.internal.PublicTransportSwitzerlandBindingConstants.*;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.publictransportswitzerland", service = ThingHandlerFactory.class)
public class PublicTransportSwitzerlandHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_STATIONBOARD);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_STATIONBOARD);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
if (categoryElement == null || numberElement == null || destinationElement == null
|| departureTimeElement == null) {
- logger.warn("Skipping stationboard item."
- + "One of the following is null: category: {}, number: {}, destination: {}, departureTime: {}",
- categoryElement, numberElement, destinationElement, departureTimeElement);
+ logger.warn("""
+ Skipping stationboard item.\
+ One of the following is null: category: {}, number: {}, destination: {}, departureTime: {}\
+ """, categoryElement, numberElement, destinationElement, departureTimeElement);
continue;
}
*/
public @Nullable Sink getSink(String name) {
for (AbstractAudioDeviceConfig item : items) {
- if (item.getPaName().equalsIgnoreCase(name) && item instanceof Sink) {
- return (Sink) item;
+ if (item.getPaName().equalsIgnoreCase(name) && item instanceof Sink sink) {
+ return sink;
}
}
return null;
*/
public @Nullable Sink getSink(int id) {
for (AbstractAudioDeviceConfig item : items) {
- if (item.getId() == id && item instanceof Sink) {
- return (Sink) item;
+ if (item.getId() == id && item instanceof Sink sink) {
+ return sink;
}
}
return null;
*/
public @Nullable Source getSource(int id) {
for (AbstractAudioDeviceConfig item : items) {
- if (item.getId() == id && item instanceof Source) {
- return (Source) item;
+ if (item.getId() == id && item instanceof Source source) {
+ return source;
}
}
return null;
currentTry++;
} while (currentTry < 3);
- logger.warn("The pulseaudio binding tried 3 times to load the module-simple-protocol-tcp"
- + " on random port on the pulseaudio server and give up trying");
+ logger.warn("""
+ The pulseaudio binding tried 3 times to load the module-simple-protocol-tcp\
+ on random port on the pulseaudio server and give up trying\
+ """);
return Optional.empty();
}
Map<String, Object> properties = new HashMap<>();
// All devices need this parameter
properties.put(PulseaudioBindingConstants.DEVICE_PARAMETER_NAME_OR_DESCRIPTION, uidName);
- if (device instanceof Sink) {
- if (((Sink) device).isCombinedSink()) {
+ if (device instanceof Sink sink) {
+ if (sink.isCombinedSink()) {
thingType = PulseaudioBindingConstants.COMBINED_SINK_THING_TYPE;
} else {
thingType = PulseaudioBindingConstants.SINK_THING_TYPE;
import java.io.IOException;
import java.math.BigDecimal;
-import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PulseaudioBridgeHandler extends BaseBridgeHandler implements PulseAudioBindingConfigurationListener {
private final Logger logger = LoggerFactory.getLogger(PulseaudioBridgeHandler.class);
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .singleton(PulseaudioBindingConstants.BRIDGE_THING_TYPE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set
+ .of(PulseaudioBindingConstants.BRIDGE_THING_TYPE);
public String host = "localhost";
public int port = 4712;
@Override
public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
- if (childHandler instanceof PulseaudioHandler) {
- this.childHandlersInitialized.add((PulseaudioHandler) childHandler);
+ if (childHandler instanceof PulseaudioHandler pulsaudioHandler) {
+ this.childHandlersInitialized.add(pulsaudioHandler);
} else {
logger.error("This bridge can only support PulseaudioHandler child");
}
return null;
}
ThingHandler handler = bridge.getHandler();
- if (handler instanceof PulseaudioBridgeHandler) {
- return (PulseaudioBridgeHandler) handler;
+ if (handler instanceof PulseaudioBridgeHandler pulseaudioBridgeHandler) {
+ return pulseaudioBridgeHandler;
} else {
logger.debug("No available bridge handler found for device {} bridge {} .",
safeGetDeviceNameOrDescription(), bridge.getUID());
briHandler.getClient().setVolumePercent(device, newVolume);
updateState = new PercentType(newVolume);
savedVolume = newVolume;
- } else if (command instanceof PercentType) {
- DecimalType volume = (DecimalType) command;
+ } else if (command instanceof PercentType volume) {
briHandler.getClient().setVolumePercent(device, volume.intValue());
- updateState = (PercentType) command;
+ updateState = volume;
savedVolume = volume.intValue();
- } else if (command instanceof DecimalType) {
- // set volume
- DecimalType volume = (DecimalType) command;
+ } else if (command instanceof DecimalType volume) {
briHandler.getClient().setVolume(device, volume.intValue());
- updateState = (DecimalType) command;
+ updateState = volume;
savedVolume = volume.intValue();
}
} else if (channelUID.getId().equals(MUTE_CHANNEL)) {
- if (command instanceof OnOffType) {
+ if (command instanceof OnOffType onOffCommand) {
briHandler.getClient().setMute(device, OnOffType.ON.equals(command));
- updateState = (OnOffType) command;
+ updateState = onOffCommand;
}
} else if (channelUID.getId().equals(SLAVES_CHANNEL)) {
- if (device instanceof Sink && ((Sink) device).isCombinedSink()) {
+ if (device instanceof Sink sink && sink.isCombinedSink()) {
if (command instanceof StringType) {
List<Sink> slaves = new ArrayList<>();
for (String slaveName : command.toString().split(",")) {
logger.warn("{} is no combined sink", device);
}
} else if (channelUID.getId().equals(ROUTE_TO_SINK_CHANNEL)) {
- if (device instanceof SinkInput) {
+ if (device instanceof SinkInput input) {
Sink newSink = null;
- if (command instanceof DecimalType) {
- newSink = briHandler.getClient().getSink(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ newSink = briHandler.getClient().getSink(decimalCommand.intValue());
} else {
newSink = briHandler.getClient().getSink(command.toString());
}
if (newSink != null) {
logger.debug("rerouting {} to {}", device, newSink);
- briHandler.getClient().moveSinkInput(((SinkInput) device), newSink);
+ briHandler.getClient().moveSinkInput(input, newSink);
updateState = new StringType(newSink.getPaName());
} else {
logger.warn("no sink {} found", command.toString());
updateState(MUTE_CHANNEL, OnOffType.from(device.isMuted()));
org.openhab.binding.pulseaudio.internal.items.AbstractAudioDeviceConfig.State state = device.getState();
updateState(STATE_CHANNEL, state != null ? new StringType(state.toString()) : new StringType("-"));
- if (device instanceof SinkInput) {
- updateState(ROUTE_TO_SINK_CHANNEL, new StringType(
- Optional.ofNullable(((SinkInput) device).getSink()).map(Sink::getPaName).orElse("-")));
+ if (device instanceof SinkInput input) {
+ updateState(ROUTE_TO_SINK_CHANNEL,
+ new StringType(Optional.ofNullable(input.getSink()).map(Sink::getPaName).orElse("-")));
}
- if (device instanceof Sink && ((Sink) device).isCombinedSink()) {
- updateState(SLAVES_CHANNEL, new StringType(String.join(",", ((Sink) device).getCombinedSinkNames())));
+ if (device instanceof Sink sink && sink.isCombinedSink()) {
+ updateState(SLAVES_CHANNEL, new StringType(String.join(",", sink.getCombinedSinkNames())));
}
audioSinkSetup();
audioSourceSetup();
*/
package org.openhab.binding.pushbullet.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
// List of all Thing Type UIDs
public static final ThingTypeUID THING_TYPE_BOT = new ThingTypeUID(BINDING_ID, "bot");
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_BOT);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_BOT);
// List of all Channel ids
public static final String RECIPIENT = "recipient";
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
-import java.util.Collections;
import java.util.Properties;
+import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(PushbulletActions.class);
+ return Set.of(PushbulletActions.class);
}
public boolean sendPush(@Nullable String recipient, @Nullable String message, String type) {
logger.debug("Unpacked Response: {}", response);
- stream.close();
-
if ((null != response) && (null == response.getPushError())) {
result = true;
}
*/
package org.openhab.binding.qbus.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
// bridge
public static final ThingTypeUID BRIDGE_THING_TYPE = new ThingTypeUID(BINDING_ID, "bridge");
- 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);
// Bridge config properties
public static final String CONFIG_HOST_NAME = "addr";
public static final String CONFIG_PORT = "port";
*/
public ThingStatusDetail getStatusDetails() {
ThingStatusInfo status = thing.getStatusInfo();
- ThingStatusDetail detail = status.getStatusDetail();
- return detail;
+ return status.getStatusDetail();
}
/**
@Override
protected @Nullable ThingHandler createHandler(Thing thing) {
if (BRIDGE_THING_TYPES_UIDS.contains(thing.getThingTypeUID())) {
- QbusBridgeHandler handler = new QbusBridgeHandler((Bridge) thing);
- return handler;
+ return new QbusBridgeHandler((Bridge) thing);
} else if (SCENE_THING_TYPES_UIDS.contains(thing.getThingTypeUID())) {
return new QbusSceneHandler(thing);
} else if (BISTABIEL_THING_TYPES_UIDS.contains(thing.getThingTypeUID())) {
qDimmer.execute(sendvalue, snr);
}
}
- } else if (command instanceof PercentType) {
- int percentToInt = ((PercentType) command).intValue();
+ } else if (command instanceof PercentType percentCommand) {
+ int percentToInt = percentCommand.intValue();
if (PercentType.ZERO.equals(command)) {
qDimmer.execute(0, snr);
} else {
"No bridge handler initialized for " + type + " with id " + globalId + ".");
return null;
}
- QbusCommunication qComm = qBridgeHandler.getCommunication();
- return qComm;
+ return qBridgeHandler.getCommunication();
}
/**
"No bridge initialized for " + type + " with ID " + globalId);
return null;
}
- QbusBridgeHandler qBridgeHandler = (QbusBridgeHandler) qBridge.getHandler();
- return qBridgeHandler;
+ return (QbusBridgeHandler) qBridge.getHandler();
}
/**
private void handleScreenposCommand(QbusRol qRol, Command command) throws InterruptedException, IOException {
String snr = getSN();
if (snr != null) {
- if (command instanceof UpDownType) {
- UpDownType upDown = (UpDownType) command;
- if (upDown == DOWN) {
+ if (command instanceof UpDownType upDownCommand) {
+ if (upDownCommand == DOWN) {
qRol.execute(0, snr);
} else {
qRol.execute(100, snr);
}
- } else if (command instanceof IncreaseDecreaseType) {
- IncreaseDecreaseType inc = (IncreaseDecreaseType) command;
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
int stepValue = ((Number) getConfig().get(CONFIG_STEP_VALUE)).intValue();
Integer currentValue = qRol.getState();
int newValue;
int sendValue;
if (currentValue != null) {
- if (inc == IncreaseDecreaseType.INCREASE) {
+ if (increaseDecreaseCommand == increaseDecreaseCommand.INCREASE) {
newValue = currentValue + stepValue;
// round down to step multiple
newValue = newValue - newValue % stepValue;
qRol.execute(sendValue, snr);
}
}
- } else if (command instanceof PercentType) {
- PercentType p = (PercentType) command;
- int pp = p.intValue();
- if (PercentType.ZERO.equals(p)) {
+ } else if (command instanceof PercentType percentCommand) {
+ int pp = percentCommand.intValue();
+ if (PercentType.ZERO.equals(percentCommand)) {
qRol.execute(0, snr);
} else {
qRol.execute(pp, snr);
qRol.executeSlats(sendValue, snr);
}
}
- } else if (command instanceof PercentType) {
- int percentToInt = ((PercentType) command).intValue();
+ } else if (command instanceof PercentType percentCommand) {
+ int percentToInt = percentCommand.intValue();
if (PercentType.ZERO.equals(command)) {
qRol.executeSlats(0, snr);
} else {
throws InterruptedException, IOException {
String snr = getSN();
if (snr != null) {
- if (command instanceof DecimalType) {
- int mode = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ int mode = decimalCommand.intValue();
qThermostat.executeMode(mode, snr);
}
}
throws InterruptedException, IOException {
String snr = getSN();
if (snr != null) {
- if (command instanceof QuantityType<?>) {
- QuantityType<?> s = (QuantityType<?>) command;
- double sp = s.doubleValue();
- QuantityType<?> spCelcius = s.toUnit(CELSIUS);
+ if (command instanceof QuantityType<?> quantityCommand) {
+ double sp = quantityCommand.doubleValue();
+ QuantityType<?> spCelcius = quantityCommand.toUnit(CELSIUS);
if (spCelcius != null) {
qThermostat.executeSetpoint(sp, snr);
}
if (ctdState != null) {
- if (ctdType.equals("bistabiel")) {
+ if ("bistabiel".equals(ctdType)) {
QbusBistabiel output = new QbusBistabiel(ctdId);
if (!bistabiel.containsKey(ctdId)) {
output.setQComm(this);
} else {
output.updateState(ctdStateI);
}
- } else if (ctdType.equals("dimmer")) {
+ } else if ("dimmer".equals(ctdType)) {
QbusDimmer output = new QbusDimmer(ctdId);
if (!dimmer.containsKey(ctdId)) {
output.setQComm(this);
} else {
output.updateState(ctdStateI);
}
- } else if (ctdType.equals("CO2")) {
+ } else if ("CO2".equals(ctdType)) {
QbusCO2 output = new QbusCO2();
if (!co2.containsKey(ctdId)) {
output.updateState(ctdStateI);
} else {
output.updateState(ctdStateI);
}
- } else if (ctdType.equals("scene")) {
+ } else if ("scene".equals(ctdType)) {
QbusScene output = new QbusScene(ctdId);
if (!scene.containsKey(ctdId)) {
output.setQComm(this);
scene.put(ctdId, output);
}
- } else if (ctdType.equals("rol")) {
+ } else if ("rol".equals(ctdType)) {
QbusRol output = new QbusRol(ctdId);
if (!rol.containsKey(ctdId)) {
output.setQComm(this);
}
}
} else if (ctdMeasuredD != null && ctdSetpointD != null && ctdMmodeI != null) {
- if (ctdType.equals("thermostat")) {
+ if ("thermostat".equals(ctdType)) {
QbusThermostat output = new QbusThermostat(ctdId);
if (!thermostat.containsKey(ctdId)) {
output.setQComm(this);
public enum ArmingActionType {
ARM_AWAY,
ARM_STAY,
- DISARM;
+ DISARM
}
ARMING,
ERROR,
INFO,
- ZONE_EVENT;
+ ZONE_EVENT
}
*/
public enum InfoEventType {
SUMMARY,
- SECURE_ARM;
+ SECURE_ARM
}
public enum ZoneEventType {
ZONE_ACTIVE,
ZONE_ADD,
- ZONE_UPDATE;
+ ZONE_UPDATE
}
POLICE,
@SerializedName("")
ZONEOPEN,
- NONE;
+ NONE
}
ARM_STAY,
DISARM,
ENTRY_DELAY,
- EXIT_DELAY;
+ EXIT_DELAY
}
@SerializedName("Idle")
IDlE,
@SerializedName("Tamper")
- TAMPER;
+ TAMPER
}
@SerializedName("120")
ZWAVE_SIREN,
@SerializedName("121")
- COUNT;
+ COUNT
}
@Override
public void setThingHandler(ThingHandler handler) {
- if (handler instanceof QolsysIQChildDiscoveryHandler) {
- ((QolsysIQChildDiscoveryHandler) handler).setDiscoveryService(this);
+ if (handler instanceof QolsysIQChildDiscoveryHandler childDiscoveryHandler) {
+ childDiscoveryHandler.setDiscoveryService(this);
this.thingHandler = handler;
}
}
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(QolsysIQChildDiscoveryService.class);
+ return Set.of(QolsysIQChildDiscoveryService.class);
}
@Override
private @Nullable QolsysIQPartitionHandler partitionHandler(int partitionId) {
for (Thing thing : getThing().getThings()) {
ThingHandler handler = thing.getHandler();
- if (handler instanceof QolsysIQPartitionHandler) {
- if (((QolsysIQPartitionHandler) handler).getPartitionId() == partitionId) {
- return (QolsysIQPartitionHandler) handler;
+ if (handler instanceof QolsysIQPartitionHandler partitionHandler) {
+ if (partitionHandler.getPartitionId() == partitionId) {
+ return partitionHandler;
}
}
}
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(QolsysIQChildDiscoveryService.class);
+ return Set.of(QolsysIQChildDiscoveryService.class);
}
@Override
private @Nullable QolsysIQZoneHandler zoneHandler(int zoneId) {
for (Thing thing : getThing().getThings()) {
ThingHandler handler = thing.getHandler();
- if (handler instanceof QolsysIQZoneHandler) {
- if (((QolsysIQZoneHandler) handler).getZoneId() == zoneId) {
- return (QolsysIQZoneHandler) handler;
+ if (handler instanceof QolsysIQZoneHandler zoneHandler) {
+ if (zoneHandler.getZoneId() == zoneId) {
+ return zoneHandler;
}
}
}
Bridge bridge = getBridge();
if (bridge != null) {
BridgeHandler handler = bridge.getHandler();
- if (handler instanceof QolsysIQPanelHandler) {
- return (QolsysIQPanelHandler) handler;
+ if (handler instanceof QolsysIQPanelHandler panelHandler) {
+ return panelHandler;
}
}
return null;
private void initializeZone() {
Bridge bridge = getBridge();
BridgeHandler handler = bridge == null ? null : bridge.getHandler();
- if (bridge != null && handler instanceof QolsysIQPartitionHandler) {
+ if (bridge != null && handler instanceof QolsysIQPartitionHandler partitionHandler) {
if (handler.getThing().getStatus() != ThingStatus.ONLINE) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
return;
}
- Zone z = ((QolsysIQPartitionHandler) handler).getZone(getZoneId());
+ Zone z = partitionHandler.getZone(getZoneId());
if (z == null) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Zone not found in partition");
return;
ThingTypeUID thingTypeUID = thing.getThingTypeUID();
if (thingTypeUID.equals(THING_TYPE_RTHERM)) {
- RadioThermostatHandler handler = new RadioThermostatHandler(thing, stateDescriptionProvider, httpClient);
- return handler;
+ return new RadioThermostatHandler(thing, stateDescriptionProvider, httpClient);
}
return null;
// The setpoint mode is controlled by the name of setpoint attribute sent to the thermostat.
// Temporary mode uses setpoint names prefixed with "t_" while absolute mode uses "a_"
- if (config.setpointMode.equals("absolute")) {
+ if ("absolute".equals(config.setpointMode)) {
this.setpointCmdKeyPrefix = "a_";
}
State state = null;
if (value == null) {
state = UnDefType.UNDEF;
- } else if (value instanceof PointType) {
- state = (PointType) value;
- } else if (value instanceof ZonedDateTime) {
- state = new DateTimeType((ZonedDateTime) value);
- } else if (value instanceof QuantityType<?>) {
- state = (QuantityType<?>) value;
- } else if (value instanceof Number) {
- state = new DecimalType((Number) value);
+ } else if (value instanceof PointType pointCommand) {
+ state = pointCommand;
+ } else if (value instanceof ZonedDateTime zonedDateTimeCommand) {
+ state = new DateTimeType(zonedDateTimeCommand);
+ } else if (value instanceof QuantityType<?> quantityCommand) {
+ state = quantityCommand;
+ } else if (value instanceof Number numberCommand) {
+ state = new DecimalType(numberCommand);
} else if (value instanceof String) {
state = new StringType(value.toString());
- } else if (value instanceof OnOffType) {
- state = (OnOffType) value;
+ } else if (value instanceof OnOffType onOffCommand) {
+ state = onOffCommand;
} else {
logger.warn("Update channel {}: Unsupported value type {}", channelId,
value.getClass().getSimpleName());
*/
package org.openhab.binding.remoteopenhab.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
public static final ThingTypeUID THING_TYPE_THING = new ThingTypeUID(BINDING_ID, "thing");
// All supported Bridge types
- public static final Set<ThingTypeUID> SUPPORTED_BRIDGE_TYPES_UIDS = Collections.singleton(BRIDGE_TYPE_SERVER);
+ public static final Set<ThingTypeUID> SUPPORTED_BRIDGE_TYPES_UIDS = Set.of(BRIDGE_TYPE_SERVER);
// All supported Thing types
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_THING);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_THING);
// List of all channel types
public static final String CHANNEL_TYPE_TRIGGER = "trigger";
@Override
public void setThingHandler(ThingHandler handler) {
- if (handler instanceof RemoteopenhabBridgeHandler) {
- this.bridgeHandler = (RemoteopenhabBridgeHandler) handler;
+ if (handler instanceof RemoteopenhabBridgeHandler remoteopenhabBridgeHandler) {
+ this.bridgeHandler = remoteopenhabBridgeHandler;
this.restClient = bridgeHandler.gestRestClient();
}
}
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
} else if (acceptedItemType.startsWith(CoreItemFactory.NUMBER + ":")) {
// Item type Number with dimension
if (stateType == null || "Quantity".equals(stateType)) {
- List<Class<? extends State>> stateTypes = Collections.singletonList(QuantityType.class);
+ List<Class<? extends State>> stateTypes = List.of(QuantityType.class);
channelState = TypeParser.parseState(stateTypes, state);
} else if ("Decimal".equals(stateType)) {
channelState = new DecimalType(state);
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(RemoteopenhabDiscoveryService.class);
+ return Set.of(RemoteopenhabDiscoveryService.class);
}
}
String statusLine = statusCode + " " + response.getReason();
throw new RemoteopenhabException("@text/exception.http-call-failed", statusLine);
}
- String encoding = response.getEncoding() != null ? response.getEncoding().replaceAll("\"", "").trim()
+ String encoding = response.getEncoding() != null ? response.getEncoding().replace("\"", "").trim()
: StandardCharsets.UTF_8.name();
return new String(response.getContent(), encoding);
}
- } catch (RemoteopenhabException e) {
- throw e;
} catch (ExecutionException e) {
// After a long network outage, the first HTTP request will fail with an EOFException exception.
// We retry the request a second time in this case.
JsonObject attributes = getAttributes(responseJson);
if (attributes != null) {
if (attributes.get("hvacStatus") != null) {
- hvacstatus = attributes.get("hvacStatus").getAsString().equals("on");
+ hvacstatus = "on".equals(attributes.get("hvacStatus").getAsString());
}
if (attributes.get("externalTemperature") != null) {
externalTemperature = attributes.get("externalTemperature").getAsDouble();
String url = null;
for (JsonElement asset : assetsJson) {
if (asset.getAsJsonObject().get("assetType") != null
- && asset.getAsJsonObject().get("assetType").getAsString().equals("PICTURE")) {
+ && "PICTURE".equals(asset.getAsJsonObject().get("assetType").getAsString())) {
if (asset.getAsJsonObject().get("renditions") != null) {
JsonArray renditions = asset.getAsJsonObject().get("renditions").getAsJsonArray();
for (JsonElement rendition : renditions) {
- if (rendition.getAsJsonObject().get("resolutionType") != null
- && rendition.getAsJsonObject().get("resolutionType").getAsString()
- .equals("ONE_MYRENAULT_SMALL")) {
+ if (rendition.getAsJsonObject().get("resolutionType") != null && "ONE_MYRENAULT_SMALL"
+ .equals(rendition.getAsJsonObject().get("resolutionType").getAsString())) {
url = rendition.getAsJsonObject().get("url").getAsString();
break;
}
public void actionPause(boolean mode) throws RenaultForbiddenException, RenaultNotImplementedException,
RenaultActionException, RenaultAPIGatewayException {
-
final String apiMode = mode ? "pause" : "resume";
final String path = "/commerce/v1/accounts/" + kamereonaccountId + "/kamereon/kcm/v1/vehicles/" + config.vin
+ "/charge/pause-resume?country=" + getCountry(config);
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
-
switch (channelUID.getId()) {
case RenaultBindingConstants.CHANNEL_HVAC_TARGET_TEMPERATURE:
if (!car.isDisableHvac()) {
if (command instanceof RefreshType) {
updateState(CHANNEL_HVAC_TARGET_TEMPERATURE,
new QuantityType<Temperature>(car.getHvacTargetTemperature(), SIUnits.CELSIUS));
- } else if (command instanceof DecimalType) {
- car.setHvacTargetTemperature(((DecimalType) command).doubleValue());
+ } else if (command instanceof DecimalType decimalCommand) {
+ car.setHvacTargetTemperature(decimalCommand.doubleValue());
updateState(CHANNEL_HVAC_TARGET_TEMPERATURE,
new QuantityType<Temperature>(car.getHvacTargetTemperature(), SIUnits.CELSIUS));
} else if (command instanceof QuantityType) {
import java.io.IOException;
import java.net.InetAddress;
import java.util.Collection;
-import java.util.Collections;
import java.util.Locale;
import java.util.Objects;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(ResolDeviceDiscoveryService.class);
+ return Set.of(ResolDeviceDiscoveryService.class);
}
public void registerResolThingListener(ResolEmuEMThingHandler resolEmuEMThingHandler) {
getThing().getThings().stream().forEach(thing -> {
ThingHandler th = thing.getHandler();
- if (th instanceof ResolEmuEMThingHandler) {
- ((ResolEmuEMThingHandler) th).stop();
+ if (th instanceof ResolEmuEMThingHandler resolEmuEMThingHandler) {
+ resolEmuEMThingHandler.stop();
}
});
getThing().getThings().stream().forEach(thing -> {
ThingHandler th = thing.getHandler();
- if (th instanceof ResolEmuEMThingHandler) {
- ((ResolEmuEMThingHandler) th).useConnection(c);
+ if (th instanceof ResolEmuEMThingHandler resolEmuEMThingHandler) {
+ resolEmuEMThingHandler.useConnection(c);
}
});
} catch (IOException e) {
connection.disconnect();
getThing().getThings().stream().forEach(thing -> {
ThingHandler th = thing.getHandler();
- if (th instanceof ResolEmuEMThingHandler) {
- ((ResolEmuEMThingHandler) th).stop();
+ if (th instanceof ResolEmuEMThingHandler resolEmuEMThingHandler) {
+ resolEmuEMThingHandler.stop();
}
});
-
}
} catch (IOException ioe) {
// we don't care about exceptions on disconnect in dispose
ResolBridgeHandler bridgeHandler = null;
ThingHandler handler = bridge.getHandler();
- if (handler instanceof ResolBridgeHandler) {
- bridgeHandler = (ResolBridgeHandler) handler;
+ if (handler instanceof ResolBridgeHandler resolBridgeHandler) {
+ bridgeHandler = resolBridgeHandler;
} else {
logger.debug("No available bridge handler found yet. Bridge: {} .", bridge.getUID());
}
float value = 0;
int intValue = 0;
- if (command instanceof QuantityType<?>) {
- value = Objects.requireNonNullElse(((QuantityType<?>) command).toUnit(SIUnits.CELSIUS),
+ if (command instanceof QuantityType<?> quantityCommand) {
+ value = Objects.requireNonNullElse(quantityCommand.toUnit(SIUnits.CELSIUS),
new QuantityType<>(888.8, SIUnits.CELSIUS)).floatValue();
- } else if (command instanceof OnOffType) {
- intValue = ((OnOffType) command).equals(OnOffType.ON) ? 1 : 0;
- } else if (command instanceof DecimalType) {
- intValue = ((DecimalType) command).intValue();
+ } else if (command instanceof OnOffType onOffCommand) {
+ intValue = onOffCommand.equals(OnOffType.ON) ? 1 : 0;
+ } else if (command instanceof DecimalType decimalCommand) {
+ intValue = decimalCommand.intValue();
value = intValue;
} else {
/* nothing to do */
ResolBridgeHandler bridgeHandler = null;
ThingHandler handler = bridge.getHandler();
- if (handler instanceof ResolBridgeHandler) {
- bridgeHandler = (ResolBridgeHandler) handler;
+ if (handler instanceof ResolBridgeHandler resolBridgeHandler) {
+ bridgeHandler = resolBridgeHandler;
} else {
logger.debug("No available bridge handler found yet. Bridge: {} .", bridge.getUID());
}
@Override
public void setThingHandler(ThingHandler handler) {
- if (handler instanceof ResolBridgeHandler) {
- resolBridgeHandler = (ResolBridgeHandler) handler;
+ if (handler instanceof ResolBridgeHandler resolBridgeHandler) {
+ this.resolBridgeHandler = resolBridgeHandler;
}
}
*/
package org.openhab.binding.revogi.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.revogi", service = ThingHandlerFactory.class)
public class RevogiSmartStripControlHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .singleton(RevogiSmartStripControlBindingConstants.SMART_STRIP_THING_TYPE);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set
+ .of(RevogiSmartStripControlBindingConstants.SMART_STRIP_THING_TYPE);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
*/
package org.openhab.binding.revogi.internal;
-import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component(service = DiscoveryService.class, configurationPid = "discovery.revogi")
@NonNullByDefault
public class RevogiSmartStripDiscoveryService extends AbstractDiscoveryService {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections
- .singleton(RevogiSmartStripControlBindingConstants.SMART_STRIP_THING_TYPE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set
+ .of(RevogiSmartStripControlBindingConstants.SMART_STRIP_THING_TYPE);
private final RevogiDiscoveryService revogiDiscoveryService;
public void discoverSmartStripSuccesfully() {
// given
DiscoveryResponseDTO discoveryResponse = new DiscoveryResponseDTO("1234", "reg", "sak", "Strip", "mac", "5.11");
- List<UdpResponseDTO> discoveryString = Collections.singletonList(new UdpResponseDTO(
+ List<UdpResponseDTO> discoveryString = List.of(new UdpResponseDTO(
"{\"response\":0,\"data\":{\"sn\":\"1234\",\"regid\":\"reg\",\"sak\":\"sak\",\"name\":\"Strip\",\"mac\":\"mac\",\"ver\":\"5.11\"}}",
"127.0.0.1"));
when(udpSenderService.broadcastUdpDatagram("00sw=all,,,;"))
@Test
public void invalidUdpResponse() throws ExecutionException, InterruptedException {
// given
- List<UdpResponseDTO> discoveryString = Collections
- .singletonList(new UdpResponseDTO("something invalid", "12345"));
+ List<UdpResponseDTO> discoveryString = List.of(new UdpResponseDTO("something invalid", "12345"));
when(udpSenderService.broadcastUdpDatagram("00sw=all,,,;"))
.thenReturn(CompletableFuture.completedFuture(discoveryString));
import static org.mockito.Mockito.when;
import java.util.Arrays;
-import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
// given
StatusDTO status = new StatusDTO(true, 200, Arrays.asList(0, 0, 0, 0, 0, 0), Arrays.asList(0, 0, 0, 0, 0, 0),
Arrays.asList(0, 0, 0, 0, 0, 0));
- List<UdpResponseDTO> statusString = Collections.singletonList(new UdpResponseDTO(
+ List<UdpResponseDTO> statusString = List.of(new UdpResponseDTO(
"V3{\"response\":90,\"code\":200,\"data\":{\"switch\":[0,0,0,0,0,0],\"watt\":[0,0,0,0,0,0],\"amp\":[0,0,0,0,0,0]}}",
"127.0.0.1"));
when(udpSenderService.sendMessage("V3{\"sn\":\"serial\", \"cmd\": 90}", "127.0.0.1"))
@Test
public void invalidUdpResponse() {
// given
- List<UdpResponseDTO> statusString = Collections.singletonList(new UdpResponseDTO("something invalid", "12345"));
+ List<UdpResponseDTO> statusString = List.of(new UdpResponseDTO("something invalid", "12345"));
when(udpSenderService.sendMessage("V3{\"sn\":\"serial\", \"cmd\": 90}", "127.0.0.1"))
.thenReturn(CompletableFuture.completedFuture(statusString));
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@Test
public void getStatusSuccesfully() {
// given
- List<UdpResponseDTO> response = Collections
- .singletonList(new UdpResponseDTO("V3{\"response\":20,\"code\":200}", "127.0.0.1"));
+ List<UdpResponseDTO> response = List.of(new UdpResponseDTO("V3{\"response\":20,\"code\":200}", "127.0.0.1"));
when(udpSenderService.sendMessage("V3{\"sn\":\"serial\", \"cmd\": 20, \"port\": 1, \"state\": 1}", "127.0.0.1"))
.thenReturn(CompletableFuture.completedFuture(response));
@Test
public void getStatusSuccesfullyWithBroadcast() {
// given
- List<UdpResponseDTO> response = Collections
- .singletonList(new UdpResponseDTO("V3{\"response\":20,\"code\":200}", "127.0.0.1"));
+ List<UdpResponseDTO> response = List.of(new UdpResponseDTO("V3{\"response\":20,\"code\":200}", "127.0.0.1"));
when(udpSenderService.broadcastUdpDatagram("V3{\"sn\":\"serial\", \"cmd\": 20, \"port\": 1, \"state\": 1}"))
.thenReturn(CompletableFuture.completedFuture(response));
@Test
public void invalidUdpResponse() {
// given
- List<UdpResponseDTO> response = Collections.singletonList(new UdpResponseDTO("something invalid", "12345"));
+ List<UdpResponseDTO> response = List.of(new UdpResponseDTO("something invalid", "12345"));
when(udpSenderService.sendMessage("V3{\"sn\":\"serial\", \"cmd\": 20, \"port\": 1, \"state\": 1}", "127.0.0.1"))
.thenReturn(CompletableFuture.completedFuture(response));
}
logger.debug("Discovery done");
-
} catch (IOException e) {
logger.error("Error occurred during discovery", e);
} catch (UnsatisfiedLinkError e) {
@Override
public void setThingHandler(ThingHandler handler) {
- if (handler instanceof RFXComBridgeHandler) {
- bridgeHandler = (RFXComBridgeHandler) handler;
+ if (handler instanceof RFXComBridgeHandler rfxComBridgeHandler) {
+ bridgeHandler = rfxComBridgeHandler;
}
}
import java.io.IOException;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Queue;
+import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledFuture;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(RFXComDeviceDiscoveryService.class);
+ return Set.of(RFXComDeviceDiscoveryService.class);
}
@Override
logger.error("Connection to RFXCOM transceiver failed", e);
if ("device not opened (3)".equalsIgnoreCase(e.getMessage())) {
if (connector instanceof RFXComJD2XXConnector) {
- logger.info("Automatically Discovered RFXCOM bridges use FTDI chip driver (D2XX)."
- + " Reason for this error normally is related to operating system native FTDI drivers,"
- + " which prevent D2XX driver to open device."
- + " To solve this problem, uninstall OS FTDI native drivers or add manually universal bridge 'RFXCOM USB Transceiver',"
- + " which use normal serial port driver rather than D2XX.");
+ logger.info(
+ """
+ Automatically Discovered RFXCOM bridges use FTDI chip driver (D2XX).\
+ Reason for this error normally is related to operating system native FTDI drivers,\
+ which prevent D2XX driver to open device.\
+ To solve this problem, uninstall OS FTDI native drivers or add manually universal bridge 'RFXCOM USB Transceiver',\
+ which use normal serial port driver rather than D2XX.\
+ """);
}
}
} catch (Exception e) {
RFXComMessage message = messageFactory.createMessage(packet);
logger.debug("Message received: {}", message);
- if (message instanceof RFXComInterfaceMessage) {
- RFXComInterfaceMessage msg = (RFXComInterfaceMessage) message;
+ if (message instanceof RFXComInterfaceMessage msg) {
if (msg.subType == SubType.RESPONSE) {
if (msg.command == Commands.GET_STATUS) {
logger.debug("RFXCOM transceiver/receiver type: {}, hw version: {}.{}, fw version: {}",
logger.debug("Interface response received: {}", msg);
transmitQueue.sendNext();
}
- } else if (message instanceof RFXComTransmitterMessage) {
- RFXComTransmitterMessage resp = (RFXComTransmitterMessage) message;
-
+ } else if (message instanceof RFXComTransmitterMessage resp) {
logger.debug("Transmitter response received: {}", resp);
transmitQueue.sendNext();
- } else if (message instanceof RFXComDeviceMessage) {
+ } else if (message instanceof RFXComDeviceMessage deviceMessage) {
for (DeviceMessageListener deviceStatusListener : deviceStatusListeners) {
try {
- deviceStatusListener.onDeviceMessageReceived(getThing().getUID(),
- (RFXComDeviceMessage) message);
+ deviceStatusListener.onDeviceMessageReceived(getThing().getUID(), deviceMessage);
} catch (Exception e) {
// catch all exceptions give all handlers a fair chance of handling the messages
logger.error("An exception occurred while calling the DeviceStatusListener", e);
}
}
} else {
- logger.warn("The received message cannot be processed, please create an "
- + "issue at the relevant tracker. Received message: {}", message);
+ logger.warn("""
+ The received message cannot be processed, please create an \
+ issue at the relevant tracker. Received message: {}\
+ """, message);
}
} catch (RFXComMessageNotImplementedException e) {
logger.debug("Message not supported, data: {}", HexUtils.bytesToHex(packet));
@Override
public void convertFromState(String channelId, Type type) throws RFXComUnsupportedChannelException {
if (CHANNEL_CHIME_SOUND.equals(channelId)) {
- if (type instanceof DecimalType) {
- chimeSound = ((DecimalType) type).intValue();
+ if (type instanceof DecimalType decimalCommand) {
+ chimeSound = decimalCommand.intValue();
} else {
throw new RFXComUnsupportedChannelException("Channel " + channelId + " does not accept " + type);
}
case "OFF":
return Commands.valueOf(stringCommand);
}
- } else if (type instanceof DecimalType) {
- Commands speedCommand = Commands.bySpeed(subType, ((DecimalType) type).intValue());
+ } else if (type instanceof DecimalType decimalCommand) {
+ Commands speedCommand = Commands.bySpeed(subType, decimalCommand.intValue());
if (speedCommand != null) {
return speedCommand;
}
command = (type == OnOffType.ON ? Commands.ON : Commands.OFF);
dimmingLevel = 0;
- } else if (type instanceof PercentType) {
+ } else if (type instanceof PercentType percentCommand) {
command = Commands.SET_LEVEL;
- dimmingLevel = (byte) getDimLevelFromPercentType((PercentType) type);
+ dimmingLevel = (byte) getDimLevelFromPercentType(percentCommand);
if (dimmingLevel == 0) {
command = Commands.OFF;
break;
case CHANNEL_COMMAND_ID:
- if (type instanceof DecimalType) {
- commandId = (byte) ((DecimalType) type).intValue();
+ if (type instanceof DecimalType decimalCommand) {
+ commandId = (byte) decimalCommand.intValue();
} else {
throw new RFXComInvalidStateException(channelId, type.toString(),
"Channel only supports DecimalType");
command = (type == OnOffType.ON ? Commands.ON : Commands.OFF);
dimmingLevel = 0;
- } else if (type instanceof PercentType) {
+ } else if (type instanceof PercentType percentCommand) {
command = Commands.SET_LEVEL;
- dimmingLevel = (byte) getDimLevelFromPercentType((PercentType) type);
+ dimmingLevel = (byte) getDimLevelFromPercentType(percentCommand);
if (dimmingLevel == 0) {
command = Commands.OFF;
command = (type == UpDownType.UP ? Commands.UP : Commands.DOWN);
} else if (type == StopMoveType.STOP) {
command = Commands.STOP;
- } else if (type instanceof PercentType) {
- command = ((PercentType) type).as(UpDownType.class) == UpDownType.UP ? Commands.UP : Commands.DOWN;
+ } else if (type instanceof PercentType percentCommand) {
+ command = percentCommand.as(UpDownType.class) == UpDownType.UP ? Commands.UP : Commands.DOWN;
} else {
throw new RFXComUnsupportedChannelException("Channel " + channelId + " does not accept " + type);
}
}
private @Nullable Double getStateAsDouble(State state) {
- if (state instanceof DecimalType) {
- return ((DecimalType) state).doubleValue();
+ if (state instanceof DecimalType decimalCommand) {
+ return decimalCommand.doubleValue();
} else {
return null;
}
import static org.openhab.binding.rme.internal.RMEBindingConstants.THING_TYPE_MANAGER;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.rme")
public class RMEHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_MANAGER);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_MANAGER);
private final SerialPortManager serialPortManager;
}
case MODE: {
StringType stringType = null;
- if (matcher.group(i).equals("0")) {
+ if ("0".equals(matcher.group(i))) {
stringType = MANUAL;
- } else if (matcher.group(i).equals("1")) {
+ } else if ("1".equals(matcher.group(i))) {
stringType = AUTOMATIC;
}
if (stringType != null) {
}
case SOURCE: {
StringType stringType = null;
- if (matcher.group(i).equals("0")) {
+ if ("0".equals(matcher.group(i))) {
stringType = RAIN;
- } else if (matcher.group(i).equals("1")) {
+ } else if ("1".equals(matcher.group(i))) {
stringType = CITY;
}
if (stringType != null) {
break;
}
default:
- if (matcher.group(i).equals("0")) {
+ if ("0".equals(matcher.group(i))) {
updateState(new ChannelUID(getThing().getUID(), DataField.get(i).channelID()),
OnOffType.OFF);
- } else if (matcher.group(i).equals("1")) {
+ } else if ("1".equals(matcher.group(i))) {
updateState(new ChannelUID(getThing().getUID(), DataField.get(i).channelID()),
OnOffType.ON);
}
private void sendCommand(ChannelUID channelUID, Command command) {
switch (channelUID.getId()) {
case CHANNEL_MOWER_NAME:
- if (command instanceof StringType) {
- updateName((StringType) command);
+ if (command instanceof StringType stringCommand) {
+ updateName(stringCommand);
} else {
logger.debug("Got name update of type {} but StringType is expected.",
command.getClass().getName());
break;
case CHANNEL_MOWER_START:
- if (command instanceof OnOffType) {
- handleStartStop((OnOffType) command);
+ if (command instanceof OnOffType onOffCommand) {
+ handleStartStop(onOffCommand);
} else {
logger.debug("Got stopped update of type {} but OnOffType is expected.",
command.getClass().getName());
@Test
public void shouldParseVersionInfoV1betaToNA() {
- String versionResponse = "{\n" + "mower: {\n" + "hardware: {\n" + "serial: 170602001,\n"
- + "production: \"2017-02-07 15:12:00\"\n" + "},\n" + "msw: {\n" + "title: \"420\",\n"
- + "version: \"7.10.00\",\n" + "compiled: \"2016-11-29 08:44:06\"\n" + "},\n" + "sub: {\n"
- + "version: \"6.01.00\"\n" + "}\n" + "},\n" + "serial: \"05D80037-39355548-43163930\",\n"
- + "bootloader: {\n" + "version: \"V0.4\",\n" + "compiled: \"2016-10-22 01:12:00\",\n"
- + "comment: \"\"\n" + "},\n" + "wlan: {\n" + "at-version: \"V1.4.0\",\n" + "sdk-version: \"V2.1.0\"\n"
- + "},\n" + "application: {\n" + "version: \"V1.0\",\n" + "compiled: \"2018-03-12 21:01:00\",\n"
- + "comment: \"Release V1.0 Beta2\"\n" + "},\n" + "successful: true\n" + "}";
+ String versionResponse = """
+ {
+ mower: {
+ hardware: {
+ serial: 170602001,
+ production: "2017-02-07 15:12:00"
+ },
+ msw: {
+ title: "420",
+ version: "7.10.00",
+ compiled: "2016-11-29 08:44:06"
+ },
+ sub: {
+ version: "6.01.00"
+ }
+ },
+ serial: "05D80037-39355548-43163930",
+ bootloader: {
+ version: "V0.4",
+ compiled: "2016-10-22 01:12:00",
+ comment: ""
+ },
+ wlan: {
+ at-version: "V1.4.0",
+ sdk-version: "V2.1.0"
+ },
+ application: {
+ version: "V1.0",
+ compiled: "2018-03-12 21:01:00",
+ comment: "Release V1.0 Beta2"
+ },
+ successful: true
+ }\
+ """;
VersionInfo versionInfo = subject.parse(versionResponse, VersionInfo.class);
assertTrue(versionInfo.isSuccessful());
assertEquals("n/a", versionInfo.getRobonect().getSerial());
ThingTypeUID thingTypeUID = thing.getThingTypeUID();
if (SUPPORTED_THING_TYPES_UIDS.contains(thingTypeUID)) {
- RokuHandler handler = new RokuHandler(thing, httpClient, stateDescriptionProvider);
- return handler;
+ return new RokuHandler(thing, httpClient, stateDescriptionProvider);
}
return null;
@Component(service = DiscoveryService.class, configurationPid = "discovery.roku")
public class RokuDiscoveryService extends AbstractDiscoveryService {
private final Logger logger = LoggerFactory.getLogger(RokuDiscoveryService.class);
- private static final String ROKU_DISCOVERY_MESSAGE = "M-SEARCH * HTTP/1.1\r\n" + "Host: 239.255.255.250:1900\r\n"
- + "Man: \"ssdp:discover\"\r\n" + "ST: roku:ecp\r\n" + "\r\n";
+ private static final String ROKU_DISCOVERY_MESSAGE = """
+ M-SEARCH * HTTP/1.1\r
+ Host: 239.255.255.250:1900\r
+ Man: "ssdp:discover"\r
+ ST: roku:ecp\r
+ \r
+ """;
private static final Pattern USN_PATTERN = Pattern.compile("^(uuid:roku:)?ecp:([0-9a-zA-Z]{1,16})");
} else if (radioPreset > 0 && command instanceof IncreaseDecreaseType
&& command == IncreaseDecreaseType.DECREASE) {
value = radioPreset - 1;
- } else if (command instanceof DecimalType) {
- value = ((DecimalType) command).intValue();
+ } else if (command instanceof DecimalType decimalCommand) {
+ value = decimalCommand.intValue();
}
if (value >= 1 && value <= 30) {
RotelSource source = sources[0];
} else if (!model.hasDimmerControl()) {
success = false;
logger.debug("Command {} from channel {} failed: unavailable feature", command, channel);
- } else if (command instanceof PercentType) {
- int dimmer = (int) Math.round(((PercentType) command).doubleValue() / 100.0
+ } else if (command instanceof PercentType percentCommand) {
+ int dimmer = (int) Math.round(percentCommand.doubleValue() / 100.0
* (model.getDimmerLevelMax() - model.getDimmerLevelMin()))
+ model.getDimmerLevelMin();
sendCommand(RotelCommand.DIMMER_LEVEL_SET, dimmer);
sendCommand(upCmd);
} else if (command instanceof IncreaseDecreaseType && command == IncreaseDecreaseType.DECREASE) {
sendCommand(downCmd);
- } else if (command instanceof DecimalType && setCmd == null) {
- int value = ((DecimalType) command).intValue();
+ } else if (command instanceof DecimalType decimalCommand && setCmd == null) {
+ int value = decimalCommand.intValue();
if (value >= minVolume && value <= maxVolume) {
if (value > current) {
sendCommand(upCmd);
sendCommand(downCmd);
}
}
- } else if (command instanceof PercentType && setCmd != null) {
- int value = (int) Math.round(((PercentType) command).doubleValue() / 100.0 * (maxVolume - minVolume))
- + minVolume;
+ } else if (command instanceof PercentType percentCommand && setCmd != null) {
+ int value = (int) Math.round(percentCommand.doubleValue() / 100.0 * (maxVolume - minVolume)) + minVolume;
sendCommand(setCmd, value);
} else {
logger.debug("Command {} from channel {} failed: invalid command value", command, channel);
} else if (command instanceof IncreaseDecreaseType && command == IncreaseDecreaseType.DECREASE) {
selectToneControl(nbSelect);
sendCommand(downCmd);
- } else if (command instanceof DecimalType) {
- int value = ((DecimalType) command).intValue();
+ } else if (command instanceof DecimalType decimalCommand) {
+ int value = decimalCommand.intValue();
if (value >= minToneLevel && value <= maxToneLevel) {
if (protocol != RotelProtocol.HEX) {
sendCommand(setCmd, value);
sendCommand(rightCmd);
} else if (command instanceof IncreaseDecreaseType && command == IncreaseDecreaseType.DECREASE) {
sendCommand(leftCmd);
- } else if (command instanceof DecimalType) {
- int value = ((DecimalType) command).intValue();
+ } else if (command instanceof DecimalType decimalCommand) {
+ int value = decimalCommand.intValue();
if (value >= minBalanceLevel && value <= maxBalanceLevel) {
sendCommand(setCmd, value);
}
break;
case KEY_TRACK:
source = sources[0];
- if (source != null && source.getName().equals("CD") && !model.hasSourceControl()) {
+ if (source != null && "CD".equals(source.getName()) && !model.hasSourceControl()) {
track = Integer.parseInt(value);
updateChannelState(CHANNEL_TRACK);
}
RotelSource source = sources[0];
if (model != RotelModel.RCD1570 && model != RotelModel.RCD1572
&& (model != RotelModel.RCX1500 || source == null
- || !source.getName().equals("CD"))) {
+ || !"CD".equals(source.getName()))) {
sendCommand(RotelCommand.PLAY_STATUS);
Thread.sleep(SLEEP_INTV);
} else {
sendCommand(RotelCommand.PLAY_STATUS);
Thread.sleep(SLEEP_INTV);
RotelSource source = sources[0];
- if (source != null && source.getName().equals("CD") && !model.hasSourceControl()) {
+ if (source != null && "CD".equals(source.getName()) && !model.hasSourceControl()) {
sendCommand(RotelCommand.TRACK);
Thread.sleep(SLEEP_INTV);
sendCommand(RotelCommand.RANDOM_MODE);
}
connector.writeOutput(cmd, message);
- if (connector instanceof RotelSimuConnector) {
+ if (connector instanceof RotelSimuConnector simuConnector) {
if ((protocol == RotelProtocol.HEX && cmd.getHexType() != 0)
|| (protocol == RotelProtocol.ASCII_V1 && cmd.getAsciiCommandV1() != null)
|| (protocol == RotelProtocol.ASCII_V2 && cmd.getAsciiCommandV2() != null)) {
- ((RotelSimuConnector) connector).buildFeedbackMessage(cmd, value);
+ simuConnector.buildFeedbackMessage(cmd, value);
}
}
}
final DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID)
.withProperty(RioSourceConfig.SOURCE, s).withBridge(sysHandler.getThing().getUID())
- .withLabel((name == null || name.isEmpty() || name.equalsIgnoreCase("null") ? "Source" : name)
+ .withLabel((name == null || name.isEmpty() || "null".equalsIgnoreCase(name) ? "Source" : name)
+ " (" + s + ")")
.build();
thingDiscovered(discoveryResult);
final DiscoveryResult discoveryResult = DiscoveryResultBuilder.create(thingUID)
.withProperty(RioZoneConfig.ZONE, z).withBridge(controllerUID)
- .withLabel((name.equalsIgnoreCase("null") ? "Zone" : name) + " (" + z + ")").build();
+ .withLabel(("null".equalsIgnoreCase(name) ? "Zone" : name) + " (" + z + ")").build();
thingDiscovered(discoveryResult);
}
}
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
* 120 seconds (depending on how many network interfaces there are)
*/
public RioSystemDiscovery() {
- super(Collections.singleton(RioConstants.BRIDGE_TYPE_RIO), 120);
+ super(Set.of(RioConstants.BRIDGE_TYPE_RIO), 120);
}
/**
final Object response = responses.poll(1, TimeUnit.SECONDS);
if (response != null) {
- if (response instanceof String) {
+ if (response instanceof String stringCommand) {
logger.debug("Dispatching response: {}", response);
for (SocketSessionListener listener : listeners) {
- listener.responseReceived((String) response);
+ listener.responseReceived(stringCommand);
}
- } else if (response instanceof IOException) {
+ } else if (response instanceof IOException ioException) {
logger.debug("Dispatching exception: {}", response);
for (SocketSessionListener listener : listeners) {
- listener.responseException((IOException) response);
+ listener.responseException(ioException);
}
} else {
logger.warn("Unknown response class: {}", response);
// will not come in until the other commands have been processed. So we need a large wait
// time for it to be sent to us
final Object lastResponse = responses.poll(60, TimeUnit.SECONDS);
- if (lastResponse instanceof String) {
- return (String) lastResponse;
- } else if (lastResponse instanceof IOException) {
- throw (IOException) lastResponse;
+ if (lastResponse instanceof String stringCommand) {
+ return stringCommand;
+ } else if (lastResponse instanceof IOException ioException) {
+ throw ioException;
} else if (lastResponse == null) {
throw new IOException("Didn't receive response in time");
} else {
public void channelUnlinked(ChannelUID channelUID) {
// Remove any state when unlinking (that way if it is relinked - we get it)
final RioHandlerCallback callback = getProtocolHandler().getCallback();
- if (callback instanceof StatefulHandlerCallback) {
- ((StatefulHandlerCallback) callback).removeState(channelUID.getId());
+ if (callback instanceof StatefulHandlerCallback handlerCallback) {
+ handlerCallback.removeState(channelUID.getId());
}
super.channelUnlinked(channelUID);
}
public void channelUnlinked(ChannelUID channelUID) {
// Remove any state when unlinking (that way if it is relinked - we get it)
final RioHandlerCallback callback = getProtocolHandler().getCallback();
- if (callback instanceof StatefulHandlerCallback) {
- ((StatefulHandlerCallback) callback).removeState(channelUID.getId());
+ if (callback instanceof StatefulHandlerCallback handlerCallback) {
+ handlerCallback.removeState(channelUID.getId());
}
super.channelUnlinked(channelUID);
}
if (childHandler == null) {
throw new IllegalArgumentException("childHandler cannot be null");
}
- if (childHandler instanceof RioZoneHandler) {
- final RioHandlerCallback callback = ((RioZoneHandler) childHandler).getRioHandlerCallback();
+ if (childHandler instanceof RioZoneHandler zoneHandler) {
+ final RioHandlerCallback callback = zoneHandler.getRioHandlerCallback();
if (callback != null) {
if (added) {
callback.addListener(RioConstants.CHANNEL_ZONENAME, handlerCallbackListener);
JsonElement je = JsonParser.parseReader(in);
- if (je instanceof JsonPrimitive) {
+ if (je instanceof JsonPrimitive jsonPrimitive) {
value = new AtomicReference<>();
- value.set(((JsonPrimitive) je).getAsString());
- } else if (je instanceof JsonObject) {
- JsonObject jsonObject = (JsonObject) je;
+ value.set(jsonPrimitive.getAsString());
+ } else if (je instanceof JsonObject jsonObject) {
value = new AtomicReference<>();
value.set(jsonObject.get("value").getAsString());
}
infoLock.lock();
try {
- infoText.append(infoTextValue.toString());
- if (attr != null && attr.toString().indexOf("E") >= 0) {
+ infoText.append(infoTextValue);
+ if (attr != null && attr.toString().contains("E")) {
final String text = infoText.toString();
infoText.setLength(0);
}
if (id.equals(RioConstants.CHANNEL_SYSLANG)) {
- if (command instanceof StringType) {
- getProtocolHandler().setSystemLanguage(((StringType) command).toString());
+ if (command instanceof StringType stringCommand) {
+ getProtocolHandler().setSystemLanguage(stringCommand.toString());
} else {
logger.debug("Received a SYSTEM LANGUAGE channel command with a non StringType: {}", command);
}
if (childHandler == null) {
throw new IllegalArgumentException("childHandler cannot be null");
}
- if (childHandler instanceof RioSourceHandler) {
- final RioHandlerCallback callback = ((RioSourceHandler) childHandler).getRioHandlerCallback();
+ if (childHandler instanceof RioSourceHandler sourceHandler) {
+ final RioHandlerCallback callback = sourceHandler.getRioHandlerCallback();
if (callback != null) {
if (added) {
callback.addListener(RioConstants.CHANNEL_SOURCENAME, handlerCallbackListener);
}
if (id.equals(RioConstants.CHANNEL_ZONEBASS)) {
- if (command instanceof DecimalType) {
- getProtocolHandler().setZoneBass(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ getProtocolHandler().setZoneBass(decimalCommand.intValue());
} else {
logger.debug("Received a ZONE BASS channel command with a non DecimalType: {}", command);
}
} else if (id.equals(RioConstants.CHANNEL_ZONETREBLE)) {
- if (command instanceof DecimalType) {
- getProtocolHandler().setZoneTreble(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ getProtocolHandler().setZoneTreble(decimalCommand.intValue());
} else {
logger.debug("Received a ZONE TREBLE channel command with a non DecimalType: {}", command);
}
} else if (id.equals(RioConstants.CHANNEL_ZONEBALANCE)) {
- if (command instanceof DecimalType) {
- getProtocolHandler().setZoneBalance(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ getProtocolHandler().setZoneBalance(decimalCommand.intValue());
} else {
logger.debug("Received a ZONE BALANCE channel command with a non DecimalType: {}", command);
}
} else if (id.equals(RioConstants.CHANNEL_ZONETURNONVOLUME)) {
- if (command instanceof PercentType) {
- getProtocolHandler().setZoneTurnOnVolume(((PercentType) command).intValue() / 100d);
- } else if (command instanceof DecimalType) {
- getProtocolHandler().setZoneTurnOnVolume(((DecimalType) command).doubleValue());
+ if (command instanceof PercentType percentCommand) {
+ getProtocolHandler().setZoneTurnOnVolume(percentCommand.intValue() / 100d);
+ } else if (command instanceof DecimalType decimalCommand) {
+ getProtocolHandler().setZoneTurnOnVolume(decimalCommand.doubleValue());
} else {
logger.debug("Received a ZONE TURN ON VOLUME channel command with a non PercentType/DecimalType: {}",
command);
}
} else if (id.equals(RioConstants.CHANNEL_ZONESLEEPTIMEREMAINING)) {
- if (command instanceof DecimalType) {
- getProtocolHandler().setZoneSleepTimeRemaining(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ getProtocolHandler().setZoneSleepTimeRemaining(decimalCommand.intValue());
} else {
logger.debug("Received a ZONE SLEEP TIME REMAINING channel command with a non DecimalType: {}",
command);
}
} else if (id.equals(RioConstants.CHANNEL_ZONESOURCE)) {
- if (command instanceof DecimalType) {
- getProtocolHandler().setZoneSource(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ getProtocolHandler().setZoneSource(decimalCommand.intValue());
} else {
logger.debug("Received a ZONE SOURCE channel command with a non DecimalType: {}", command);
}
logger.debug("Received a ZONE STATUS channel command with a non OnOffType: {}", command);
}
} else if (id.equals(RioConstants.CHANNEL_ZONEPARTYMODE)) {
- if (command instanceof StringType) {
- getProtocolHandler().setZonePartyMode(((StringType) command).toString());
+ if (command instanceof StringType stringCommand) {
+ getProtocolHandler().setZonePartyMode(stringCommand.toString());
} else {
logger.debug("Received a ZONE PARTY MODE channel command with a non StringType: {}", command);
}
} else if (id.equals(RioConstants.CHANNEL_ZONEDONOTDISTURB)) {
- if (command instanceof StringType) {
- getProtocolHandler().setZoneDoNotDisturb(((StringType) command).toString());
+ if (command instanceof StringType stringCommand) {
+ getProtocolHandler().setZoneDoNotDisturb(stringCommand.toString());
} else {
logger.debug("Received a ZONE DO NOT DISTURB channel command with a non StringType: {}", command);
}
getProtocolHandler().setZoneStatus(command == OnOffType.ON);
} else if (command instanceof IncreaseDecreaseType) {
getProtocolHandler().setZoneVolume(command == IncreaseDecreaseType.INCREASE);
- } else if (command instanceof PercentType) {
- getProtocolHandler().setZoneVolume(((PercentType) command).intValue() / 100d);
- } else if (command instanceof DecimalType) {
- getProtocolHandler().setZoneVolume(((DecimalType) command).doubleValue());
+ } else if (command instanceof PercentType percentCommand) {
+ getProtocolHandler().setZoneVolume(percentCommand.intValue() / 100d);
+ } else if (command instanceof DecimalType decimalCommand) {
+ getProtocolHandler().setZoneVolume(decimalCommand.doubleValue());
} else {
logger.debug(
"Received a ZONE VOLUME channel command with a non OnOffType/IncreaseDecreaseType/PercentType/DecimalTye: {}",
}
} else if (id.equals(RioConstants.CHANNEL_ZONEKEYPRESS)) {
- if (command instanceof StringType) {
- getProtocolHandler().sendKeyPress(((StringType) command).toString());
+ if (command instanceof StringType stringCommand) {
+ getProtocolHandler().sendKeyPress(stringCommand.toString());
} else {
logger.debug("Received a ZONE KEYPRESS channel command with a non StringType: {}", command);
}
} else if (id.equals(RioConstants.CHANNEL_ZONEKEYRELEASE)) {
- if (command instanceof StringType) {
- getProtocolHandler().sendKeyRelease(((StringType) command).toString());
+ if (command instanceof StringType stringCommand) {
+ getProtocolHandler().sendKeyRelease(stringCommand.toString());
} else {
logger.debug("Received a ZONE KEYRELEASE channel command with a non StringType: {}", command);
}
} else if (id.equals(RioConstants.CHANNEL_ZONEKEYHOLD)) {
- if (command instanceof StringType) {
- getProtocolHandler().sendKeyHold(((StringType) command).toString());
+ if (command instanceof StringType stringCommand) {
+ getProtocolHandler().sendKeyHold(stringCommand.toString());
} else {
logger.debug("Received a ZONE KEYHOLD channel command with a non StringType: {}", command);
}
} else if (id.equals(RioConstants.CHANNEL_ZONEKEYCODE)) {
- if (command instanceof StringType) {
- getProtocolHandler().sendKeyCode(((StringType) command).toString());
+ if (command instanceof StringType stringCommand) {
+ getProtocolHandler().sendKeyCode(stringCommand.toString());
} else {
logger.debug("Received a ZONE KEYCODE channel command with a non StringType: {}", command);
}
} else if (id.equals(RioConstants.CHANNEL_ZONEEVENT)) {
- if (command instanceof StringType) {
- getProtocolHandler().sendEvent(((StringType) command).toString());
+ if (command instanceof StringType stringCommand) {
+ getProtocolHandler().sendEvent(stringCommand.toString());
} else {
logger.debug("Received a ZONE EVENT channel command with a non StringType: {}", command);
}
import static org.openhab.binding.sagercaster.internal.SagerCasterBindingConstants.THING_TYPE_SAGERCASTER;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.sagercaster")
@NonNullByDefault
public class SagerCasterHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_SAGERCASTER);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_SAGERCASTER);
private final WindDirectionStateDescriptionProvider stateDescriptionProvider;
private final SagerWeatherCaster sagerWeatherCaster;
d1 = "Z";
}
}
- String forecast = forecaster.getProperty(
- d1 + String.valueOf(sagerPressure) + String.valueOf(pressureEvolution) + String.valueOf(nubes));
+ String forecast = forecaster.getProperty(d1 + sagerPressure + pressureEvolution + nubes);
prevision = Optional.ofNullable(forecast != null ? new SagerPrediction(forecast) : null);
}
switch (id) {
case CHANNEL_CLOUDINESS:
logger.debug("Cloud level changed, updating forecast");
- if (command instanceof QuantityType) {
- QuantityType<?> cloudiness = (QuantityType<?>) command;
+ if (command instanceof QuantityType cloudiness) {
scheduler.submit(() -> {
sagerWeatherCaster.setCloudLevel(cloudiness.intValue());
postNewForecast();
}
case CHANNEL_IS_RAINING:
logger.debug("Rain status updated, updating forecast");
- if (command instanceof OnOffType) {
- OnOffType isRaining = (OnOffType) command;
+ if (command instanceof OnOffType isRaining) {
scheduler.submit(() -> {
sagerWeatherCaster.setRaining(isRaining == OnOffType.ON);
postNewForecast();
break;
case CHANNEL_RAIN_QTTY:
logger.debug("Rain status updated, updating forecast");
- if (command instanceof QuantityType) {
- updateRain((QuantityType<?>) command);
- } else if (command instanceof DecimalType) {
- updateRain((DecimalType) command);
+ if (command instanceof QuantityType quantityCommand) {
+ updateRain(quantityCommand);
+ } else if (command instanceof DecimalType decimalCommand) {
+ updateRain(decimalCommand);
} else {
logger.debug("Channel '{}' accepts Number, Number:(Speed|Length) commands.", channelUID);
}
break;
case CHANNEL_WIND_SPEED:
logger.debug("Updated wind speed, updating forecast");
- if (command instanceof DecimalType) {
- DecimalType newValue = (DecimalType) command;
+ if (command instanceof DecimalType newValue) {
scheduler.submit(() -> {
sagerWeatherCaster.setBeaufort(newValue.intValue());
postNewForecast();
import static org.openhab.binding.samsungtv.internal.SamsungTvBindingConstants.SAMSUNG_TV_THING_TYPE;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.samsungtv")
public class SamsungTvHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(SAMSUNG_TV_THING_TYPE);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(SAMSUNG_TV_THING_TYPE);
private @NonNullByDefault({}) UpnpIOService upnpIOService;
private @NonNullByDefault({}) UpnpService upnpService;
static {
String os = System.getProperty("os.name").toLowerCase();
LOGGER.debug("os: {}", os);
- if ((os.indexOf("win") >= 0)) {
+ if ((os.contains("win"))) {
COMMAND = "arp -a %s";
- } else if ((os.indexOf("mac") >= 0)) {
+ } else if ((os.contains("mac"))) {
COMMAND = "arp %s";
} else { // linux
if (checkIfLinuxCommandExists("arp")) {
import static org.openhab.binding.samsungtv.internal.SamsungTvBindingConstants.SAMSUNG_TV_THING_TYPE;
import static org.openhab.binding.samsungtv.internal.config.SamsungTvConfiguration.HOST_NAME;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(SAMSUNG_TV_THING_TYPE);
+ return Set.of(SAMSUNG_TV_THING_TYPE);
}
@Override
value = Math.min(max, currentValue + 1);
} else if (command instanceof IncreaseDecreaseType && command == IncreaseDecreaseType.DECREASE) {
value = Math.max(min, currentValue - 1);
- } else if (command instanceof DecimalType) {
- value = ((DecimalType) command).intValue();
+ } else if (command instanceof DecimalType decimalCommand) {
+ value = decimalCommand.intValue();
} else {
throw new NumberFormatException("Command '" + command + "' not supported");
}
case "CurrentMute":
State newState = UnDefType.UNDEF;
if (value != null) {
- newState = value.equals("true") ? OnOffType.ON : OnOffType.OFF;
+ newState = "true".equals(value) ? OnOffType.ON : OnOffType.OFF;
}
listener.valueReceived(MUTE, newState);
break;
KeyCode key = null;
- if (remoteController instanceof RemoteControllerWebSocket) {
- RemoteControllerWebSocket remoteControllerWebSocket = (RemoteControllerWebSocket) remoteController;
+ if (remoteController instanceof RemoteControllerWebSocket remoteControllerWebSocket) {
switch (channel) {
case BROWSER_URL:
if (command instanceof StringType) {
return;
case CHANNEL:
- if (command instanceof DecimalType) {
- int val = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ int val = decimalCommand.intValue();
int num4 = val / 1000 % 10;
int num3 = val / 100 % 10;
int num2 = val / 10 % 10;
private void sendKeyCodePress(KeyCode key) {
try {
- if (remoteController != null && remoteController instanceof RemoteControllerWebSocket) {
- ((RemoteControllerWebSocket) remoteController).sendKeyPress(key);
+ if (remoteController instanceof RemoteControllerWebSocket remoteControllerWebSocket) {
+ remoteControllerWebSocket.sendKeyPress(key);
}
} catch (RemoteControllerException e) {
reportError(String.format("Could not send command to device on %s:%d", host, port), e);
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof SatelEventLogHandler) {
- this.handler = (SatelEventLogHandler) handler;
+ if (handler instanceof SatelEventLogHandler logHandler) {
+ this.handler = logHandler;
}
}
if (year > currentYear) {
year -= 4;
}
- LocalDateTime result = LocalDateTime.of(year, (payload[2] >> 4) & 0x0f, payload[1] & 0x1f, minutes / 60,
- minutes % 60);
- return result;
+ return LocalDateTime.of(year, (payload[2] >> 4) & 0x0f, payload[1] & 0x1f, minutes / 60, minutes % 60);
}
/**
public String getVersion(int offset) {
// build version string
final byte[] payload = getResponse().getPayload();
- String verStr = new String(payload, offset, 1) + "." + new String(payload, offset + 1, 2) + " "
+ return new String(payload, offset, 1) + "." + new String(payload, offset + 1, 2) + " "
+ new String(payload, offset + 3, 4) + "-" + new String(payload, offset + 7, 2) + "-"
+ new String(payload, offset + 9, 2);
- return verStr;
}
}
import static org.openhab.binding.satel.internal.SatelBindingConstants.*;
-import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
@NonNullByDefault
public class Atd100Handler extends WirelessChannelsHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_ATD100);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_ATD100);
private final Logger logger = LoggerFactory.getLogger(getClass());
import java.util.Collection;
import java.util.Collections;
+import java.util.List;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@NonNullByDefault
public class Ethm1BridgeHandler extends SatelBridgeHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_ETHM1);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_ETHM1);
private final Logger logger = LoggerFactory.getLogger(Ethm1BridgeHandler.class);
// Check whether an IP address is provided
if (host.isBlank()) {
- configStatusMessages = Collections.singletonList(ConfigStatusMessage.Builder.error(HOST)
- .withMessageKeySuffix("hostEmpty").withArguments(HOST).build());
+ configStatusMessages = List.of(ConfigStatusMessage.Builder.error(HOST).withMessageKeySuffix("hostEmpty")
+ .withArguments(HOST).build());
} else {
configStatusMessages = Collections.emptyList();
}
import java.util.Collection;
import java.util.Collections;
+import java.util.List;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@NonNullByDefault
public class IntRSBridgeHandler extends SatelBridgeHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_INTRS);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_INTRS);
private final Logger logger = LoggerFactory.getLogger(IntRSBridgeHandler.class);
// Check whether a serial port is provided
if (port.isBlank()) {
- configStatusMessages = Collections.singletonList(ConfigStatusMessage.Builder.error(PORT)
- .withMessageKeySuffix("portEmpty").withArguments(PORT).build());
+ configStatusMessages = List.of(ConfigStatusMessage.Builder.error(PORT).withMessageKeySuffix("portEmpty")
+ .withArguments(PORT).build());
} else {
configStatusMessages = Collections.emptyList();
}
import java.nio.charset.Charset;
import java.time.ZonedDateTime;
import java.util.Collection;
-import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
@NonNullByDefault
public class SatelEventLogHandler extends SatelThingHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_EVENTLOG);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_EVENTLOG);
private static final String NOT_AVAILABLE_TEXT = "N/A";
private static final String DETAILS_SEPARATOR = ", ";
public void handleCommand(ChannelUID channelUID, Command command) {
logger.debug("New command for {}: {}", channelUID, command);
- if (CHANNEL_INDEX.equals(channelUID.getId()) && command instanceof DecimalType) {
- int eventIndex = ((DecimalType) command).intValue();
+ if (CHANNEL_INDEX.equals(channelUID.getId()) && command instanceof DecimalType decimalCommand) {
+ int eventIndex = decimalCommand.intValue();
withBridgeHandlerPresent(bridgeHandler -> readEvent(eventIndex).ifPresent(entry -> {
// update items
updateState(CHANNEL_INDEX, new DecimalType(entry.getIndex()));
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(SatelEventLogActions.class);
+ return Set.of(SatelEventLogActions.class);
}
/**
eventDetails = "." + readEventCmd.getSource() + "."
+ (readEventCmd.getObject() * 32 + readEventCmd.getUserControlNumber());
Optional<EventDescription> eventDescNext = getEventDescription(readEventCmd.getNextIndex());
- if (!eventDescNext.isPresent()) {
+ if (eventDescNext.isEmpty()) {
return Optional.empty();
}
final EventDescription eventDescNextItem = eventDescNext.get();
import static org.openhab.binding.satel.internal.SatelBindingConstants.THING_TYPE_OUTPUT;
-import java.util.Collections;
import java.util.Optional;
import java.util.Set;
@NonNullByDefault
public class SatelOutputHandler extends WirelessChannelsHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_OUTPUT);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_OUTPUT);
public SatelOutputHandler(Thing thing) {
super(thing);
import static org.openhab.binding.satel.internal.SatelBindingConstants.THING_TYPE_PARTITION;
-import java.util.Collections;
import java.util.Optional;
import java.util.Set;
@NonNullByDefault
public class SatelPartitionHandler extends SatelStateThingHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_PARTITION);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_PARTITION);
public SatelPartitionHandler(Thing thing) {
super(thing);
import static org.openhab.binding.satel.internal.SatelBindingConstants.*;
-import java.util.Collections;
import java.util.Optional;
import java.util.Set;
@NonNullByDefault
public class SatelShutterHandler extends SatelStateThingHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_SHUTTER);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_SHUTTER);
private final Logger logger = LoggerFactory.getLogger(SatelShutterHandler.class);
import static org.openhab.binding.satel.internal.SatelBindingConstants.*;
import java.util.Collection;
-import java.util.Collections;
import java.util.LinkedList;
import java.util.Optional;
import java.util.Set;
@NonNullByDefault
public class SatelSystemHandler extends SatelStateThingHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_SYSTEM);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_SYSTEM);
private static final Set<String> STATUS_CHANNELS = Stream
.of(CHANNEL_DATE_TIME, CHANNEL_SERVICE_MODE, CHANNEL_TROUBLES, CHANNEL_TROUBLES_MEMORY,
DateTimeType dateTime = null;
if (command instanceof StringType) {
dateTime = DateTimeType.valueOf(command.toString());
- } else if (command instanceof DateTimeType) {
- dateTime = (DateTimeType) command;
+ } else if (command instanceof DateTimeType dateTimeCommand) {
+ dateTime = dateTimeCommand;
}
if (dateTime != null) {
return Optional.of(new SetClockCommand(dateTime.getZonedDateTime()
final Bridge bridge = getBridge();
if (bridge != null) {
final ThingHandler handler = bridge.getHandler();
- if (handler != null && handler instanceof SatelBridgeHandler) {
- ((SatelBridgeHandler) handler).addEventListener(this);
- this.bridgeHandler = (SatelBridgeHandler) handler;
+ if (handler instanceof SatelBridgeHandler satelBridgeHandler) {
+ satelBridgeHandler.addEventListener(this);
+ this.bridgeHandler = satelBridgeHandler;
}
if (bridge.getStatus() == ThingStatus.ONLINE) {
updateStatus(ThingStatus.ONLINE);
import static org.openhab.binding.satel.internal.SatelBindingConstants.THING_TYPE_ZONE;
-import java.util.Collections;
import java.util.Optional;
import java.util.Set;
@NonNullByDefault
public class SatelZoneHandler extends WirelessChannelsHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_ZONE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_ZONE);
public SatelZoneHandler(Thing thing) {
super(thing);
@Override
protected int getStateBitNbr(StateType stateType) {
int bitNbr = getThingConfig().getId() - 1;
- if (stateType instanceof TroubleState) {
+ if (stateType instanceof TroubleState troubleState) {
// for wireless devices we need to correct bit number
- switch ((TroubleState) stateType) {
+ switch (troubleState) {
case DEVICE_LOBATT1:
case DEVICE_NOCOMM1:
case OUTPUT_NOCOMM1:
}
// build encryption/decryption key based on given password
- byte passwordBytes[] = keyString.getBytes();
+ byte[] passwordBytes = keyString.getBytes();
byte[] keyBytes = new byte[24];
for (int i = 0; i < 12; ++i) {
* @throws GeneralSecurityException
* on decryption errors
*/
- public void decrypt(byte buffer[]) throws GeneralSecurityException {
+ public void decrypt(byte[] buffer) throws GeneralSecurityException {
byte[] cv = new byte[16];
byte[] c = new byte[16];
byte[] temp = new byte[16];
* @param buffer bytes to encrypt
* @throws GeneralSecurityException on encryption errors
*/
- public void encrypt(byte buffer[]) throws GeneralSecurityException {
+ public void encrypt(byte[] buffer) throws GeneralSecurityException {
byte[] cv = new byte[16];
byte[] p = new byte[16];
int count = buffer.length;
* @return the message as array of bytes
*/
public byte[] getBytes() {
- byte buffer[] = new byte[this.payload.length + 3];
+ byte[] buffer = new byte[this.payload.length + 3];
buffer[0] = this.command;
if (this.payload.length > 0) {
System.arraycopy(this.payload, 0, buffer, 1, this.payload.length);
String uuid = getThing().getProperties().get(STATION_UUID);
if (uuid == null) {
Object uuidObj = getThing().getConfiguration().get(STATION_UUID);
- if (uuidObj instanceof String) {
- uuid = (String) uuidObj;
+ if (uuidObj instanceof String stringValue) {
+ uuid = stringValue;
}
}
return uuid == null ? "" : uuid;
*/
package org.openhab.binding.senechome.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.senechome", service = ThingHandlerFactory.class)
public class SenecHomeHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .singleton(SenecHomeBindingConstants.THING_TYPE_SENEC_HOME_BATTERY);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set
+ .of(SenecHomeBindingConstants.THING_TYPE_SENEC_HOME_BATTERY);
private HttpClient httpClient;
*/
package org.openhab.binding.seneye.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
public static final String PARAMETER_PASSWORD = "password";
public static final String PARAMETER_POLLTIME = "polltime";
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_SENEYE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_SENEYE);
}
import static org.openhab.binding.seneye.internal.SeneyeBindingConstants.THING_TYPE_SENEYE;
-import java.util.Collections;
import java.util.Set;
import org.openhab.binding.seneye.internal.handler.SeneyeHandler;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.seneye")
public class SeneyeHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_SENEYE);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_SENEYE);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
}
private String getTickAsDate(String tick) {
- String date = new java.text.SimpleDateFormat(DateTimeType.DATE_PATTERN_WITH_TZ_AND_MS_ISO)
+ return new java.text.SimpleDateFormat(DateTimeType.DATE_PATTERN_WITH_TZ_AND_MS_ISO)
.format(new java.util.Date(Long.parseLong(tick) * 1000));
- return date;
}
public String getWrong_slideString() {
}
// ok, initialization succeeded
- cachedSeneyeDeviceReading = new ExpiringCache<>(TimeUnit.SECONDS.toMillis(10), () -> {
- return seneyeService.getDeviceReadings();
- });
+ cachedSeneyeDeviceReading = new ExpiringCache<>(TimeUnit.SECONDS.toMillis(10),
+ () -> seneyeService.getDeviceReadings());
seneyeService.startAutomaticRefresh(scheduler, this);
import static org.openhab.binding.sensebox.internal.SenseBoxBindingConstants.THING_TYPE_BOX;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@NonNullByDefault
public class SenseBoxHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_BOX);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_BOX);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
public String getUnit() {
// the uom library uses the 'MICRO SIGN', so if we encounter the GREEK SMALL LETTER MU,
// replace it with the proper representation.
- return unit != null ? unit.replaceAll("\u03bc", "\u00b5") : "";
+ return unit != null ? unit.replace("\u03bc", "\u00b5") : "";
}
public void setUnit(String unit) {
}
if (senseBoxId != null && validConfig) {
- cache.put(CACHE_KEY_DATA, () -> {
- return connection.reallyFetchDataFromServer(senseBoxId);
- });
+ cache.put(CACHE_KEY_DATA, () -> connection.reallyFetchDataFromServer(senseBoxId));
updateStatus(ThingStatus.UNKNOWN);
startAutomaticRefresh();
} else {
*/
package org.openhab.binding.sensibo.internal.discovery;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
*/
@NonNullByDefault
public class SensiboDiscoveryService extends AbstractDiscoveryService {
- public static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPES_UIDS = Collections
- .singleton(SensiboBindingConstants.THING_TYPE_SENSIBOSKY);
+ public static final Set<ThingTypeUID> DISCOVERABLE_THING_TYPES_UIDS = Set
+ .of(SensiboBindingConstants.THING_TYPE_SENSIBOSKY);
private static final long REFRESH_INTERVAL_MINUTES = 60;
private final Logger logger = LoggerFactory.getLogger(SensiboDiscoveryService.class);
private final SensiboAccountHandler accountHandler;
final SensiboModel model = accountHandler.getModel();
for (final SensiboSky pod : model.getPods()) {
final ThingUID podUID = new ThingUID(SensiboBindingConstants.THING_TYPE_SENSIBOSKY, accountUID,
- String.valueOf(pod.getMacAddress()));
+ pod.getMacAddress());
Map<String, String> properties = pod.getThingProperties();
// DiscoveryResult result uses Map<String,Object> as properties while ThingBuilder uses
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
} else {
updateState(channelUID, UnDefType.UNDEF);
}
- } else if (command instanceof DecimalType) {
- final DecimalType newValue = (DecimalType) command;
+ } else if (command instanceof DecimalType newValue) {
updateTimer(newValue.intValue());
} else {
updateTimer(null);
} else {
updateState(channelUID, UnDefType.UNDEF);
}
- } else if (command instanceof StringType) {
- final StringType newValue = (StringType) command;
+ } else if (command instanceof StringType newValue) {
updateAcState(sensiboSky, FAN_LEVEL_PROPERTY, newValue.toString());
}
}
} else {
updateState(channelUID, UnDefType.UNDEF);
}
- } else if (command instanceof StringType) {
- final StringType newValue = (StringType) command;
+ } else if (command instanceof StringType newValue) {
updateAcState(sensiboSky, SWING_PROPERTY, newValue.toString());
}
}
} else {
updateState(channelUID, UnDefType.UNDEF);
}
- } else if (command instanceof StringType) {
- final StringType newValue = (StringType) command;
+ } else if (command instanceof StringType newValue) {
updateAcState(sensiboSky, MODE_PROPERTY, newValue.toString());
addDynamicChannelsAndProperties(sensiboSky);
}
updateState(channelUID, UnDefType.UNDEF);
}
});
- if (!sensiboSky.getAcState().isPresent()) {
+ if (sensiboSky.getAcState().isEmpty()) {
updateState(channelUID, UnDefType.UNDEF);
}
- } else if (command instanceof QuantityType<?>) {
- QuantityType<?> newValue = (QuantityType<?>) command;
+ } else if (command instanceof QuantityType<?> newValue) {
if (!Objects.equals(sensiboSky.getTemperatureUnit(), newValue.getUnit())) {
// If quantity is given in celsius when fahrenheit is used or opposite
try {
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(CallbackChannelsTypeProvider.class);
+ return Set.of(CallbackChannelsTypeProvider.class);
}
@Override
final ChannelTypeUID channelTypeUID = new ChannelTypeUID(SensiboBindingConstants.BINDING_ID,
channelTypePrefix + getThing().getUID().getId());
final List<StateOption> stateOptions = options.stream()
- .map(e -> new StateOption(e.toString(), e instanceof String ? beautify((String) e) : e.toString()))
+ .map(e -> new StateOption(e.toString(), e instanceof String s ? beautify(s) : e.toString()))
.collect(Collectors.toList());
StateDescriptionFragmentBuilder stateDescription = StateDescriptionFragmentBuilder.create().withReadOnly(false)
public static double convert(Object o) {
// ensure value not null
double value = UNDEF;
- if (o instanceof Number) {
- value = ((Number) o).doubleValue();
+ if (o instanceof Number number) {
+ value = number.doubleValue();
} else if (o instanceof String) {
value = Double.parseDouble(o.toString());
}
SensorData d = valueArray[0];
// Assure latest data is taken
String dateStr = d.getTimeStamp();
- if (dateStr.equals("2020-06-09 06:38:08")) {
+ if ("2020-06-09 06:38:08".equals(dateStr)) {
// take newer one
d = valueArray[1];
}
public class FileReader {
public static @Nullable String readFileInString(String filename) {
- try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "CP1252"));) {
+ try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "CP1252"))) {
StringBuffer buf = new StringBuffer();
String sCurrentLine;
*/
package org.openhab.binding.serialbutton.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@NonNullByDefault
public class SerialButtonHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .singleton(SerialButtonBindingConstants.THING_TYPE_BUTTON);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set
+ .of(SerialButtonBindingConstants.THING_TYPE_BUTTON);
private @NonNullByDefault({}) SerialPortManager serialPortManager;
*/
@Override
protected synchronized void removeHandler(@NonNull ThingHandler thingHandler) {
- if (thingHandler instanceof ShellyBaseHandler) {
- ((ShellyBaseHandler) thingHandler).stop();
+ if (thingHandler instanceof ShellyBaseHandler shellyBaseHandler) {
+ shellyBaseHandler.stop();
String uid = thingHandler.getThing().getUID().getAsString();
thingTable.removeThing(uid);
}
// continue until we find the correct one
continue;
}
- if (d.desc.equalsIgnoreCase("brightness")) {
+ if ("brightness".equalsIgnoreCase(d.desc)) {
brightness = update.value;
- } else if (d.desc.equalsIgnoreCase("output") || d.desc.equalsIgnoreCase("state")) {
+ } else if ("output".equalsIgnoreCase(d.desc) || "state".equalsIgnoreCase(d.desc)) {
power = update.value;
}
}
int idx = 0;
for (Map.Entry<String, CoIotDescrSen> se : sensorMap.entrySet()) {
CoIotDescrSen sen = se.getValue();
- if (sen.desc.equalsIgnoreCase("external_temperature") || sen.desc.equalsIgnoreCase("external temperature c")
- || (sen.desc.equalsIgnoreCase("extTemp") && !sen.unit.equalsIgnoreCase(SHELLY_TEMP_FAHRENHEIT))) {
+ if ("external_temperature".equalsIgnoreCase(sen.desc) || "external temperature c".equalsIgnoreCase(sen.desc)
+ || ("extTemp".equalsIgnoreCase(sen.desc) && !sen.unit.equalsIgnoreCase(SHELLY_TEMP_FAHRENHEIT))) {
idx++; // iterate from temperature1..2..n
}
if (sen.id.equalsIgnoreCase(sensorId)) {
break;
case "3104": // T, deviceTemp, Celsius -40/300; 999=unknown
if ("targetTemp".equalsIgnoreCase(sen.desc)) {
-
break; // target temp in F-> ignore
}
// sensor_0: T, internalTemp, F, 39/88, unknown 999
}
break;
case "9102": // EV, wakeupEvent, battery/button/periodic/poweron/sensor/ext_power, "unknown"=unknown
- if (s.valueArray.size() > 0) {
+ if (!s.valueArray.isEmpty()) {
thingHandler.updateWakeupReason(s.valueArray);
lastWakeup = (String) s.valueArray.get(0);
}
// The device changes the serial on every update, receiving a message with the same serial is a
// duplicate, excep for battery devices! Those reset the serial every time when they wake-up
if ((serial == lastSerial) && payload.equals(lastPayload) && (!profile.hasBattery
- || coiot.getLastWakeup().equalsIgnoreCase("ext_power") || ((serial & 0xFF) != 0))) {
+ || "ext_power".equalsIgnoreCase(coiot.getLastWakeup()) || ((serial & 0xFF) != 0))) {
logger.debug("{}: Serial {} was already processed, ignore update", thingName, serial);
return;
}
addRelaySettings(relays, dc.switch2);
addRelaySettings(relays, dc.switch3);
addRelaySettings(relays, dc.switch100);
- return relays.size() > 0 ? relays : null;
+ return !relays.isEmpty() ? relays : null;
}
private void addRelaySettings(ArrayList<@Nullable ShellySettingsRelay> relays,
fav.name = fav.pos + "%";
profile.settings.favorites.add(fav);
}
- profile.settings.favoritesEnabled = profile.settings.favorites.size() > 0;
+ profile.settings.favoritesEnabled = !profile.settings.favorites.isEmpty();
logger.debug("{}: Roller Favorites loaded: {}", thingName,
profile.settings.favoritesEnabled ? profile.settings.favorites.size() : "none");
}
if (dc.led != null) {
profile.settings.ledStatusDisable = !getBool(dc.led.sysLedEnable);
- profile.settings.ledPowerDisable = getString(dc.led.powerLed).equals("off");
+ profile.settings.ledPowerDisable = "off".equals(getString(dc.led.powerLed));
}
profile.initialized = true;
authInfo = new Shelly2AuthChallenge();
for (String o : options) {
String key = substringBefore(o, "=").stripLeading().trim();
- String value = substringAfter(o, "=").replaceAll("\"", "").trim();
+ String value = substringAfter(o, "=").replace("\"", "").trim();
switch (key) {
case "Digest qop":
authInfo.authType = SHELLY2_AUTHTTYPE_DIGEST;
// return sub element result as requested class type
json = gson.toJson(gson.fromJson(json, Shelly2RpcBaseMessage.class).result);
boolean isString = response.result instanceof String;
- return fromJson(gson, isString && ((String) response.result).equalsIgnoreCase("null") ? "{}" : json,
+ return fromJson(gson, isString && "null".equalsIgnoreCase(((String) response.result)) ? "{}" : json,
classOfT);
} else {
// return direct format
} else {
for (Shelly2NotifyEvent e : events.params.events) {
if (getString(e.event).startsWith(SHELLY2_EVENT_BLUPREFIX)) {
- String address = getString(e.data.addr).replaceAll(":", "");
+ String address = getString(e.data.addr).replace(":", "");
if (thingTable != null && thingTable.findThing(address) != null) {
if (thingTable != null) { // known device
ShellyThingInterface thing = thingTable.getThing(address);
logger.debug("{}: Unable to process event", thingName, e);
t.incProtErrors();
}
-
if (updated) {
-
}
}
break;
case CONFIG_AUTOCOIOT:
Object value = e.getValue();
- if (value instanceof String) {
+ if (value instanceof String stringValue) {
// support config through shelly.cfg
- autoCoIoT = ((String) value).equalsIgnoreCase("true");
+ autoCoIoT = "true".equalsIgnoreCase(stringValue);
} else {
autoCoIoT = (boolean) value;
}
}
if (tmpPrf.settings.sleepMode != null && !tmpPrf.isTRV) {
// Sensor, usually 12h, H&T in USB mode 10min
- tmpPrf.updatePeriod = getString(tmpPrf.settings.sleepMode.unit).equalsIgnoreCase("m")
+ tmpPrf.updatePeriod = "m".equalsIgnoreCase(getString(tmpPrf.settings.sleepMode.unit))
? tmpPrf.settings.sleepMode.period * 60 // minutes
: tmpPrf.settings.sleepMode.period * 3600; // hours
tmpPrf.updatePeriod += 60; // give 1min extra
}
private double getNumber(Command command) {
- if (command instanceof QuantityType) {
- return ((QuantityType<?>) command).doubleValue();
+ if (command instanceof QuantityType quantityCommand) {
+ return quantityCommand.doubleValue();
}
- if (command instanceof DecimalType) {
- return ((DecimalType) command).doubleValue();
+ if (command instanceof DecimalType decimalCommand) {
+ return decimalCommand.doubleValue();
}
- if (command instanceof Number) {
- return ((Number) command).doubleValue();
+ if (command instanceof Number numberCommand) {
+ return numberCommand.doubleValue();
}
throw new IllegalArgumentException("Invalid Number type for conversion: " + command);
}
profile.hostname, profile.deviceType, profile.hwRev, profile.hwBatchId, profile.fwVersion,
profile.fwDate);
logger.debug("{}: Shelly settings info for {}: {}", thingName, profile.hostname, profile.settingsJson);
- logger.debug("{}: Device "
- + "hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{}), ext. Switch Add-On: {}"
- + ",isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}, BLU Gateway support: {}"
- + ",alwaysOn:{}, updatePeriod:{}sec", thingName, profile.hasRelays, profile.numRelays, profile.isRoller,
- profile.numRollers, profile.isDimmer, profile.numMeters, profile.isEMeter,
- profile.settings.extSwitch != null ? "installed" : "n/a", profile.isSensor, profile.isDW,
- profile.hasBattery, profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "",
- profile.isSense, profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2,
- profile.inColor, profile.alwaysOn, profile.updatePeriod, config.enableBluGateway);
+ logger.debug(
+ """
+ {}: Device \
+ hasRelays:{} (numRelays={}),isRoller:{} (numRoller={}),isDimmer:{},numMeter={},isEMeter:{}), ext. Switch Add-On: {}\
+ ,isSensor:{},isDS:{},hasBattery:{}{},isSense:{},isMotion:{},isLight:{},isBulb:{},isDuo:{},isRGBW2:{},inColor:{}, BLU Gateway support: {}\
+ ,alwaysOn:{}, updatePeriod:{}sec\
+ """,
+ thingName, profile.hasRelays, profile.numRelays, profile.isRoller, profile.numRollers, profile.isDimmer,
+ profile.numMeters, profile.isEMeter, profile.settings.extSwitch != null ? "installed" : "n/a",
+ profile.isSensor, profile.isDW, profile.hasBattery,
+ profile.hasBattery ? " (low battery threshold=" + config.lowBattery + "%)" : "", profile.isSense,
+ profile.isMotion, profile.isLight, profile.isBulb, profile.isDuo, profile.isRGBW2, profile.inColor,
+ profile.alwaysOn, profile.updatePeriod, config.enableBluGateway);
if (profile.status.extTemperature != null || profile.status.extHumidity != null
|| profile.status.extVoltage != null || profile.status.extAnalogInput != null) {
logger.debug("{}: Shelly Add-On detected with at least 1 external sensor", thingName);
String payload = "";
String parmType = getString(parameters.get("type"));
String event = !parmType.isEmpty() ? parmType : type;
- boolean isButton = profile.inButtonMode(idx - 1) || type.equals("button");
+ boolean isButton = profile.inButtonMode(idx - 1) || "button".equals(type);
switch (event) {
case SHELLY_EVENT_SHORTPUSH:
case SHELLY_EVENT_DOUBLE_SHORTPUSH:
return;
}
- config.deviceAddress = config.deviceAddress.toLowerCase().replaceAll(":", ""); // remove : from MAC address and
- // convert to lower case
+ config.deviceAddress = config.deviceAddress.toLowerCase().replace(":", ""); // remove : from MAC address and
+ // convert to lower case
if (!config.deviceIp.isEmpty()) {
try {
InetAddress addr = InetAddress.getByName(config.deviceIp);
}
}
if (!gen2 && bindingConfig.autoCoIoT && ((version.compare(prf.fwVersion, SHELLY_API_MIN_FWCOIOT)) >= 0)
- || (prf.fwVersion.equalsIgnoreCase("production_test"))) {
+ || ("production_test".equalsIgnoreCase(prf.fwVersion))) {
if (!config.eventsCoIoT) {
logger.info("{}: {}", thingName, messages.get("versioncheck.autocoiot"));
}
public double getChannelDouble(String group, String channel) {
State value = getChannelValue(group, channel);
if (value != UnDefType.NULL) {
- if (value instanceof QuantityType) {
- return ((QuantityType<?>) value).toBigDecimal().doubleValue();
+ if (value instanceof QuantityType quantityCommand) {
+ return quantityCommand.toBigDecimal().doubleValue();
}
- if (value instanceof DecimalType) {
- return ((DecimalType) value).doubleValue();
+ if (value instanceof DecimalType decimalCommand) {
+ return decimalCommand.doubleValue();
}
}
return -1;
* @author Markus Michels - Initial contribution
*/
public class ShellyBluSensorHandler extends ShellyBaseHandler {
- private final static Logger logger = LoggerFactory.getLogger(ShellyBluSensorHandler.class);
+ private static final Logger logger = LoggerFactory.getLogger(ShellyBluSensorHandler.class);
public ShellyBluSensorHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
final ShellyBindingConfiguration bindingConfig, final ShellyThingTable thingTable,
public static void addBluThing(String gateway, Shelly2NotifyEvent e, ShellyThingTable thingTable) {
String model = substringBefore(getString(e.data.name), "-").toUpperCase();
- String mac = e.data.addr.replaceAll(":", "");
+ String mac = e.data.addr.replace(":", "");
String ttype = "";
logger.debug("{}: Create thing for new BLU device {}: {} / {}", gateway, e.data.name, model, mac);
ThingTypeUID tuid;
}
public Integer[] fromRGBW(String rgbwString) {
- Integer values[] = new Integer[4];
+ Integer[] values = new Integer[4];
values[0] = values[1] = values[2] = values[3] = -1;
try {
- String rgbw[] = rgbwString.split(",");
+ String[] rgbw = rgbwString.split(",");
for (int i = 0; i < rgbw.length; i++) {
values[i] = Integer.parseInt(rgbw[i]);
}
// EM: compute from provided values
if (emeter.reactive != null && Math.abs(emeter.power) + Math.abs(emeter.reactive) > 1.5) {
- double pf = emeter.power / Math.sqrt(emeter.power * emeter.power + emeter.reactive * emeter.reactive);
- return pf;
+ return emeter.power / Math.sqrt(emeter.power * emeter.power + emeter.reactive * emeter.reactive);
}
return 0.0;
}
updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_PPM, toQuantityType(
getInteger(sdata.concentration.ppm).doubleValue(), DIGITS_NONE, Units.PARTS_PER_MILLION));
}
- if ((sdata.adcs != null) && (sdata.adcs.size() > 0)) {
+ if ((sdata.adcs != null) && (!sdata.adcs.isEmpty())) {
ShellyADC adc = sdata.adcs.get(0);
updated |= thingHandler.updateChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_VOLTAGE,
toQuantityType(getDouble(adc.voltage), 2, Units.VOLT));
break;
}
- if (command instanceof PercentType) {
- Float percent = ((PercentType) command).floatValue();
+ if (command instanceof PercentType percentCommand) {
+ Float percent = percentCommand.floatValue();
value = percent.intValue(); // 0..100% = 0..100
logger.debug("{}: Set brightness to {}%/{}", thingName, percent, value);
- } else if (command instanceof DecimalType) {
- value = ((DecimalType) command).intValue();
+ } else if (command instanceof DecimalType decimalCommand) {
+ value = decimalCommand.intValue();
logger.debug("{}: Set brightness to {} (Integer)", thingName, value);
}
if (value == 0) {
api.setLightTurn(lightId, SHELLY_API_OFF);
update = false;
} else {
- if (command instanceof IncreaseDecreaseType) {
+ if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
ShellyShortLightStatus light = api.getLightStatus(lightId);
- if (((IncreaseDecreaseType) command).equals(IncreaseDecreaseType.INCREASE)) {
+ if (increaseDecreaseCommand.equals(IncreaseDecreaseType.INCREASE)) {
value = Math.min(light.brightness + DIM_STEPSIZE, 100);
} else {
value = Math.max(light.brightness - DIM_STEPSIZE, 0);
case CHANNEL_COLOR_TEMP:
Integer temp = -1;
- if (command instanceof PercentType) {
- logger.debug("{}: Set color temp to {}%", thingName, ((PercentType) command).floatValue());
- Float percent = ((PercentType) command).floatValue() / 100;
+ if (command instanceof PercentType percentCommand) {
+ logger.debug("{}: Set color temp to {}%", thingName, percentCommand.floatValue());
+ Float percent = percentCommand.floatValue() / 100;
temp = new DecimalType(col.minTemp + ((col.maxTemp - col.minTemp)) * percent).intValue();
logger.debug("{}: Converted color-temp {}% to {}K (from Percent to Integer)", thingName,
percent, temp);
- } else if (command instanceof DecimalType) {
- temp = ((DecimalType) command).intValue();
+ } else if (command instanceof DecimalType decimalCommand) {
+ temp = decimalCommand.intValue();
logger.debug("{}: Set color temp to {}K (Integer)", thingName, temp);
}
validateRange(CHANNEL_COLOR_TEMP, temp, col.minTemp, col.maxTemp);
private boolean handleColorPicker(ShellyDeviceProfile profile, Integer lightId, ShellyColorUtils col,
Command command) throws ShellyApiException {
boolean updated = false;
- if (command instanceof HSBType) {
- HSBType hsb = (HSBType) command;
-
+ if (command instanceof HSBType hsb) {
logger.debug("HSB-Info={}, Hue={}, getRGB={}, toRGB={}/{}/{}", hsb, hsb.getHue(),
String.format("0x%08X", hsb.getRGB()), hsb.toRGB()[0], hsb.toRGB()[1], hsb.toRGB()[2]);
if (hsb.toString().contains("360,")) {
col.setBrightness(getColorFromHSB(hsb.getBrightness(), BRIGHTNESS_FACTOR));
// white, gain and temp are not part of the HSB color scheme
updated = true;
- } else if (command instanceof PercentType) {
+ } else if (command instanceof PercentType percentCommand) {
if (!profile.inColor || profile.isBulb) {
- col.brightness = SHELLY_MAX_BRIGHTNESS * ((PercentType) command).intValue();
+ col.brightness = SHELLY_MAX_BRIGHTNESS * percentCommand.intValue();
updated = true;
}
- } else if (command instanceof OnOffType) {
- logger.debug("{}: Switch light {}", thingName, command);
- api.setLightParm(lightId, SHELLY_LIGHT_TURN,
- (OnOffType) command == OnOffType.ON ? SHELLY_API_ON : SHELLY_API_OFF);
- col.power = (OnOffType) command;
+ } else if (command instanceof OnOffType onOffCommand) {
+ logger.debug("{}: Switch light {}", thingName, onOffCommand);
+ api.setLightParm(lightId, SHELLY_LIGHT_TURN, onOffCommand == OnOffType.ON ? SHELLY_API_ON : SHELLY_API_OFF);
+ col.power = onOffCommand;
} else if (command instanceof IncreaseDecreaseType) {
if (!profile.inColor || profile.isBulb) {
logger.debug("{}: {} brightness by {}", thingName, command, SHELLY_DIM_STEPSIZE);
throws ShellyApiException, IllegalArgumentException {
Integer value = -1;
logger.debug("{}: Set {} to {} ({})", thingName, colorName, command, command.getClass());
- if (command instanceof PercentType) {
- PercentType percent = (PercentType) command;
- double v = (double) maxValue * percent.doubleValue() / 100.0;
+ if (command instanceof PercentType percentCommand) {
+ double v = (double) maxValue * percentCommand.doubleValue() / 100.0;
value = (int) v;
- logger.debug("{}: Value for {} is in percent: {}%={}", thingName, colorName, percent, value);
- } else if (command instanceof DecimalType) {
- value = ((DecimalType) command).intValue();
+ logger.debug("{}: Value for {} is in percent: {}%={}", thingName, colorName, percentCommand, value);
+ } else if (command instanceof DecimalType decimalCommand) {
+ value = decimalCommand.intValue();
logger.debug("Value for {} is a number: {}", colorName, value);
- } else if (command instanceof OnOffType) {
- value = ((OnOffType) command).equals(OnOffType.ON) ? SHELLY_MAX_COLOR : SHELLY_MIN_COLOR;
+ } else if (command instanceof OnOffType onOffCommand) {
+ value = onOffCommand.equals(OnOffType.ON) ? SHELLY_MAX_COLOR : SHELLY_MIN_COLOR;
logger.debug("{}: Value for {} of type OnOff was converted to {}", thingName, colorName, value);
} else {
throw new IllegalArgumentException(
break;
case CHANNEL_ROL_CONTROL_FAV:
- if (command instanceof Number) {
- int id = ((Number) command).intValue() - 1;
+ if (command instanceof Number numberCommand) {
+ int id = numberCommand.intValue() - 1;
int pos = profile.getRollerFav(id);
if (pos > 0) {
logger.debug("{}: Selecting favorite {}, position = {}", thingName, id, pos);
*/
private void handleBrightness(Command command, Integer index) throws ShellyApiException {
Integer value = -1;
- if (command instanceof PercentType) { // Dimmer
- value = ((PercentType) command).intValue();
- } else if (command instanceof DecimalType) { // Number
- value = ((DecimalType) command).intValue();
- } else if (command instanceof OnOffType) { // Switch
+ if (command instanceof PercentType percentCommand) { // Dimmer
+ value = percentCommand.intValue();
+ } else if (command instanceof DecimalType decimalCommand) { // Number
+ value = decimalCommand.intValue();
+ } else if (command instanceof OnOffType onOffCommand) { // Switch
logger.debug("{}: Switch output {}", thingName, command);
- updateBrightnessChannel(index, (OnOffType) command, value);
+ updateBrightnessChannel(index, onOffCommand, value);
return;
} else if (command instanceof IncreaseDecreaseType) {
ShellyShortLightStatus light = api.getLightStatus(index);
}
if (command == UpDownType.UP || command == OnOffType.ON
- || ((command instanceof DecimalType) && (((DecimalType) command).intValue() == 100))) {
+ || ((command instanceof DecimalType decimalCommand) && (decimalCommand.intValue() == 100))) {
logger.debug("{}: Open roller", thingName);
int shpos = profile.getRollerFav(config.favoriteUP - 1);
if (shpos > 0) {
api.setRollerTurn(index, SHELLY_ALWD_ROLLER_TURN_OPEN);
}
} else if (command == UpDownType.DOWN || command == OnOffType.OFF
- || ((command instanceof DecimalType) && (((DecimalType) command).intValue() == 0))) {
+ || ((command instanceof DecimalType decimalCommand) && (decimalCommand.intValue() == 0))) {
logger.debug("{}: Closing roller", thingName);
int shpos = profile.getRollerFav(config.favoriteDOWN - 1);
if (shpos > 0) {
api.setRollerTurn(index, SHELLY_ALWD_ROLLER_TURN_STOP);
} else {
logger.debug("{}: Set roller to position {}", thingName, command);
- if (command instanceof PercentType) {
- PercentType p = (PercentType) command;
- position = p.intValue();
- } else if (command instanceof DecimalType) {
- DecimalType d = (DecimalType) command;
- position = d.intValue();
+ if (command instanceof PercentType percentCommand) {
+ position = percentCommand.intValue();
+ } else if (command instanceof DecimalType decimalCommand) {
+ position = decimalCommand.intValue();
} else {
throw new IllegalArgumentException(
"Invalid value type for roller control/position" + command.getClass().toString());
public @Nullable V put(K key, V value) {
Date date = new Date();
timeMap.put(key, date.getTime());
- V returnVal = super.put(key, value);
- return returnVal;
+ return super.put(key, value);
}
@Override
properties.clear();
properties.put("numberDevices", "<span class=\"footerDevices\">" + "Number of devices: " + filteredDevices
- + " of " + String.valueOf(getThingHandlers().size()) + " </span>");
+ + " of " + getThingHandlers().size() + " </span>");
properties.put(ATTRIBUTE_CSS_FOOTER, loadHTML(OVERVIEW_FOOTER, properties));
html += deviceHtml + loadHTML(FOOTER_HTML, properties);
return new ShellyMgrResponse(fillAttributes(html, properties), HttpStatus.OK_200);
State state = thingHandler.getChannelValue(group, attribute);
String value = "";
if (state != UnDefType.NULL) {
- if (state instanceof DateTimeType) {
- DateTimeType dt = (DateTimeType) state;
+ if (state instanceof DateTimeType dateTimeState) {
switch (attribute) {
case ATTRIBUTE_LAST_ALARM:
- value = dt.format(null).replace('T', ' ').replace('-', '/');
+ value = dateTimeState.format(null).replace('T', ' ').replace('-', '/');
break;
default:
- value = getTimestamp(dt);
- value = dt.format(null).replace('T', ' ').replace('-', '/');
+ value = getTimestamp(dateTimeState);
+ value = dateTimeState.format(null).replace('T', ' ').replace('-', '/');
}
} else {
value = state.toString();
? new ChannelTypeUID(channelDef.typeId)
: new ChannelTypeUID(BINDING_ID, channelDef.typeId);
ChannelBuilder builder;
- if (channelDef.typeId.equalsIgnoreCase("system:button")) {
+ if ("system:button".equalsIgnoreCase(channelDef.typeId)) {
builder = ChannelBuilder.create(channelUID, null).withKind(ChannelKind.TRIGGER);
} else {
builder = ChannelBuilder.create(channelUID, channelDef.itemType);
}
public static Double getNumber(Command command) throws IllegalArgumentException {
- if (command instanceof DecimalType) {
- return ((DecimalType) command).doubleValue();
+ if (command instanceof DecimalType decimalCommand) {
+ return decimalCommand.doubleValue();
}
- if (command instanceof QuantityType) {
- return ((QuantityType<?>) command).doubleValue();
+ if (command instanceof QuantityType quantityCommand) {
+ return quantityCommand.doubleValue();
}
throw new IllegalArgumentException("Unable to convert number");
}
private static final String API = "https://api.climatixic.com/";
- private static final String ARG_RDS = "?filterId=[" + "{\"asn\":\"RDS110\"}," + "{\"asn\":\"RDS120\"},"
- + "{\"asn\":\"RDS110.R\"}," + "{\"asn\":\"RDS120.B\"}" + "]";
+ private static final String ARG_RDS = """
+ ?filterId=[\
+ {"asn":"RDS110"},\
+ {"asn":"RDS120"},\
+ {"asn":"RDS110.R"},\
+ {"asn":"RDS120.B"}\
+ ]\
+ """;
private static final String ARG_PARENT = "?parentId=[\"%s\"]&take=100";
private static final String ARG_POINT = "?filterId=[%s]";
bridgeUID, label, plantId);
thingDiscovered(disco);
- ;
} catch (RdsCloudException e) {
logger.warn(LOG_SYSTEM_EXCEPTION, "publishPlant()", e.getClass().getName(), e.getMessage());
} catch (JsonParseException | IOException e) {
import org.openhab.core.thing.ThingStatusDetail;
import org.openhab.core.thing.ThingStatusInfo;
import org.openhab.core.thing.binding.BaseThingHandler;
-import org.openhab.core.thing.binding.BridgeHandler;
import org.openhab.core.types.Command;
import org.openhab.core.types.RefreshType;
import org.openhab.core.types.State;
switch (channel.id) {
case CHA_TARGET_TEMP: {
Command doCommand = command;
- if (command instanceof QuantityType<?>) {
+ if (command instanceof QuantityType<?> quantityCommand) {
Unit<?> unit = points.getPointByClass(channel.clazz).getUnit();
- QuantityType<?> temp = ((QuantityType<?>) command).toUnit(unit);
+ QuantityType<?> temp = quantityCommand.toUnit(unit);
if (temp != null) {
doCommand = temp;
}
private RdsCloudHandler getCloudHandler() throws RdsCloudException {
@Nullable
Bridge b;
- @Nullable
- BridgeHandler h;
- if ((b = getBridge()) != null && (h = b.getHandler()) != null && h instanceof RdsCloudHandler) {
- return (RdsCloudHandler) h;
+ if ((b = getBridge()) != null && (b.getHandler() instanceof RdsCloudHandler cloudHandler)) {
+ return cloudHandler;
}
throw new RdsCloudException("no cloud handler found");
}
import static org.openhab.binding.siemensrds.internal.RdsBindingConstants.*;
-import java.util.Arrays;
-import java.util.Collections;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;
@Component(configurationPid = "binding.siemensrds", service = ThingHandlerFactory.class)
public class RdsHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .unmodifiableSet(new HashSet<>(Arrays.asList(THING_TYPE_CLOUD, THING_TYPE_RDS)));
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_CLOUD, THING_TYPE_RDS);
private final Map<ThingUID, ServiceRegistration<?>> discos = new HashMap<>();
protected @Nullable ThingHandler createHandler(Thing thing) {
ThingTypeUID thingTypeUID = thing.getThingTypeUID();
- if ((thingTypeUID.equals(THING_TYPE_CLOUD)) && (thing instanceof Bridge)) {
- RdsCloudHandler handler = new RdsCloudHandler((Bridge) thing);
+ if ((thingTypeUID.equals(THING_TYPE_CLOUD)) && (thing instanceof Bridge bridge)) {
+ RdsCloudHandler handler = new RdsCloudHandler(bridge);
createDiscoveryService(handler);
return handler;
}
@Override
protected synchronized void removeHandler(ThingHandler handler) {
- if (handler instanceof RdsCloudHandler) {
- destroyDiscoveryService((RdsCloudHandler) handler);
+ if (handler instanceof RdsCloudHandler cloudHandler) {
+ destroyDiscoveryService(cloudHandler);
}
}
@Override
public void refreshValueFrom(BasePoint from) {
super.refreshValueFrom(from);
- if (from instanceof NestedNumberPoint) {
- NestedNumberValue fromInner = ((NestedNumberPoint) from).inner;
+ if (from instanceof NestedNumberPoint point) {
+ NestedNumberValue fromInner = point.inner;
NestedNumberValue thisInner = this.inner;
if (thisInner != null && fromInner != null) {
thisInner.value = fromInner.value;
@Override
public void refreshValueFrom(BasePoint from) {
super.refreshValueFrom(from);
- if (from instanceof NumberPoint) {
- this.value = ((NumberPoint) from).value;
+ if (from instanceof NumberPoint point) {
+ this.value = point.value;
}
}
}
@NonNullByDefault
public class PointDeserializer implements JsonDeserializer<BasePoint> {
- private static enum PointType {
+ private enum PointType {
UNDEFINED,
STRING,
NESTED_NUMBER,
@Override
public void refreshValueFrom(BasePoint from) {
super.refreshValueFrom(from);
- if (from instanceof StringPoint) {
- this.value = ((StringPoint) from).value;
+ if (from instanceof StringPoint stringPoint) {
+ this.value = stringPoint.value;
}
}
}
*/
package org.openhab.binding.silvercrestwifisocket.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* The supported thing types.
*/
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_WIFI_SOCKET);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_WIFI_SOCKET);
// -------------- Configuration arguments ----------------
/**
*/
package org.openhab.binding.silvercrestwifisocket.internal;
-import java.util.Collections;
import java.util.Set;
import org.openhab.binding.silvercrestwifisocket.internal.exceptions.MacAddressNotValidException;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.silvercrestwifisocket")
public class SilvercrestWifiSocketHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .singleton(SilvercrestWifiSocketBindingConstants.THING_TYPE_WIFI_SOCKET);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set
+ .of(SilvercrestWifiSocketBindingConstants.THING_TYPE_WIFI_SOCKET);
private final Logger logger = LoggerFactory.getLogger(SilvercrestWifiSocketHandlerFactory.class);
// if the host of the packet is different from the host address set in handler, update the host
// address.
if (!receivedMessage.getHostAddress().equals(this.hostAddress)) {
- logger.debug(
- "The host of the packet is different from the host address set in handler. "
- + "Will update the host address. handler of mac: {}. "
- + "Old host address: '{}' -> new host address: '{}'",
- this.macAddress, this.hostAddress, receivedMessage.getHostAddress());
+ logger.debug("""
+ The host of the packet is different from the host address set in handler. \
+ Will update the host address. handler of mac: {}. \
+ Old host address: '{}' -> new host address: '{}'\
+ """, this.macAddress, this.hostAddress, receivedMessage.getHostAddress());
this.hostAddress = receivedMessage.getHostAddress();
this.saveConfigurationsUsingCurrentStates();
if (ValidationUtils.isMacNotValid(macAddress)) {
throw new MacAddressNotValidException("Mac address is not valid", macAddress);
}
- this.macAddress = macAddress.replaceAll(":", "").toUpperCase();
+ this.macAddress = macAddress.replace(":", "").toUpperCase();
}
if (this.macAddress == null) {
throw new MacAddressNotValidException("Mac address is not valid", this.macAddress);
InputStream inputStream = clientSocket.getInputStream();
outToServer.write(command.getPayload());
outToServer.flush();
- SinopeAnswer answ = command.getReplyAnswer(inputStream);
-
- return answ;
+ return command.getReplyAnswer(inputStream);
}
synchronized SinopeAnswer execute(SinopeDataRequest command) throws UnknownHostException, IOException {
if (getSinopeGatewayHandler() != null) {
try {
if (SinopeBindingConstants.CHANNEL_SETTEMP.equals(channelUID.getId())
- && command instanceof QuantityType) {
- setSetpointTemp(((QuantityType<?>) command).floatValue());
+ && command instanceof QuantityType quantityCommand) {
+ setSetpointTemp(quantityCommand.floatValue());
}
if (SinopeBindingConstants.CHANNEL_SETMODE.equals(channelUID.getId())
- && command instanceof DecimalType) {
- setSetpointMode(((DecimalType) command).intValue());
+ && command instanceof DecimalType decimalCommand) {
+ setSetpointMode(decimalCommand.intValue());
}
} catch (IOException e) {
logger.debug("Cannot handle command for channel {} because of {}", channelUID.getId(),
@Override
protected byte[] getFrameData() {
int appDataLen = getAppDataSize();
- byte b[] = new byte[seq.length + 1 + 1 + 1 + res3.length + res4.length + dstDeviceId.length + 1 + appDataLen];
+ byte[] b = new byte[seq.length + 1 + 1 + 1 + res3.length + res4.length + dstDeviceId.length + 1 + appDataLen];
ByteBuffer bb = ByteBuffer.wrap(b);
private final int init;
/** The Constant crcTable. */
- private static final int crcTable[] = { 0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31,
+ private static final int[] crcTable = { 0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31,
0x24, 0x23, 0x2a, 0x2d, 0x70, 0x77, 0x7e, 0x79, 0x6c, 0x6b, 0x62, 0x65, 0x48, 0x4f, 0x46, 0x41, 0x54, 0x53,
0x5a, 0x5d, 0xe0, 0xe7, 0xee, 0xe9, 0xfc, 0xfb, 0xf2, 0xf5, 0xd8, 0xdf, 0xd6, 0xd1, 0xc4, 0xc3, 0xca, 0xcd,
0x90, 0x97, 0x9e, 0x99, 0x8c, 0x8b, 0x82, 0x85, 0xa8, 0xaf, 0xa6, 0xa1, 0xb4, 0xb3, 0xba, 0xbd, 0xc7, 0xc0,
*
* @param buffer the buffer
*/
+ @Override
public void update(byte[] buffer) {
update(buffer, 0, buffer.length);
}
@Override
protected void removeHandler(final ThingHandler thingHandler) {
logger.debug("Removing SleepIQ thing handler");
- if (thingHandler instanceof SleepIQCloudHandler) {
- unregisterBedDiscoveryService((SleepIQCloudHandler) thingHandler);
+ if (thingHandler instanceof SleepIQCloudHandler sleepIQCloudHandler) {
+ unregisterBedDiscoveryService(sleepIQCloudHandler);
}
}
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
*/
@NonNullByDefault
public class SleepIQCloudHandler extends ConfigStatusBridgeHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPE_UIDS = Collections.singleton(THING_TYPE_CLOUD);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPE_UIDS = Set.of(THING_TYPE_CLOUD);
private static final int SLEEPER_POLLING_INTERVAL_HOURS = 12;
import static org.openhab.binding.sleepiq.internal.SleepIQBindingConstants.*;
-import java.util.Collections;
import java.util.Set;
import java.util.concurrent.TimeUnit;
*/
@NonNullByDefault
public class SleepIQDualBedHandler extends BaseThingHandler implements BedStatusListener {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPE_UIDS = Collections.singleton(THING_TYPE_DUAL_BED);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPE_UIDS = Set.of(THING_TYPE_DUAL_BED);
private static final long GET_SLEEP_DATA_DELAY_MINUTES = 5;
switch (channelId) {
case CHANNEL_LEFT_SLEEP_NUMBER:
case CHANNEL_RIGHT_SLEEP_NUMBER:
- if (command instanceof DecimalType) {
+ if (command instanceof DecimalType decimalCommand) {
Side side = Side.convertFromGroup(groupId);
logger.debug("BedHandler: Set sleepnumber to {} for bedId={}, side={}", command, bedId, side);
SleepIQCloudHandler cloudHandler = getCloudHandler();
if (cloudHandler != null) {
- cloudHandler.setSleepNumber(bedId, side, ((DecimalType) command).intValue());
+ cloudHandler.setSleepNumber(bedId, side, decimalCommand.intValue());
}
}
break;
case CHANNEL_LEFT_FOUNDATION_PRESET:
case CHANNEL_RIGHT_FOUNDATION_PRESET:
logger.debug("Received command {} on channel {} to set preset", command, channelUID);
- if (isFoundationInstalled() && command instanceof DecimalType) {
+ if (isFoundationInstalled() && command instanceof DecimalType decimalCommand) {
try {
Side side = Side.convertFromGroup(groupId);
- FoundationPreset preset = FoundationPreset.forValue(((DecimalType) command).intValue());
+ FoundationPreset preset = FoundationPreset.forValue(decimalCommand.intValue());
logger.debug("BedHandler: Set foundation preset to {} for bedId={}, side={}", command, bedId,
side);
SleepIQCloudHandler cloudHandler = getCloudHandler();
*/
package org.openhab.binding.smaenergymeter.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
// List of all Thing Type UIDs
public static final ThingTypeUID THING_TYPE_ENERGY_METER = new ThingTypeUID(BINDING_ID, "energymeter");
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_ENERGY_METER);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_ENERGY_METER);
// List of all Channel IDs
public static final String CHANNEL_POWER_IN = "powerIn";
socket.receive(msgPacket);
String sma = new String(Arrays.copyOfRange(bytes, 0x00, 0x03));
- if (!sma.equals("SMA")) {
+ if (!"SMA".equals(sma)) {
throw new IOException("Not a SMA telegram." + sma);
}
* @throws IOException
* if an I/O error occurred.
*/
+ @Override
void close() throws IOException;
/**
public static final String CHANNEL_TYPE_METERREADER_OBIS = "channel-type:" + BINDING_ID + ":obis";
public static String getObisChannelIdPattern(String obis) {
- return obis.replaceAll("\\.", "-").replaceAll(":|\\*", "_");
+ return obis.replace(".", "-").replaceAll(":|\\*", "_");
}
public static String getObisChannelId(String obis) {
valueString += " " + value.getUnit();
}
State state = TypeParser.parseState(List.of(QuantityType.class, StringType.class), valueString);
- if (channel != null && state instanceof QuantityType) {
+ if (channel != null && state instanceof QuantityType quantityCommand) {
state = applyConformity(channel, (QuantityType<Q>) state);
Number conversionRatio = (Number) channel.getConfiguration()
.get(SmartMeterBindingConstants.CONFIGURATION_CONVERSION);
if (conversionRatio != null) {
- state = ((QuantityType<?>) state).divide(BigDecimal.valueOf(conversionRatio.doubleValue()));
+ state = quantityCommand.divide(BigDecimal.valueOf(conversionRatio.doubleValue()));
}
}
return state;
import static org.openhab.binding.smartmeter.SmartMeterBindingConstants.THING_TYPE_SMLREADER;
-import java.util.Collections;
import java.util.Set;
import java.util.function.Supplier;
@NonNullByDefault
public class SmartMeterHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_SMLREADER);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_SMLREADER);
private @NonNullByDefault({}) SmartMeterChannelTypeProvider channelProvider;
private @NonNullByDefault({}) Supplier<SerialPortManager> serialPortManagerSupplier = () -> null;
String[] split = substring.split(":");
int negatePosition = Integer.parseInt(split[0]);
boolean negateBit = Integer.parseInt(split[1]) == 0 ? false : true;
- boolean status = split.length > 2 ? split[2].equalsIgnoreCase("status") : false;
+ boolean status = split.length > 2 ? "status".equalsIgnoreCase(split[2]) : false;
return new NegateBitModel((byte) negatePosition, negateBit, obis, status);
}
} catch (Exception e) {
* @return the hex encoded OBIS code as readable string.
*/
protected static String getObisAsString(byte[] octetBytes) {
- String formattedObis = String.format(SmartMeterBindingConstants.OBIS_FORMAT_MINIMAL, byteToInt(octetBytes[0]),
+ return String.format(SmartMeterBindingConstants.OBIS_FORMAT_MINIMAL, byteToInt(octetBytes[0]),
byteToInt(octetBytes[1]), byteToInt(octetBytes[2]), byteToInt(octetBytes[3]), byteToInt(octetBytes[4]));
-
- return formattedObis;
}
public String getObisCode() {
public void testNegateHandlingTrue() {
String negateProperty = "1-0_1-8-0:5:1";
- boolean negateState = NegateHandler.shouldNegateState(negateProperty, obis -> {
- return new MeterValue<>(obis, "65954", null);
- });
+ boolean negateState = NegateHandler.shouldNegateState(negateProperty,
+ obis -> new MeterValue<>(obis, "65954", null));
assertTrue(negateState);
}
public void testNegateHandlingFalse() {
String negateProperty = "1-0_1-8-0:5:1";
- boolean negateState = NegateHandler.shouldNegateState(negateProperty, obis -> {
- return new MeterValue<>(obis, "0", null, "65922");
- });
+ boolean negateState = NegateHandler.shouldNegateState(negateProperty,
+ obis -> new MeterValue<>(obis, "0", null, "65922"));
assertFalse(negateState);
}
* @throws TimeoutException
* @throws ExecutionException
*/
+ @Override
public void sendDeviceCommand(String path, int timeout, String data)
throws InterruptedException, TimeoutException, ExecutionException {
ContentResponse response = httpClient
// The command should be of HSBType. The hue component needs to be divided by 3.6 to convert 0-360 degrees to
// 0-100 percent
// The easiest way to do this is to create a new HSBType with the hue component changed.
- if (command instanceof HSBType) {
- HSBType hsb = (HSBType) command;
- double hue = Math.round((hsb.getHue().doubleValue() / 3.60)); // add .5 to round
+ if (command instanceof HSBType hsbCommand) {
+ double hue = Math.round((hsbCommand.getHue().doubleValue() / 3.60)); // add .5 to round
long hueInt = (long) hue;
- HSBType hsb100 = new HSBType(new DecimalType(hueInt), hsb.getSaturation(), hsb.getBrightness());
+ HSBType hsb100 = new HSBType(new DecimalType(hueInt), hsbCommand.getSaturation(),
+ hsbCommand.getBrightness());
// now use the default converter to convert to a JSON string
jsonMsg = defaultConvertToSmartthings(channelUid, hsb100);
} else {
}
// Get the RGB colors
- int rgb[] = new int[3];
+ int[] rgb = new int[3];
for (int i = 0, pos = 1; i < 3; i++, pos += 2) {
String c = value.substring(pos, pos + 2);
rgb[i] = Integer.parseInt(c, 16);
@Override
public String convertToSmartthings(ChannelUID channelUid, Command command) {
- String jsonMsg = defaultConvertToSmartthings(channelUid, command);
- return jsonMsg;
+ return defaultConvertToSmartthings(channelUid, command);
}
/*
}
// Get the RGB colors
- int rgb[] = new int[3];
+ int[] rgb = new int[3];
for (int i = 0, pos = 1; i < 3; i++, pos += 2) {
String c = value.substring(pos, pos + 2);
rgb[i] = Integer.parseInt(c, 16);
}
// Convert to state
- State state = HSBType.fromRGB(rgb[0], rgb[1], rgb[2]);
- return state;
+ return HSBType.fromRGB(rgb[0], rgb[1], rgb[2]);
}
}
protected String defaultConvertToSmartthings(ChannelUID channelUid, Command command) {
String value;
- if (command instanceof DateTimeType) {
- DateTimeType dt = (DateTimeType) command;
- value = dt.format("%m/%d/%Y %H.%M.%S");
- } else if (command instanceof HSBType) {
- HSBType hsb = (HSBType) command;
- value = String.format("[%d, %d, %d ]", hsb.getHue().intValue(), hsb.getSaturation().intValue(),
- hsb.getBrightness().intValue());
+ if (command instanceof DateTimeType dateTimeCommand) {
+ value = dateTimeCommand.format("%m/%d/%Y %H.%M.%S");
+ } else if (command instanceof HSBType hsbCommand) {
+ value = String.format("[%d, %d, %d ]", hsbCommand.getHue().intValue(),
+ hsbCommand.getSaturation().intValue(), hsbCommand.getBrightness().intValue());
} else if (command instanceof DecimalType) {
value = command.toString();
} else if (command instanceof IncreaseDecreaseType) { // Need to surround with double quotes
value = command.toString().toLowerCase();
}
- String jsonMsg = String.format(
+ return String.format(
"{\"capabilityKey\": \"%s\", \"deviceDisplayName\": \"%s\", \"capabilityAttribute\": \"%s\", \"value\": %s}",
thingTypeId, smartthingsName, channelUid.getId(), value);
-
- return jsonMsg;
}
protected String surroundWithQuotes(String param) {
return UnDefType.UNDEF;
case "Dimmer":
// The value coming in should be a number
- if (deviceValue instanceof String) {
- return new PercentType((String) deviceValue);
+ if (deviceValue instanceof String stringCommand) {
+ return new PercentType(stringCommand);
} else {
logger.warn("Failed to convert {} with a value of {} from class {} to an appropriate type.",
deviceType, deviceValue, deviceValue.getClass().getName());
return UnDefType.UNDEF;
}
case "Number":
- if (deviceValue instanceof String) {
- return new DecimalType(Double.parseDouble((String) deviceValue));
+ if (deviceValue instanceof String stringCommand2) {
+ return new DecimalType(Double.parseDouble(stringCommand2));
} else if (deviceValue instanceof Double) {
return new DecimalType((Double) deviceValue);
} else if (deviceValue instanceof Long) {
// But if the result is from sensor change via a subscription to a threeAxis device the results will
// be a String of the format "value":"-873,-70,484"
// which GSON returns as a LinkedTreeMap
- if (deviceValue instanceof String) {
- return new StringType((String) deviceValue);
+ if (deviceValue instanceof String stringCommand3) {
+ return new StringType(stringCommand3);
} else if (deviceValue instanceof Map<?, ?>) {
Map<String, String> map = (Map<String, String>) deviceValue;
String s = String.format("%.0f,%.0f,%.0f", map.get("x"), map.get("y"), map.get("z"));
@Override
public String convertToSmartthings(ChannelUID channelUid, Command command) {
- String jsonMsg = defaultConvertToSmartthings(channelUid, command);
- return jsonMsg;
+ return defaultConvertToSmartthings(channelUid, command);
}
@Override
public State convertToOpenHab(@Nullable String acceptedChannelType, SmartthingsStateData dataFromSmartthings) {
- State state = defaultConvertToOpenHab(acceptedChannelType, dataFromSmartthings);
- return state;
+ return defaultConvertToOpenHab(acceptedChannelType, dataFromSmartthings);
}
}
public String convertToSmartthings(ChannelUID channelUid, Command command) {
String jsonMsg;
- if (command instanceof HSBType) {
- HSBType hsb = (HSBType) command;
- double hue = hsb.getHue().doubleValue() / 3.60;
- String value = String.format("[%.0f, %d, %d ]", hue, hsb.getSaturation().intValue(),
- hsb.getBrightness().intValue());
+ if (command instanceof HSBType hsbCommand) {
+ double hue = hsbCommand.getHue().doubleValue() / 3.60;
+ String value = String.format("[%.0f, %d, %d ]", hue, hsbCommand.getSaturation().intValue(),
+ hsbCommand.getBrightness().intValue());
jsonMsg = String.format(
"{\"capabilityKey\": \"%s\", \"deviceDisplayName\": \"%s\", \"capabilityAttribute\": \"%s\", \"value\": %s}",
thingTypeId, smartthingsName, channelUid.getId(), value);
}
if (acceptedChannelType != null && "Number".contentEquals(acceptedChannelType)) {
- if (deviceValue instanceof String) {
- double d = Double.parseDouble((String) deviceValue);
+ if (deviceValue instanceof String stringCommand) {
+ double d = Double.parseDouble(stringCommand);
d *= 3.6;
return new DecimalType(d);
} else if (deviceValue instanceof Long) {
double d = ((Long) deviceValue).longValue();
d *= 3.6;
return new DecimalType(d);
- } else if (deviceValue instanceof BigDecimal) {
- double d = ((BigDecimal) deviceValue).doubleValue();
+ } else if (deviceValue instanceof BigDecimal decimalValue) {
+ double d = decimalValue.doubleValue();
d *= 3.6;
return new DecimalType(d);
- } else if (deviceValue instanceof Number) {
- double d = ((Number) deviceValue).doubleValue();
+ } else if (deviceValue instanceof Number numberValue) {
+ double d = numberValue.doubleValue();
d *= 3.6;
return new DecimalType(d);
} else {
@Override
public String convertToSmartthings(ChannelUID channelUid, Command command) {
- String smartthingsValue = (command.toString().toLowerCase().equals("open")) ? "open" : "close";
+ String smartthingsValue = ("open".equals(command.toString().toLowerCase())) ? "open" : "close";
smartthingsValue = surroundWithQuotes(smartthingsValue);
- String jsonMsg = String.format("{\"capabilityKey\": \"%s\", \"deviceDisplayName\": \"%s\", \"value\": %s}",
- thingTypeId, smartthingsName, smartthingsValue);
-
- return jsonMsg;
+ return String.format("{\"capabilityKey\": \"%s\", \"deviceDisplayName\": \"%s\", \"value\": %s}", thingTypeId,
+ smartthingsName, smartthingsValue);
}
@Override
public State convertToOpenHab(@Nullable String acceptedChannelType, SmartthingsStateData dataFromSmartthings) {
- State state = defaultConvertToOpenHab(acceptedChannelType, dataFromSmartthings);
-
- return state;
+ return defaultConvertToOpenHab(acceptedChannelType, dataFromSmartthings);
}
}
* @return channel id
*/
private String getSmartthingsAttributeFromChannel(ChannelUID channelUID) {
- String id = channelUID.getId();
- return id;
+ return channelUID.getId();
}
/**
try {
Constructor<?> constr = Class.forName(converterClassName.toString()).getDeclaredConstructor(Thing.class);
constr.setAccessible(true);
- SmartthingsConverter cvtr = (SmartthingsConverter) constr.newInstance(thing);
- return cvtr;
+ return (SmartthingsConverter) constr.newInstance(thing);
} catch (ClassNotFoundException e) {
// Most of the time there is no channel specific converter, the default converter is all that is needed.
logger.trace("No Custom converter exists for {} ({})", converterName, converterClassName);
break;
}
- Channel channel = ChannelBuilder.create(channelUID, itemType)
- .withType(new ChannelTypeUID(BINDING_ID, channelID)).build();
- return channel;
+ return ChannelBuilder.create(channelUID, itemType).withType(new ChannelTypeUID(BINDING_ID, channelID)).build();
}
/**
import static org.openhab.binding.smhi.internal.SmhiBindingConstants.THING_TYPE_FORECAST;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.smhi", service = ThingHandlerFactory.class)
public class SmhiHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_FORECAST);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_FORECAST);
private final HttpClient httpClient;
pduString = "00" + pduString;
}
Pdu pdu = parser.parsePdu(pduString);
- if (pdu instanceof SmsDeliveryPdu) {
+ if (pdu instanceof SmsDeliveryPdu deliveryPdu) {
logger.debug("PDU = {}", pdu.toString());
InboundMessage msg = null;
if (pdu.isBinary()) {
- msg = new InboundBinaryMessage((SmsDeliveryPdu) pdu, memLocation, memIndex);
+ msg = new InboundBinaryMessage(deliveryPdu, memLocation, memIndex);
} else {
- msg = new InboundMessage((SmsDeliveryPdu) pdu, memLocation, memIndex);
+ msg = new InboundMessage(deliveryPdu, memLocation, memIndex);
}
msg.setGatewayId(this.modem.getGatewayId());
msg.setGatewayId(this.modem.getGatewayId());
mpMsgList.add(tmpList);
}
}
- } else if (pdu instanceof SmsStatusReportPdu) {
+ } else if (pdu instanceof SmsStatusReportPdu statusReportPdu) {
DeliveryReportMessage msg;
- msg = new DeliveryReportMessage((SmsStatusReportPdu) pdu, memLocation, memIndex);
+ msg = new DeliveryReportMessage(statusReportPdu, memLocation, memIndex);
msg.setGatewayId(this.modem.getGatewayId());
messageList.add(msg);
}
String messageSignature = message.getSignature();
if (!this.modem.getReadMessagesSet().contains(messageSignature)) {
this.modem.getDeviceInformation().increaseTotalReceived();
- if (message instanceof DeliveryReportMessage) {
- modem.processDeliveryReport((DeliveryReportMessage) message);
+ if (message instanceof DeliveryReportMessage deliveryReportMessage) {
+ modem.processDeliveryReport(deliveryReportMessage);
} else {
modem.processMessage(message);
}
b.append(String.format("Recipient Address: %s%n", getRecipientAddress()));
b.append(String.format("Payload Type: %s%n", payload.getType()));
b.append(String.format("Text payload: %s%n", payload.getText() == null ? "null" : payload.getText()));
- if (this instanceof InboundMessage) {
+ if (this instanceof InboundMessage message) {
b.append(String.format("Sent Date: %s%n", getSentDate()));
- b.append(String.format("Memory Storage Location: %s%n", ((InboundMessage) this).getMemLocation()));
- b.append(String.format("Memory Index: %d%n", ((InboundMessage) this).getMemIndex()));
- b.append(String.format("Memory MP Index: %s%n", ((InboundMessage) this).getMpMemIndex()));
+ b.append(String.format("Memory Storage Location: %s%n", message.getMemLocation()));
+ b.append(String.format("Memory Index: %d%n", message.getMemIndex()));
+ b.append(String.format("Memory MP Index: %s%n", message.getMpMemIndex()));
}
- if (this instanceof OutboundMessage) {
+ if (this instanceof OutboundMessage message) {
b.append(String.format("Sent Date: %s%n",
- (((OutboundMessage) this).getSentStatus() == SentStatus.Sent ? getSentDate() : "N/A")));
+ (message.getSentStatus() == SentStatus.Sent ? getSentDate() : "N/A")));
String ids = "";
- for (String opId : ((OutboundMessage) this).getOperatorMessageIds()) {
+ for (String opId : message.getOperatorMessageIds()) {
ids += (ids.length() == 0 ? opId : "," + opId);
}
b.append(String.format("Operator Message IDs: %s%n", ids));
- b.append(String.format("Status: %s%n", ((OutboundMessage) this).getSentStatus().toString()));
- b.append(String.format("Failure: %s%n", ((OutboundMessage) this).getFailureCause().toString()));
+ b.append(String.format("Status: %s%n", message.getSentStatus().toString()));
+ b.append(String.format("Failure: %s%n", message.getFailureCause().toString()));
b.append(String.format("Request Delivery Reports: %b%n",
- ((OutboundMessage) this).getRequestDeliveryReport()));
+ message.getRequestDeliveryReport()));
}
- if (this instanceof DeliveryReportMessage) {
+ if (this instanceof DeliveryReportMessage message) {
b.append(String.format("Original Operator Message Id: %s%n",
- ((DeliveryReportMessage) this).getOriginalOperatorMessageId()));
- b.append(String.format("Delivery Date: %s%n", ((DeliveryReportMessage) this).getOriginalReceivedDate()));
- b.append(String.format("Delivery Status: %s%n", ((DeliveryReportMessage) this).getDeliveryStatus()));
+ message.getOriginalOperatorMessageId()));
+ b.append(String.format("Delivery Date: %s%n", message.getOriginalReceivedDate()));
+ b.append(String.format("Delivery Status: %s%n", message.getDeliveryStatus()));
}
b.append(String
.format("== MESSAGE END ========================================================================%n"));
public static void sendSMS(@Nullable ThingActions actions, @Nullable String recipient, @Nullable String message,
@Nullable String encoding) {
- if (actions instanceof SMSModemActions) {
- ((SMSModemActions) actions).sendSMS(recipient, message, encoding);
+ if (actions instanceof SMSModemActions smsModemActions) {
+ smsModemActions.sendSMS(recipient, message, encoding);
} else {
throw new IllegalArgumentException("Instance is not an SMSModemActions class.");
}
thing.getUID(), getRecipient());
}
ThingHandler handler = bridge.getHandler();
- if (handler instanceof SMSModemBridgeHandler) {
- this.bridgeHandler = (SMSModemBridgeHandler) handler;
+ if (handler instanceof SMSModemBridgeHandler smsModemBridgeHandler) {
+ this.bridgeHandler = smsModemBridgeHandler;
} else {
throw new ConfigurationException("No available bridge handler found for SMSConversation {} bridge {} .",
thing.getUID(), bridge.getUID());
@Override
public void setThingHandler(ThingHandler handler) {
- if (handler instanceof SncfBridgeHandler) {
- this.bridgeHandler = (SncfBridgeHandler) handler;
- this.locationProvider = ((SncfBridgeHandler) handler).getLocationProvider();
+ if (handler instanceof SncfBridgeHandler sncfBridgeHandler) {
+ this.bridgeHandler = sncfBridgeHandler;
+ this.locationProvider = sncfBridgeHandler.getLocationProvider();
}
}
}
} else {
Command rawValue = command;
- if (command instanceof QuantityType) {
+ if (command instanceof QuantityType quantityCommand) {
Unit<?> channelUnit = channel.unit;
if (channelUnit == null) {
- rawValue = new DecimalType(((QuantityType<?>) command).toBigDecimal());
+ rawValue = new DecimalType(quantityCommand.toBigDecimal());
} else {
- QuantityType<?> convertedValue = ((QuantityType<?>) command).toUnit(channelUnit);
+ QuantityType<?> convertedValue = quantityCommand.toUnit(channelUnit);
if (convertedValue == null) {
logger.warn("Cannot convert '{}' to configured unit '{}'", command, channelUnit);
return;
octets[3] << 24 | octets[4] << 16 | octets[5] << 8 | octets[6]);
state = channelUnit == null ? new DecimalType(floatValue)
: new QuantityType<>(floatValue, channelUnit);
-
} else {
throw new UnsupportedOperationException("Unknown opaque datatype" + value);
}
private Variable convertDatatype(Command command, SnmpDatatype datatype) {
switch (datatype) {
case INT32 -> {
- if (command instanceof DecimalType) {
- return new Integer32(((DecimalType) command).intValue());
- } else if (command instanceof StringType) {
- return new Integer32((new DecimalType(((StringType) command).toString())).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ return new Integer32(decimalCommand.intValue());
+ } else if (command instanceof StringType stringCommand) {
+ return new Integer32((new DecimalType(stringCommand.toString())).intValue());
}
}
case UINT32 -> {
- if (command instanceof DecimalType) {
- return new UnsignedInteger32(((DecimalType) command).intValue());
- } else if (command instanceof StringType) {
- return new UnsignedInteger32((new DecimalType(((StringType) command).toString())).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ return new UnsignedInteger32(decimalCommand.intValue());
+ } else if (command instanceof StringType stringCommand) {
+ return new UnsignedInteger32((new DecimalType(stringCommand.toString())).intValue());
}
}
case COUNTER64 -> {
- if (command instanceof DecimalType) {
- return new Counter64(((DecimalType) command).longValue());
- } else if (command instanceof StringType) {
- return new Counter64((new DecimalType(((StringType) command).toString())).longValue());
+ if (command instanceof DecimalType decimalCommand) {
+ return new Counter64(decimalCommand.longValue());
+ } else if (command instanceof StringType stringCommand) {
+ return new Counter64((new DecimalType(stringCommand.toString())).longValue());
}
}
case FLOAT, STRING -> {
- if (command instanceof DecimalType) {
- return new OctetString(((DecimalType) command).toString());
- } else if (command instanceof StringType) {
- return new OctetString(((StringType) command).toString());
+ if (command instanceof DecimalType decimalCommand) {
+ return new OctetString(decimalCommand.toString());
+ } else if (command instanceof StringType stringCommand) {
+ return new OctetString(stringCommand.toString());
}
}
case HEXSTRING -> {
- if (command instanceof StringType) {
- String commandString = ((StringType) command).toString().toLowerCase();
+ if (command instanceof StringType stringCommand) {
+ String commandString = stringCommand.toString().toLowerCase();
Matcher commandMatcher = HEXSTRING_VALIDITY.matcher(commandString);
if (commandMatcher.matches()) {
commandString = HEXSTRING_EXTRACTOR.matcher(commandString).replaceAll("");
}
}
case IPADDRESS -> {
- if (command instanceof StringType) {
- return new IpAddress(((StringType) command).toString());
+ if (command instanceof StringType stringCommand) {
+ return new IpAddress(stringCommand.toString());
}
}
default -> {
import static org.openhab.binding.snmp.internal.SnmpBindingConstants.THING_TYPE_TARGET;
import java.io.IOException;
-import java.util.Collections;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.Vector;
setup(SnmpBindingConstants.CHANNEL_TYPE_UID_STRING, channelMode);
PDU responsePDU = new PDU(PDU.RESPONSE,
- Collections.singletonList(new VariableBinding(new OID(TEST_OID), new OctetString(TEST_STRING))));
+ List.of(new VariableBinding(new OID(TEST_OID), new OctetString(TEST_STRING))));
ResponseEvent event = new ResponseEvent("test", null, null, responsePDU, null);
thingHandler.onResponse(event);
String onValue, String offValue, Variable value, boolean refresh) {
setup(SnmpBindingConstants.CHANNEL_TYPE_UID_SWITCH, channelMode, datatype, onValue, offValue);
- PDU responsePDU = new PDU(PDU.RESPONSE,
- Collections.singletonList(new VariableBinding(new OID(TEST_OID), value)));
+ PDU responsePDU = new PDU(PDU.RESPONSE, List.of(new VariableBinding(new OID(TEST_OID), value)));
ResponseEvent event = new ResponseEvent("test", null, null, responsePDU, null);
thingHandler.onResponse(event);
import static org.mockito.Mockito.*;
import java.io.IOException;
-import java.util.Collections;
+import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
@Test
public void testStringChannelsProperlyUpdatingOnHexString() throws IOException {
setup(SnmpBindingConstants.CHANNEL_TYPE_UID_STRING, SnmpChannelMode.READ, SnmpDatatype.HEXSTRING);
- PDU responsePDU = new PDU(PDU.RESPONSE, Collections
- .singletonList(new VariableBinding(new OID(TEST_OID), OctetString.fromHexStringPairs("aa11bb"))));
+ PDU responsePDU = new PDU(PDU.RESPONSE,
+ List.of(new VariableBinding(new OID(TEST_OID), OctetString.fromHexStringPairs("aa11bb"))));
ResponseEvent event = new ResponseEvent("test", null, null, responsePDU, null);
thingHandler.onResponse(event);
verify(thingHandlerCallback, atLeast(1)).stateUpdated(eq(CHANNEL_UID), eq(new StringType("aa 11 bb")));
import static org.mockito.Mockito.*;
import java.io.IOException;
-import java.util.Collections;
+import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
@Test
public void testSwitchChannelsProperlyUpdatingOnValue() throws IOException {
setup(SnmpBindingConstants.CHANNEL_TYPE_UID_SWITCH, SnmpChannelMode.READ, SnmpDatatype.STRING, "on", "off");
- PDU responsePDU = new PDU(PDU.RESPONSE,
- Collections.singletonList(new VariableBinding(new OID(TEST_OID), new OctetString("on"))));
+ PDU responsePDU = new PDU(PDU.RESPONSE, List.of(new VariableBinding(new OID(TEST_OID), new OctetString("on"))));
ResponseEvent event = new ResponseEvent("test", null, null, responsePDU, null);
thingHandler.onResponse(event);
verifyResponse(OnOffType.ON);
@Test
public void testSwitchChannelsProperlyUpdatingOffValue() throws IOException {
setup(SnmpBindingConstants.CHANNEL_TYPE_UID_SWITCH, SnmpChannelMode.READ, SnmpDatatype.INT32, "0", "3");
- PDU responsePDU = new PDU(PDU.RESPONSE,
- Collections.singletonList(new VariableBinding(new OID(TEST_OID), new Integer32(3))));
+ PDU responsePDU = new PDU(PDU.RESPONSE, List.of(new VariableBinding(new OID(TEST_OID), new Integer32(3))));
ResponseEvent event = new ResponseEvent("test", null, null, responsePDU, null);
thingHandler.onResponse(event);
verifyResponse(OnOffType.OFF);
public void testSwitchChannelsProperlyUpdatingHexValue() throws IOException {
setup(SnmpBindingConstants.CHANNEL_TYPE_UID_SWITCH, SnmpChannelMode.READ, SnmpDatatype.HEXSTRING, "AA bb 11",
"cc ba 1d");
- PDU responsePDU = new PDU(PDU.RESPONSE, Collections
- .singletonList(new VariableBinding(new OID(TEST_OID), OctetString.fromHexStringPairs("aabb11"))));
+ PDU responsePDU = new PDU(PDU.RESPONSE,
+ List.of(new VariableBinding(new OID(TEST_OID), OctetString.fromHexStringPairs("aabb11"))));
ResponseEvent event = new ResponseEvent("test", null, null, responsePDU, null);
thingHandler.onResponse(event);
verifyResponse(OnOffType.ON);
@Test
public void testSwitchChannelsIgnoresArbitraryValue() throws IOException {
setup(SnmpBindingConstants.CHANNEL_TYPE_UID_SWITCH, SnmpChannelMode.READ, SnmpDatatype.COUNTER64, "0", "12223");
- PDU responsePDU = new PDU(PDU.RESPONSE,
- Collections.singletonList(new VariableBinding(new OID(TEST_OID), new Counter64(17))));
+ PDU responsePDU = new PDU(PDU.RESPONSE, List.of(new VariableBinding(new OID(TEST_OID), new Counter64(17))));
ResponseEvent event = new ResponseEvent("test", null, null, responsePDU, null);
thingHandler.onResponse(event);
verify(thingHandlerCallback, never()).stateUpdated(eq(CHANNEL_UID), any());
@Test
public void testSwitchChannelSendsUndefExceptionValue() throws IOException {
setup(SnmpBindingConstants.CHANNEL_TYPE_UID_SWITCH, SnmpChannelMode.READ, SnmpDatatype.COUNTER64, "0", "12223");
- PDU responsePDU = new PDU(PDU.RESPONSE,
- Collections.singletonList(new VariableBinding(new OID(TEST_OID), Null.noSuchInstance)));
+ PDU responsePDU = new PDU(PDU.RESPONSE, List.of(new VariableBinding(new OID(TEST_OID), Null.noSuchInstance)));
ResponseEvent event = new ResponseEvent("test", null, null, responsePDU, null);
thingHandler.onResponse(event);
verifyResponse(UnDefType.UNDEF);
public void testSwitchChannelSendsConfiguredExceptionValue() throws IOException {
setup(SnmpBindingConstants.CHANNEL_TYPE_UID_SWITCH, SnmpChannelMode.READ, SnmpDatatype.COUNTER64, "0", "12223",
"OFF");
- PDU responsePDU = new PDU(PDU.RESPONSE,
- Collections.singletonList(new VariableBinding(new OID(TEST_OID), Null.noSuchInstance)));
+ PDU responsePDU = new PDU(PDU.RESPONSE, List.of(new VariableBinding(new OID(TEST_OID), Null.noSuchInstance)));
ResponseEvent event = new ResponseEvent("test", null, null, responsePDU, null);
thingHandler.onResponse(event);
verifyResponse(OnOffType.OFF);
*/
package org.openhab.binding.solaredge.internal;
-import java.util.Collections;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public static final String STATUS_NO_METER_CONFIGURED = "@text/status.no.meter.configured";
public static final String STATUS_WAITING_FOR_LOGIN = "@text/status.waiting.for.login";
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_GENERIC);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_GENERIC);
}
public @Nullable Channel getChannel(String groupId, String channelId) {
ThingUID thingUID = this.getThing().getUID();
ChannelGroupUID channelGroupUID = new ChannelGroupUID(thingUID, groupId);
- Channel channel = getThing().getChannel(new ChannelUID(channelGroupUID, channelId));
- return channel;
+ return getThing().getChannel(new ChannelUID(channelGroupUID, channelId));
}
}
*/
private final void fillAggregateData(AggregatePeriod period, String unit, MeterTelemetries meter, String channelId,
Map<Channel, State> valueMap) {
-
String group = convertPeriodToGroup(period);
List<MeterTelemetry> values = meter.values;
import static org.openhab.binding.solarlog.internal.SolarLogBindingConstants.THING_SOLARLOG;
-import java.util.Collections;
import java.util.Set;
import org.openhab.binding.solarlog.internal.handler.SolarLogHandler;
@Component(configurationPid = "binding.solarlog", service = ThingHandlerFactory.class)
public class SolarLogHandlerFactory extends BaseThingHandlerFactory {
private final Logger logger = LoggerFactory.getLogger(SolarLogHandlerFactory.class);
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_SOLARLOG);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_SOLARLOG);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
@Override
public void setThingHandler(final @Nullable ThingHandler handler) {
- if (handler instanceof EnergyManagerHandler) {
- this.energyManagerHandler = (EnergyManagerHandler) handler;
+ if (handler instanceof EnergyManagerHandler energyManagerHandler) {
+ this.energyManagerHandler = energyManagerHandler;
}
}
* @return guid for openhab
*/
private String rewriteGuid(String emGuid) {
- return emGuid.replaceAll(":", "-");
+ return emGuid.replace(":", "-");
}
public class EnergymanagerScan implements Runnable {
public SolarwattTag(String tagName) {
this.tagName = tagName;
- char chars[] = tagName.toCharArray();
+ char[] chars = tagName.toCharArray();
chars[0] = Character.toLowerCase(chars[0]);
this.channelName = new String(chars);
}
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
*/
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(SolarwattDevicesDiscoveryService.class);
+ return Set.of(SolarwattDevicesDiscoveryService.class);
}
/**
Bridge bridge = this.getBridge();
if (bridge != null) {
BridgeHandler bridgeHandler = bridge.getHandler();
- if (bridgeHandler instanceof EnergyManagerHandler) {
- return (EnergyManagerHandler) bridgeHandler;
+ if (bridgeHandler instanceof EnergyManagerHandler energyManagerHandler) {
+ return energyManagerHandler;
} else {
// happens while dynamically reloading the binding
this.logger.warn("BridgeHandler is not implementing EnergyManagerHandler {}", bridgeHandler);
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof SomfyMyLinkBridgeHandler) {
- this.mylinkHandler = (SomfyMyLinkBridgeHandler) handler;
+ if (handler instanceof SomfyMyLinkBridgeHandler bridgeHandler) {
+ this.mylinkHandler = bridgeHandler;
}
}
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Objects;
+import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(SomfyMyLinkDeviceDiscoveryService.class);
+ return Set.of(SomfyMyLinkDeviceDiscoveryService.class);
}
private boolean validConfiguration(@Nullable SomfyMyLinkConfiguration config) {
SomfyTahomaBridgeHandler bridgeHandler = null;
if (thing != null) {
thingHandler = thing.getHandler();
- if (thingHandler instanceof SomfyTahomaBridgeHandler) {
- bridgeHandler = (SomfyTahomaBridgeHandler) thingHandler;
+ if (thingHandler instanceof SomfyTahomaBridgeHandler tahomaBridgeHandler) {
+ bridgeHandler = tahomaBridgeHandler;
}
}
if (thing == null) {
@Override
public void setThingHandler(@NonNullByDefault({}) ThingHandler handler) {
- if (handler instanceof SomfyTahomaBridgeHandler) {
- bridgeHandler = (SomfyTahomaBridgeHandler) handler;
+ if (handler instanceof SomfyTahomaBridgeHandler tahomaBridgeHandler) {
+ bridgeHandler = tahomaBridgeHandler;
}
}
}
public int toInteger(Command command) {
- return (command instanceof DecimalType) ? ((DecimalType) command).intValue() : 0;
+ return (command instanceof DecimalType dateTimeCommand) ? dateTimeCommand.intValue() : 0;
}
public @Nullable BigDecimal toTemperature(Command command) {
BigDecimal temperature = null;
- if (command instanceof QuantityType<?>) {
- QuantityType<?> quantity = (QuantityType<?>) command;
- QuantityType<?> convertedQuantity = quantity.toUnit(getTemperatureUnit());
+ if (command instanceof QuantityType<?> quantityCommand) {
+ QuantityType<?> convertedQuantity = quantityCommand.toUnit(getTemperatureUnit());
if (convertedQuantity != null) {
- quantity = convertedQuantity;
+ quantityCommand = convertedQuantity;
}
- temperature = quantity.toBigDecimal();
- } else if (command instanceof DecimalType) {
- temperature = ((DecimalType) command).toBigDecimal();
+ temperature = quantityCommand.toBigDecimal();
+ } else if (command instanceof DecimalType decimalCommand) {
+ temperature = decimalCommand.toBigDecimal();
}
return temperature;
}
import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledFuture;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(SomfyTahomaItemDiscoveryService.class);
+ return Set.of(SomfyTahomaItemDiscoveryService.class);
}
@Override
private void unregisterExecution(String execId) {
if (executions.containsValue(execId)) {
- executions.values().removeAll(Collections.singleton(execId));
+ executions.values().removeAll(Set.of(execId));
} else {
logger.debug("Cannot remove execution id: {}, because it is not registered", execId);
}
Channel chLevel = thing.getChannel(HEATING_LEVEL);
if (chLevel != null) {
State newState = parseTahomaState(state);
- if (newState != null && newState instanceof PercentType) {
- int value = ((PercentType) newState).intValue();
+ if (newState instanceof PercentType percentState) {
+ int value = percentState.intValue();
PercentType inverted = new PercentType(100 - value);
updateState(chLevel.getUID(), inverted);
}
Object relaunchValue = data.get("relaunch");
if (relaunchValue != null) {
- this.boostMode = relaunchValue.toString().equalsIgnoreCase("on");
+ this.boostMode = "on".equalsIgnoreCase(relaunchValue.toString());
logger.debug("Boost Value: {}", this.boostMode);
updateState(BOOST_MODE, OnOffType.from(this.boostMode));
}
Object awayValue = data.get("absence");
if (awayValue != null) {
- this.awayMode = awayValue.toString().equalsIgnoreCase("on");
+ this.awayMode = "on".equalsIgnoreCase(awayValue.toString());
logger.debug("Away Value: {}", this.awayMode);
updateState(AWAY_MODE, OnOffType.from(this.awayMode));
}
}
break;
case CHANNEL_ALARM_SOUND:
- if (command instanceof StringType) {
- connector.setAlarmSound(alarmPosition, (StringType) command);
+ if (command instanceof StringType stringCommand) {
+ connector.setAlarmSound(alarmPosition, stringCommand);
}
break;
case CHANNEL_ALARM_VOLUME:
logger.debug("Method failed: {}", statusLine);
}
- final String encoding = response.getEncoding() != null ? response.getEncoding().replaceAll("\"", "").trim()
+ final String encoding = response.getEncoding() != null ? response.getEncoding().replace("\"", "").trim()
: StandardCharsets.UTF_8.name();
try {
newValue = "100";
} else if (command == OnOffType.OFF) {
newValue = "0";
- } else if (command instanceof DecimalType) {
- newValue = String.valueOf(((DecimalType) command).intValue());
+ } else if (command instanceof DecimalType decimalCommand) {
+ newValue = String.valueOf(decimalCommand.intValue());
} else {
return;
}
} else if (command == IncreaseDecreaseType.DECREASE && currentValue != null) {
int i = Integer.valueOf(currentValue);
newValue = String.valueOf(Math.max(minValue, i - 1));
- } else if (command instanceof DecimalType) {
- newValue = String.valueOf(((DecimalType) command).intValue());
+ } else if (command instanceof DecimalType decimalCommand) {
+ newValue = String.valueOf(decimalCommand.intValue());
}
}
return newValue;
Thing thing = localThingRegistry.get(new ThingUID(supportedThingType, remotePlayerName));
if (thing != null) {
ThingHandler handler = thing.getHandler();
- if (handler instanceof ZonePlayerHandler) {
- return (ZonePlayerHandler) handler;
+ if (handler instanceof ZonePlayerHandler zonePlayerHandler) {
+ return zonePlayerHandler;
}
}
}
if (SonosBindingConstants.SUPPORTED_THING_TYPES_UIDS.contains(aThing.getThingTypeUID())
&& aThing.getConfiguration().get(ZonePlayerConfiguration.UDN).equals(remotePlayerName)) {
ThingHandler handler = aThing.getHandler();
- if (handler instanceof ZonePlayerHandler) {
- return (ZonePlayerHandler) handler;
+ if (handler instanceof ZonePlayerHandler zonePlayerHandler) {
+ return zonePlayerHandler;
}
}
}
}
public void snoozeAlarm(Command command) {
- if (isAlarmRunning() && command instanceof DecimalType) {
- int minutes = ((DecimalType) command).intValue();
+ if (isAlarmRunning() && command instanceof DecimalType decimalCommand) {
+ int minutes = decimalCommand.intValue();
Map<String, String> inputs = new HashMap<>();
}
public void playTrack(Command command) {
- if (command instanceof DecimalType) {
+ if (command instanceof DecimalType decimalCommand) {
try {
ZonePlayerHandler coordinator = getCoordinatorHandler();
- String trackNumber = String.valueOf(((DecimalType) command).intValue());
+ String trackNumber = String.valueOf(decimalCommand.intValue());
coordinator.setCurrentURI(QUEUE_URI + coordinator.getUDN() + "#0", "");
* Use empty String "" to switch the sleep timer off
*/
public void setSleepTimer(Command command) {
- if (command instanceof DecimalType) {
+ if (command instanceof DecimalType decimalCommand) {
this.service.invokeAction(this, SERVICE_AV_TRANSPORT, ACTION_CONFIGURE_SLEEP_TIMER, Map.of("InstanceID",
- "0", "NewSleepTimerDuration", sleepSecondsToTimeStr(((DecimalType) command).longValue())));
+ "0", "NewSleepTimerDuration", sleepSecondsToTimeStr(decimalCommand.longValue())));
}
}
* ' - '
*/
public static String escapeXml(String xml) {
- xml = xml.replaceAll("&", "&");
- xml = xml.replaceAll("<", "<");
- xml = xml.replaceAll(">", ">");
- xml = xml.replaceAll("\"", """);
- xml = xml.replaceAll("'", "'");
+ xml = xml.replace("&", "&");
+ xml = xml.replace("<", "<");
+ xml = xml.replace(">", ">");
+ xml = xml.replace("\"", """);
+ xml = xml.replace("'", "'");
return xml;
}
* ' - '
*/
public static String unEscapeXml(String xml) {
- xml = xml.replaceAll("&", "&");
- xml = xml.replaceAll("<", "<");
- xml = xml.replaceAll(">", ">");
- xml = xml.replaceAll(""", "\"");
- xml = xml.replaceAll("'", "'");
+ xml = xml.replace("&", "&");
+ xml = xml.replace("<", "<");
+ xml = xml.replace(">", ">");
+ xml = xml.replace(""", "\"");
+ xml = xml.replace("'", "'");
return xml;
}
}
updateState(channelUID, new StringType(result.get("soundField")));
}
}
- if (command instanceof StringType) {
+ if (command instanceof StringType stringCommand) {
logger.debug("handleSoundSettings set {}", command);
- connection.setSoundSettings("soundField", ((StringType) command).toString());
+ connection.setSoundSettings("soundField", stringCommand.toString());
}
}
updateState(channelUID, new StringType(result.get("nightMode")));
}
}
- if (command instanceof OnOffType) {
+ if (command instanceof OnOffType onOffCommand) {
logger.debug("handleNightMode set {}", command);
- connection.setSoundSettings("nightMode", ((OnOffType) command) == OnOffType.ON ? "on" : "off");
+ connection.setSoundSettings("nightMode", onOffCommand == OnOffType.ON ? "on" : "off");
}
}
throw new IOException(ex.getCause());
}
}
- if (command instanceof OnOffType) {
+ if (command instanceof OnOffType onOffCommand) {
logger.debug("handlePowerCommand set {} {}", zone, command);
- connection.setPower(((OnOffType) command) == OnOffType.ON, zone);
+ connection.setPower(onOffCommand == OnOffType.ON, zone);
}
}
throw new IOException(ex.getCause());
}
}
- if (command instanceof PercentType) {
+ if (command instanceof PercentType percentCommand) {
logger.debug("handleVolumeCommand PercentType set {} {}", zone, command);
- connection.setVolume(((PercentType) command).intValue(), zone);
+ connection.setVolume(percentCommand.intValue(), zone);
}
if (command instanceof IncreaseDecreaseType) {
logger.debug("handleVolumeCommand IncreaseDecreaseType set {} {}", zone, command);
String change = command == IncreaseDecreaseType.INCREASE ? "+1" : "-1";
connection.setVolume(change, zone);
}
- if (command instanceof OnOffType) {
+ if (command instanceof OnOffType onOffCommand) {
logger.debug("handleVolumeCommand OnOffType set {} {}", zone, command);
- connection.setMute(((OnOffType) command) == OnOffType.ON, zone);
+ connection.setMute(onOffCommand == OnOffType.ON, zone);
}
}
throw new IOException(ex.getCause());
}
}
- if (command instanceof OnOffType) {
+ if (command instanceof OnOffType onOffCommand) {
logger.debug("handleMuteCommand set {} {}", zone, command);
- connection.setMute(((OnOffType) command) == OnOffType.ON, zone);
+ connection.setMute(onOffCommand == OnOffType.ON, zone);
}
}
if (command instanceof RefreshType) {
updateState(channelUID, new DecimalType(currentRadioStation));
}
- if (command instanceof DecimalType) {
- currentRadioStation = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ currentRadioStation = decimalCommand.intValue();
String radioCommand = "radio:fm?contentId=" + currentRadioStation;
for (int i = 1; i <= 4; i++) {
if (command instanceof RefreshType) {
updateState(channelUID, new StringType(""));
}
- if (command instanceof StringType) {
- switch (((StringType) command).toString()) {
+ if (command instanceof StringType stringCommand) {
+ switch (stringCommand.toString()) {
case "fwdSeeking":
connection.radioSeekFwd();
break;
String path = (String) config.get(SonyAudioBindingConstants.SCALAR_PATH_PARAMETER);
Object port_o = config.get(SonyAudioBindingConstants.SCALAR_PORT_PARAMETER);
int port = 10000;
- if (port_o instanceof BigDecimal) {
- port = ((BigDecimal) port_o).intValue();
+ if (port_o instanceof BigDecimal decimalValue) {
+ port = decimalValue.intValue();
} else if (port_o instanceof Integer) {
port = (int) port_o;
}
Object refresh_o = config.get(SonyAudioBindingConstants.REFRESHINTERVAL);
int refresh = 0;
- if (refresh_o instanceof BigDecimal) {
- refresh = ((BigDecimal) refresh_o).intValue();
+ if (refresh_o instanceof BigDecimal decimalValue) {
+ refresh = decimalValue.intValue();
} else if (refresh_o instanceof Integer) {
refresh = (int) refresh_o;
}
if (result != null) {
logger.debug("SrsZr5Handler Updating sound field to {} {}", result.get("clearAudio"),
result.get("soundField"));
- if (result.get("clearAudio").equalsIgnoreCase("on")) {
+ if ("on".equalsIgnoreCase(result.get("clearAudio"))) {
updateState(channelUID, new StringType("clearAudio"));
} else {
updateState(channelUID, new StringType(result.get("soundField")));
throw new IOException(ex.getCause());
}
}
- if (command instanceof StringType) {
- if (((StringType) command).toString().equalsIgnoreCase("clearAudio")) {
+ if (command instanceof StringType stringCommand) {
+ if ("clearAudio".equalsIgnoreCase(stringCommand.toString())) {
connection.setSoundSettings("clearAudio", "on");
} else {
- connection.setSoundSettings("soundField", ((StringType) command).toString());
+ connection.setSoundSettings("soundField", stringCommand.toString());
}
}
}
if (result != null) {
logger.debug("StrDn1080Handler Updateing sound field to {} {}", result.get("pureDirect"),
result.get("soundField"));
- if (result.get("pureDirect").equalsIgnoreCase("on")) {
+ if ("on".equalsIgnoreCase(result.get("pureDirect"))) {
updateState(channelUID, new StringType("pureDirect"));
} else {
updateState(channelUID, new StringType(result.get("soundField")));
throw new IOException(ex.getCause());
}
}
- if (command instanceof StringType) {
- if (((StringType) command).toString().equalsIgnoreCase("pureDirect")) {
+ if (command instanceof StringType stringCommand) {
+ if ("pureDirect".equalsIgnoreCase(stringCommand.toString())) {
connection.setSoundSettings("pureDirect", "on");
} else {
- connection.setSoundSettings("soundField", ((StringType) command).toString());
+ connection.setSoundSettings("soundField", stringCommand.toString());
}
}
}
}
}
- if (json.get("method").getAsString().equalsIgnoreCase("notifyPlayingContentInfo")) {
+ if ("notifyPlayingContentInfo".equalsIgnoreCase(json.get("method").getAsString())) {
SonyAudioInput input = new SonyAudioInput();
input.input = param.get("uri").getAsString();
if (param.has("broadcastFreq")) {
listener.updateSeekStation("");
}
- if (json.get("method").getAsString().equalsIgnoreCase("notifyVolumeInformation")) {
+ if ("notifyVolumeInformation".equalsIgnoreCase(json.get("method").getAsString())) {
SonyAudioVolume volume = new SonyAudioVolume();
int rawVolume = param.get("volume").getAsInt();
volume.volume = Math.round(100 * (rawVolume - min_volume) / (max_volume - min_volume));
- volume.mute = param.get("mute").getAsString().equalsIgnoreCase("on");
+ volume.mute = "on".equalsIgnoreCase(param.get("mute").getAsString());
listener.updateVolume(zone, volume);
}
- if (json.get("method").getAsString().equalsIgnoreCase("notifyPowerStatus")) {
+ if ("notifyPowerStatus".equalsIgnoreCase(json.get("method").getAsString())) {
String power = param.get("status").getAsString();
- listener.updatePowerStatus(zone, power.equalsIgnoreCase("active"));
+ listener.updatePowerStatus(zone, "active".equalsIgnoreCase(power));
}
listener.updateConnectionState(true);
for (Iterator<Notification> iter = notifications.disabled.listIterator(); iter.hasNext();) {
Notification a = iter.next();
- if (a.name.equalsIgnoreCase("notifyPlayingContentInfo")) {
+ if ("notifyPlayingContentInfo".equalsIgnoreCase(a.name)) {
notifications.enabled.add(a);
iter.remove();
}
for (Iterator<Notification> iter = notifications.disabled.listIterator(); iter.hasNext();) {
Notification a = iter.next();
- if (a.name.equalsIgnoreCase("notifyVolumeInformation")) {
+ if ("notifyVolumeInformation".equalsIgnoreCase(a.name)) {
notifications.enabled.add(a);
iter.remove();
}
for (Iterator<Notification> iter = notifications.disabled.listIterator(); iter.hasNext();) {
Notification a = iter.next();
- if (a.name.equalsIgnoreCase("notifyPowerStatus")) {
+ if ("notifyPowerStatus".equalsIgnoreCase(a.name)) {
notifications.enabled.add(a);
iter.remove();
}
JsonObject terminal = terminals.next().getAsJsonObject();
String uri = terminal.get("uri").getAsString();
if (uri.equalsIgnoreCase("extOutput:zone?zone=" + Integer.toString(zone))) {
- return terminal.get("active").getAsString().equalsIgnoreCase("active") ? true : false;
+ return "active".equalsIgnoreCase(terminal.get("active").getAsString()) ? true : false;
}
}
}
if (element != null && element.isJsonArray()) {
String powerStatus = element.getAsJsonArray().get(0).getAsJsonObject().get("status").getAsString();
- return powerStatus.equalsIgnoreCase("active") ? true : false;
+ return "active".equalsIgnoreCase(powerStatus) ? true : false;
}
throw new IOException("Unexpected responses: Unable to parse GetPowerStatus response message");
}
ret.volume = vol;
String mute = result.get("mute").getAsString();
- ret.mute = mute.equalsIgnoreCase("on") ? true : false;
+ ret.mute = "on".equalsIgnoreCase(mute) ? true : false;
return ret;
}
refreshChannel(CHANNEL_XVCOLOR, true);
break;
case CHANNEL_CONTRAST:
- if (command instanceof DecimalType) {
- connector.setContrast(((DecimalType) command).intValue());
- } else if (command instanceof PercentType) {
- connector.setContrast(((PercentType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ connector.setContrast(decimalCommand.intValue());
+ } else if (command instanceof PercentType percentCommand) {
+ connector.setContrast(percentCommand.intValue());
} else {
throw new SonyProjectorException("Invalid command value");
}
break;
case CHANNEL_BRIGHTNESS:
- if (command instanceof DecimalType) {
- connector.setBrightness(((DecimalType) command).intValue());
- } else if (command instanceof PercentType) {
- connector.setBrightness(((PercentType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ connector.setBrightness(decimalCommand.intValue());
+ } else if (command instanceof PercentType percentCommand2) {
+ connector.setBrightness(percentCommand2.intValue());
} else {
throw new SonyProjectorException("Invalid command value");
}
break;
case CHANNEL_COLOR:
- if (command instanceof DecimalType) {
- connector.setColor(((DecimalType) command).intValue());
- } else if (command instanceof PercentType) {
- connector.setColor(((PercentType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ connector.setColor(decimalCommand.intValue());
+ } else if (command instanceof PercentType percentCommand3) {
+ connector.setColor(percentCommand3.intValue());
} else {
throw new SonyProjectorException("Invalid command value");
}
break;
case CHANNEL_HUE:
- if (command instanceof DecimalType) {
- connector.setHue(((DecimalType) command).intValue());
- } else if (command instanceof PercentType) {
- connector.setHue(((PercentType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ connector.setHue(decimalCommand.intValue());
+ } else if (command instanceof PercentType percentCommand4) {
+ connector.setHue(percentCommand4.intValue());
} else {
throw new SonyProjectorException("Invalid command value");
}
break;
case CHANNEL_SHARPNESS:
- if (command instanceof DecimalType) {
- connector.setSharpness(((DecimalType) command).intValue());
- } else if (command instanceof PercentType) {
- connector.setSharpness(((PercentType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ connector.setSharpness(decimalCommand.intValue());
+ } else if (command instanceof PercentType percentCommand5) {
+ connector.setSharpness(percentCommand5.intValue());
} else {
throw new SonyProjectorException("Invalid command value");
}
refreshChannel(CHANNEL_IRIS_MANUAL, true);
break;
case CHANNEL_IRIS_MANUAL:
- if (command instanceof DecimalType) {
- connector.setIrisManual(((DecimalType) command).intValue());
- } else if (command instanceof PercentType) {
- connector.setIrisManual(((PercentType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ connector.setIrisManual(decimalCommand.intValue());
+ } else if (command instanceof PercentType percentCommand6) {
+ connector.setIrisManual(percentCommand6.intValue());
} else {
throw new SonyProjectorException("Invalid command value");
}
@Override
public void setThingHandler(ThingHandler handler) {
- if (handler instanceof SoulissGatewayHandler) {
- SoulissGatewayHandler localGwHandler = (SoulissGatewayHandler) handler;
+ if (handler instanceof SoulissGatewayHandler localGwHandler) {
this.soulissGwHandler = localGwHandler;
localGwHandler.discoverResult = this;
}
package org.openhab.binding.souliss.internal.handler;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(SoulissGatewayDiscovery.class);
+ return Set.of(SoulissGatewayDiscovery.class);
}
@Override
public void setState(@Nullable PrimitiveType state) {
super.setLastStatusStored();
if (state != null) {
- if (state instanceof OnOffType) {
- this.updateState(SoulissBindingConstants.STATEONOFF_CHANNEL, (OnOffType) state);
+ if (state instanceof OnOffType onOffCommand) {
+ this.updateState(SoulissBindingConstants.STATEONOFF_CHANNEL, onOffCommand);
}
- if (state instanceof OpenClosedType) {
- this.updateState(SoulissBindingConstants.STATEOPENCLOSE_CHANNEL, (OpenClosedType) state);
+ if (state instanceof OpenClosedType openClosedCommand) {
+ this.updateState(SoulissBindingConstants.STATEOPENCLOSE_CHANNEL, openClosedCommand);
}
}
}
break;
case SoulissBindingConstants.LED_COLOR_CHANNEL:
- if (command instanceof HSBType) {
- HSBType localHsbState = (HSBType) command;
-
+ if (command instanceof HSBType localHsbState) {
updateState(SoulissBindingConstants.DIMMER_BRIGHTNESS_CHANNEL,
PercentType.valueOf(hsbState.getBrightness().toString()));
commandSendRgb(SoulissProtocolConstants.SOULISS_T1N_SET,
break;
case SoulissBindingConstants.DIMMER_BRIGHTNESS_CHANNEL:
- if (command instanceof PercentType) {
- updateState(SoulissBindingConstants.DIMMER_BRIGHTNESS_CHANNEL, (PercentType) command);
+ if (command instanceof PercentType percentCommand) {
+ updateState(SoulissBindingConstants.DIMMER_BRIGHTNESS_CHANNEL, percentCommand);
commandSEND(SoulissProtocolConstants.SOULISS_T1N_SET,
- (byte) (((PercentType) command).shortValue() * 255.00 / 100.00));
+ (byte) (percentCommand.shortValue() * 255.00 / 100.00));
} else if (command.equals(OnOffType.ON)) {
commandSEND(SoulissProtocolConstants.SOULISS_T1N_ON_CMD);
}
public void setState(PrimitiveType state) {
- if (state instanceof PercentType) {
- this.updateState(SoulissBindingConstants.ROLLERSHUTTER_CHANNEL, (PercentType) state);
+ if (state instanceof PercentType percentCommand) {
+ this.updateState(SoulissBindingConstants.ROLLERSHUTTER_CHANNEL, percentCommand);
}
}
}
break;
case SoulissBindingConstants.T31_SETPOINT_CHANNEL:
- if (command instanceof QuantityType<?>) {
- int uu = HalfFloatUtils.fromFloat(((QuantityType<?>) command).floatValue());
+ if (command instanceof QuantityType<?> quantityCommand) {
+ int uu = HalfFloatUtils.fromFloat(quantityCommand.floatValue());
byte b2 = (byte) (uu >> 8);
byte b1 = (byte) uu;
// setpoint command
this.updateState(SoulissBindingConstants.T31_BUTTON_CHANNEL, OnOffType.OFF);
super.setLastStatusStored();
- if (state instanceof StringType) {
+ if (state instanceof StringType stringState) {
switch (state.toString()) {
case SoulissBindingConstants.T31_FANLOW_MESSAGE_FAN_CHANNEL:
case SoulissBindingConstants.T31_FANMEDIUM_MESSAGE_FAN_CHANNEL:
case SoulissBindingConstants.T31_FANAUTO_MESSAGE_FAN_CHANNEL:
case SoulissBindingConstants.T31_FANOFF_MESSAGE_FAN_CHANNEL:
if (!fanStateValue.equals(state)) {
- this.updateState(SoulissBindingConstants.T31_FAN_CHANNEL, (StringType) state);
- fanStateValue = (StringType) state;
+ this.updateState(SoulissBindingConstants.T31_FAN_CHANNEL, stringState);
+ fanStateValue = stringState;
}
break;
case SoulissBindingConstants.T31_HEATINGMODE_MESSAGE_MODE_CHANNEL:
if (!modeStateValue.equals(state)) {
- this.updateState(SoulissBindingConstants.T31_MODE_CHANNEL, (StringType) state);
- modeStateValue = (StringType) state;
+ this.updateState(SoulissBindingConstants.T31_MODE_CHANNEL, stringState);
+ modeStateValue = stringState;
}
break;
case SoulissBindingConstants.T31_COOLINGMODE_MESSAGE_MODE_CHANNEL:
if (!modeStateValue.equals(state)) {
- this.updateState(SoulissBindingConstants.T31_MODE_CHANNEL, (StringType) state);
- modeStateValue = (StringType) state;
+ this.updateState(SoulissBindingConstants.T31_MODE_CHANNEL, stringState);
+ modeStateValue = stringState;
}
break;
case SoulissBindingConstants.T31_OFF_MESSAGE_SYSTEM_CHANNEL:
if (!powerState.equals(state)) {
this.updateState(SoulissBindingConstants.T31_SYSTEM_CHANNEL, OnOffType.OFF);
- powerState = (StringType) state;
+ powerState = stringState;
}
break;
case SoulissBindingConstants.T31_ON_MESSAGE_SYSTEM_CHANNEL:
if (!powerState.equals(state)) {
this.updateState(SoulissBindingConstants.T31_SYSTEM_CHANNEL, OnOffType.ON);
- powerState = (StringType) state;
+ powerState = stringState;
}
break;
case SoulissBindingConstants.T31_ON_MESSAGE_FIRE_CHANNEL:
if (!fireState.equals(state)) {
this.updateState(SoulissBindingConstants.T31_FIRE_CHANNEL, OnOffType.ON);
- fireState = (StringType) state;
+ fireState = stringState;
}
break;
case SoulissBindingConstants.T31_OFF_MESSAGE_FIRE_CHANNEL:
if (!fireState.equals(state)) {
this.updateState(SoulissBindingConstants.T31_FIRE_CHANNEL, OnOffType.OFF);
- fireState = (StringType) state;
+ fireState = stringState;
}
break;
}
public void setState(PrimitiveType state) {
- if (state instanceof OnOffType) {
- this.updateState(SoulissBindingConstants.T4N_ONOFFALARM_CHANNEL, (OnOffType) state);
+ if (state instanceof OnOffType onOffState) {
+ this.updateState(SoulissBindingConstants.T4N_ONOFFALARM_CHANNEL, onOffState);
} else if (state instanceof StringType) {
switch (String.valueOf(state)) {
case SoulissBindingConstants.T4N_ALARMON_MESSAGE_CHANNEL:
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
- if (command instanceof DecimalType) {
- int uu = HalfFloatUtils.fromFloat(((DecimalType) command).floatValue());
+ if (command instanceof DecimalType decimalCommand) {
+ int uu = HalfFloatUtils.fromFloat(decimalCommand.floatValue());
byte b2 = (byte) (uu >> 8);
byte b1 = (byte) uu;
// setpoint command
public void run() {
DatagramSocket sender = null;
- try (var channel = DatagramChannel.open();) {
+ try (var channel = DatagramChannel.open()) {
if (checkTime()) {
PacketStruct sp = pop();
if (sp != null) {
if ((versionString != null) && !versionString.isEmpty()) {
int newLI = versionString.indexOf(System.lineSeparator());
String versionLine = versionString.substring(0, newLI);
- if (versionString.indexOf("Speedtest by Ookla") > -1) {
+ if (versionString.contains("Speedtest by Ookla")) {
logger.debug("Speedtest Version: {}", versionLine);
return true;
} else {
ResultContainer tmpCont = doExecuteRequest(" -f json --accept-license --accept-gdpr" + postCommand,
ResultContainer.class);
if (tmpCont != null) {
- if (tmpCont.getType().equals("result")) {
+ if ("result".equals(tmpCont.getType())) {
pingJitter = tmpCont.getPing().getJitter();
pingLatency = tmpCont.getPing().getLatency();
downloadBandwidth = tmpCont.getDownload().getBandwidth();
updateState(new ChannelUID(getThing().getUID(), SpeedtestBindingConstants.UPLOAD_ELAPSED), newState);
updateState(new ChannelUID(getThing().getUID(), SpeedtestBindingConstants.INTERFACE_EXTERNALIP),
- new StringType(String.valueOf(interfaceExternalIp)));
+ new StringType(interfaceExternalIp));
updateState(new ChannelUID(getThing().getUID(), SpeedtestBindingConstants.INTERFACE_INTERNALIP),
- new StringType(String.valueOf(interfaceInternalIp)));
- updateState(new ChannelUID(getThing().getUID(), SpeedtestBindingConstants.ISP),
- new StringType(String.valueOf(isp)));
+ new StringType(interfaceInternalIp));
+ updateState(new ChannelUID(getThing().getUID(), SpeedtestBindingConstants.ISP), new StringType(isp));
updateState(new ChannelUID(getThing().getUID(), SpeedtestBindingConstants.RESULT_URL),
- new StringType(String.valueOf(resultUrl)));
- updateState(new ChannelUID(getThing().getUID(), SpeedtestBindingConstants.SERVER),
- new StringType(String.valueOf(server)));
+ new StringType(resultUrl));
+ updateState(new ChannelUID(getThing().getUID(), SpeedtestBindingConstants.SERVER), new StringType(server));
}
/**
} else {
logger.debug("Splitting by spaces");
try {
- String[] splitCmd = commandLine.split(" ");
- return splitCmd;
+ return commandLine.split(" ");
} catch (PatternSyntaxException e) {
logger.warn("An exception occurred while splitting '{}': '{}'", commandLine, e.getMessage());
return new String[] {};
@Override
protected synchronized void removeHandler(ThingHandler thingHandler) {
- if (thingHandler instanceof SpotifyBridgeHandler) {
- authService.removeSpotifyAccountHandler((SpotifyBridgeHandler) thingHandler);
+ if (thingHandler instanceof SpotifyBridgeHandler bridgeHandler) {
+ authService.removeSpotifyAccountHandler(bridgeHandler);
}
}
}
} catch (ExecutionException e) {
final Throwable cause = e.getCause();
- if (cause instanceof RuntimeException) {
- throw (RuntimeException) cause;
+ if (cause instanceof RuntimeException runtimeException) {
+ throw runtimeException;
} else {
throw new SpotifyException(e.getMessage(), e);
}
import static org.openhab.binding.spotify.internal.SpotifyBindingConstants.THING_TYPE_DEVICE;
import java.time.Duration;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
// id for device is derived by stripping id of device with this length
private static final int PLAYER_ID_LENGTH = 4;
// Only devices can be discovered. A bridge must be manually added.
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_DEVICE);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_DEVICE);
// The call to listDevices is fast
private static final int DISCOVERY_TIME_SECONDS = 10;
// Check every minute for new devices
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof SpotifyAccountHandler) {
- bridgeHandler = (SpotifyAccountHandler) handler;
+ if (handler instanceof SpotifyAccountHandler accountHandler) {
+ bridgeHandler = accountHandler;
bridgeUID = bridgeHandler.getUID();
}
}
commandRun = handleDevicePlay(command, active, deviceId);
break;
case CHANNEL_DEVICESHUFFLE:
- if (command instanceof OnOffType) {
- spotifyApi.setShuffleState(deviceId, (OnOffType) command);
+ if (command instanceof OnOffType onOffCommand) {
+ spotifyApi.setShuffleState(deviceId, onOffCommand);
commandRun = true;
}
break;
commandRun = true;
}
case CHANNEL_DEVICEVOLUME:
- if (command instanceof DecimalType) {
- final PercentType volume = command instanceof PercentType ? (PercentType) command
- : new PercentType(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ final PercentType volume = command instanceof PercentType percentType ? percentType
+ : new PercentType(decimalCommand.intValue());
spotifyApi.setVolume(deviceId, volume.intValue());
commandRun = true;
}
String url;
- if (audioStream instanceof URLAudioStream) {
- url = ((URLAudioStream) audioStream).getURL();
+ if (audioStream instanceof URLAudioStream urlAudioStream) {
+ url = urlAudioStream.getURL();
tryClose(audioStream);
} else {
try {
@Override
protected synchronized void removeHandler(ThingHandler thingHandler) {
- if (thingHandler instanceof SqueezeBoxServerHandler) {
+ if (thingHandler instanceof SqueezeBoxServerHandler serverHandler) {
logger.trace("removing handler for bridge thing {}", thingHandler.getThing());
ServiceRegistration<?> serviceReg = this.discoveryServiceRegs.get(thingHandler.getThing().getUID());
discoveryService.cancelRequestPlayerJob();
// Unregister the PlayerListener from the SqueezeBoxServerHandler
- ((SqueezeBoxServerHandler) thingHandler).unregisterSqueezeBoxPlayerListener(
+ serverHandler.unregisterSqueezeBoxPlayerListener(
(SqueezeBoxPlayerEventListener) bundleContext.getService(serviceReg.getReference()));
// Unregister the PlayerListener service
}
}
- if (thingHandler instanceof SqueezeBoxPlayerHandler) {
- SqueezeBoxServerHandler bridge = ((SqueezeBoxPlayerHandler) thingHandler).getSqueezeBoxServerHandler();
+ if (thingHandler instanceof SqueezeBoxPlayerHandler playerHandler) {
+ SqueezeBoxServerHandler bridge = playerHandler.getSqueezeBoxServerHandler();
if (bridge != null) {
// Unregister the player's audio sink
logger.trace("Unregistering the audio sync service for player thing {}",
}
logger.trace("removing handler for player thing {}", thingHandler.getThing());
- bridge.removePlayerCache(((SqueezeBoxPlayerHandler) thingHandler).getMac());
+ bridge.removePlayerCache(playerHandler.getMac());
}
}
}
import static org.openhab.binding.squeezebox.internal.SqueezeBoxBindingConstants.SQUEEZEBOXSERVER_THING_TYPE;
import java.net.URI;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(SQUEEZEBOXSERVER_THING_TYPE);
+ return Set.of(SQUEEZEBOXSERVER_THING_TYPE);
}
@Override
}
logger.trace("Mode is {} for player {}", mode, mac);
- if (mode.equals("play")) {
+ if ("play".equals(mode)) {
this.started.set(true);
- } else if (this.started.get() && mode.equals("stop")) {
+ } else if (this.started.get() && "stop".equals(mode)) {
this.stopped.set(true);
}
- if (mode.equals("pause")) {
+ if ("pause".equals(mode)) {
this.paused.set(true);
}
}
public class SqueezeBoxPlayerHandler extends BaseThingHandler implements SqueezeBoxPlayerEventListener {
private final Logger logger = LoggerFactory.getLogger(SqueezeBoxPlayerHandler.class);
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .singleton(SQUEEZEBOXPLAYER_THING_TYPE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(SQUEEZEBOXPLAYER_THING_TYPE);
/**
* We need to remember some states to change offsets in volume, time index,
}
break;
case CHANNEL_VOLUME:
- if (command instanceof PercentType) {
- squeezeBoxServerHandler.setVolume(mac, ((PercentType) command).intValue());
+ if (command instanceof PercentType percentCommand) {
+ squeezeBoxServerHandler.setVolume(mac, percentCommand.intValue());
} else if (command.equals(IncreaseDecreaseType.INCREASE)) {
squeezeBoxServerHandler.volumeUp(mac, currentVolume());
} else if (command.equals(IncreaseDecreaseType.DECREASE)) {
}
break;
case CHANNEL_SLEEP:
- if (command instanceof DecimalType) {
- Duration sleepDuration = Duration.ofMinutes(((DecimalType) command).longValue());
+ if (command instanceof DecimalType decimalCommand) {
+ Duration sleepDuration = Duration.ofMinutes(decimalCommand.longValue());
if (sleepDuration.isNegative() || sleepDuration.compareTo(Duration.ofDays(1)) > 0) {
logger.debug("Sleep timer of {} minutes must be >= 0 and <= 1 day", sleepDuration.toMinutes());
return;
private int cachedStateAsInt(String key) {
State state = stateMap.get(key);
- return state instanceof DecimalType ? ((DecimalType) state).intValue() : 0;
+ return state instanceof DecimalType decimalValue ? decimalValue.intValue() : 0;
}
/**
public class SqueezeBoxServerHandler extends BaseBridgeHandler {
private final Logger logger = LoggerFactory.getLogger(SqueezeBoxServerHandler.class);
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .singleton(SQUEEZEBOXSERVER_THING_TYPE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(SQUEEZEBOXSERVER_THING_TYPE);
// time in seconds to try to reconnect
private static final int RECONNECT_TIME = 60;
int newVolume = volume;
newVolume = Math.min(100, newVolume);
newVolume = Math.max(0, newVolume);
- sendCommand(mac + " mixer volume " + String.valueOf(newVolume));
+ sendCommand(mac + " mixer volume " + newVolume);
}
public void showString(String mac, String line) {
}
public void showString(String mac, String line, int duration) {
- sendCommand(mac + " show line1:" + line + " duration:" + String.valueOf(duration));
+ sendCommand(mac + " show line1:" + line + " duration:" + duration);
}
public void showStringHuge(String mac, String line) {
}
public void showStringHuge(String mac, String line, int duration) {
- sendCommand(mac + " show line1:" + line + " font:huge duration:" + String.valueOf(duration));
+ sendCommand(mac + " show line1:" + line + " font:huge duration:" + duration);
}
public void showStrings(String mac, String line1, String line2) {
}
public void showStrings(String mac, String line1, String line2, int duration) {
- sendCommand(mac + " show line1:" + line1 + " line2:" + line2 + " duration:" + String.valueOf(duration));
+ sendCommand(mac + " show line1:" + line1 + " line2:" + line2 + " duration:" + duration);
}
public void playFavorite(String mac, String favorite) {
}
public void sleep(String mac, Duration sleepDuration) {
- sendCommand(mac + " sleep " + String.valueOf(sleepDuration.toSeconds()));
+ sendCommand(mac + " sleep " + sleepDuration.toSeconds());
}
/**
}
String action = messageParts[2];
String mode;
- if (action.equals("newsong")) {
+ if ("newsong".equals(action)) {
mode = "play";
// Execute in separate thread to avoid delaying listener
scheduler.execute(() -> updateCustomButtons(mac));
// Set the track duration to 0
updatePlayer(listener -> listener.durationEvent(mac, 0));
- } else if (action.equals("pause")) {
+ } else if ("pause".equals(action)) {
if (messageParts.length < 4) {
return;
}
- mode = messageParts[3].equals("0") ? "play" : "pause";
- } else if (action.equals("stop")) {
+ mode = "0".equals(messageParts[3]) ? "play" : "pause";
+ } else if ("stop".equals(action)) {
mode = "stop";
} else if ("play".equals(action) && "playlist".equals(messageParts[1])) {
if (messageParts.length >= 4) {
}
private void handleSourceChangeMessage(String mac, String rawSource) {
- String source = URLDecoder.decode(rawSource);
+ String source = URLDecoder.decode(rawSource, StandardCharsets.UTF_8);
updatePlayer(listener -> listener.sourceChangeEvent(mac, source));
}
return;
}
// server prefsets
- if (messageParts[2].equals("server")) {
+ if ("server".equals(messageParts[2])) {
String function = messageParts[3];
String value = messageParts[4];
- if (function.equals("power")) {
- final boolean power = value.equals("1");
+ if ("power".equals(function)) {
+ final boolean power = "1".equals(value);
updatePlayer(listener -> listener.powerChangeEvent(mac, power));
- } else if (function.equals("volume")) {
+ } else if ("volume".equals(function)) {
final int volume = (int) Double.parseDouble(value);
updatePlayer(listener -> listener.absoluteVolumeChangeEvent(mac, volume));
}
String quote = includeQuotes.booleanValue() ? "\"" : "";
StringBuilder sb = new StringBuilder();
for (Favorite favorite : favorites) {
- sb.append(favorite.shortId).append("=").append(quote).append(favorite.name.replaceAll(",", ""))
+ sb.append(favorite.shortId).append("=").append(quote).append(favorite.name.replace(",", ""))
.append(quote).append(",");
}
List<Thing> things = bridge.getThings();
for (Thing thing : things) {
ThingHandler handler = thing.getHandler();
- if (handler instanceof SqueezeBoxPlayerEventListener && !squeezeBoxPlayerListeners.contains(handler)) {
- event.updateListener((SqueezeBoxPlayerEventListener) handler);
+ if (handler instanceof SqueezeBoxPlayerEventListener playerEventListener
+ && !squeezeBoxPlayerListeners.contains(handler)) {
+ event.updateListener(playerEventListener);
}
}
}
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.util.Arrays;
-import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public static final ThingTypeUID THING_TYPE_FLAP_DEVICE = new ThingTypeUID(BINDING_ID, "flapDevice");
public static final ThingTypeUID THING_TYPE_FEEDER_DEVICE = new ThingTypeUID(BINDING_ID, "feederDevice");
- public static final Set<ThingTypeUID> BRIDGE_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_BRIDGE);
+ public static final Set<ThingTypeUID> BRIDGE_THING_TYPES_UIDS = Set.of(THING_TYPE_BRIDGE);
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = new HashSet<>(Arrays.asList(THING_TYPE_HOUSEHOLD,
THING_TYPE_PET, THING_TYPE_HUB_DEVICE, THING_TYPE_FLAP_DEVICE, THING_TYPE_FEEDER_DEVICE));
import static org.openhab.binding.surepetcare.internal.SurePetcareConstants.*;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
private final Logger logger = LoggerFactory.getLogger(SurePetcareDiscoveryService.class);
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_BRIDGE);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BRIDGE);
private static final int DISCOVER_TIMEOUT_SECONDS = 5;
private static final int DISCOVERY_SCAN_DELAY_MINUTES = 1;
import static org.openhab.binding.surepetcare.internal.SurePetcareConstants.*;
import java.util.Collection;
-import java.util.Collections;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(SurePetcareDiscoveryService.class);
+ return Set.of(SurePetcareDiscoveryService.class);
}
@Override
@Activate
public StationDbService() {
try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("/db/stations.json");
- Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8);) {
+ Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
stations = Arrays.asList(gson.fromJson(reader, Station[].class));
} catch (IOException | JsonSyntaxException | JsonIOException e) {
private static final int HV_LESS_THAN_10_HP_LIMIT = 96;
private static final int HV_LESS_THAN_50_HP_LIMIT = 98;
- public static enum HorizontalVisibility {
+ public enum HorizontalVisibility {
UNDEFINED,
LESS_THAN_1,
LESS_THAN_10,
import java.net.InetAddress;
import java.net.UnknownHostException;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
private final Logger logger = LoggerFactory.getLogger(SysteminfoDiscoveryService.class);
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_COMPUTER);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_COMPUTER);
private static final int DISCOVERY_TIME_SECONDS = 30;
private static final String THING_UID_VALID_CHARS = "A-Za-z0-9_-";
protected String getHostName() throws UnknownHostException {
InetAddress addr = InetAddress.getLocalHost();
- String hostname = addr.getHostName();
- return hostname;
+ return addr.getHostName();
}
}
}
if (channelGroupID.contains(CHANNEL_GROUP_CURRENT_PROCESS)) {
- int pid = systeminfo.getCurrentProcessID();
- return pid;
+ return systeminfo.getCurrentProcessID();
}
// First try to get device index in group id, delete all non-digits from id
String command = buildUrl(CMD_LOGIN) + "user=" + encodedUser + "&" + "psw=" + encodedPass;
response = sendCommand(command, METHOD_GET, "");
- return !response.equals("Unauthorized");
+ return !"Unauthorized".equals(response);
}
public String cmdListUnits() {
@Override
public TouchWandUnitDataAlarmSensor deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
-
TouchWandUnitDataAlarmSensor touchWandUnitDataAlarmSensor = new TouchWandUnitDataAlarmSensor();
JsonObject jsonObject = json.getAsJsonObject();
JsonObject.class);
if (currentStatusObj != null) {
-
TouchWandAlarmSensorCurrentStatus touchWandUnitDataAlarmSensorCurrentStatus = touchWandUnitDataAlarmSensor
.getCurrStatus();