updateOvenData(postData);
}
} else if (channelUID.getId().equals(CHANNELSPTEMP)) {
- if (command instanceof QuantityType<?>) {
- QuantityType<?> value = (QuantityType<?>) command;
-
+ if (command instanceof QuantityType<?> quantityCommand) {
Unit<Temperature> unit = SIUnits.CELSIUS;
- value = value.toUnit(unit);
+ QuantityType<?> value = quantityCommand.toUnit(unit);
if (value != null) {
double a = value.doubleValue();
String postdata = "{\"sp_temp\":" + a + "}";
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException(e);
}
- byte[] result = md.digest(input);
- return result;
+ return md.digest(input);
}
private static String bytesToHex(byte[] bytes) {
import static org.openhab.binding.harmonyhub.internal.HarmonyHubBindingConstants.*;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
private final Logger logger = LoggerFactory.getLogger(HarmonyDeviceHandler.class);
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(HARMONY_DEVICE_THING_TYPE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(HARMONY_DEVICE_THING_TYPE);
private final HarmonyHubDynamicTypeProvider typeProvider;
switch (channel.getUID().getId()) {
case CHANNEL_CURRENT_ACTIVITY:
- if (command instanceof DecimalType) {
+ if (command instanceof DecimalType decimalCommand) {
try {
- client.startActivity(((DecimalType) command).intValue());
+ client.startActivity(decimalCommand.intValue());
} catch (Exception e) {
logger.warn("Could not start activity", e);
}
// Hayward Command html
public static final String COMMAND_PARAMETERS = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Request>";
- public static final String COMMAND_SCHEDULE = "<Parameter name=\"IsCountDownTimer\" dataType=\"bool\">false</Parameter>"
- + "<Parameter name=\"StartTimeHours\" dataType=\"int\">0</Parameter>"
- + "<Parameter name=\"StartTimeMinutes\" dataType=\"int\">0</Parameter>"
- + "<Parameter name=\"EndTimeHours\" dataType=\"int\">0</Parameter>"
- + "<Parameter name=\"EndTimeMinutes\" dataType=\"int\">0</Parameter>"
- + "<Parameter name=\"DaysActive\" dataType=\"int\">0</Parameter>"
- + "<Parameter name=\"Recurring\" dataType=\"bool\">false</Parameter>";
+ public static final String COMMAND_SCHEDULE = """
+ <Parameter name="IsCountDownTimer" dataType="bool">false</Parameter>\
+ <Parameter name="StartTimeHours" dataType="int">0</Parameter>\
+ <Parameter name="StartTimeMinutes" dataType="int">0</Parameter>\
+ <Parameter name="EndTimeHours" dataType="int">0</Parameter>\
+ <Parameter name="EndTimeMinutes" dataType="int">0</Parameter>\
+ <Parameter name="DaysActive" dataType="int">0</Parameter>\
+ <Parameter name="Recurring" dataType="bool">false</Parameter>\
+ """;
}
if (bridge != null) {
HaywardBridgeHandler bridgehandler = (HaywardBridgeHandler) bridge.getHandler();
if (bridgehandler != null) {
- if (bridgehandler.account.units.equals("Standard")) {
+ if ("Standard".equals(bridgehandler.account.units)) {
return new QuantityType<>(Integer.parseInt(value), ImperialUnits.FAHRENHEIT);
} else {
return new QuantityType<>(Integer.parseInt(value), SIUnits.CELSIUS);
return "0";
} else if (command == OnOffType.ON) {
return "1";
- } else if (command instanceof DecimalType) {
- return ((DecimalType) command).toString();
- } else if (command instanceof QuantityType) {
- return ((QuantityType<?>) command).format("%1.0f");
+ } else if (command instanceof DecimalType decimalCommand) {
+ return decimalCommand.toString();
+ } else if (command instanceof QuantityType quantityCommand) {
+ return quantityCommand.format("%1.0f");
} else {
return command.toString();
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof HaywardBridgeHandler) {
- this.discoveryBridgehandler = (HaywardBridgeHandler) handler;
+ if (handler instanceof HaywardBridgeHandler bridgeHandler) {
+ this.discoveryBridgehandler = bridgeHandler;
}
}
HaywardBridgeHandler bridgehandler = (HaywardBridgeHandler) bridge.getHandler();
if (bridgehandler != null) {
// *****Request Alarm List from Hayward server
- String urlParameters = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Request><Name>GetAlarmList</Name><Parameters>"
- + "<Parameter name=\"Token\" dataType=\"String\">" + bridgehandler.account.token
- + "</Parameter>" + "<Parameter name=\"MspSystemID\" dataType=\"int\">"
- + bridgehandler.account.mspSystemID + "</Parameter>"
+ String urlParameters = """
+ <?xml version="1.0" encoding="utf-8"?><Request><Name>GetAlarmList</Name><Parameters>\
+ <Parameter name="Token" dataType="String">\
+ """ + bridgehandler.account.token + "</Parameter>"
+ + "<Parameter name=\"MspSystemID\" dataType=\"int\">" + bridgehandler.account.mspSystemID
+ + "</Parameter>"
+ "<Parameter name=\"CultureInfoName\" dataType=\"String\">en-us</Parameter></Parameters></Request>";
try {
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(HaywardDiscoveryService.class);
+ return Set.of(HaywardDiscoveryService.class);
}
public HaywardBridgeHandler(HaywardDynamicStateDescriptionProvider stateDescriptionProvider, Bridge bridge,
String status;
// *****Login to Hayward server
- String urlParameters = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Request>" + "<Name>Login</Name><Parameters>"
- + "<Parameter name=\"UserName\" dataType=\"String\">" + config.username + "</Parameter>"
- + "<Parameter name=\"Password\" dataType=\"String\">" + config.password + "</Parameter>"
- + "</Parameters></Request>";
+ String urlParameters = """
+ <?xml version="1.0" encoding="utf-8"?><Request>\
+ <Name>Login</Name><Parameters>\
+ <Parameter name="UserName" dataType="String">\
+ """ + config.username + "</Parameter>" + "<Parameter name=\"Password\" dataType=\"String\">"
+ + config.password + "</Parameter>" + "</Parameters></Request>";
xmlResponse = httpXmlResponse(urlParameters);
String xmlResponse;
// *****getApiDef from Hayward server
- String urlParameters = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Request><Name>GetAPIDef</Name><Parameters>"
- + "<Parameter name=\"Token\" dataType=\"String\">" + account.token + "</Parameter>"
- + "<Parameter name=\"MspSystemID\" dataType=\"int\">" + account.mspSystemID + "</Parameter>;"
+ String urlParameters = """
+ <?xml version="1.0" encoding="utf-8"?><Request><Name>GetAPIDef</Name><Parameters>\
+ <Parameter name="Token" dataType="String">\
+ """ + account.token + "</Parameter>" + "<Parameter name=\"MspSystemID\" dataType=\"int\">"
+ + account.mspSystemID + "</Parameter>;"
+ "<Parameter name=\"Version\" dataType=\"string\">0.4</Parameter >\r\n"
+ "<Parameter name=\"Language\" dataType=\"string\">en</Parameter >\r\n" + "</Parameters></Request>";
String status;
// *****Get MSP
- String urlParameters = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Request><Name>GetSiteList</Name><Parameters>"
- + "<Parameter name=\"Token\" dataType=\"String\">" + account.token
- + "</Parameter><Parameter name=\"UserID\" dataType=\"String\">" + account.userID
+ String urlParameters = """
+ <?xml version="1.0" encoding="utf-8"?><Request><Name>GetSiteList</Name><Parameters>\
+ <Parameter name="Token" dataType="String">\
+ """ + account.token + "</Parameter><Parameter name=\"UserID\" dataType=\"String\">" + account.userID
+ "</Parameter></Parameters></Request>";
xmlResponse = httpXmlResponse(urlParameters);
public synchronized String getMspConfig() throws HaywardException, InterruptedException {
// *****getMspConfig from Hayward server
- String urlParameters = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Request><Name>GetMspConfigFile</Name><Parameters>"
- + "<Parameter name=\"Token\" dataType=\"String\">" + account.token + "</Parameter>"
- + "<Parameter name=\"MspSystemID\" dataType=\"int\">" + account.mspSystemID
- + "</Parameter><Parameter name=\"Version\" dataType=\"string\">0</Parameter>\r\n"
+ String urlParameters = """
+ <?xml version="1.0" encoding="utf-8"?><Request><Name>GetMspConfigFile</Name><Parameters>\
+ <Parameter name="Token" dataType="String">\
+ """ + account.token + "</Parameter>" + "<Parameter name=\"MspSystemID\" dataType=\"int\">"
+ + account.mspSystemID + "</Parameter><Parameter name=\"Version\" dataType=\"string\">0</Parameter>\r\n"
+ "</Parameters></Request>";
String xmlResponse = httpXmlResponse(urlParameters);
public synchronized boolean getTelemetryData() throws HaywardException, InterruptedException {
// *****getTelemetry from Hayward server
- String urlParameters = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Request><Name>GetTelemetryData</Name><Parameters>"
- + "<Parameter name=\"Token\" dataType=\"String\">" + account.token + "</Parameter>"
- + "<Parameter name=\"MspSystemID\" dataType=\"int\">" + account.mspSystemID
- + "</Parameter></Parameters></Request>";
+ String urlParameters = """
+ <?xml version="1.0" encoding="utf-8"?><Request><Name>GetTelemetryData</Name><Parameters>\
+ <Parameter name="Token" dataType="String">\
+ """ + account.token + "</Parameter>" + "<Parameter name=\"MspSystemID\" dataType=\"int\">"
+ + account.mspSystemID + "</Parameter></Parameters></Request>";
String xmlResponse = httpXmlResponse(urlParameters);
data = bridgehandler.evaluateXPath("//Chlorinator/@status", xmlResponse);
updateData(HaywardBindingConstants.CHANNEL_CHLORINATOR_STATUS, data.get(i));
- if (data.get(i).equals("0")) {
+ if ("0".equals(data.get(i))) {
updateData(HaywardBindingConstants.CHANNEL_CHLORINATOR_ENABLE, "0");
// chlorState is used to set the chlorinator cfgState in the timedPercent command
this.chlorState = "2";
data = bridgehandler.evaluateXPath("//ColorLogic-Light/@lightState", xmlResponse);
updateData(HaywardBindingConstants.CHANNEL_COLORLOGIC_LIGHTSTATE, data.get(i));
- if (data.get(i).equals("0")) {
+ if ("0".equals(data.get(i))) {
updateData(HaywardBindingConstants.CHANNEL_COLORLOGIC_ENABLE, "0");
} else {
updateData(HaywardBindingConstants.CHANNEL_COLORLOGIC_ENABLE, "1");
updateData(HaywardBindingConstants.CHANNEL_FILTER_SPEEDRPM, rpmSpeed.toString());
}
- if (data.get(i).equals("0")) {
+ if ("0".equals(data.get(i))) {
updateData(HaywardBindingConstants.CHANNEL_FILTER_ENABLE, "0");
} else {
updateData(HaywardBindingConstants.CHANNEL_FILTER_ENABLE, "1");
// Enable
data = bridgehandler.evaluateXPath("//Heater/@enable", xmlResponse);
- if (data.get(i).equals("0")) {
+ if ("0".equals(data.get(i))) {
updateData(HaywardBindingConstants.CHANNEL_HEATER_ENABLE, "0");
} else {
updateData(HaywardBindingConstants.CHANNEL_HEATER_ENABLE, "1");
updateData(HaywardBindingConstants.CHANNEL_PUMP_SPEEDRPM, rpmSpeed.toString());
}
- if (data.get(i).equals("0")) {
+ if ("0".equals(data.get(i))) {
updateData(HaywardBindingConstants.CHANNEL_PUMP_ENABLE, "0");
} else {
updateData(HaywardBindingConstants.CHANNEL_PUMP_ENABLE, "1");
updateData(HaywardBindingConstants.CHANNEL_VIRTUALHEATER_CURRENTSETPOINT, data.get(i));
data = bridgehandler.evaluateXPath("//VirtualHeater/@enable", xmlResponse);
- if (data.get(i).equals("yes")) {
+ if ("yes".equals(data.get(i))) {
updateData(HaywardBindingConstants.CHANNEL_VIRTUALHEATER_ENABLE, "1");
- } else if (data.get(i).equals("no")) {
+ } else if ("no".equals(data.get(i))) {
updateData(HaywardBindingConstants.CHANNEL_VIRTUALHEATER_ENABLE, "0");
}
}
import static org.openhab.binding.hccrubbishcollection.internal.HCCRubbishCollectionBindingConstants.*;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
public class HCCRubbishCollectionHandlerFactory extends BaseThingHandlerFactory {
private final HttpClient httpClient;
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_COLLECTION);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_COLLECTION);
@Activate
public HCCRubbishCollectionHandlerFactory(final @Reference HttpClientFactory httpClientFactory) {
String content = "{CMD=";
content = content + command.toString() + "B";
- content = content + String.valueOf(outputPort) + ".";
+ content = content + outputPort + ".";
InputStream stream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
String httpMethod = "GET";
String url = "http://" + host + "/switch.cgi?command=3&data0=";
- url = url + String.valueOf(outputPort) + "&data1=";
+ url = url + outputPort + "&data1=";
url = url + command.toString() + "&checksum=";
int checksum = 3 + outputPort + sourcePort;
- url = url + String.valueOf(checksum);
+ url = url + checksum;
try {
HttpUtil.executeUrl(httpMethod, url, null, null, null, timeout);
* @throws HubProcessingException if any error occurs.
*/
public void stopShade(int shadeId) throws HubProcessingException {
- invoke(HttpMethod.PUT, shadeStop, Query.of(IDS, Integer.valueOf(shadeId).toString()), null);
+ invoke(HttpMethod.PUT, shadeStop, Query.of(IDS, Integer.toString(shadeId)), null);
}
/**
String label = getScheduledEventName(referencedName, scheduledEvent);
String description = translationProvider.getText("dynamic-channel.automation-enabled.description",
referencedName);
- Channel channel = ChannelBuilder.create(channelUid, CoreItemFactory.SWITCH).withType(channelTypeUid)
- .withLabel(label).withDescription(description).build();
-
- return channel;
+ return ChannelBuilder.create(channelUid, CoreItemFactory.SWITCH).withType(channelTypeUid).withLabel(label)
+ .withDescription(description).build();
}
private @Nullable String getReferencedSceneOrSceneCollectionName(ScheduledEvent scheduledEvent) {
for (Thing thing : thingRegistry.getAll()) {
ThingHandler thingHandler = thing.getHandler();
- if (thingHandler instanceof HDPowerViewHubHandler) {
+ if (thingHandler instanceof HDPowerViewHubHandler hubHandler) {
console.println("Generation 1/2 API hub: " + thing.getLabel());
- HDPowerViewWebTargets webTargets = ((HDPowerViewHubHandler) thingHandler).getWebTargets();
+ HDPowerViewWebTargets webTargets = hubHandler.getWebTargets();
try {
List<ShadeData> shades = webTargets.getShades().shadeData;
} catch (HubException e) {
console.println("Error retrieving ID's: " + e.getMessage());
}
- } else if (thingHandler instanceof GatewayBridgeHandler) {
+ } else if (thingHandler instanceof GatewayBridgeHandler gatewayHandler) {
console.println("Generation 3 API gateway: " + thing.getLabel());
- GatewayWebTargets webTargets = ((GatewayBridgeHandler) thingHandler).getWebTargets();
+ GatewayWebTargets webTargets = gatewayHandler.getWebTargets();
try {
List<Shade> shades = webTargets.getShades();
* @param propertyValue
*/
public void logPropertyMismatch(String propertyKey, int type, int capabilities, boolean propertyValue) {
- logger.warn(
- "The '{}:{}' property actually reported by shade 'type:{}' is different "
- + "than expected from its 'capabilities:{}' in the database!{}",
- propertyKey, propertyValue, type, capabilities, REQUEST_DEVELOPERS_TO_UPDATE);
+ logger.warn("""
+ The '{}:{}' property actually reported by shade 'type:{}' is different \
+ than expected from its 'capabilities:{}' in the database!{}\
+ """, propertyKey, propertyValue, type, capabilities, REQUEST_DEVELOPERS_TO_UPDATE);
}
}
*/
package org.openhab.binding.hdpowerview.internal.discovery;
-import java.util.Collections;
import java.util.List;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
private final ShadeCapabilitiesDatabase db = new ShadeCapabilitiesDatabase();
public HDPowerViewDeviceDiscoveryService(HDPowerViewHubHandler hub) {
- super(Collections.singleton(HDPowerViewBindingConstants.THING_TYPE_SHADE), 60, true);
+ super(Set.of(HDPowerViewBindingConstants.THING_TYPE_SHADE), 60, true);
this.hub = hub;
this.scanner = createScanner();
}
import static org.openhab.binding.hdpowerview.internal.HDPowerViewBindingConstants.*;
-import java.util.Collections;
import java.util.Set;
import javax.jmdns.ServiceInfo;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(THING_TYPE_HUB);
+ return Set.of(THING_TYPE_HUB);
}
@Override
import static org.openhab.binding.hdpowerview.internal.HDPowerViewBindingConstants.*;
import java.net.UnknownHostException;
-import java.util.Collections;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
private @Nullable ScheduledFuture<?> backgroundFuture;
public HDPowerViewHubDiscoveryService() {
- super(Collections.singleton(THING_TYPE_HUB), 60, true);
+ super(Set.of(THING_TYPE_HUB), 60, true);
scanner = createScanner();
}
*/
package org.openhab.binding.hdpowerview.internal.discovery;
-import java.util.Collections;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
private @Nullable ScheduledFuture<?> backgroundFuture;
public ShadeDiscoveryService(GatewayBridgeHandler hub) {
- super(Collections.singleton(HDPowerViewBindingConstants.THING_TYPE_SHADE3), 60, true);
+ super(Set.of(HDPowerViewBindingConstants.THING_TYPE_SHADE3), 60, true);
this.hub = hub;
this.scanner = createScanner();
}
if (shadeCapabilities.supportsPrimary() && shadeCapabilities.supportsSecondary()) {
// on dual rail shades constrain percent to not move the lower rail above the upper
State secondary = getState(shadeCapabilities, SECONDARY_POSITION);
- if (secondary instanceof PercentType) {
- int secPercent = ((PercentType) secondary).intValue();
+ if (secondary instanceof PercentType percentCommand) {
+ int secPercent = percentCommand.intValue();
if (percent < secPercent) {
percent = secPercent;
}
if (shadeCapabilities.supportsPrimary() && shadeCapabilities.supportsSecondary()) {
// on dual rail shades constrain percent to not move the upper rail below the lower
State primary = getState(shadeCapabilities, PRIMARY_POSITION);
- if (primary instanceof PercentType) {
- int primaryPercent = ((PercentType) primary).intValue();
+ if (primary instanceof PercentType percentCommand) {
+ int primaryPercent = percentCommand.intValue();
if (percent > primaryPercent) {
percent = primaryPercent;
}
public enum PowerType {
BATTERY,
HARDWIRED,
- RECHARGEABLE;
+ RECHARGEABLE
}
@Override
public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
- if (childHandler instanceof ShadeThingHandler) {
- refreshShade(((ShadeThingHandler) childHandler).getShadeId());
+ if (childHandler instanceof ShadeThingHandler shadeThingHandler) {
+ refreshShade(shadeThingHandler.getShadeId());
}
}
continue;
}
ThingHandler handler = thing.getHandler();
- if (handler instanceof HDPowerViewShadeHandler) {
- ((HDPowerViewShadeHandler) handler).requestRefreshShadePosition();
+ if (handler instanceof HDPowerViewShadeHandler shadeHandler) {
+ shadeHandler.requestRefreshShadePosition();
} else {
int shadeId = item.getValue();
logger.debug("Shade '{}' handler not initialized", shadeId);
continue;
}
ThingHandler handler = thing.getHandler();
- if (handler instanceof HDPowerViewShadeHandler) {
- ((HDPowerViewShadeHandler) handler).requestRefreshShadeBatteryLevel();
+ if (handler instanceof HDPowerViewShadeHandler shadeHandler) {
+ shadeHandler.requestRefreshShadeBatteryLevel();
} else {
int shadeId = item.getValue();
logger.debug("Shade '{}' handler not initialized", shadeId);
HubShadeTimeoutException {
switch (channelId) {
case CHANNEL_SHADE_POSITION:
- if (command instanceof PercentType) {
- moveShade(PRIMARY_POSITION, ((PercentType) command).intValue(), webTargets, shadeId);
+ if (command instanceof PercentType percentCommand) {
+ moveShade(PRIMARY_POSITION, percentCommand.intValue(), webTargets, shadeId);
} else if (command instanceof UpDownType) {
moveShade(PRIMARY_POSITION, UpDownType.UP == command ? 0 : 100, webTargets, shadeId);
} else if (command instanceof StopMoveType) {
break;
case CHANNEL_SHADE_VANE:
- if (command instanceof PercentType) {
- moveShade(VANE_TILT_POSITION, ((PercentType) command).intValue(), webTargets, shadeId);
+ if (command instanceof PercentType percentCommand) {
+ moveShade(VANE_TILT_POSITION, percentCommand.intValue(), webTargets, shadeId);
} else if (command instanceof OnOffType) {
moveShade(VANE_TILT_POSITION, OnOffType.ON == command ? 100 : 0, webTargets, shadeId);
}
break;
case CHANNEL_SHADE_SECONDARY_POSITION:
- if (command instanceof PercentType) {
- moveShade(SECONDARY_POSITION, ((PercentType) command).intValue(), webTargets, shadeId);
+ if (command instanceof PercentType percentCommand) {
+ moveShade(SECONDARY_POSITION, percentCommand.intValue(), webTargets, shadeId);
} else if (command instanceof UpDownType) {
moveShade(SECONDARY_POSITION, UpDownType.UP == command ? 0 : 100, webTargets, shadeId);
} else if (command instanceof StopMoveType) {
break;
case CHANNEL_SHADE_COMMAND:
- if (command instanceof StringType) {
- if (COMMAND_IDENTIFY.equals(((StringType) command).toString())) {
+ if (command instanceof StringType stringCommand) {
+ if (COMMAND_IDENTIFY.equals(stringCommand.toString())) {
logger.debug("Identify shade {}", shadeId);
identifyShade(webTargets, shadeId);
- } else if (COMMAND_CALIBRATE.equals(((StringType) command).toString())) {
+ } else if (COMMAND_CALIBRATE.equals(stringCommand.toString())) {
logger.debug("Calibrate shade {}", shadeId);
calibrateShade(webTargets, shadeId);
}
try {
switch (channelUID.getId()) {
case CHANNEL_SHADE_POSITION:
- if (command instanceof PercentType) {
- position.setPosition(PRIMARY_POSITION, ((PercentType) command));
+ if (command instanceof PercentType percentCommand) {
+ position.setPosition(PRIMARY_POSITION, percentCommand);
webTargets.moveShade(shadeId, new Shade().setShadePosition(position));
break;
} else if (command instanceof UpDownType) {
throw new IllegalArgumentException(INVALID_COMMAND);
case CHANNEL_SHADE_SECONDARY_POSITION:
- if (command instanceof PercentType) {
- position.setPosition(SECONDARY_POSITION, ((PercentType) command));
+ if (command instanceof PercentType percentCommand) {
+ position.setPosition(SECONDARY_POSITION, percentCommand);
webTargets.moveShade(shadeId, new Shade().setShadePosition(position));
break;
} else if (command instanceof UpDownType) {
throw new IllegalArgumentException(INVALID_COMMAND);
case CHANNEL_SHADE_VANE:
- if (command instanceof PercentType) {
- position.setPosition(VANE_TILT_POSITION, ((PercentType) command));
+ if (command instanceof PercentType percentCommand) {
+ position.setPosition(VANE_TILT_POSITION, percentCommand);
webTargets.moveShade(shadeId, new Shade().setShadePosition(position));
break;
} else if (command instanceof UpDownType) {
throw new IllegalArgumentException(INVALID_COMMAND);
case CHANNEL_SHADE_COMMAND:
- if ((command instanceof StringType) && COMMAND_IDENTIFY.equals(((StringType) command).toString())) {
+ if ((command instanceof StringType stringCommand)
+ && COMMAND_IDENTIFY.equals(stringCommand.toString())) {
webTargets.jogShade(shadeId);
break;
}
*/
@NonNullByDefault
public class MockedLocaleProvider implements LocaleProvider {
+ @Override
public Locale getLocale() {
return Locale.ENGLISH;
}
if (logger.isTraceEnabled()) {
logger.trace("initialize() Request : {}", systemTarget.resolveTemplate("ip", ipAddress)
.resolveTemplate("cmd", INFO).getUri().toASCIIString());
- if (jsonObject.get("success").toString().equals("true")) {
+ if ("true".equals(jsonObject.get("success").toString())) {
logger.trace("initialize() Response: {}", jsonObject.get("result"));
}
- if (jsonObject.get("success").toString().equals("false")) {
+ if ("false".equals(jsonObject.get("success").toString())) {
logger.trace("initialize() Response: {}", jsonObject.get("error"));
}
}
- if (jsonObject.get("success").toString().equals("false")) {
+ if ("false".equals(jsonObject.get("success").toString())) {
RESTError error = gson.fromJson(jsonObject.get("error").toString(), RESTError.class);
logger.debug(
"An error occurred while communicating with the Helios IP Vario '{}': code '{}', param '{}' : '{}'",
return;
}
- if (jsonObject.get("success").toString().equals("true")) {
+ if ("true".equals(jsonObject.get("success").toString())) {
if (logJob == null || logJob.isCancelled()) {
logJob = scheduler.scheduleWithFixedDelay(logRunnable, 0, 1, TimeUnit.SECONDS);
}
logTarget.resolveTemplate("ip", ipAddress).resolveTemplate("cmd", SUBSCRIBE)
.queryParam("include", "new").queryParam("duration", HELIOS_DURATION).getUri()
.toASCIIString());
- if (jsonObject.get("success").toString().equals("true")) {
+ if ("true".equals(jsonObject.get("success").toString())) {
logger.trace("subscribe() Response: {}", jsonObject.get("result"));
}
- if (jsonObject.get("success").toString().equals("false")) {
+ if ("false".equals(jsonObject.get("success").toString())) {
logger.trace("subscribe() Response: {}", jsonObject.get("error"));
}
}
- if (jsonObject.get("success").toString().equals("true")) {
+ if ("true".equals(jsonObject.get("success").toString())) {
RESTSubscribeResponse subscribeResponse = gson.fromJson(jsonObject.get("result").toString(),
RESTSubscribeResponse.class);
logger.debug("The subscription id to pull logs from the Helios IP Vario '{}' is '{}'",
logger.trace("unsubscribe() Request : {}",
logTarget.resolveTemplate("ip", ipAddress).resolveTemplate("cmd", UNSUBSCRIBE)
.queryParam("id", logSubscriptionID).getUri().toASCIIString());
- if (jsonObject.get("success").toString().equals("true")) {
+ if ("true".equals(jsonObject.get("success").toString())) {
logger.trace("unsubscribe() Response: {}", jsonObject.get("result"));
}
- if (jsonObject.get("success").toString().equals("false")) {
+ if ("false".equals(jsonObject.get("success").toString())) {
logger.trace("unsubscribe() Response: {}", jsonObject.get("error"));
}
}
- if (jsonObject.get("success").toString().equals("true")) {
+ if ("true".equals(jsonObject.get("success").toString())) {
logger.debug("Successfully unsubscribed from the log entries of the Helios IP Vario '{}'",
getThing().getUID().toString());
} else {
logTarget.resolveTemplate("ip", ipAddress).resolveTemplate("cmd", PULL)
.queryParam("id", logSubscriptionID).queryParam("timeout", HELIOS_PULL_DURATION)
.getUri().toASCIIString());
- if (jsonObject.get("success").toString().equals("true")) {
+ if ("true".equals(jsonObject.get("success").toString())) {
logger.trace("pullLog() Response: {}", jsonObject.get("result"));
}
- if (jsonObject.get("success").toString().equals("false")) {
+ if ("false".equals(jsonObject.get("success").toString())) {
logger.trace("pullLog() Response: {}", jsonObject.get("error"));
}
}
- if (jsonObject.get("success").toString().equals("true")) {
+ if ("true".equals(jsonObject.get("success").toString())) {
logger.trace("Successfully pulled log entries from the Helios IP Vario '{}'",
getThing().getUID().toString());
JsonObject js = (JsonObject) jsonObject.get("result");
if (logger.isTraceEnabled()) {
logger.trace("getSwitches() Request : {}", switchTarget.resolveTemplate("ip", ipAddress)
.resolveTemplate("cmd", CAPABILITIES).getUri().toASCIIString());
- if (jsonObject.get("success").toString().equals("true")) {
+ if ("true".equals(jsonObject.get("success").toString())) {
logger.trace("getSwitches() Response: {}", jsonObject.get("result"));
}
- if (jsonObject.get("success").toString().equals("false")) {
+ if ("false".equals(jsonObject.get("success").toString())) {
logger.trace("getSwitches() Response: {}", jsonObject.get("error"));
}
}
- if (jsonObject.get("success").toString().equals("true")) {
+ if ("true".equals(jsonObject.get("success").toString())) {
logger.debug("Successfully requested switch capabilities from the Helios IP Vario '{}'",
getThing().getUID().toString());
String result = jsonObject.get("result").toString();
logger.trace("triggerSwitch() Request : {}",
switchTarget.resolveTemplate("ip", ipAddress).resolveTemplate("cmd", CONTROL)
.queryParam("switch", id).queryParam("action", "trigger").getUri().toASCIIString());
- if (jsonObject.get("success").toString().equals("true")) {
+ if ("true".equals(jsonObject.get("success").toString())) {
logger.trace("triggerSwitch() Response: {}", jsonObject.get("result"));
}
- if (jsonObject.get("success").toString().equals("false")) {
+ if ("false".equals(jsonObject.get("success").toString())) {
logger.trace("triggerSwitch() Response: {}", jsonObject.get("error"));
}
}
- if (jsonObject.get("success").toString().equals("true")) {
+ if ("true".equals(jsonObject.get("success").toString())) {
logger.debug("Successfully triggered a switch on the Helios IP Vario '{}'",
getThing().getUID().toString());
} else {
switchTarget.resolveTemplate("ip", ipAddress).resolveTemplate("cmd", CONTROL)
.queryParam("switch", id).queryParam("action", flag ? "on" : "off").getUri()
.toASCIIString());
- if (jsonObject.get("success").toString().equals("true")) {
+ if ("true".equals(jsonObject.get("success").toString())) {
logger.trace("enableSwitch() Response: {}", jsonObject.get("result"));
}
- if (jsonObject.get("success").toString().equals("false")) {
+ if ("false".equals(jsonObject.get("success").toString())) {
logger.trace("enableSwitch() Response: {}", jsonObject.get("error"));
}
}
- if (jsonObject.get("success").toString().equals("true")) {
+ if ("true".equals(jsonObject.get("success").toString())) {
logger.debug("Successfully dis/enabled a switch on the Helios IP Vario '{}'",
getThing().getUID().toString());
} else {
if (logger.isTraceEnabled()) {
logger.trace("getPorts() Request : {}", portTarget.resolveTemplate("ip", ipAddress)
.resolveTemplate("cmd", CAPABILITIES).getUri().toASCIIString());
- if (jsonObject.get("success").toString().equals("true")) {
+ if ("true".equals(jsonObject.get("success").toString())) {
logger.trace("getPorts() Response: {}", jsonObject.get("result"));
}
- if (jsonObject.get("success").toString().equals("false")) {
+ if ("false".equals(jsonObject.get("success").toString())) {
logger.trace("getPorts() Response: {}", jsonObject.get("error"));
}
}
- if (jsonObject.get("success").toString().equals("true")) {
+ if ("true".equals(jsonObject.get("success").toString())) {
logger.debug("Successfully requested port capabilities from the Helios IP Vario '{}'",
getThing().getUID().toString());
JsonObject js = (JsonObject) jsonObject.get("result");
if (logger.isTraceEnabled()) {
logger.trace("configureRunnable Request : {}", systemTarget.resolveTemplate("ip", ipAddress)
.resolveTemplate("cmd", INFO).getUri().toASCIIString());
- if (jsonObject.get("success").toString().equals("true")) {
+ if ("true".equals(jsonObject.get("success").toString())) {
logger.trace("configureRunnable Response: {}", jsonObject.get("result"));
}
- if (jsonObject.get("success").toString().equals("false")) {
+ if ("false".equals(jsonObject.get("success").toString())) {
logger.trace("configureRunnable Response: {}", jsonObject.get("error"));
}
}
if (switches != null) {
for (RESTSwitch aSwitch : switches) {
- if (aSwitch.enabled.equals("true")) {
+ if ("true".equals(aSwitch.enabled)) {
logger.debug("Adding a channel to the Helios IP Vario '{}' for the switch with id '{}'",
getThing().getUID().toString(), aSwitch.id);
ThingBuilder thingBuilder = editThing();
break;
}
case AUDIOLOOPTEST: {
- if (event.params.get("result").getAsString().equals("passed")) {
+ if ("passed".equals(event.params.get("result").getAsString())) {
updateState(AUDIO_LOOP_TEST, OnOffType.ON);
- } else if (event.params.get("result").getAsString().equals("failed")) {
+ } else if ("failed".equals(event.params.get("result").getAsString())) {
updateState(AUDIO_LOOP_TEST, OnOffType.OFF);
} else {
updateState(AUDIO_LOOP_TEST, UnDefType.UNDEF);
break;
}
case MOTIONDETECTED: {
- if (event.params.get("state").getAsString().equals("in")) {
+ if ("in".equals(event.params.get("state").getAsString())) {
updateState(MOTION, OnOffType.ON);
- } else if (event.params.get("state").getAsString().equals("out")) {
+ } else if ("out".equals(event.params.get("state").getAsString())) {
updateState(MOTION, OnOffType.OFF);
} else {
updateState(MOTION, UnDefType.UNDEF);
break;
}
case NOISEDETECTED: {
- if (event.params.get("state").getAsString().equals("in")) {
+ if ("in".equals(event.params.get("state").getAsString())) {
updateState(NOISE, OnOffType.ON);
- } else if (event.params.get("state").getAsString().equals("out")) {
+ } else if ("out".equals(event.params.get("state").getAsString())) {
updateState(NOISE, OnOffType.OFF);
} else {
updateState(NOISE, UnDefType.UNDEF);
case CODEENTERED: {
triggerChannel(CODE, event.params.get("code").getAsString());
- if (event.params.get("valid").getAsString().equals("true")) {
+ if ("true".equals(event.params.get("valid").getAsString())) {
updateState(CODE_VALID, OnOffType.ON);
- } else if (event.params.get("valid").getAsString().equals("false")) {
+ } else if ("false".equals(event.params.get("valid").getAsString())) {
updateState(CODE_VALID, OnOffType.OFF);
} else {
updateState(CODE_VALID, UnDefType.UNDEF);
case CARDENTERED: {
triggerChannel(CARD, event.params.get("uid").getAsString());
- if (event.params.get("valid").getAsString().equals("true")) {
+ if ("true".equals(event.params.get("valid").getAsString())) {
updateState(CARD_VALID, OnOffType.ON);
- } else if (event.params.get("valid").getAsString().equals("false")) {
+ } else if ("false".equals(event.params.get("valid").getAsString())) {
updateState(CARD_VALID, OnOffType.OFF);
} else {
updateState(CARD_VALID, UnDefType.UNDEF);
ChannelUID inputChannel = new ChannelUID(getThing().getUID(),
"io" + event.params.get("port").getAsString());
- if (event.params.get("state").getAsString().equals("true")) {
+ if ("true".equals(event.params.get("state").getAsString())) {
updateState(inputChannel, OnOffType.ON);
- } else if (event.params.get("state").getAsString().equals("false")) {
+ } else if ("false".equals(event.params.get("state").getAsString())) {
updateState(inputChannel, OnOffType.OFF);
} else {
updateState(inputChannel, UnDefType.UNDEF);
ChannelUID inputChannel = new ChannelUID(getThing().getUID(),
"io" + event.params.get("port").getAsString());
- if (event.params.get("state").getAsString().equals("true")) {
+ if ("true".equals(event.params.get("state").getAsString())) {
updateState(inputChannel, OnOffType.ON);
- } else if (event.params.get("state").getAsString().equals("false")) {
+ } else if ("false".equals(event.params.get("state").getAsString())) {
updateState(inputChannel, OnOffType.OFF);
} else {
updateState(inputChannel, UnDefType.UNDEF);
break;
}
case SWITCHSTATECHANGED: {
- if (event.params.get("state").getAsString().equals("true")) {
+ if ("true".equals(event.params.get("state").getAsString())) {
updateState(SWITCH_STATE, OnOffType.ON);
- } else if (event.params.get("state").getAsString().equals("false")) {
+ } else if ("false".equals(event.params.get("state").getAsString())) {
updateState(SWITCH_STATE, OnOffType.OFF);
} else {
updateState(SWITCH_STATE, UnDefType.UNDEF);
import static org.openhab.binding.heliosventilation.internal.HeliosVentilationBindingConstants.THING_TYPE_HELIOS_VENTILATION;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.heliosventilation", service = ThingHandlerFactory.class)
public class HeliosVentilationHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .singleton(THING_TYPE_HELIOS_VENTILATION);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_HELIOS_VENTILATION);
private final SerialPortManager serialPortManager;
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof HeosBridgeHandler) {
- this.handler = (HeosBridgeHandler) handler;
+ if (handler instanceof HeosBridgeHandler bridgeHandler) {
+ this.handler = bridgeHandler;
}
}
import static org.openhab.binding.heos.internal.HeosBindingConstants.*;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(THING_TYPE_BRIDGE);
+ return Set.of(THING_TYPE_BRIDGE);
}
@Override
import java.io.IOException;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
try {
@Nullable
ThingHandler handler = thing.getHandler();
- if (handler instanceof HeosThingBaseHandler) {
+ if (handler instanceof HeosThingBaseHandler heosHandler) {
Set<String> target = handler instanceof HeosPlayerHandler ? players : groups;
- HeosThingBaseHandler heosHandler = (HeosThingBaseHandler) handler;
String id = heosHandler.getId();
if (target.contains(id)) {
} else if (childHandler instanceof HeosPlayerHandler) {
String channelIdentifier = "P" + childThing.getUID().getId();
updateThingChannels(channelManager.removeSingleChannel(channelIdentifier));
- } else if (childHandler instanceof HeosGroupHandler) {
+ } else if (childHandler instanceof HeosGroupHandler groupHandler) {
String channelIdentifier = "G" + childThing.getUID().getId();
updateThingChannels(channelManager.removeSingleChannel(channelIdentifier));
// removes the handler from the groupMemberMap that handler is no longer called
// if group is getting online
- removeGroupHandlerInformation((HeosGroupHandler) childHandler);
+ removeGroupHandlerInformation(groupHandler);
}
}
String pid = "";
@Nullable
ThingHandler handler = childThing.getHandler();
- if (handler instanceof HeosPlayerHandler) {
+ if (handler instanceof HeosPlayerHandler playerHandler) {
channelIdentifier = "P" + childThing.getUID().getId();
- pid = ((HeosPlayerHandler) handler).getId();
- } else if (handler instanceof HeosGroupHandler) {
+ pid = playerHandler.getId();
+ } else if (handler instanceof HeosGroupHandler groupHandler) {
channelIdentifier = "G" + childThing.getUID().getId();
if (groupId == null) {
- pid = ((HeosGroupHandler) handler).getId();
+ pid = groupHandler.getId();
} else {
pid = groupId;
}
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singletonList(HeosActions.class);
+ return List.of(HeosActions.class);
}
public void registerMediaEventListener(HeosMediaEventListener heosMediaEventListener) {
case GET_NOW_PLAYING_MEDIA:
@Nullable
T mediaPayload = responseObject.payload;
- if (mediaPayload instanceof Media) {
- handleThingMediaUpdate((Media) mediaPayload);
+ if (mediaPayload instanceof Media media) {
+ handleThingMediaUpdate(media);
}
break;
case GET_PLAYER_INFO:
@Nullable
T playerPayload = responseObject.payload;
- if (playerPayload instanceof Player) {
- handlePlayerInfo((Player) playerPayload);
+ if (playerPayload instanceof Player player) {
+ handlePlayerInfo(player);
}
break;
}
throw new ReadException(e);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
- if (cause instanceof IOException) {
- throw (IOException) cause;
+ if (cause instanceof IOException exception) {
+ throw exception;
} else {
throw new ReadException(cause);
}
@Test
public void get_players() {
HeosResponseObject<Player[]> response = subject.parseResponse(
- "{\"heos\": {\"command\": \"player/get_players\", \"result\": \"success\", \"message\": \"\"}, \"payload\": ["
- + "{\"name\": \"Kantoor HEOS 3\", \"pid\": -831584083, \"model\": \"HEOS 3\", \"version\": \"1.520.200\", \"ip\": \"192.168.1.230\", \"network\": \"wired\", \"lineout\": 0, \"serial\": \"ACNG9180110887\"}, "
- + "{\"name\": \"HEOS Bar\", \"pid\": 1958912779, \"model\": \"HEOS Bar\", \"version\": \"1.520.200\", \"ip\": \"192.168.1.195\", \"network\": \"wired\", \"lineout\": 0, \"serial\": \"ADAG9180917029\"}]}",
+ """
+ {"heos": {"command": "player/get_players", "result": "success", "message": ""}, "payload": [\
+ {"name": "Kantoor HEOS 3", "pid": -831584083, "model": "HEOS 3", "version": "1.520.200", "ip": "192.168.1.230", "network": "wired", "lineout": 0, "serial": "ACNG9180110887"}, \
+ {"name": "HEOS Bar", "pid": 1958912779, "model": "HEOS Bar", "version": "1.520.200", "ip": "192.168.1.195", "network": "wired", "lineout": 0, "serial": "ADAG9180917029"}]}\
+ """,
Player[].class);
assertEquals(HeosCommandGroup.PLAYER, response.heosCommand.commandGroup);
@Test
public void get_now_playing_media() {
HeosResponseObject<Media> response = subject.parseResponse(
- "{\"heos\": {\"command\": \"player/get_now_playing_media\", \"result\": \"success\", \"message\": \"pid=1958912779\"}, \"payload\": "
- + "{\"type\": \"song\", \"song\": \"Solo (feat. Demi Lovato)\", \"album\": \"What Is Love? (Deluxe)\", \"artist\": \"Clean Bandit\", \"image_url\": \"http://192.168.1.230:8015//m-browsableMediaUri/getImageFromTag/mnt/326C72A3E307501E47DE2B0F47D90EB8/Clean%20Bandit/What%20Is%20Love_%20(Deluxe)/03%20Solo%20(feat.%20Demi%20Lovato).m4a\", \"album_id\": \"\", \"mid\": \"http://192.168.1.230:8015/m-1c176905-f6c7-d168-dc35-86b4735c5976/Clean+Bandit/What+Is+Love_+(Deluxe)/03+Solo+(feat.+Demi+Lovato).m4a\", \"qid\": 1, \"sid\": 1024}, \"options\": []}\n",
+ """
+ {"heos": {"command": "player/get_now_playing_media", "result": "success", "message": "pid=1958912779"}, "payload": \
+ {"type": "song", "song": "Solo (feat. Demi Lovato)", "album": "What Is Love? (Deluxe)", "artist": "Clean Bandit", "image_url": "http://192.168.1.230:8015//m-browsableMediaUri/getImageFromTag/mnt/326C72A3E307501E47DE2B0F47D90EB8/Clean%20Bandit/What%20Is%20Love_%20(Deluxe)/03%20Solo%20(feat.%20Demi%20Lovato).m4a", "album_id": "", "mid": "http://192.168.1.230:8015/m-1c176905-f6c7-d168-dc35-86b4735c5976/Clean+Bandit/What+Is+Love_+(Deluxe)/03+Solo+(feat.+Demi+Lovato).m4a", "qid": 1, "sid": 1024}, "options": []}
+ """,
Media.class);
assertEquals(HeosCommandGroup.PLAYER, response.heosCommand.commandGroup);
@Test
public void browse_playlist() {
HeosResponseObject<BrowseResult[]> response = subject.parseResponse(
- "{\"heos\": {\"command\": \"browse/browse\", \"result\": \"success\", \"message\": \"sid=1025&returned=6&count=6\"}, \"payload\": ["
- + "{\"container\": \"yes\", \"type\": \"playlist\", \"cid\": \"132562\", \"playable\": \"yes\", \"name\": \"Maaike Ouboter - En hoe het dan ook weer dag wordt\", \"image_url\": \"\"}, "
- + "{\"container\": \"yes\", \"type\": \"playlist\", \"cid\": \"132563\", \"playable\": \"yes\", \"name\": \"Maaike Ouboter - Vanaf nu is het van jou\", \"image_url\": \"\"}, "
- + "{\"container\": \"yes\", \"type\": \"playlist\", \"cid\": \"162887\", \"playable\": \"yes\", \"name\": \"Easy listening\", \"image_url\": \"\"}, "
- + "{\"container\": \"yes\", \"type\": \"playlist\", \"cid\": \"174461\", \"playable\": \"yes\", \"name\": \"Nieuwe muziek 5-2019\", \"image_url\": \"\"}, "
- + "{\"container\": \"yes\", \"type\": \"playlist\", \"cid\": \"194000\", \"playable\": \"yes\", \"name\": \"Nieuwe muziek 2019-05\", \"image_url\": \"\"}, "
- + "{\"container\": \"yes\", \"type\": \"playlist\", \"cid\": \"194001\", \"playable\": \"yes\", \"name\": \"Clean Bandit\", \"image_url\": \"\"}]}",
+ """
+ {"heos": {"command": "browse/browse", "result": "success", "message": "sid=1025&returned=6&count=6"}, "payload": [\
+ {"container": "yes", "type": "playlist", "cid": "132562", "playable": "yes", "name": "Maaike Ouboter - En hoe het dan ook weer dag wordt", "image_url": ""}, \
+ {"container": "yes", "type": "playlist", "cid": "132563", "playable": "yes", "name": "Maaike Ouboter - Vanaf nu is het van jou", "image_url": ""}, \
+ {"container": "yes", "type": "playlist", "cid": "162887", "playable": "yes", "name": "Easy listening", "image_url": ""}, \
+ {"container": "yes", "type": "playlist", "cid": "174461", "playable": "yes", "name": "Nieuwe muziek 5-2019", "image_url": ""}, \
+ {"container": "yes", "type": "playlist", "cid": "194000", "playable": "yes", "name": "Nieuwe muziek 2019-05", "image_url": ""}, \
+ {"container": "yes", "type": "playlist", "cid": "194001", "playable": "yes", "name": "Clean Bandit", "image_url": ""}]}\
+ """,
BrowseResult[].class);
assertEquals(HeosCommandGroup.BROWSE, response.heosCommand.commandGroup);
@Test
public void browse_favorites() {
HeosResponseObject<BrowseResult[]> response = subject.parseResponse(
- "{\"heos\": {\"command\": \"browse/browse\", \"result\": \"success\", \"message\": \"sid=1028&returned=3&count=3\"}, \"payload\": ["
- + "{\"container\": \"no\", \"mid\": \"s6707\", \"type\": \"station\", \"playable\": \"yes\", \"name\": \"NPO 3FM 96.8 (Top 40 %26 Pop Music)\", \"image_url\": \"http://cdn-profiles.tunein.com/s6707/images/logoq.png?t=636268\"}, "
- + "{\"container\": \"no\", \"mid\": \"s2967\", \"type\": \"station\", \"playable\": \"yes\", \"name\": \"Classic FM Nederland (Classical Music)\", \"image_url\": \"http://cdn-radiotime-logos.tunein.com/s2967q.png\"}, "
- + "{\"container\": \"no\", \"mid\": \"s1993\", \"type\": \"station\", \"playable\": \"yes\", \"name\": \"BNR Nieuwsradio\", \"image_url\": \"http://cdn-radiotime-logos.tunein.com/s1993q.png\"}], "
- + "\"options\": [{\"browse\": [{\"id\": 20, \"name\": \"Remove from HEOS Favorites\"}]}]}",
+ """
+ {"heos": {"command": "browse/browse", "result": "success", "message": "sid=1028&returned=3&count=3"}, "payload": [\
+ {"container": "no", "mid": "s6707", "type": "station", "playable": "yes", "name": "NPO 3FM 96.8 (Top 40 %26 Pop Music)", "image_url": "http://cdn-profiles.tunein.com/s6707/images/logoq.png?t=636268"}, \
+ {"container": "no", "mid": "s2967", "type": "station", "playable": "yes", "name": "Classic FM Nederland (Classical Music)", "image_url": "http://cdn-radiotime-logos.tunein.com/s2967q.png"}, \
+ {"container": "no", "mid": "s1993", "type": "station", "playable": "yes", "name": "BNR Nieuwsradio", "image_url": "http://cdn-radiotime-logos.tunein.com/s1993q.png"}], \
+ "options": [{"browse": [{"id": 20, "name": "Remove from HEOS Favorites"}]}]}\
+ """,
BrowseResult[].class);
assertEquals(HeosCommandGroup.BROWSE, response.heosCommand.commandGroup);
@Test
public void get_groups() {
HeosResponseObject<Group[]> response = subject.parseResponse(
- "{\"heos\": {\"command\": \"group/get_groups\", \"result\": \"success\", \"message\": \"\"}, \"payload\": [ "
- + "{\"name\": \"Group 1\", \"gid\": \"214243242\", \"players\": [ {\"name\": \"HEOS 1\", \"pid\": \"2142443242\", \"role\": \"leader\"}, {\"name\": \"HEOS 3\", \"pid\": \"32432423432\", \"role\": \"member\"}, {\"name\": \"HEOS 5\", \"pid\": \"342423564\", \"role\": \"member\"}]}, "
- + "{\"name\": \"Group 2\", \"gid\": \"2142432342\", \"players\": [ {\"name\": \"HEOS 3\", \"pid\": \"32432423432\", \"role\": \"member\"}, {\"name\": \"HEOS 5\", \"pid\": \"342423564\", \"role\": \"member\"}]}]}",
+ """
+ {"heos": {"command": "group/get_groups", "result": "success", "message": ""}, "payload": [ \
+ {"name": "Group 1", "gid": "214243242", "players": [ {"name": "HEOS 1", "pid": "2142443242", "role": "leader"}, {"name": "HEOS 3", "pid": "32432423432", "role": "member"}, {"name": "HEOS 5", "pid": "342423564", "role": "member"}]}, \
+ {"name": "Group 2", "gid": "2142432342", "players": [ {"name": "HEOS 3", "pid": "32432423432", "role": "member"}, {"name": "HEOS 5", "pid": "342423564", "role": "member"}]}]}\
+ """,
Group[].class);
assertEquals(HeosCommandGroup.GROUP, response.heosCommand.commandGroup);
(command == UpDownType.UP) ? ControlAddress.OPEN : ControlAddress.CLOSE);
} else if (command instanceof StopMoveType) {
pkt = buildPacket(Function.CONTROL, ControlAddress.STOP);
- } else if (command instanceof DecimalType) {
- pkt = buildPacket(Function.CONTROL, ControlAddress.PERCENT, ((DecimalType) command).byteValue());
+ } else if (command instanceof DecimalType decimalCommand) {
+ pkt = buildPacket(Function.CONTROL, ControlAddress.PERCENT, decimalCommand.byteValue());
}
break;
case CHANNEL_REVERSE:
*/
package org.openhab.binding.homeconnect.internal.client;
-import static java.util.Collections.singletonList;
import static org.openhab.binding.homeconnect.internal.HomeConnectBindingConstants.*;
import static org.openhab.binding.homeconnect.internal.client.HttpHelper.*;
private void checkResponseCode(int desiredCode, Request request, ContentResponse response, @Nullable String haId,
@Nullable String requestPayload)
throws CommunicationException, AuthorizationException, ApplianceOfflineException {
- checkResponseCode(singletonList(desiredCode), request, response, haId, requestPayload);
+ checkResponseCode(List.of(desiredCode), request, response, haId, requestPayload);
}
private void checkResponseCode(List<Integer> desiredCodes, Request request, ContentResponse response,
@Override
public void setThingHandler(ThingHandler handler) {
- if (handler instanceof HomeConnectBridgeHandler) {
- this.bridgeHandler = (HomeConnectBridgeHandler) handler;
+ if (handler instanceof HomeConnectBridgeHandler homeConnectBridgeHandler) {
+ this.bridgeHandler = homeConnectBridgeHandler;
}
}
Bridge bridge = getBridge();
if (bridge != null) {
BridgeHandler bridgeHandler = bridge.getHandler();
- if (bridgeHandler instanceof HomeConnectBridgeHandler) {
- return Optional.of((HomeConnectBridgeHandler) bridgeHandler);
+ if (bridgeHandler instanceof HomeConnectBridgeHandler homeConnectBridgeHandler) {
+ return Optional.of(homeConnectBridgeHandler);
}
}
return Optional.empty();
* @param channelUID channel UID
*/
protected void updateChannel(ChannelUID channelUID) {
- if (!getApiClient().isPresent()) {
+ if (getApiClient().isEmpty()) {
logger.error("Cannot update channel. No instance of api client found! thing={}, haId={}", getThingLabel(),
getThingHaId());
return;
protected void handleTemperatureCommand(final ChannelUID channelUID, final Command command,
final HomeConnectApiClient apiClient)
throws CommunicationException, AuthorizationException, ApplianceOfflineException {
- if (command instanceof QuantityType) {
- QuantityType<?> quantity = (QuantityType<?>) command;
-
+ if (command instanceof QuantityType quantityCommand) {
String value;
String unit;
try {
- if (quantity.getUnit().equals(SIUnits.CELSIUS) || quantity.getUnit().equals(ImperialUnits.FAHRENHEIT)) {
- unit = quantity.getUnit().toString();
- value = String.valueOf(quantity.intValue());
+ if (quantityCommand.getUnit().equals(SIUnits.CELSIUS)
+ || quantityCommand.getUnit().equals(ImperialUnits.FAHRENHEIT)) {
+ unit = quantityCommand.getUnit().toString();
+ value = String.valueOf(quantityCommand.intValue());
} else {
logger.debug("Converting target temperature from {}{} to °C value. thing={}, haId={}",
- quantity.intValue(), quantity.getUnit().toString(), getThingLabel(), getThingHaId());
+ quantityCommand.intValue(), quantityCommand.getUnit().toString(), getThingLabel(),
+ getThingHaId());
unit = "°C";
- var celsius = quantity.toUnit(SIUnits.CELSIUS);
+ var celsius = quantityCommand.toUnit(SIUnits.CELSIUS);
if (celsius == null) {
- logger.warn("Converting temperature to celsius failed! quantity={}", quantity);
+ logger.warn("Converting temperature to celsius failed! quantity={}", quantityCommand);
value = null;
} else {
value = String.valueOf(celsius.intValue());
} else {
newBrightness = currentBrightness - BRIGHTNESS_DIM_STEP;
}
- } else if (command instanceof PercentType) {
- newBrightness = (int) Math.floor(((PercentType) command).doubleValue());
- } else if (command instanceof DecimalType) {
- newBrightness = ((DecimalType) command).intValue();
+ } else if (command instanceof PercentType percentCommand) {
+ newBrightness = (int) Math.floor(percentCommand.doubleValue());
+ } else if (command instanceof DecimalType decimalCommand) {
+ newBrightness = decimalCommand.intValue();
}
// check in in range
apiClient.setAmbientLightColorState(getThingHaId(), STATE_AMBIENT_LIGHT_COLOR_CUSTOM_COLOR);
}
- if (command instanceof HSBType) {
- apiClient.setAmbientLightCustomColorState(getThingHaId(), mapColor((HSBType) command));
+ if (command instanceof HSBType hsbCommand) {
+ apiClient.setAmbientLightCustomColorState(getThingHaId(), mapColor(hsbCommand));
} else if (command instanceof StringType) {
apiClient.setAmbientLightCustomColorState(getThingHaId(), command.toFullString());
}
.filter(option -> OPTION_DRYER_DRYING_TARGET.equals(option.getKey())).findFirst();
// Save options in cache only if we got options for all expected channels
- if (cacheToSet && (!channelSpinSpeed.isPresent() || optionsSpinSpeed.isPresent())
- && (!channelTemperature.isPresent() || optionsTemperature.isPresent())
- && (!channelDryingTarget.isPresent() || optionsDryingTarget.isPresent())) {
+ if (cacheToSet && (channelSpinSpeed.isEmpty() || optionsSpinSpeed.isPresent())
+ && (channelTemperature.isEmpty() || optionsTemperature.isPresent())
+ && (channelDryingTarget.isEmpty() || optionsDryingTarget.isPresent())) {
logger.debug("Saving options in cache for program '{}'.", programKey);
availableProgramOptionsCache.put(programKey, availableProgramOptions);
}
private boolean addUnsupportedProgramInCache(String programKey) {
Optional<AvailableProgram> prog = programsCache.stream().filter(program -> programKey.equals(program.getKey()))
.findFirst();
- if (!prog.isPresent()) {
+ if (prog.isEmpty()) {
programsCache.add(new AvailableProgram(programKey, false));
logger.debug("{} added in programs cache as an unsupported program", programKey);
return true;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(HomeConnectDiscoveryService.class);
+ return Set.of(HomeConnectDiscoveryService.class);
}
/**
@NonNullByDefault
public class HomeConnectHoodHandler extends AbstractHomeConnectThingHandler {
- private static final String START_VENTING_INTENSIVE_STAGE_PAYLOAD_TEMPLATE = "\n" + "{\n" + " \"data\": {\n"
- + " \"key\": \"Cooking.Common.Program.Hood.Venting\",\n" + " \"options\": [\n"
- + " {\n" + " \"key\": \"Cooking.Common.Option.Hood.IntensiveLevel\",\n"
- + " \"value\": \"%s\"\n" + " }\n" + " ]\n" + " }\n" + "}";
+ private static final String START_VENTING_INTENSIVE_STAGE_PAYLOAD_TEMPLATE = """
- private static final String START_VENTING_STAGE_PAYLOAD_TEMPLATE = "\n" + "{\n" + " \"data\": {\n"
- + " \"key\": \"Cooking.Common.Program.Hood.Venting\",\n" + " \"options\": [\n"
- + " {\n" + " \"key\": \"Cooking.Common.Option.Hood.VentingLevel\",\n"
- + " \"value\": \"%s\"\n" + " }\n" + " ]\n" + " }\n" + "}";
+ {
+ "data": {
+ "key": "Cooking.Common.Program.Hood.Venting",
+ "options": [
+ {
+ "key": "Cooking.Common.Option.Hood.IntensiveLevel",
+ "value": "%s"
+ }
+ ]
+ }
+ }\
+ """;
+
+ private static final String START_VENTING_STAGE_PAYLOAD_TEMPLATE = """
+
+ {
+ "data": {
+ "key": "Cooking.Common.Program.Hood.Venting",
+ "options": [
+ {
+ "key": "Cooking.Common.Option.Hood.VentingLevel",
+ "value": "%s"
+ }
+ ]
+ }
+ }\
+ """;
private final Logger logger = LoggerFactory.getLogger(HomeConnectHoodHandler.class);
@Override
public String toString() {
- return String.format(
- "%s[gatewayAddress=%s,callbackHost=%s,xmlCallbackPort=%d,binCallbackPort=%d,"
- + "gatewayType=%s,rfPort=%d,wiredPort=%d,hmIpPort=%d,cuxdPort=%d,groupPort=%d,timeout=%d,"
- + "discoveryTimeToLive=%d,installModeDuration=%d,socketMaxAlive=%d]",
- getClass().getSimpleName(), gatewayAddress, callbackHost, xmlCallbackPort, binCallbackPort, gatewayType,
- getRfPort(), getWiredPort(), getHmIpPort(), getCuxdPort(), getGroupPort(), timeout, discoveryTimeToLive,
- installModeDuration, socketMaxAlive);
+ return String.format("""
+ %s[gatewayAddress=%s,callbackHost=%s,xmlCallbackPort=%d,binCallbackPort=%d,\
+ gatewayType=%s,rfPort=%d,wiredPort=%d,hmIpPort=%d,cuxdPort=%d,groupPort=%d,timeout=%d,\
+ discoveryTimeToLive=%d,installModeDuration=%d,socketMaxAlive=%d]\
+ """, getClass().getSimpleName(), gatewayAddress, callbackHost, xmlCallbackPort, binCallbackPort,
+ gatewayType, getRfPort(), getWiredPort(), getHmIpPort(), getCuxdPort(), getGroupPort(), timeout,
+ discoveryTimeToLive, installModeDuration, socketMaxAlive);
}
}
} catch (IOException ex) {
reason = ex;
// no retries for "init" request or if connection is refused
- if ("init".equals(request.getMethodName())
- || ex.getCause() != null && ex.getCause() instanceof ExecutionException) {
+ if ("init".equals(request.getMethodName()) || ex.getCause() instanceof ExecutionException) {
break;
}
logger.debug("XmlRpcMessage failed({}), sending message again {}/{}", ex.getMessage(), rpcRetryCounter,
}
private Object[] messageData;
- private byte binRpcData[];
+ private byte[] binRpcData;
private int offset;
private String methodName;
*/
public BinRpcMessage(InputStream is, boolean methodHeader, Charset encoding) throws IOException {
this.encoding = encoding;
- byte sig[] = new byte[8];
+ byte[] sig = new byte[8];
int length = is.read(sig, 0, 4);
if (length != 4) {
throw new EOFException("Only " + length + " bytes received reading signature");
throw new EOFException("Only " + length + " bytes received reading message length");
}
int datasize = (new BigInteger(Arrays.copyOfRange(sig, 4, 8))).intValue();
- byte payload[] = new byte[datasize];
+ byte[] payload = new byte[datasize];
int offset = 0;
int currentLength;
// read rpc values
private int readInt() {
- byte bi[] = new byte[4];
+ byte[] bi = new byte[4];
System.arraycopy(binRpcData, offset, bi, 0, 4);
offset += 4;
return (new BigInteger(bi)).intValue();
}
private long readInt64() {
- byte bi[] = new byte[8];
+ byte[] bi = new byte[8];
System.arraycopy(binRpcData, offset, bi, 0, 8);
offset += 8;
return (new BigInteger(bi)).longValue();
private void addByte(byte b) {
if (offset == binRpcData.length) {
- byte newdata[] = new byte[binRpcData.length * 2];
+ byte[] newdata = new byte[binRpcData.length * 2];
System.arraycopy(binRpcData, 0, newdata, 0, binRpcData.length);
binRpcData = newdata;
}
}
private void addString(String string) {
- byte sd[] = string.getBytes(encoding);
+ byte[] sd = string.getBytes(encoding);
for (byte ch : sd) {
addByte(ch);
}
} else if (object.getClass() == Date.class) {
addInt(5);
addInt((int) ((Date) object).getTime() / 1000);
- } else if (object instanceof List<?>) {
- Collection<?> list = (Collection<?>) object;
+ } else if (object instanceof List<?> list) {
addInt(0x100);
addInt(list.size());
addList(list);
- } else if (object instanceof Map<?, ?>) {
- Map<?, ?> map = (Map<?, ?>) object;
+ } else if (object instanceof Map<?, ?> map) {
addInt(0x101);
addInt(map.size());
for (Map.Entry<?, ?> entry : map.entrySet()) {
sb.append("[\n");
}
for (Object o : c) {
- if (o instanceof Map) {
- dumpMap((Map<?, ?>) o, sb, indent + 1);
- } else if (o instanceof Object[]) {
- dumpCollection((Object[]) o, sb, indent + 1);
+ if (o instanceof Map map) {
+ dumpMap(map, sb, indent + 1);
+ } else if (o instanceof Object[] objects) {
+ dumpCollection(objects, sb, indent + 1);
} else {
for (int in = 0; in < indent; in++) {
sb.append('\t');
}
sb.append(me.getKey());
sb.append('=');
- if (o instanceof Map<?, ?>) {
+ if (o instanceof Map<?, ?> map) {
sb.append("\n");
- dumpMap((Map<?, ?>) o, sb, indent + 1);
- } else if (o instanceof Object[]) {
+ dumpMap(map, sb, indent + 1);
+ } else if (o instanceof Object[] objects) {
sb.append("\n");
- dumpCollection((Object[]) o, sb, indent + 1);
+ dumpCollection(objects, sb, indent + 1);
} else {
sb.append(o);
sb.append('\n');
tag("boolean", ((Boolean) value).booleanValue() ? "1" : "0");
} else if (clazz == Date.class) {
tag("dateTime.iso8601", xmlRpcDateFormat.format(((Date) value)));
- } else if (value instanceof Calendar) {
- generateValue(((Calendar) value).getTime());
- } else if (value instanceof byte[]) {
- tag("base64", Base64.getEncoder().encodeToString((byte[]) value));
+ } else if (value instanceof Calendar calendar) {
+ generateValue(calendar.getTime());
+ } else if (value instanceof byte[] bytes) {
+ tag("base64", Base64.getEncoder().encodeToString(bytes));
} else if (clazz.isArray() || value instanceof List) {
sb.append("<array><data>");
Object[] array = null;
- if (value instanceof List) {
- array = ((List<?>) value).toArray();
+ if (value instanceof List list) {
+ array = list.toArray();
} else {
array = (Object[]) value;
}
public void startElement(String uri, String localName, String qName, Attributes attributes)
throws SAXException {
String tag = qName.toLowerCase();
- if (tag.equals("array") || tag.equals("struct")) {
+ if ("array".equals(tag) || "struct".equals(tag)) {
currentDataObject.addLast(new ArrayList<>());
}
- isValueTag = tag.equals("value");
+ isValueTag = "value".equals(tag);
tagValue = new StringBuilder();
}
* Converts the object to a string array.
*/
protected String[] toOptionList(Object optionList) {
- if (optionList != null && optionList instanceof Object[]) {
- Object[] vl = (Object[]) optionList;
+ if (optionList != null && optionList instanceof Object[] vl) {
String[] stringArray = new String[vl.length];
for (int i = 0; i < vl.length; i++) {
stringArray[i] = vl[i].toString();
if (value == null || value.isBlank()) {
return null;
}
- if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("on")) {
+ if ("true".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value)) {
return (Boolean.TRUE);
- } else if (value.equalsIgnoreCase("false") || value.equalsIgnoreCase("off")) {
+ } else if ("false".equalsIgnoreCase(value) || "off".equalsIgnoreCase(value)) {
return (Boolean.FALSE);
} else if (value.matches("(-|\\+)?[0-9]+")) {
return (Integer.valueOf(value));
// suppress warning for this datapoint due wrong CCU metadata
String deviceType = channel.getDevice().getType();
- boolean isHmSenMdirNextTrans = dpInfo.getName().equals("NEXT_TRANSMISSION")
+ boolean isHmSenMdirNextTrans = "NEXT_TRANSMISSION".equals(dpInfo.getName())
&& (deviceType.startsWith("HM-Sen-MDIR-O") || deviceType.startsWith("HM-Sen-MDIR-WM55")
|| deviceType.startsWith("HM-Sec-MDIR-2"));
if (!isHmSenMdirNextTrans) {
* @author Gerhard Riegler - Initial contribution
*/
public class BinRpcNetworkService implements Runnable {
- private static final byte BIN_EMPTY_STRING[] = { 'B', 'i', 'n', 1, 0, 0, 0, 8, 0, 0, 0, 3, 0, 0, 0, 0 };
- private static final byte BIN_EMPTY_ARRAY[] = { 'B', 'i', 'n', 1, 0, 0, 0, 8, 0, 0, 1, 0, 0, 0, 0, 0 };
- private static final byte BIN_EMPTY_EVENT_LIST[] = { 'B', 'i', 'n', 1, 0, 0, 0, 21, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0,
+ private static final byte[] BIN_EMPTY_STRING = { 'B', 'i', 'n', 1, 0, 0, 0, 8, 0, 0, 0, 3, 0, 0, 0, 0 };
+ private static final byte[] BIN_EMPTY_ARRAY = { 'B', 'i', 'n', 1, 0, 0, 0, 8, 0, 0, 1, 0, 0, 0, 0, 0 };
+ private static final byte[] BIN_EMPTY_EVENT_LIST = { 'B', 'i', 'n', 1, 0, 0, 0, 21, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0,
3, 0, 0, 0, 5, 'e', 'v', 'e', 'n', 't' };
private static final String RPC_POOL_NAME = "homematicRpc";
@Override
public void initialize(HmDevice device) {
- if (!device.isGatewayExtras() && !(device.getHmInterface() == HmInterface.CUXD)) {
+ if (!device.isGatewayExtras() && device.getHmInterface() != HmInterface.CUXD) {
HmDatapoint dp = addDatapoint(device, 0, getName(), HmValueType.ENUM, 0, false);
dp.setOptions(new String[] { MODE_LOCKED, MODE_RESET, MODE_FORCE, MODE_DEFER });
dp.setMinValue(0);
@Override
public void initialize(HmDevice device) {
- if (!device.isGatewayExtras() && !(device.getHmInterface() == HmInterface.CUXD)) {
+ if (!device.isGatewayExtras() && device.getHmInterface() != HmInterface.CUXD) {
addDatapoint(device, 0, getName(), HmValueType.BOOL, Boolean.FALSE, false);
}
}
@Override
public void initialize(HmDevice device) {
- if (device.getType().startsWith(DEVICE_TYPE_19_REMOTE_CONTROL)
- && !(device.getHmInterface() == HmInterface.CUXD)) {
+ if (device.getType().startsWith(DEVICE_TYPE_19_REMOTE_CONTROL) && device.getHmInterface() != HmInterface.CUXD) {
addDatapoint(device, 18, getName(), HmValueType.STRING, null, false);
}
}
@Override
public boolean canHandleCommand(HmDatapoint dp, Object value) {
- boolean isLevel = DATAPOINT_NAME_LEVEL.equals(dp.getName()) && value != null && value instanceof Number
- && ((Number) value).doubleValue() > 0.0;
+ boolean isLevel = DATAPOINT_NAME_LEVEL.equals(dp.getName()) && value != null
+ && value instanceof Number numberCommand && numberCommand.doubleValue() > 0.0;
boolean isState = DATAPOINT_NAME_STATE.equals(dp.getName()) && MiscUtils.isTrueValue(value);
return ((isLevel || isState) && getVirtualDatapointValue(dp.getChannel()) > 0.0)
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketTimeoutException;
-import java.util.Collections;
+import java.util.Set;
import java.util.concurrent.Future;
import org.openhab.binding.homematic.internal.discovery.eq3udp.Eq3UdpRequest;
private NetworkAddressService networkAddressService;
public CcuDiscoveryService() {
- super(Collections.singleton(THING_TYPE_BRIDGE), 5, true);
+ super(Set.of(THING_TYPE_BRIDGE), 5, true);
}
@Override
import static org.openhab.binding.homematic.internal.HomematicBindingConstants.THING_TYPE_BRIDGE;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(THING_TYPE_BRIDGE);
+ return Set.of(THING_TYPE_BRIDGE);
}
@Override
import static org.openhab.binding.homematic.internal.HomematicBindingConstants.BINDING_ID;
-import java.util.Collections;
+import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
private volatile Object installModeSync = new Object();
public HomematicDeviceDiscoveryService() {
- super(Collections.singleton(new ThingTypeUID(BINDING_ID, "-")), DISCOVER_TIMEOUT_SECONDS, false);
+ super(Set.of(new ThingTypeUID(BINDING_ID, "-")), DISCOVER_TIMEOUT_SECONDS, false);
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof HomematicBridgeHandler) {
- this.bridgeHandler = (HomematicBridgeHandler) handler;
+ if (handler instanceof HomematicBridgeHandler homematicBridgeHandler) {
+ this.bridgeHandler = homematicBridgeHandler;
this.bridgeHandler.setDiscoveryService(this);
}
}
import java.io.IOException;
import java.util.Collection;
-import java.util.Collections;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(HomematicDeviceDiscoveryService.class);
+ return Set.of(HomematicDeviceDiscoveryService.class);
}
@Override
if (dp != null) {
try {
if (newValue != null) {
- if (newValue instanceof BigDecimal) {
- final BigDecimal decimal = (BigDecimal) newValue;
+ if (newValue instanceof BigDecimal decimal) {
if (dp.isIntegerType()) {
newValue = decimal.intValue();
} else if (dp.isFloatType()) {
newValue = decimal.doubleValue();
}
- } else if (newValue instanceof String && dp.isEnumType()) {
- newValue = dp.getOptionIndex((String) newValue);
+ } else if (newValue instanceof String string && dp.isEnumType()) {
+ newValue = dp.getOptionIndex(string);
}
if (!Objects.equals(dp.getValue(), newValue)) {
sendDatapoint(dp, new HmDatapointConfig(), newValue);
@Override
public String toString() {
- return String.format("%s[name=%s,value=%s,defaultValue=%s,type=%s,minValue=%s,maxValue=%s,options=%s,"
- + "readOnly=%b,readable=%b,unit=%s,description=%s,info=%s,paramsetType=%s,virtual=%b,trigger=%b]",
- getClass().getSimpleName(), name, value, defaultValue, type, minValue, maxValue,
+ return String.format("""
+ %s[name=%s,value=%s,defaultValue=%s,type=%s,minValue=%s,maxValue=%s,options=%s,\
+ readOnly=%b,readable=%b,unit=%s,description=%s,info=%s,paramsetType=%s,virtual=%b,trigger=%b]\
+ """, getClass().getSimpleName(), name, value, defaultValue, type, minValue, maxValue,
(options == null ? null : String.join(";", options)), readOnly, readable, unit, description, info,
paramsetType, virtual, trigger);
}
@Override
public boolean equals(Object obj) {
- if (obj == null || !(obj instanceof HmDatapointInfo)) {
+ if (!(obj instanceof HmDatapointInfo)) {
return false;
}
HmDatapointInfo comp = (HmDatapointInfo) obj;
@Override
public boolean equals(Object obj) {
- if (obj == null || !(obj instanceof HmDevice)) {
+ if (!(obj instanceof HmDevice)) {
return false;
}
HmDevice comp = (HmDevice) obj;
for (String deviceType : firmwaresByType.keySet()) {
Set<String> firmwares = firmwaresByType.get(deviceType);
if (firmwares.size() > 1) {
- logger.info(
- "Multiple firmware versions for device type '{}' found ({}). "
- + "Make sure, all devices of the same type have the same firmware version, "
- + "otherwise you MAY have channel and/or datapoint errors in the logfile",
- deviceType, String.join(", ", firmwares));
+ logger.info("""
+ Multiple firmware versions for device type '{}' found ({}). \
+ Make sure, all devices of the same type have the same firmware version, \
+ otherwise you MAY have channel and/or datapoint errors in the logfile\
+ """, deviceType, String.join(", ", firmwares));
}
}
}
*/
public static boolean isIgnoredDatapoint(HmDatapoint dp) {
for (String testValue : IGNORE_DATAPOINT_NAMES) {
- if (dp.getName().indexOf(testValue) > -1) {
+ if (dp.getName().contains(testValue)) {
return true;
}
}
@Override
public String toString() {
- return String.format("P1 [version: %d model: %s ssid: %s signal: %d"
- + " imp1: %f imp2: %f exp1: %f exp2: %f active: %f active1: %f active2: %f active3: %f gas: %f timestamp: %.0f]",
+ return String.format(
+ """
+ P1 [version: %d model: %s ssid: %s signal: %d\
+ imp1: %f imp2: %f exp1: %f exp2: %f active: %f active1: %f active2: %f active3: %f gas: %f timestamp: %.0f]\
+ """,
smrVersion, meterModel, wifiSsid, wifiStrength, totalEnergyImportT1Kwh, totalEnergyImportT2Kwh,
totalEnergyExportT1Kwh, totalEnergyExportT2Kwh, activePowerW, activePowerL1W, activePowerL2W,
activePowerL3W, totalGasM3, gasTimestamp);
boolean localScannerStatus = false;
for (Node n = root.getFirstChild(); n != null; n = n.getNextSibling()) {
- if (n instanceof Element) {
- Element feature = (Element) n;
-
+ if (n instanceof Element feature) {
NodeList resourceType = feature.getElementsByTagName("dd:ResourceType");
if (resourceType.getLength() > 0) {
int value = 0;
for (Node n = parentNode.getFirstChild(); n != null; n = n.getNextSibling()) {
- if (n instanceof Element) {
- Element nodeItem = (Element) n;
+ if (n instanceof Element nodeItem) {
if (nodeItem.getElementsByTagName(collateTagName).item(0).getTextContent()
.equalsIgnoreCase(collateTagNameValue)) {
int nodeValue = Integer
String contentString = contentProvider == null ? "null"
: StreamSupport.stream(contentProvider.spliterator(), false)
.map(b -> StandardCharsets.UTF_8.decode(b).toString()).collect(Collectors.joining(", "));
- String logString = "Method = {" + request.getMethod() + "}, Headers = {"
+ return "Method = {" + request.getMethod() + "}, Headers = {"
+ request.getHeaders().stream().map(HttpField::toString).collect(Collectors.joining(", "))
+ "}, Content = {" + contentString + "}";
-
- return logString;
}
/**
return string;
}
- if (command instanceof HSBType) {
- HSBType newState = (HSBType) command;
+ if (command instanceof HSBType newState) {
state = newState;
return hsbToString(newState);
- } else if (command instanceof PercentType && state instanceof HSBType) {
- HSBType newState = new HSBType(((HSBType) state).getBrightness(), ((HSBType) state).getSaturation(),
- (PercentType) command);
+ } else if (command instanceof PercentType percentCommand && state instanceof HSBType hsb) {
+ HSBType newState = new HSBType(hsb.getBrightness(), hsb.getSaturation(), percentCommand);
state = newState;
return hsbToString(newState);
}
public State toState(String string) {
State newState = UnDefType.UNDEF;
if (string.equals(channelConfig.onValue)) {
- if (state instanceof HSBType) {
- newState = new HSBType(((HSBType) state).getHue(), ((HSBType) state).getSaturation(),
- PercentType.HUNDRED);
+ if (state instanceof HSBType hsb) {
+ newState = new HSBType(hsb.getHue(), hsb.getSaturation(), PercentType.HUNDRED);
} else {
newState = HSBType.WHITE;
}
} else if (string.equals(channelConfig.offValue)) {
- if (state instanceof HSBType) {
- newState = new HSBType(((HSBType) state).getHue(), ((HSBType) state).getSaturation(), PercentType.ZERO);
+ if (state instanceof HSBType hsb) {
+ newState = new HSBType(hsb.getHue(), hsb.getSaturation(), PercentType.ZERO);
} else {
newState = HSBType.BLACK;
}
- } else if (string.equals(channelConfig.increaseValue) && state instanceof HSBType) {
- BigDecimal newBrightness = ((HSBType) state).getBrightness().toBigDecimal().add(channelConfig.step);
+ } else if (string.equals(channelConfig.increaseValue) && state instanceof HSBType hsb) {
+ BigDecimal newBrightness = hsb.getBrightness().toBigDecimal().add(channelConfig.step);
if (HUNDRED.compareTo(newBrightness) < 0) {
newBrightness = HUNDRED;
}
- newState = new HSBType(((HSBType) state).getHue(), ((HSBType) state).getSaturation(),
- new PercentType(newBrightness));
- } else if (string.equals(channelConfig.decreaseValue) && state instanceof HSBType) {
- BigDecimal newBrightness = ((HSBType) state).getBrightness().toBigDecimal().subtract(channelConfig.step);
+ newState = new HSBType(hsb.getHue(), hsb.getSaturation(), new PercentType(newBrightness));
+ } else if (string.equals(channelConfig.decreaseValue) && state instanceof HSBType hsb) {
+ BigDecimal newBrightness = hsb.getBrightness().toBigDecimal().subtract(channelConfig.step);
if (BigDecimal.ZERO.compareTo(newBrightness) > 0) {
newBrightness = BigDecimal.ZERO;
}
- newState = new HSBType(((HSBType) state).getHue(), ((HSBType) state).getSaturation(),
- new PercentType(newBrightness));
+ newState = new HSBType(hsb.getHue(), hsb.getSaturation(), new PercentType(newBrightness));
} else {
Matcher matcher = TRIPLE_MATCHER.matcher(string);
if (matcher.matches()) {
return string;
}
- if (command instanceof PercentType) {
- return ((PercentType) command).toString();
+ if (command instanceof PercentType percentCommand) {
+ return percentCommand.toString();
}
throw new IllegalArgumentException("Command type '" + command.toString() + "' not supported");
newState = PercentType.HUNDRED;
} else if (string.equals(channelConfig.offValue)) {
newState = PercentType.ZERO;
- } else if (string.equals(channelConfig.increaseValue) && state instanceof PercentType) {
- BigDecimal newBrightness = ((PercentType) state).toBigDecimal().add(channelConfig.step);
+ } else if (string.equals(channelConfig.increaseValue) && state instanceof PercentType brightnessState) {
+ BigDecimal newBrightness = brightnessState.toBigDecimal().add(channelConfig.step);
if (HUNDRED.compareTo(newBrightness) < 0) {
newBrightness = HUNDRED;
}
newState = new PercentType(newBrightness);
- } else if (string.equals(channelConfig.decreaseValue) && state instanceof PercentType) {
- BigDecimal newBrightness = ((PercentType) state).toBigDecimal().subtract(channelConfig.step);
+ } else if (string.equals(channelConfig.decreaseValue) && state instanceof PercentType brightnessState) {
+ BigDecimal newBrightness = brightnessState.toBigDecimal().subtract(channelConfig.step);
if (BigDecimal.ZERO.compareTo(newBrightness) > 0) {
newBrightness = BigDecimal.ZERO;
}
this.toState = toState;
}
+ @Override
protected State toState(String value) {
try {
return toState.apply(value);
return null;
}
+ @Override
protected String toString(Command command) {
return command.toString();
}
return string;
}
- if (command instanceof PercentType) {
+ if (command instanceof PercentType brightnessState) {
final String downValue = channelConfig.downValue;
final String upValue = channelConfig.upValue;
if (command.equals(PercentType.HUNDRED) && downValue != null) {
} else if (command.equals(PercentType.ZERO) && upValue != null) {
return upValue;
} else {
- return ((PercentType) command).toString();
+ return brightnessState.toString();
}
}
}
private String responseToLogString(Response response) {
- String logString = "Code = {" + response.getStatus() + "}, Headers = {"
+ return "Code = {" + response.getStatus() + "}, Headers = {"
+ response.getHeaders().stream().map(HttpField::toString).collect(Collectors.joining(", "))
+ "}, Content = {" + getContentAsString() + "}";
- return logString;
}
}
private void sendGraphQLMutation(String content)
throws HydrawiseConnectionException, HydrawiseAuthenticationException, HydrawiseCommandException {
Mutation mutation = new Mutation(content);
- logger.debug("Sending Mutation {}", gson.toJson(mutation).toString());
- String response = sendGraphQLRequest(gson.toJson(mutation).toString());
+ logger.debug("Sending Mutation {}", gson.toJson(mutation));
+ String response = sendGraphQLRequest(gson.toJson(mutation));
logger.debug("Mutation response {}", response);
try {
MutationResponse mResponse = gson.fromJson(response, MutationResponse.class);
throw new HydrawiseCommandException("Malformed response: " + response);
}
Optional<MutationResponseStatus> status = mResponse.data.values().stream().findFirst();
- if (!status.isPresent()) {
+ if (status.isEmpty()) {
throw new HydrawiseCommandException("Unknown response: " + response);
}
if (status.get().status != StatusCode.OK) {
public enum StatusCode {
OK,
WARNING,
- ERROR;
+ ERROR
}
}
public LocalScheduleResponse getLocalSchedule()
throws HydrawiseConnectionException, HydrawiseAuthenticationException {
String json = doGet(localGetURL);
- LocalScheduleResponse response = gson.fromJson(json, LocalScheduleResponse.class);
- return response;
+ return gson.fromJson(json, LocalScheduleResponse.class);
}
/**
throws HydrawiseConnectionException, HydrawiseAuthenticationException, HydrawiseCommandException {
String json = doGet(url);
SetZoneResponse response = gson.fromJson(json, SetZoneResponse.class);
- if (response.messageType.equals("error")) {
+ if ("error".equals(response.messageType)) {
throw new HydrawiseCommandException(response.message);
}
return response.message;
*/
package org.openhab.binding.hydrawise.internal.discovery;
-import java.util.Collections;
import java.util.Date;
import java.util.List;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
HydrawiseAccountHandler handler;
public HydrawiseCloudControllerDiscoveryService() {
- super(Collections.singleton(HydrawiseBindingConstants.THING_TYPE_CONTROLLER), TIMEOUT, true);
+ super(Set.of(HydrawiseBindingConstants.THING_TYPE_CONTROLLER), TIMEOUT, true);
}
@Override
String.valueOf(id));
thingDiscovered(DiscoveryResultBuilder.create(thingUID).withLabel(label).withBridge(bridgeUID)
.withProperty(HydrawiseBindingConstants.CONFIG_CONTROLLER_ID, id)
- .withRepresentationProperty(String.valueOf(HydrawiseBindingConstants.CONFIG_CONTROLLER_ID))
- .build());
+ .withRepresentationProperty(HydrawiseBindingConstants.CONFIG_CONTROLLER_ID).build());
}
}
}
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;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(HydrawiseCloudControllerDiscoveryService.class);
+ return Set.of(HydrawiseCloudControllerDiscoveryService.class);
}
public void addControllerListeners(HydrawiseControllerListener listener) {
if (response == null) {
throw new HydrawiseConnectionException("Malformed response");
}
- if (response.errors != null && response.errors.size() > 0) {
+ if (response.errors != null && !response.errors.isEmpty()) {
throw new HydrawiseConnectionException(response.errors.stream().map(error -> error.message).reduce("",
(messages, message) -> messages + message + ". "));
}
}
updateGroupState(CHANNEL_GROUP_ALLZONES, CHANNEL_ZONE_RUN,
- status.running.size() > 0 ? OnOffType.ON : OnOffType.OFF);
+ !status.running.isEmpty() ? OnOffType.ON : OnOffType.OFF);
});
}
package org.openhab.binding.hyperion.internal;
import java.math.BigDecimal;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(HyperionBindingConstants.THING_TYPE_SERVER_NG);
+ return Set.of(HyperionBindingConstants.THING_TYPE_SERVER_NG);
}
@Override
outToServer.writeBytes(json + System.lineSeparator());
outToServer.flush();
response = inFromServer.readLine();
- } catch (IOException e) {
- throw e;
}
logger.debug("Received: {}", response);
return response;
}
private void handleBrightness(Command command) throws IOException, CommandUnsuccessfulException {
- if (command instanceof PercentType) {
- PercentType percent = (PercentType) command;
+ if (command instanceof PercentType percentCommand) {
Transform transform = new Transform();
- transform.setLuminanceGain(percent.doubleValue() / 100);
+ transform.setLuminanceGain(percentCommand.doubleValue() / 100);
TransformCommand transformCommand = new TransformCommand(transform);
sendCommand(transformCommand);
} else {
}
private void handleColor(Command command) throws IOException, CommandUnsuccessfulException {
- if (command instanceof HSBType) {
- HSBType color = (HSBType) command;
- Color c = new Color(color.getRGB());
+ if (command instanceof HSBType hsbCommand) {
+ Color c = new Color(hsbCommand.getRGB());
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
// update Hyperion, older API compatibility
Hyperion hyperion = info.getHyperion();
if (hyperion != null) {
-
updateHyperion(hyperion);
}
}
private void handleBrightness(Command command) throws IOException, CommandUnsuccessfulException {
- if (command instanceof PercentType) {
- PercentType percent = (PercentType) command;
- int brightnessValue = percent.intValue();
+ if (command instanceof PercentType percentCommand) {
+ int brightnessValue = percentCommand.intValue();
Adjustment adjustment = new Adjustment();
adjustment.setBrightness(brightnessValue);
}
private void handleColor(Command command) throws IOException, CommandUnsuccessfulException {
- if (command instanceof HSBType) {
- HSBType color = (HSBType) command;
- Color c = new Color(color.getRGB());
+ if (command instanceof HSBType hsbCommand) {
+ Color c = new Color(hsbCommand.getRGB());
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
JsonObject iammeterData = iammeterDataElement.getAsJsonObject();
String keyWord = "Datas";
if (iammeterData.has("Datas") && iammeterData.has("SN")) {
- String groups[] = { "powerPhaseA", "powerPhaseB", "powerPhaseC" };
+ String[] groups = { "powerPhaseA", "powerPhaseB", "powerPhaseC" };
for (int row = 0; row < groups.length; row++) {
String gpName = groups[row];
List<Channel> chnList = getThing().getChannelsOfGroup(gpName);
: "on".equals(command.toString()) ? "1" : command.toString();
client.lightCommand(serialNumber, sessionId, auxId, cmd,
AuxiliaryType.fromChannelTypeUID(getChannelTypeUID(channelUID)).getSubType());
- } else if (command instanceof OnOffType) {
+ } else if (command instanceof OnOffType onOffCommand) {
// these are toggle commands and require we have the current state to turn on/off
Auxiliary[] auxs = client.getAux(serialNumber, sessionId);
Optional<Auxiliary> optional = Arrays.stream(auxs).filter(o -> o.getName().equals(channelName))
.findFirst();
if (optional.isPresent()) {
- OnOffType onOffCommand = (OnOffType) command;
State currentState = toState(channelName, "Switch", optional.get().getState());
if (!currentState.equals(onOffCommand)) {
client.auxSetCommand(serialNumber, sessionId, channelName);
client.setPoolTemp(serialNumber, sessionId, value.floatValue());
}
}
- } else if (command instanceof OnOffType) {
- OnOffType onOffCommand = (OnOffType) command;
+ } else if (command instanceof OnOffType onOffCommand) {
// these are toggle commands and require we have the current state to turn on/off
if (channelName.startsWith("onetouch_")) {
OneTouch[] ota = client.getOneTouch(serialNumber, sessionId);
import static org.openhab.binding.icalendar.internal.ICalendarBindingConstants.*;
-import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ICalendarHandlerFactory extends BaseThingHandlerFactory {
private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Stream
- .of(Collections.singleton(THING_TYPE_CALENDAR), Collections.singleton(THING_TYPE_FILTERED_EVENTS))
- .flatMap(Set::stream).collect(Collectors.toSet());
+ .of(Set.of(THING_TYPE_CALENDAR), Set.of(THING_TYPE_FILTERED_EVENTS)).flatMap(Set::stream)
+ .collect(Collectors.toSet());
private final Logger logger = LoggerFactory.getLogger(ICalendarHandlerFactory.class);
private final HttpClient sharedHttpClient;
return null;
}
if (thingTypeUID.equals(THING_TYPE_CALENDAR)) {
- if (thing instanceof Bridge) {
- return new ICalendarHandler((Bridge) thing, sharedHttpClient, eventPublisher, tzProvider);
+ if (thing instanceof Bridge bridge) {
+ return new ICalendarHandler(bridge, sharedHttpClient, eventPublisher, tzProvider);
} else {
logger.warn(
"The API of iCalendar has changed. You have to recreate the calendar according to the docs.");
thingBuilder.withoutChannel(toDelete.getUID());
});
- resultChannels.stream().filter((ResultChannelSet current) -> {
- return (getThing().getChannelsOfGroup(current.resultGroup.toString()).size() == 0);
- }).forEach((ResultChannelSet current) -> {
- for (ChannelBuilder builder : handlerCallback.createChannelBuilders(current.resultGroup,
- GROUP_TYPE_UID)) {
- Channel currentChannel = builder.build();
- Channel existingChannel = getThing().getChannel(currentChannel.getUID());
- if (existingChannel == null) {
- thingBuilder.withChannel(currentChannel);
- }
- }
- });
+ resultChannels
+ .stream().filter((ResultChannelSet current) -> (getThing()
+ .getChannelsOfGroup(current.resultGroup.toString()).isEmpty()))
+ .forEach((ResultChannelSet current) -> {
+ for (ChannelBuilder builder : handlerCallback.createChannelBuilders(current.resultGroup,
+ GROUP_TYPE_UID)) {
+ Channel currentChannel = builder.build();
+ Channel existingChannel = getThing().getChannel(currentChannel.getUID());
+ if (existingChannel == null) {
+ thingBuilder.withChannel(currentChannel);
+ }
+ }
+ });
}
updateThing(thingBuilder.build());
}
* @param childHandler the handler to be updated
*/
private void updateChild(@Nullable ThingHandler childHandler) {
- if (childHandler instanceof CalendarUpdateListener) {
+ if (childHandler instanceof CalendarUpdateListener updateListener) {
logger.trace("Notifying {} about fresh calendar.", childHandler.getThing().getUID());
try {
- ((CalendarUpdateListener) childHandler).onCalendarUpdated();
+ updateListener.onCalendarUpdated();
} catch (Exception e) {
logger.trace("The update of a child handler failed. Ignoring.", e);
}
*/
@NonNullByDefault
public class EventTextFilter {
- public static enum Type {
+ public enum Type {
TEXT,
REGEX
}
- public static enum Field {
+ public enum Field {
SUMMARY,
DESCRIPTION,
COMMENT,
@Override
protected void removeHandler(ThingHandler thingHandler) {
- if (thingHandler instanceof ICloudAccountBridgeHandler) {
- unregisterDeviceDiscoveryService((ICloudAccountBridgeHandler) thingHandler);
+ if (thingHandler instanceof ICloudAccountBridgeHandler iCloudAccountBridgeHandler) {
+ unregisterDeviceDiscoveryService(iCloudAccountBridgeHandler);
}
}
authState = AuthState.INITIAL;
}
- this.iCloudDeviceInformationCache = new ExpiringCache<>(CACHE_EXPIRY, () -> {
- return callApiWithRetryAndExceptionHandling(() -> {
+ this.iCloudDeviceInformationCache = new ExpiringCache<>(CACHE_EXPIRY,
+ () -> callApiWithRetryAndExceptionHandling(() ->
// callApiWithRetryAndExceptionHanlding ensures that iCloudService is not null when the following is
// called. Cannot use method local iCloudService instance here, because instance may be replaced with a
// new
// one during retry.
- return iCloudService.getDevices().refreshClient();
- });
-
- });
+ iCloudService.getDevices().refreshClient()));
updateStatus(ThingStatus.UNKNOWN);
Bridge bridge = getBridge();
if (bridge != null) {
ThingHandler bridgeHandler = bridge.getHandler();
- if (bridgeHandler instanceof ICloudAccountBridgeHandler) {
- ((ICloudAccountBridgeHandler) bridgeHandler).unregisterListener(this);
+ if (bridgeHandler instanceof ICloudAccountBridgeHandler iCloudAccountBridgeHandler) {
+ iCloudAccountBridgeHandler.unregisterListener(this);
}
}
super.dispose();
@BeforeEach
public void setUp() {
final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
- if (logger instanceof ch.qos.logback.classic.Logger) {
- ((ch.qos.logback.classic.Logger) logger).setLevel(ch.qos.logback.classic.Level.DEBUG);
+ if (logger instanceof ch.qos.logback.classic.Logger qLogger) {
+ qLogger.setLevel(ch.qos.logback.classic.Level.DEBUG);
}
}
@Test
@EnabledIfSystemProperty(named = "icloud.test.email", matches = ".*", disabledReason = "Only for manual execution.")
public void testDiscovery() {
-
String icloudDeviceRespond = """
{
"userInfo": {
}
private List<IhcEnumValue> getEnumValues(WSResourceValue value) {
- if (value instanceof WSEnumValue) {
- return enumDictionary.getEnumValues(((WSEnumValue) value).definitionTypeID);
+ if (value instanceof WSEnumValue enumValue) {
+ return enumDictionary.getEnumValues(enumValue.definitionTypeID);
}
return null;
}
}
private void checkPotentialButtonPresses(WSResourceValue value) {
- if (value instanceof WSBooleanValue) {
- if (((WSBooleanValue) value).value) {
+ if (value instanceof WSBooleanValue booleanValue) {
+ if (booleanValue.value) {
// potential button press
lastUpdate.put(value.resourceID, LocalDateTime.now());
updateTriggers(value.resourceID, Duration.ZERO);
long retval;
Object paramValue = context.getConfiguration().get(param);
logger.debug("Configuring profile with {} parameter '{}'", param, paramValue);
- if (paramValue instanceof BigDecimal) {
- retval = ((BigDecimal) paramValue).longValue();
+ if (paramValue instanceof BigDecimal decimalParam) {
+ retval = decimalParam.longValue();
} else {
logger.debug("Parameter '{}' is not of type BigDecimal, using default value '{}'", param, defValue);
retval = defValue;
private void init() throws IhcFatalExecption {
try {
-
// Create a local instance of cookie store
cookieStore = new BasicCookieStore();
dbFactory.setXIncludeAware(false);
dbFactory.setExpandEntityReferences(false);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
- Document doc = dBuilder.parse(fXmlFile);
- return doc;
+ return dBuilder.parse(fXmlFile);
} catch (IOException | ParserConfigurationException | SAXException e) {
throw new IhcExecption(e);
}
// @formatter:off
final String soapQuery =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
- + "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n"
- + " <soapenv:Body>\n"
- + " <authenticate1 xmlns=\"utcs\">\n"
- + " <password>%s</password>\n"
- + " <username>%s</username>\n"
- + " <application>%s</application>\n"
- + " </authenticate1>\n"
- + " </soapenv:Body>\n"
- + "</soapenv:Envelope>";
+ """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <soapenv:Body>
+ <authenticate1 xmlns="utcs">
+ <password>%s</password>
+ <username>%s</username>
+ <application>%s</application>
+ </authenticate1>
+ </soapenv:Body>
+ </soapenv:Envelope>\
+ """;
// @formatter:on
String query = String.format(soapQuery, password, username, application);
// @formatter:off
protected static final String EMPTY_QUERY =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
- + "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
- + " <soapenv:Body>\n"
- + " </soapenv:Body>\n"
- + "</soapenv:Envelope>";
+ """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
+ <soapenv:Body>
+ </soapenv:Body>
+ </soapenv:Envelope>\
+ """;
// @formatter:on
private String url;
public synchronized WSFile getProjectSegment(int index, int major, int minor) throws IhcExecption {
// @formatter:off
final String soapQuery =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
- + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
- + " <soap:Body>\n"
- + " <ns1:getIHCProjectSegment1 xmlns:ns1=\"utcs\" xsi:type=\"xsd:int\">%s</ns1:getIHCProjectSegment1>\n"
- + " <ns2:getIHCProjectSegment2 xmlns:ns2=\"utcs\" xsi:type=\"xsd:int\">%s</ns2:getIHCProjectSegment2>\n"
- + " <ns3:getIHCProjectSegment3 xmlns:ns3=\"utcs\" xsi:type=\"xsd:int\">%s</ns3:getIHCProjectSegment3>\n"
- + " </soap:Body>\n"
- + "</soap:Envelope>";
+ """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
+ <soap:Body>
+ <ns1:getIHCProjectSegment1 xmlns:ns1="utcs" xsi:type="xsd:int">%s</ns1:getIHCProjectSegment1>
+ <ns2:getIHCProjectSegment2 xmlns:ns2="utcs" xsi:type="xsd:int">%s</ns2:getIHCProjectSegment2>
+ <ns3:getIHCProjectSegment3 xmlns:ns3="utcs" xsi:type="xsd:int">%s</ns3:getIHCProjectSegment3>
+ </soap:Body>
+ </soap:Envelope>\
+ """;
// @formatter:on
String query = String.format(soapQuery, index, major, minor);
int timeoutInSeconds) throws IhcExecption {
// @formatter:off
final String soapQuery =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
- + "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
- + " <soapenv:Body>\n"
- + " <ns1:waitForControllerStateChange1 xmlns:ns1=\"utcs\" xsi:type=\"ns1:WSControllerState\">\n"
- + " <ns1:state xsi:type=\"xsd:string\">%s</ns1:state>\n"
- + " </ns1:waitForControllerStateChange1>\n"
- + " <ns2:waitForControllerStateChange2 xmlns:ns2=\"utcs\" xsi:type=\"xsd:int\">%s</ns2:waitForControllerStateChange2>\n"
- + " </soapenv:Body>\n"
- + "</soapenv:Envelope>";
+ """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
+ <soapenv:Body>
+ <ns1:waitForControllerStateChange1 xmlns:ns1="utcs" xsi:type="ns1:WSControllerState">
+ <ns1:state xsi:type="xsd:string">%s</ns1:state>
+ </ns1:waitForControllerStateChange1>
+ <ns2:waitForControllerStateChange2 xmlns:ns2="utcs" xsi:type="xsd:int">%s</ns2:waitForControllerStateChange2>
+ </soapenv:Body>
+ </soapenv:Envelope>\
+ """;
// @formatter:on
String query = String.format(soapQuery, previousState.getState(), timeoutInSeconds);
public WSResourceValue resourceQuery(int resoureId) throws IhcExecption {
// @formatter:off
final String soapQuery =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
- + "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
- + " <soapenv:Body>\n"
- + " <ns1:getRuntimeValue1 xmlns:ns1=\"utcs\">%s</ns1:getRuntimeValue1>\n"
- + " </soapenv:Body>\n"
- + "</soapenv:Envelope>";
+ """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
+ <soapenv:Body>
+ <ns1:getRuntimeValue1 xmlns:ns1="utcs">%s</ns1:getRuntimeValue1>
+ </soapenv:Body>
+ </soapenv:Envelope>\
+ """;
// @formatter:on
String query = String.format(soapQuery, String.valueOf(resoureId));
public boolean resourceUpdate(WSResourceValue value) throws IhcExecption {
boolean retval = false;
- if (value instanceof WSFloatingPointValue) {
- retval = resourceUpdate((WSFloatingPointValue) value);
- } else if (value instanceof WSBooleanValue) {
- retval = resourceUpdate((WSBooleanValue) value);
- } else if (value instanceof WSIntegerValue) {
- retval = resourceUpdate((WSIntegerValue) value);
- } else if (value instanceof WSTimerValue) {
- retval = resourceUpdate((WSTimerValue) value);
- } else if (value instanceof WSWeekdayValue) {
- retval = resourceUpdate((WSWeekdayValue) value);
- } else if (value instanceof WSEnumValue) {
- retval = resourceUpdate((WSEnumValue) value);
- } else if (value instanceof WSTimeValue) {
- retval = resourceUpdate((WSTimeValue) value);
- } else if (value instanceof WSDateValue) {
- retval = resourceUpdate((WSDateValue) value);
+ if (value instanceof WSFloatingPointValue pointValue) {
+ retval = resourceUpdate(pointValue);
+ } else if (value instanceof WSBooleanValue booleanValue) {
+ retval = resourceUpdate(booleanValue);
+ } else if (value instanceof WSIntegerValue integerValue) {
+ retval = resourceUpdate(integerValue);
+ } else if (value instanceof WSTimerValue timerValue) {
+ retval = resourceUpdate(timerValue);
+ } else if (value instanceof WSWeekdayValue weekdayValue) {
+ retval = resourceUpdate(weekdayValue);
+ } else if (value instanceof WSEnumValue enumValue) {
+ retval = resourceUpdate(enumValue);
+ } else if (value instanceof WSTimeValue timeValue) {
+ retval = resourceUpdate(timeValue);
+ } else if (value instanceof WSDateValue dateValue) {
+ retval = resourceUpdate(dateValue);
} else {
throw new IhcExecption("Unsupported value type " + value.getClass().toString());
}
public boolean resourceUpdate(WSBooleanValue value) throws IhcExecption {
// @formatter:off
final String soapQuery =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
- + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
- + " <soap:Body>\n"
- + " <setResourceValue1 xmlns=\"utcs\">\n"
- + " <value xmlns:q1=\"utcs.values\" xsi:type=\"q1:WSBooleanValue\">\n"
- + " <q1:value>%s</q1:value>\n"
- + " </value>\n"
- + " <resourceID>%s</resourceID>\n"
- + " <isValueRuntime>true</isValueRuntime>\n"
- + " </setResourceValue1>\n"
- + " </soap:Body>\n"
- + "</soap:Envelope>";
+ """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
+ <soap:Body>
+ <setResourceValue1 xmlns="utcs">
+ <value xmlns:q1="utcs.values" xsi:type="q1:WSBooleanValue">
+ <q1:value>%s</q1:value>
+ </value>
+ <resourceID>%s</resourceID>
+ <isValueRuntime>true</isValueRuntime>
+ </setResourceValue1>
+ </soap:Body>
+ </soap:Envelope>\
+ """;
// @formatter:on
String query = String.format(soapQuery, value.value ? "true" : "false", value.resourceID);
public boolean resourceUpdate(WSFloatingPointValue value) throws IhcExecption {
// @formatter:off
final String soapQuery =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
- + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
- + " <soap:Body>\n"
- + " <setResourceValue1 xmlns=\"utcs\">\n"
- + " <value xmlns:q1=\"utcs.values\" xsi:type=\"q1:WSFloatingPointValue\">\n"
- + " <q1:maximumValue>%s</q1:maximumValue>\n"
- + " <q1:minimumValue>%s</q1:minimumValue>\n"
- + " <q1:floatingPointValue>%s</q1:floatingPointValue>\n"
- + " </value>\n"
- + " <resourceID>%s</resourceID>\n"
- + " <isValueRuntime>true</isValueRuntime>\n"
- + " </setResourceValue1>\n"
- + " </soap:Body>\n"
- + "</soap:Envelope>";
+ """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
+ <soap:Body>
+ <setResourceValue1 xmlns="utcs">
+ <value xmlns:q1="utcs.values" xsi:type="q1:WSFloatingPointValue">
+ <q1:maximumValue>%s</q1:maximumValue>
+ <q1:minimumValue>%s</q1:minimumValue>
+ <q1:floatingPointValue>%s</q1:floatingPointValue>
+ </value>
+ <resourceID>%s</resourceID>
+ <isValueRuntime>true</isValueRuntime>
+ </setResourceValue1>
+ </soap:Body>
+ </soap:Envelope>\
+ """;
// @formatter:on
String query = String.format(soapQuery, value.maximumValue, value.minimumValue, value.value, value.resourceID);
public boolean resourceUpdate(WSIntegerValue value) throws IhcExecption {
// @formatter:off
final String soapQuery =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
- + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
- + " <soap:Body>\n"
- + " <setResourceValue1 xmlns=\"utcs\">\n"
- + " <value xmlns:q1=\"utcs.values\" xsi:type=\"q1:WSIntegerValue\">\n"
- + " <q1:maximumValue>%s</q1:maximumValue>\n"
- + " <q1:minimumValue>%s</q1:minimumValue>\n"
- + " <q1:integer>%s</q1:integer>\n"
- + " </value>\n"
- + " <resourceID>%s</resourceID>\n"
- + " <isValueRuntime>true</isValueRuntime>\n"
- + " </setResourceValue1>\n"
- + " </soap:Body>\n"
- + "</soap:Envelope>";
+ """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
+ <soap:Body>
+ <setResourceValue1 xmlns="utcs">
+ <value xmlns:q1="utcs.values" xsi:type="q1:WSIntegerValue">
+ <q1:maximumValue>%s</q1:maximumValue>
+ <q1:minimumValue>%s</q1:minimumValue>
+ <q1:integer>%s</q1:integer>
+ </value>
+ <resourceID>%s</resourceID>
+ <isValueRuntime>true</isValueRuntime>
+ </setResourceValue1>
+ </soap:Body>
+ </soap:Envelope>\
+ """;
// @formatter:on
String query = String.format(soapQuery, value.maximumValue, value.minimumValue, value.value, value.resourceID);
public boolean resourceUpdate(WSTimerValue value) throws IhcExecption {
// @formatter:off
final String soapQuery =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
- + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
- + " <soap:Body>\n"
- + " <setResourceValue1 xmlns=\"utcs\">\n"
- + " <value xmlns:q1=\"utcs.values\" xsi:type=\"q1:WSTimerValue\">\n"
- + " <q1:milliseconds>%s</q1:milliseconds>\n"
- + " </value>\n"
- + " <resourceID>%s</resourceID>\n"
- + " <isValueRuntime>true</isValueRuntime>\n"
- + " </setResourceValue1>\n"
- + " </soap:Body>\n"
- + "</soap:Envelope>";
+ """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
+ <soap:Body>
+ <setResourceValue1 xmlns="utcs">
+ <value xmlns:q1="utcs.values" xsi:type="q1:WSTimerValue">
+ <q1:milliseconds>%s</q1:milliseconds>
+ </value>
+ <resourceID>%s</resourceID>
+ <isValueRuntime>true</isValueRuntime>
+ </setResourceValue1>
+ </soap:Body>
+ </soap:Envelope>\
+ """;
// @formatter:on
String query = String.format(soapQuery, value.milliseconds, value.resourceID);
public boolean resourceUpdate(WSWeekdayValue value) throws IhcExecption {
// @formatter:off
final String soapQuery =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
- + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
- + " <soap:Body>\n"
- + " <setResourceValue1 xmlns=\"utcs\">\n"
- + " <value xmlns:q1=\"utcs.values\" xsi:type=\"q1:WSWeekdayValue\">\n"
- + " <q1:weekdayNumber>%s</q1:weekdayNumber>\n"
- + " </value>\n"
- + " <resourceID>%s</resourceID>\n"
- + " <isValueRuntime>true</isValueRuntime>\n"
- + " </setResourceValue1>\n"
- + " </soap:Body>\n"
- + "</soap:Envelope>";
+ """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
+ <soap:Body>
+ <setResourceValue1 xmlns="utcs">
+ <value xmlns:q1="utcs.values" xsi:type="q1:WSWeekdayValue">
+ <q1:weekdayNumber>%s</q1:weekdayNumber>
+ </value>
+ <resourceID>%s</resourceID>
+ <isValueRuntime>true</isValueRuntime>
+ </setResourceValue1>
+ </soap:Body>
+ </soap:Envelope>\
+ """;
// @formatter:on
String query = String.format(soapQuery, value.weekdayNumber, value.resourceID);
public boolean resourceUpdate(WSEnumValue value) throws IhcExecption {
// @formatter:off
final String soapQuery =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
- + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
- + " <soap:Body>\n"
- + " <setResourceValue1 xmlns=\"utcs\">\n"
- + " <value xmlns:q1=\"utcs.values\" xsi:type=\"q1:WSEnumValue\">\n"
- + " <q1:definitionTypeID>%s</q1:definitionTypeID>\n"
- + " <q1:enumValueID>%s</q1:enumValueID>\n"
- + " <q1:enumName>%s</q1:enumName>\n"
- + " </value>\n"
- + " <resourceID>%s</resourceID>\n"
- + " <isValueRuntime>true</isValueRuntime>\n"
- + " </setResourceValue1>\n"
- + " </soap:Body>\n"
- + "</soap:Envelope>";
+ """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
+ <soap:Body>
+ <setResourceValue1 xmlns="utcs">
+ <value xmlns:q1="utcs.values" xsi:type="q1:WSEnumValue">
+ <q1:definitionTypeID>%s</q1:definitionTypeID>
+ <q1:enumValueID>%s</q1:enumValueID>
+ <q1:enumName>%s</q1:enumName>
+ </value>
+ <resourceID>%s</resourceID>
+ <isValueRuntime>true</isValueRuntime>
+ </setResourceValue1>
+ </soap:Body>
+ </soap:Envelope>\
+ """;
// @formatter:on
String query = String.format(soapQuery, value.definitionTypeID, value.enumValueID, value.enumName,
public boolean resourceUpdate(WSTimeValue value) throws IhcExecption {
// @formatter:off
final String soapQuery =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
- + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
- + " <soap:Body>\n"
- + " <setResourceValue1 xmlns=\"utcs\">\n"
- + " <value xmlns:q1=\"utcs.values\" xsi:type=\"q1:WSTimeValue\">\n"
- + " <q1:hours>%s</q1:hours>\n"
- + " <q1:minutes>%s</q1:minutes>\n"
- + " <q1:seconds>%s</q1:seconds>\n"
- + " </value>\n"
- + " <resourceID>%s</resourceID>\n"
- + " <isValueRuntime>true</isValueRuntime>\n"
- + " </setResourceValue1>\n"
- + " </soap:Body>\n"
- + "</soap:Envelope>";
+ """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
+ <soap:Body>
+ <setResourceValue1 xmlns="utcs">
+ <value xmlns:q1="utcs.values" xsi:type="q1:WSTimeValue">
+ <q1:hours>%s</q1:hours>
+ <q1:minutes>%s</q1:minutes>
+ <q1:seconds>%s</q1:seconds>
+ </value>
+ <resourceID>%s</resourceID>
+ <isValueRuntime>true</isValueRuntime>
+ </setResourceValue1>
+ </soap:Body>
+ </soap:Envelope>\
+ """;
// @formatter:on
String query = String.format(soapQuery, value.hours, value.minutes, value.seconds, value.resourceID);
public boolean resourceUpdate(WSDateValue value) throws IhcExecption {
// @formatter:off
final String soapQuery =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
- + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
- + " <soap:Body>\n"
- + " <setResourceValue1 xmlns=\"utcs\">\n"
- + " <value xmlns:q1=\"utcs.values\" xsi:type=\"q1:WSDateValue\">\n"
- + " <q1:month>%s</q1:month>\n"
- + " <q1:year>%s</q1:year>\n"
- + " <q1:day>%s</q1:day>\n"
- + " </value>\n"
- + " <resourceID>%s</resourceID>\n"
- + " <isValueRuntime>true</isValueRuntime>\n"
- + " </setResourceValue1>\n"
- + " </soap:Body>\n"
- + "</soap:Envelope>";
+ """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
+ <soap:Body>
+ <setResourceValue1 xmlns="utcs">
+ <value xmlns:q1="utcs.values" xsi:type="q1:WSDateValue">
+ <q1:month>%s</q1:month>
+ <q1:year>%s</q1:year>
+ <q1:day>%s</q1:day>
+ </value>
+ <resourceID>%s</resourceID>
+ <isValueRuntime>true</isValueRuntime>
+ </setResourceValue1>
+ </soap:Body>
+ </soap:Envelope>\
+ """;
// @formatter:on
String query = String.format(soapQuery, value.month, value.year, value.day, value.resourceID);
public void enableRuntimeValueNotifications(Set<Integer> resourceIdList) throws IhcExecption {
// @formatter:off
final String soapQueryPrefix =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
- + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
- + " <soap:Body>\n"
- + " <enableRuntimeValueNotifications1 xmlns=\"utcs\">\n";
+ """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
+ <soap:Body>
+ <enableRuntimeValueNotifications1 xmlns="utcs">
+ """;
final String soapQuerySuffix =
- " </enableRuntimeValueNotifications1>\n"
- + " </soap:Body>\n"
- + "</soap:Envelope>";
+ """
+ </enableRuntimeValueNotifications1>
+ </soap:Body>
+ </soap:Envelope>\
+ """;
// @formatter:on
String query = soapQueryPrefix;
public List<WSResourceValue> waitResourceValueNotifications(int timeoutInSeconds) throws IhcExecption {
// @formatter:off
final String soapQuery =
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
- + "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:utcs=\"utcs\">\n"
- + " <soapenv:Body>\n"
- + " <utcs:waitForResourceValueChanges1>%s</utcs:waitForResourceValueChanges1>\n"
- + " </soapenv:Body>\n"
- + "</soapenv:Envelope>";
+ """
+ <?xml version="1.0" encoding="UTF-8"?>
+ <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:utcs="utcs">
+ <soapenv:Body>
+ <utcs:waitForResourceValueChanges1>%s</utcs:waitForResourceValueChanges1>
+ </soapenv:Body>
+ </soapenv:Envelope>\
+ """;
// @formatter:on
String query = String.format(soapQuery, timeoutInSeconds);
@Override
public void handleCommand(InsteonChannelConfiguration conf, Command cmd, InsteonDevice dev) {
try {
- if (cmd instanceof DecimalType) {
- int v = ((DecimalType) cmd).intValue();
+ if (cmd instanceof DecimalType decimalCommand) {
+ int v = decimalCommand.intValue();
int cmd1 = (v != 1) ? 0x17 : 0x18; // start or stop
int cmd2 = (v == 2) ? 0x01 : 0; // up or down
Msg m = dev.makeStandardMessage((byte) 0x0f, (byte) cmd1, (byte) cmd2, getGroup(conf));
*/
@NonNullByDefault
public class DeviceFeature {
- public static enum QueryStatus {
+ public enum QueryStatus {
NEVER_QUERIED,
QUERY_PENDING,
QUERY_ANSWERED
}
logger.trace("{} making poll msg for {} using handler {}", getName(), getDevice().getAddress(),
pollHandler.getClass().getSimpleName());
- Msg m = pollHandler.makeMsg(device);
- return m;
+ return pollHandler.makeMsg(device);
}
/**
NodeList nodes = root.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
- if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals("device")) {
+ if (node.getNodeType() == Node.ELEMENT_NODE && "device".equals(node.getNodeName())) {
processDevice((Element) node);
}
}
private static FeatureTemplate parseFeature(Element e) throws ParsingException {
String name = e.getAttribute("name");
- boolean statusFeature = e.getAttribute("statusFeature").equals("true");
+ boolean statusFeature = "true".equals(e.getAttribute("statusFeature"));
FeatureTemplate feature = new FeatureTemplate(name, statusFeature, e.getAttribute("timeout"));
NodeList nodes = e.getChildNodes();
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element child = (Element) node;
- if (child.getTagName().equals("message-handler")) {
+ if ("message-handler".equals(child.getTagName())) {
parseMessageHandler(child, feature);
- } else if (child.getTagName().equals("command-handler")) {
+ } else if ("command-handler".equals(child.getTagName())) {
parseCommandHandler(child, feature);
- } else if (child.getTagName().equals("message-dispatcher")) {
+ } else if ("message-dispatcher".equals(child.getTagName())) {
parseMessageDispatcher(child, feature);
- } else if (child.getTagName().equals("poll-handler")) {
+ } else if ("poll-handler".equals(child.getTagName())) {
parsePollHandler(child, feature);
}
}
enum GroupMessage {
BCAST,
CLEAN,
- SUCCESS;
+ SUCCESS
};
/**
public class InsteonDevice {
private final Logger logger = LoggerFactory.getLogger(InsteonDevice.class);
- public static enum DeviceStatus {
+ public enum DeviceStatus {
INITIALIZED,
POLLING
}
protected boolean getBooleanDeviceConfig(String key, boolean def) {
Object o = feature.getDevice().getDeviceConfigMap().get(key);
if (o != null) {
- if (o instanceof Boolean) {
- return (Boolean) o;
+ if (o instanceof Boolean booleanValue) {
+ return booleanValue;
} else {
logger.warn("{} {}: The value for the '{}' key is not boolean in the device configuration parameter.",
nm(), feature.getDevice().getAddress(), key);
if (System.currentTimeMillis() - lastMessageTimestamp > MESSAGE_TIMEOUT) {
String s = "";
if (messageCount == 0) {
- s = " No messages were received, the PLM or hub might be broken. If this continues see "
- + "'Known Limitations and Issues' in the Insteon binding documentation.";
+ s = """
+ No messages were received, the PLM or hub might be broken. If this continues see \
+ 'Known Limitations and Issues' in the Insteon binding documentation.\
+ """;
}
logger.warn("Modem database download was unsuccessful, restarting!{}", s);
startDownload();
feature = DATA;
}
} else if (productKey.equals(PLM_PRODUCT_KEY)) {
- String parts[] = feature.split("#");
+ String[] parts = feature.split("#");
if (parts.length == 2 && parts[0].equalsIgnoreCase(InsteonBindingConstants.BROADCAST_ON_OFF)
&& parts[1].matches("^\\d+$")) {
feature = BROADCAST_ON_OFF;
Object groups = deviceConfigMap.get(BROADCAST_GROUPS);
if (groups != null) {
boolean valid = false;
- if (groups instanceof List<?>) {
+ if (groups instanceof List<?> list) {
valid = true;
- for (Object o : (List<?>) groups) {
+ for (Object o : list) {
if (o instanceof Double && (Double) o % 1 == 0) {
String id = InsteonBindingConstants.BROADCAST_ON_OFF + "#"
+ ((Double) o).intValue();
Map<String, Object> channelProperties = channel.getConfiguration().getProperties();
for (String key : channelProperties.keySet()) {
Object value = channelProperties.get(key);
- if (value instanceof String) {
- params.put(key, (String) value);
- } else if (value instanceof BigDecimal) {
- String s = ((BigDecimal) value).toPlainString();
+ if (value instanceof String stringValue) {
+ params.put(key, stringValue);
+ } else if (value instanceof BigDecimal decimalValue) {
+ String s = decimalValue.toPlainString();
params.put(key, s);
} else {
logger.warn("not a string or big decimal value key '{}' value '{}' {}", key, value,
feature = DATA;
}
} else if (productKey.equals(PLM_PRODUCT_KEY)) {
- String parts[] = feature.split("#");
+ String[] parts = feature.split("#");
if (parts.length == 2 && parts[0].equalsIgnoreCase(InsteonBindingConstants.BROADCAST_ON_OFF)
&& parts[1].matches("^\\d+$")) {
params.put(GROUP, parts[1]);
byte b2 = array[offset + 1];
byte b3 = array[offset + 2];
byte b4 = array[offset + 3];
- int value = ((b1 << 24) + (b2 << 16) + (b3 << 8) + (b4 << 0));
- return value;
+ return ((b1 << 24) + (b2 << 16) + (b3 << 8) + (b4 << 0));
}
/**
*/
@Override
public boolean equals(@Nullable Object o) {
- if (o instanceof Field) {
- Field f = (Field) o;
+ if (o instanceof Field f) {
return (f.getName().equals(getName())) && (f.getOffset() == getOffset());
} else {
return false;
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
- if (node.getNodeName().equals("msg")) {
+ if ("msg".equals(node.getNodeName())) {
Pair<String, Msg> msgDef = readMessageDefinition((Element) node);
messageMap.put(msgDef.getKey(), msgDef.getValue());
}
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
- if (node.getNodeName().equals("header")) {
+ if ("header".equals(node.getNodeName())) {
int o = readHeaderElement((Element) node, fieldMap);
hlength = o;
// Increment the offset by the header length
// Now we have field, only need value
String sVal = field.getTextContent();
Object val = DataTypeParser.parseDataType(dType, sVal);
- Pair<Field, Object> pair = new Pair<>(f, val);
- return pair;
+ return new Pair<>(f, val);
}
private static Msg createMsg(HashMap<Field, Object> values, int length, int headerLength, Msg.Direction dir)
} else {
throw new FieldException("data is null");
}
- if (!f.getName().equals("")) {
+ if (!"".equals(f.getName())) {
msg.addField(f);
}
}
@NonNullByDefault
public class Utils {
public static String getHexString(int b) {
- String result = String.format("%02X", b & 0xFF);
- return result;
+ return String.format("%02X", b & 0xFF);
}
public static String getHexString(byte[] b) {
}
public static byte parseByte(@Nullable String val) {
- if (val != null && !val.trim().equals("")) {
+ if (val != null && !"".equals(val.trim())) {
return (byte) Utils.from0xHexString(val.trim());
} else {
return 0x00;
}
public static int parseInt(@Nullable String val) {
- if (val != null && !val.trim().equals("")) {
+ if (val != null && !"".equals(val.trim())) {
return Integer.parseInt(val);
} else {
return 0x00;
}
public static float parseFloat(@Nullable String val) {
- if (val != null && !val.trim().equals("")) {
+ if (val != null && !"".equals(val.trim())) {
return Float.parseFloat(val.trim());
} else {
return 0;
}
public static InsteonAddress parseAddress(@Nullable String val) {
- if (val != null && !val.trim().equals("")) {
+ if (val != null && !"".equals(val.trim())) {
return InsteonAddress.parseAddress(val.trim());
} else {
return new InsteonAddress();
}
break;
case CHANNEL_TYPE_TARGETTEMP:
- if (command instanceof QuantityType) {
- QuantityType<?> celsiusTemperature = (QuantityType<?>) command;
- celsiusTemperature = celsiusTemperature.toUnit(SIUnits.CELSIUS);
+ if (command instanceof QuantityType quantityCommand) {
+ QuantityType<?> celsiusTemperature = quantityCommand.toUnit(SIUnits.CELSIUS);
if (celsiusTemperature != null) {
double doubleValue = celsiusTemperature.doubleValue();
logger.trace("targetTemp double value = {}", doubleValue);
break;
case CHANNEL_TYPE_TARGETTEMP:
uid = 9;
- if (command instanceof QuantityType) {
- QuantityType<?> newVal = (QuantityType<?>) command;
+ if (command instanceof QuantityType newVal) {
newVal = newVal.toUnit(SIUnits.CELSIUS);
if (newVal != null) {
value = newVal.intValue() * 10;
if (data != null) {
Id id = gson.fromJson(data.id, Id.class);
if (id != null) {
- sessionId[0] = id.sessionID.toString();
+ sessionId[0] = id.sessionID;
}
}
});
public @Nullable String logout(String sessionId) {
String contentString = "{\"command\":\"logout\",\"data\":{\"sessionID\":\"" + sessionId + "\"}}";
- String response = api.postRequest(config.ipAddress, contentString);
- return response;
+ return api.postRequest(config.ipAddress, contentString);
}
public void populateProperties() {
switch (element.uid) {
case 1:
updateState(CHANNEL_TYPE_POWER,
- String.valueOf(element.value).equals("0") ? OnOffType.OFF : OnOffType.ON);
+ "0".equals(String.valueOf(element.value)) ? OnOffType.OFF : OnOffType.ON);
break;
case 2:
switch (element.value) {
break;
case 14:
updateState(CHANNEL_TYPE_ERRORSTATUS,
- String.valueOf(element.value).equals("0") ? OnOffType.OFF : OnOffType.ON);
+ "0".equals(String.valueOf(element.value)) ? OnOffType.OFF : OnOffType.ON);
break;
case 15:
updateState(CHANNEL_TYPE_ERRORCODE, StringType.valueOf(String.valueOf(element.value)));
// If a camera does not need to poll a request as often as snapshots, it can be
// added here. Binding steps through the list.
public ArrayList<String> getLowPriorityRequests() {
- ArrayList<String> lowPriorityRequests = new ArrayList<String>(1);
- return lowPriorityRequests;
+ return new ArrayList<String>(1);
}
}
// If a camera does not need to poll a request as often as snapshots, it can be
// added here. Binding steps through the list.
public ArrayList<String> getLowPriorityRequests() {
- ArrayList<String> lowPriorityRequests = new ArrayList<String>(1);
- return lowPriorityRequests;
+ return new ArrayList<String>(1);
}
}
for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr
.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
- if (!inetAddress.isLoopbackAddress() && inetAddress.getHostAddress().toString().length() < 18
+ if (!inetAddress.isLoopbackAddress() && inetAddress.getHostAddress().length() < 18
&& inetAddress.isSiteLocalAddress()) {
- ipAddress = inetAddress.getHostAddress().toString();
+ ipAddress = inetAddress.getHostAddress();
}
}
}
ipCameraHandler.sendHttpGET("/param.cgi?cmd=setaudioalarmattr&enable=0");
} else if (OnOffType.ON.equals(command)) {
ipCameraHandler.sendHttpGET("/param.cgi?cmd=setaudioalarmattr&enable=1");
- } else if (command instanceof PercentType) {
- int value = ((PercentType) command).toBigDecimal().divide(BigDecimal.TEN).intValue();
+ } else if (command instanceof PercentType percentCommand) {
+ int value = percentCommand.toBigDecimal().divide(BigDecimal.TEN).intValue();
ipCameraHandler.sendHttpGET("/param.cgi?cmd=setaudioalarmattr&enable=1&threshold=" + value);
}
return;
ipCameraHandler.sendHttpGET("/cgi-bin/hi3510/param.cgi?cmd=setaudioalarmattr&-aa_enable=0");
} else if (OnOffType.ON.equals(command)) {
ipCameraHandler.sendHttpGET("/cgi-bin/hi3510/param.cgi?cmd=setaudioalarmattr&-aa_enable=1");
- } else if (command instanceof PercentType) {
- int value = ((PercentType) command).toBigDecimal().divide(BigDecimal.TEN).intValue();
+ } else if (command instanceof PercentType percentCommand) {
+ int value = percentCommand.toBigDecimal().divide(BigDecimal.TEN).intValue();
ipCameraHandler.sendHttpGET(
"/cgi-bin/hi3510/param.cgi?cmd=setaudioalarmattr&-aa_enable=1&-aa_value=" + value * 10);
}
public static final String INSTAR_HANDLER = "instarHandler";
public static final String REOLINK_HANDLER = "reolinkHandler";
- public static enum FFmpegFormat {
+ public enum FFmpegFormat {
HLS,
GIF,
RECORD,
if (msg == null || ctx == null) {
return;
}
- if (msg instanceof HttpResponse) {
- HttpResponse response = (HttpResponse) msg;
+ if (msg instanceof HttpResponse response) {
if (response.status().code() == 401) {
ctx.close();
if (!response.headers().isEmpty()) {
String authenticate = "";
for (CharSequence name : response.headers().names()) {
for (CharSequence value : response.headers().getAll(name)) {
- if (name.toString().equalsIgnoreCase("WWW-Authenticate")) {
+ if ("WWW-Authenticate".equalsIgnoreCase(name.toString())) {
authenticate = value.toString();
}
}
ipCameraHandler.sendHttpPOST("/api.cgi?cmd=SetWhiteLed" + ipCameraHandler.reolinkAuth,
"[{\"cmd\": \"SetWhiteLed\",\"param\": {\"WhiteLed\": {\"state\": 1,\"channel\": "
+ ipCameraHandler.cameraConfig.getNvrChannel() + ",\"mode\": 1}}}]");
- } else if (command instanceof PercentType) {
- int value = ((PercentType) command).toBigDecimal().intValue();
+ } else if (command instanceof PercentType percentCommand) {
+ int value = percentCommand.toBigDecimal().intValue();
ipCameraHandler.sendHttpPOST("/api.cgi?cmd=SetWhiteLed" + ipCameraHandler.reolinkAuth,
"[{\"cmd\": \"SetWhiteLed\",\"param\": {\"WhiteLed\": {\"state\": 1,\"channel\": "
+ ipCameraHandler.cameraConfig.getNvrChannel() + ",\"mode\": 1,\"bright\": " + value
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
return;
}
try {
- if (msg instanceof HttpResponse) {
- HttpResponse response = (HttpResponse) msg;
+ if (msg instanceof HttpResponse response) {
if (response.status().code() == 200) {
if (!response.headers().isEmpty()) {
for (String name : response.headers().names()) {
return;
}
}
- if (msg instanceof HttpContent) {
- HttpContent content = (HttpContent) msg;
+ if (msg instanceof HttpContent content) {
if (mjpegUri.equals(requestUrl) && !(content instanceof LastHttpContent)) {
// multiple MJPEG stream packets come back as this.
byte[] chunkedFrame = new byte[content.content().readableBytes()];
if (ctx == null) {
return;
}
- if (evt instanceof IdleStateEvent) {
- IdleStateEvent e = (IdleStateEvent) evt;
+ if (evt instanceof IdleStateEvent e) {
// If camera does not use the channel for X amount of time it will close.
if (e.state() == IdleState.READER_IDLE) {
String urlToKeepOpen = "";
} else if (OnOffType.OFF.equals(command) || DecimalType.ZERO.equals(command)) {
ffmpegMotionAlarmEnabled = false;
noMotionDetected(CHANNEL_FFMPEG_MOTION_ALARM);
- } else if (command instanceof PercentType) {
+ } else if (command instanceof PercentType percentCommand) {
ffmpegMotionAlarmEnabled = true;
- motionThreshold = ((PercentType) command).toBigDecimal();
+ motionThreshold = percentCommand.toBigDecimal();
}
setupFfmpegFormat(FFmpegFormat.RTSP_ALARMS);
return;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(IpCameraActions.class);
+ return Set.of(IpCameraActions.class);
}
}
return;
}
try {
- if (msg instanceof HttpContent) {
- HttpContent content = (HttpContent) msg;
+ if (msg instanceof HttpContent content) {
incomingMessage += content.content().toString(CharsetUtil.UTF_8);
}
if (msg instanceof LastHttpContent) {
@NonNullByDefault
public class OnvifConnection {
- public static enum RequestType {
+ public enum RequestType {
AbsoluteMove,
AddPTZConfiguration,
ContinuousMoveLeft,
for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr
.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
- if (!inetAddress.isLoopbackAddress() && inetAddress.getHostAddress().toString().length() < 18
+ if (!inetAddress.isLoopbackAddress() && inetAddress.getHostAddress().length() < 18
&& inetAddress.isSiteLocalAddress()) {
if (inetAddress.getHostAddress().equals(primaryHostAddress)) {
results.add(networkInterface);
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 IpObserverDiscoveryJob(this, host));
}
String name = (String) config.get(PRINTER_PARAMETER_NAME);
try {
Object obj = config.get(PRINTER_PARAMETER_URL);
- if (obj instanceof URL) {
- url = (URL) obj;
- } else if (obj instanceof String) {
- url = new URL((String) obj);
+ if (obj instanceof URL newUrl) {
+ url = newUrl;
+ } else if (obj instanceof String urlString) {
+ url = new URL(urlString);
}
printer = new CupsPrinter(null, url, name);
} catch (MalformedURLException e) {
import static org.openhab.binding.irobot.internal.IRobotBindingConstants.THING_TYPE_ROOMBA;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@NonNullByDefault
public class IRobotHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_ROOMBA);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_ROOMBA);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
}
public boolean cycleEnabled(int i) {
- return cycle[i].equals("start");
+ return "start".equals(cycle[i]);
}
public void enableCycle(int i, boolean enable) {
* @return the byte buffer in Hex format
*/
public ByteBuffer toHEXByteBuffer() {
- byte hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
+ byte[] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
ByteBuffer byteBuffer = toByteBuffer();
byte[] toConvert = new byte[byteBuffer.limit()];
@Override
public void setThingHandler(@Nullable ThingHandler thingHandler) {
- if (thingHandler instanceof JablotronBridgeHandler) {
- bridgeHandler = (JablotronBridgeHandler) thingHandler;
+ if (thingHandler instanceof JablotronBridgeHandler bridgeHandler) {
+ this.bridgeHandler = bridgeHandler;
}
}
import static org.openhab.binding.jablotron.JablotronBindingConstants.*;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
+import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(JablotronDiscoveryService.class);
+ return Set.of(JablotronDiscoveryService.class);
}
@Override
* @author Volker Bier - Initial contribution
*/
public class Ec3kReadingConverter implements JeeLinkReadingConverter<Ec3kReading> {
- private static final Pattern LINE_P = Pattern
- .compile("OK\\s+22\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)"
- + "\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)"
- + "\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)");
+ private static final Pattern LINE_P = Pattern.compile("""
+ OK\\s+22\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\
+ \\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\
+ \\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\\s+([0-9]+)\
+ """);
@Override
public Ec3kReading createReading(String inputLine) {
@Override
public ReadingPublisher<LgwReading> createPublisher() {
- ReadingPublisher<LgwReading> publisher = new ReadingPublisher<LgwReading>() {
+ return new ReadingPublisher<LgwReading>() {
@Override
public void publish(LgwReading reading) {
if (reading != null && getThing().getStatus() == ThingStatus.ONLINE) {
public void dispose() {
}
};
-
- return publisher;
}
}
@Override
public ReadingPublisher<Tx22Reading> createPublisher() {
- ReadingPublisher<Tx22Reading> publisher = new ReadingPublisher<Tx22Reading>() {
+ return new ReadingPublisher<Tx22Reading>() {
@Override
public void publish(Tx22Reading reading) {
if (reading != null && getThing().getStatus() == ThingStatus.ONLINE) {
public void dispose() {
}
};
-
- return publisher;
}
}
command);
if (channelUid.getIdWithoutGroup().equals(SWITCHING_STATE_CHANNEL)) {
- if (command instanceof OnOffType) {
- sendCommandRetry((OnOffType) command);
+ if (command instanceof OnOffType onOffCommand) {
+ sendCommandRetry(onOffCommand);
} else {
sendCommand(command);
}
* @author Volker Bier - Initial contribution
*/
public class RevoltReadingConverter implements JeeLinkReadingConverter<RevoltReading> {
- private static final Pattern LINE_P = Pattern
- .compile("r([0-9A-Za-z]{4})([0-9A-Za-z]{2})([0-9A-Za-z]{4})([0-9A-Za-z]{2})([0-9A-Za-z]{4})"
- + "([0-9A-Za-z]{2})([0-9A-Za-z]{4})[0-9A-Za-z][0-9A-Za-z]");
+ private static final Pattern LINE_P = Pattern.compile("""
+ r([0-9A-Za-z]{4})([0-9A-Za-z]{2})([0-9A-Za-z]{4})([0-9A-Za-z]{2})([0-9A-Za-z]{4})\
+ ([0-9A-Za-z]{2})([0-9A-Za-z]{4})[0-9A-Za-z][0-9A-Za-z]\
+ """);
@Override
public RevoltReading createReading(String inputLine) {
@Override
public ReadingPublisher<RevoltReading> createPublisher() {
- ReadingPublisher<RevoltReading> publisher = new ReadingPublisher<RevoltReading>() {
+ return new ReadingPublisher<RevoltReading>() {
@Override
public void publish(RevoltReading reading) {
if (reading != null && getThing().getStatus() == ThingStatus.ONLINE) {
public void dispose() {
}
};
-
- return publisher;
}
}
@Override
protected synchronized void removeHandler(ThingHandler thingHandler) {
- if (thingHandler instanceof JellyfinServerHandler) {
- var serverHandler = (JellyfinServerHandler) thingHandler;
+ if (thingHandler instanceof JellyfinServerHandler serverHandler) {
unregisterAuthenticationServlet(serverHandler);
}
super.removeHandler(thingHandler);
@Override
public void setThingHandler(ThingHandler thingHandler) {
- if (thingHandler instanceof JellyfinServerHandler) {
- bridgeHandler = (JellyfinServerHandler) thingHandler;
+ if (thingHandler instanceof JellyfinServerHandler bridgeHandler) {
+ this.bridgeHandler = bridgeHandler;
}
}
return null;
}
+ @Override
public void activate() {
activate(new HashMap<>());
}
new SystemApi(jellyClient).getPublicSystemInfo(asyncResponse);
try {
var publicSystemInfo = asyncResponse.awaitContent();
- discoverServer(uri.getHost(), uri.getPort(), uri.getScheme().equalsIgnoreCase("https"), uri.getPath(),
+ discoverServer(uri.getHost(), uri.getPort(), "https".equalsIgnoreCase(uri.getScheme()), uri.getPath(),
publicSystemInfo);
} catch (SyncCallback.SyncCallbackError | ApiClientException e) {
logger.warn("Discovery error: {}", e.getMessage());
private UUID parseItemUUID(Command command) throws NumberFormatException {
var itemId = command.toFullString().replace("-", "");
- UUID itemUUID = new UUID(new BigInteger(itemId.substring(0, 16), 16).longValue(),
+ return new UUID(new BigInteger(itemId.substring(0, 16), 16).longValue(),
new BigInteger(itemId.substring(16), 16).longValue());
- return itemUUID;
}
@Override
var typeMatcher = typeSearchPattern.matcher(terms);
boolean searchByTypeEnabled = typeMatcher.matches();
var type = searchByTypeEnabled ? typeMatcher.group("type") : "";
- boolean movieSearchEnabled = !searchByTypeEnabled || type.equals("movie");
- boolean seriesSearchEnabled = !searchByTypeEnabled || type.equals("series");
- boolean episodeSearchEnabled = !searchByTypeEnabled || type.equals("episode");
+ boolean movieSearchEnabled = !searchByTypeEnabled || "movie".equals(type);
+ boolean seriesSearchEnabled = !searchByTypeEnabled || "series".equals(type);
+ boolean episodeSearchEnabled = !searchByTypeEnabled || "episode".equals(type);
var searchTerms = searchByTypeEnabled ? typeMatcher.group("terms") : terms;
runItemSearchByType(searchTerms, playCommand, movieSearchEnabled, seriesSearchEnabled, episodeSearchEnabled);
}
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Objects;
+import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(JellyfinClientDiscoveryService.class);
+ return Set.of(JellyfinClientDiscoveryService.class);
}
public String getServerUrl() {
logger.warn("Api error: {}", e.getMessage());
var cause = e.getCause();
boolean unauthenticated = false;
- if (cause instanceof InvalidStatusException) {
- var status = ((InvalidStatusException) cause).getStatus();
+ if (cause instanceof InvalidStatusException invalidStatusException) {
+ var status = invalidStatusException.getStatus();
if (status == 401) {
unauthenticated = true;
}
if (handler == null) {
return;
}
- if (handler instanceof JellyfinClientHandler) {
- updateClientState((JellyfinClientHandler) handler, sessions);
+ if (handler instanceof JellyfinClientHandler clientHandler) {
+ updateClientState(clientHandler, sessions);
} else {
logger.warn("Found unknown thing-handler instance: {}", handler);
}
return awaitResult();
} catch (SyncCallbackError e) {
var cause = e.getCause();
- if (cause instanceof ApiClientException) {
- throw (ApiClientException) cause;
+ if (cause instanceof ApiClientException apiClientException) {
+ throw apiClientException;
}
throw e;
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof JuiceNetBridgeHandler) {
- JuiceNetBridgeHandler bridgeHandler = (JuiceNetBridgeHandler) handler;
+ if (handler instanceof JuiceNetBridgeHandler bridgeHandler) {
bridgeHandler.setDiscoveryService(this);
this.bridgeHandler = bridgeHandler;
} else {
import static org.openhab.binding.juicenet.internal.JuiceNetBindingConstants.*;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
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(JuiceNetDiscoveryService.class);
+ return Set.of(JuiceNetDiscoveryService.class);
}
public void handleApiException(Exception e) {
input.close();
writer.close();
output.close();
- socket.close();
} catch (IOException e) {
logger.debug("isKaleidescapeDevice() IOException: {}", e.getMessage());
}
import java.util.Arrays;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singletonList(KaleidescapeThingActions.class);
+ return List.of(KaleidescapeThingActions.class);
}
public void handleRawCommand(@Nullable String command) {
}
break;
case VOLUME:
- if (command instanceof PercentType) {
- this.volume = (int) ((PercentType) command).doubleValue();
+ if (command instanceof PercentType percentCommand) {
+ this.volume = (int) percentCommand.doubleValue();
logger.debug("Got volume command {}", this.volume);
connector.sendCommand(SEND_EVENT_VOLUME_LEVEL_EQ + this.volume);
}
import static org.openhab.binding.keba.internal.KebaBindingConstants.THING_TYPE_KECONTACTP20;
-import java.util.Collections;
import java.util.Set;
import org.openhab.binding.keba.internal.handler.KeContactHandler;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.keba")
public class KebaHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_KECONTACTP20);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_KECONTACTP20);
private final KeContactTransceiver transceiver = new KeContactTransceiver();
updateState(CHANNEL_MAX_SYSTEM_CURRENT, newState);
if (maxSystemCurrent != 0) {
if (maxSystemCurrent < maxPresetCurrent) {
- transceiver.send("curr " + String.valueOf(maxSystemCurrent), this);
+ transceiver.send("curr " + maxSystemCurrent, this);
updateState(CHANNEL_MAX_PRESET_CURRENT,
new QuantityType<ElectricCurrent>(maxSystemCurrent / 1000.0, Units.AMPERE));
updateState(CHANNEL_MAX_PRESET_CURRENT_RANGE, new QuantityType<Dimensionless>(
} else {
switch (channelUID.getId()) {
case CHANNEL_MAX_PRESET_CURRENT: {
- if (command instanceof QuantityType<?>) {
- QuantityType<?> value = ((QuantityType<?>) command).toUnit("mA");
+ if (command instanceof QuantityType<?> quantityCommand) {
+ QuantityType<?> value = quantityCommand.toUnit("mA");
- transceiver.send(
- "curr " + String.valueOf(Math.min(Math.max(6000, value.intValue()), maxSystemCurrent)),
- this);
+ transceiver.send("curr " + Math.min(Math.max(6000, value.intValue()), maxSystemCurrent), this);
}
break;
}
newValue = maxSystemCurrent;
} else if (command == OnOffType.OFF) {
newValue = 6000;
- } else if (command instanceof QuantityType<?>) {
- QuantityType<?> value = ((QuantityType<?>) command).toUnit("%");
+ } else if (command instanceof QuantityType<?> quantityCommand) {
+ QuantityType<?> value = quantityCommand.toUnit("%");
newValue = Math.round(6000 + (maxSystemCurrent - 6000) * value.doubleValue() / 100.0);
} else {
return;
}
- transceiver.send("curr " + String.valueOf(newValue), this);
+ transceiver.send("curr " + newValue, this);
}
break;
}
break;
}
case CHANNEL_SETENERGY: {
- if (command instanceof QuantityType<?>) {
- QuantityType<?> value = ((QuantityType<?>) command).toUnit(Units.WATT_HOUR);
+ if (command instanceof QuantityType<?> quantityCommand) {
+ QuantityType<?> value = quantityCommand.toUnit(Units.WATT_HOUR);
transceiver.send(
- "setenergy " + String.valueOf(
- Math.min(Math.max(0, Math.round(value.doubleValue() * 10.0)), 999999999)),
+ "setenergy " + Math.min(Math.max(0, Math.round(value.doubleValue() * 10.0)), 999999999),
this);
}
break;
private void establishConnection(KeContactHandler handler) {
String ipAddress = handler.getIPAddress();
if (handler.getThing().getStatusInfo().getStatusDetail() != ThingStatusDetail.CONFIGURATION_ERROR
- && !ipAddress.equals("")) {
+ && !"".equals(ipAddress)) {
logger.debug("Establishing the connection to the KEBA KeContact '{}'", handler.getThing().getUID());
DatagramChannel datagramChannel = null;
String decodedData = null;
JsonObject nodeRoot = null;
logger.debug("{}: trying to query information.", service);
- byte[] recData = deviceCommunicator.getDataFromService(service.toString());
+ byte[] recData = deviceCommunicator.getDataFromService(service);
try {
if (recData == null) {
logger.debug("Communication to {} is not possible!", service);
logger.warn("{}: SERVICE NOT AVAILABLE", service);
return null;
} else {
- logger.debug("{}: trying to parse {}", service, decodedData.toString());
+ logger.debug("{}: trying to parse {}", service, decodedData);
nodeRoot = (JsonObject) JsonParser.parseString(decodedData);
}
} else {
}
switch (type) {
case DATA_TYPE_STRING_VALUE: /* Check whether the type is a single value containing a string value */
- logger.debug("parseJSONData type string value: {} Type: {}", nodeRoot, itemType.toString());
+ logger.debug("parseJSONData type string value: {} Type: {}", nodeRoot, itemType);
String sVal = nodeRoot.get("value").getAsString();
object.setValue(sVal);
/* Switch Binding */
private final Logger logger = LoggerFactory.getLogger(KM200GatewayHandler.class);
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_KMDEVICE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_KMDEVICE);
private final Map<Channel, JsonObject> sendMap = Collections.synchronizedMap(new LinkedHashMap<>());
try {
date = new SimpleDateFormat(TIME_DAY_FORMAT, Locale.US).parse(value);
} catch (ParseException pe) {
- try {
- date = new SimpleDateFormat(TIME_FORMAT, Locale.US).parse(value);
- } catch (ParseException pe2) {
- throw pe2;
- }
+ date = new SimpleDateFormat(TIME_FORMAT, Locale.US).parse(value);
}
return DateTimeType.valueOf(new SimpleDateFormat(DateTimeType.DATE_PATTERN).format(date));
}
if (oldFuture != null) {
oldFuture.cancel(true);
}
- if (value instanceof IncreaseDecreaseType type) {
- channelFutures.put(channelUID, scheduler.scheduleWithFixedDelay(
- () -> postCommand(channelUID, type), 0, frequency, TimeUnit.MILLISECONDS));
+ if (value instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ channelFutures.put(channelUID,
+ scheduler.scheduleWithFixedDelay(() -> postCommand(channelUID, increaseDecreaseCommand),
+ 0, frequency, TimeUnit.MILLISECONDS));
}
} else {
if (value instanceof Command command) {
public @NonNull CompletableFuture<@Nullable Void> processAndComplete(@Nullable AudioStream audioStream) {
// we override this method to intercept URLAudioStream and handle it asynchronously. We won't wait for it to
// play through the end as it can be very long
- if (audioStream instanceof URLAudioStream) {
+ if (audioStream instanceof URLAudioStream stream) {
// Asynchronous handling for URLAudioStream. Id it is an external URL, the speaker can access it itself and
// play it. There will be no volume restoration or call to dispose / complete, but there is no need to.
- String url = ((URLAudioStream) audioStream).getURL();
+ String url = stream.getURL();
AudioFormat format = audioStream.getFormat();
logger.trace("Processing audioStream URL {} of format {}.", url, format);
handler.playURI(new StringType(url));
*/
package org.openhab.binding.kodi.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_KODI = new ThingTypeUID(BINDING_ID, "kodi");
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_KODI);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_KODI);
// List of thing parameters names
public static final String HOST_PARAMETER = "ipAddress";
Map<String, Object> properties = new HashMap<>();
properties.put(HOST_PARAMETER, device.getIdentity().getDescriptorURL().getHost());
- DiscoveryResult result = DiscoveryResultBuilder.create(thingUid).withLabel(label)
- .withProperties(properties).withRepresentationProperty(HOST_PARAMETER).build();
-
- return result;
+ return DiscoveryResultBuilder.create(thingUid).withLabel(label).withProperties(properties)
+ .withRepresentationProperty(HOST_PARAMETER).build();
}
}
return null;
private int getIntConfigParameter(String key, int defaultValue) {
Object obj = this.getConfig().get(key);
- if (obj instanceof Number) {
- return ((Number) obj).intValue();
+ if (obj instanceof Number numberValue) {
+ return numberValue.intValue();
} else if (obj instanceof String) {
return Integer.parseInt(obj.toString());
}
}
break;
case CHANNEL_VOLUME:
- if (command instanceof PercentType) {
- connection.setVolume(((PercentType) command).intValue());
+ if (command instanceof PercentType percentCommand) {
+ connection.setVolume(percentCommand.intValue());
} else if (command.equals(IncreaseDecreaseType.INCREASE)) {
connection.increaseVolume();
} else if (command.equals(IncreaseDecreaseType.DECREASE)) {
}
break;
case CHANNEL_PLAYNOTIFICATION:
- if (command instanceof StringType) {
- playNotificationSoundURI((StringType) command, true);
+ if (command instanceof StringType stringCommand) {
+ playNotificationSoundURI(stringCommand, true);
updateState(CHANNEL_PLAYNOTIFICATION, UnDefType.UNDEF);
} else if (command.equals(RefreshType.REFRESH)) {
updateState(CHANNEL_PLAYNOTIFICATION, UnDefType.UNDEF);
case CHANNEL_AUDIO_CODEC:
break;
case CHANNEL_AUDIO_INDEX:
- if (command instanceof DecimalType) {
- connection.setAudioStream(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ connection.setAudioStream(decimalCommand.intValue());
}
break;
case CHANNEL_VIDEO_CODEC:
case CHANNEL_VIDEO_INDEX:
- if (command instanceof DecimalType) {
- connection.setVideoStream(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ connection.setVideoStream(decimalCommand.intValue());
}
break;
case CHANNEL_SUBTITLE_ENABLED:
}
break;
case CHANNEL_SUBTITLE_INDEX:
- if (command instanceof DecimalType) {
- connection.setSubtitle(((DecimalType) command).intValue());
+ if (command instanceof DecimalType decimalCommand) {
+ connection.setSubtitle(decimalCommand.intValue());
}
break;
case CHANNEL_CURRENTTIME:
- if (command instanceof QuantityType) {
- connection.setTime(((QuantityType<?>) command).intValue());
+ if (command instanceof QuantityType quantityCommand) {
+ connection.setTime(quantityCommand.intValue());
}
break;
case CHANNEL_CURRENTTIMEPERCENTAGE:
private synchronized JsonArray getPlaylistsInternal() {
String method = "Playlist.GetPlaylists";
String hash = hostname + '#' + method;
- JsonElement response = REQUEST_CACHE.putIfAbsentAndGet(hash, () -> {
- return socket.callMethod(method);
- });
+ JsonElement response = REQUEST_CACHE.putIfAbsentAndGet(hash, () -> socket.callMethod(method));
if (response instanceof JsonArray) {
return response.getAsJsonArray();
@Override
protected @Nullable ThingHandler createHandler(Thing thing) {
-
KonnectedHandler thingHandler = new KonnectedHandler(thing, getCallbackUrl());
if (servlet != null) {
logger.debug("Adding thinghandler for thing {} to webhook.", thing.getUID().getId());
Map<String, Object> properties = new HashMap<>();
properties.put(BASE_URL, device.getDetails().getBaseURL());
properties.put(MAC_ADDR, device.getDetails().getSerialNumber());
- DiscoveryResult result = DiscoveryResultBuilder.create(uid).withProperties(properties)
+ return DiscoveryResultBuilder.create(uid).withProperties(properties)
.withLabel(device.getDetails().getFriendlyName()).withRepresentationProperty(MAC_ADDR).build();
- return result;
} else {
return null;
}
String zone = zoneConfig.zone;
logger.debug("The channelUID is: {} and the zone is : {}", channelUID.getAsString(), zone);
// if the command is OnOfftype
- if (command instanceof OnOffType) {
+ if (command instanceof OnOffType onOffCommand) {
if (channelType.contains(CHANNEL_SWITCH)) {
logger.debug("A command was sent to a sensor type so we are ignoring the command");
} else {
- sendActuatorCommand((OnOffType) command, zone, channelUID);
+ sendActuatorCommand(onOffCommand, zone, channelUID);
}
} else if (command instanceof RefreshType) {
// check to see if handler has been initialized before attempting to get state of pin, else wait one minute
// https://github.com/eclipse/smarthome/issues/3484 has been implemented in the framework
String[] cfg = configurationParameter.getKey().split("_");
if ("controller".equals(cfg[0])) {
- if (cfg[1].equals("softreset") && value instanceof Boolean && (Boolean) value) {
+ if ("softreset".equals(cfg[1]) && value instanceof Boolean bool && bool) {
scheduler.execute(() -> {
try {
http.doGet(baseUrl + "/settings?restart=true", null, retryCount);
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
}
});
- } else if (cfg[1].equals("removewifi") && value instanceof Boolean && (Boolean) value) {
+ } else if ("removewifi".equals(cfg[1]) && value instanceof Boolean bool && bool) {
scheduler.execute(() -> {
try {
http.doGet(baseUrl + "/settings?restore=true", null, retryCount);
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
}
});
- } else if (cfg[1].equals("sendConfig") && value instanceof Boolean && (Boolean) value) {
+ } else if ("sendConfig".equals(cfg[1]) && value instanceof Boolean bool && bool) {
scheduler.execute(() -> {
try {
String response = updateKonnectedModule();
private void getSwitchState(String zone, ChannelUID channelId) {
Channel channel = getThing().getChannel(channelId.getId());
- if (!(channel == null)) {
+ if (channel != null) {
logger.debug("getasstring: {} getID: {} getGroupId: {} toString:{}", channelId.getAsString(),
channelId.getId(), channelId.getGroupId(), channelId);
KonnectedModuleGson payload = new KonnectedModuleGson();
sessionId = extractSessionId(getAuthenticateResponseJsonObject);
- JsonObject authenticateJsonObject = JsonParser.parseString(getAuthenticateResponse.toString())
- .getAsJsonObject();
+ JsonObject authenticateJsonObject = JsonParser.parseString(getAuthenticateResponse).getAsJsonObject();
salt = authenticateJsonObject.get("salt").getAsString();
String saltedPassword = new StringBuilder(password).append(salt).toString();
int codeStartPosition = jsonResponse.indexOf("code");
transformStringBuilder.insert(codeStartPosition + 11, ']');
- String transformJsonObject = transformStringBuilder.toString();
-
- return transformJsonObject;
+ return transformStringBuilder.toString();
}
// Method extractSessionId extracts sessionId from JsonObject
valueConfiguration);
break;
case SecondGenerationBindingConstants.CHANNEL_SMARTBATTERYCONTROLSET:
- if (command.toString().equals("ON")) {
+ if ("ON".equals(command.toString())) {
valueConfiguration = "true";
}
- if (command.toString().equals("OFF")) {
+ if ("OFF".equals(command.toString())) {
valueConfiguration = "false";
}
dxsEntriesConf = "33556484";
String channel = cConfig.id;
String value = channelPostsConfigurable[channelValuesCounterConfigurable];
int dxsEntriesCheckCounter = 3;
- if (cConfig.dxsEntries.equals("33556484")) {
+ if ("33556484".equals(cConfig.dxsEntries)) {
dxsEntriesCheckCounter = 1;
}
- if (cConfig.dxsEntries.equals("33556482")) {
+ if ("33556482".equals(cConfig.dxsEntries)) {
dxsEntriesCheckCounter = 2;
}
switch (dxsEntriesCheckCounter) {
* @return the latest {@link DepartureResult}.
*/
public synchronized @Nullable DepartureResult queryKVV(final KVVStopConfig stopConfig) {
-
// is there an up-to-date value in the cache?
final DepartureResult cr = this.cache.get(stopConfig.stopId);
if (cr != null) {
/**
* Feature authentication mode.
*/
- static enum Mode {
+ enum Mode {
/**
* Basic preemptive.
**/
}
String userName = (String) request.getProperty(usernameKey);
- if (userName != null && !userName.equals("")) {
+ if (userName != null && !"".equals(userName)) {
byte[] pwdBytes;
Object password = request.getProperty(passwordKey);
- if (password instanceof byte[]) {
- pwdBytes = ((byte[]) password);
- } else if (password instanceof String) {
- pwdBytes = ((String) password).getBytes(CHARACTER_SET);
+ if (password instanceof byte[] bytes) {
+ pwdBytes = bytes;
+ } else if (password instanceof String stringValue) {
+ pwdBytes = stringValue.getBytes(CHARACTER_SET);
} else {
throw new RequestAuthenticationException("Passwort invalid.");
}
import static org.openhab.binding.lametrictime.internal.LaMetricTimeBindingConstants.THING_TYPE_DEVICE;
import static org.openhab.binding.lametrictime.internal.config.LaMetricTimeConfiguration.HOST;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(THING_TYPE_DEVICE);
+ return Set.of(THING_TYPE_DEVICE);
}
@Override
Audio audio = clock.getLocalApi().getAudio();
if (command instanceof RefreshType) {
updateState(channelUID, new PercentType(audio.getVolume()));
- } else if (command instanceof PercentType) {
+ } else if (command instanceof PercentType percentTypeCommand) {
try {
- PercentType percentTypeCommand = (PercentType) command;
int volume = percentTypeCommand.intValue();
if (volume >= 0 && volume != audio.getVolume()) {
audio.setVolume(volume);
private void updateBluetoothValue(ChannelUID channelUID, Command command, Bluetooth bluetooth) {
try {
- if (command instanceof OnOffType && channelUID.getId().equals(CHANNEL_BLUETOOTH_ACTIVE)) {
- OnOffType onOffCommand = (OnOffType) command;
+ if (command instanceof OnOffType onOffCommand && channelUID.getId().equals(CHANNEL_BLUETOOTH_ACTIVE)) {
if (onOffCommand == OnOffType.ON && !bluetooth.isActive()) {
bluetooth.setActive(true);
clock.getLocalApi().updateBluetooth(bluetooth);
private void updateDisplayValue(ChannelUID channelUID, Command command) {
try {
if (channelUID.getId().equals(CHANNEL_DISPLAY_BRIGHTNESS)) {
- if (command instanceof PercentType) {
- int brightness = ((PercentType) command).intValue();
+ if (command instanceof PercentType percentCommand) {
+ int brightness = percentCommand.intValue();
logger.debug("Set Brightness to {}.", brightness);
Display newDisplay = clock.setBrightness(brightness);
updateState(CHANNEL_DISPLAY_BRIGHTNESS_MODE, new StringType(newDisplay.getBrightnessMode()));
}
private void handleControl(final Command command) throws ApplicationActionException {
- if (command instanceof PlayPauseType) {
- switch ((PlayPauseType) command) {
+ if (command instanceof PlayPauseType playCommand) {
+ switch (playCommand) {
case PLAY:
play();
return;
}
}
- if (command instanceof NextPreviousType) {
- switch ((NextPreviousType) command) {
+ if (command instanceof NextPreviousType nextCommand) {
+ switch (nextCommand) {
case NEXT:
next();
return;
Optional<Object> outputs12 = getConfig(profileContext, "controlOutputs12");
ramp.ifPresent(b -> {
- if (b instanceof BigDecimal) {
- rampMs = (int) (((BigDecimal) b).doubleValue() * 1000);
+ if (b instanceof BigDecimal decimalValue) {
+ rampMs = (int) (decimalValue.doubleValue() * 1000);
} else {
logger.warn("Could not parse 'ramp', unexpected type, should be float: {}", ramp);
}
logger.warn("Unsupported 'ramp' setting. Will be forced to 250ms: {}", rampMs);
}
BigDecimal value;
- if (command instanceof DecimalType) {
- value = ((DecimalType) command).toBigDecimal();
- } else if (command instanceof OnOffType) {
- value = ((OnOffType) command) == OnOffType.ON ? BigDecimal.valueOf(100) : BigDecimal.ZERO;
+ if (command instanceof DecimalType decimalCommand) {
+ value = decimalCommand.toBigDecimal();
+ } else if (command instanceof OnOffType onOffCommand) {
+ value = onOffCommand == OnOffType.ON ? BigDecimal.valueOf(100) : BigDecimal.ZERO;
} else {
logger.warn("Unsupported type: {}", command.toFullString());
return;
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof PckGatewayHandler) {
- this.bridgeHandler = (PckGatewayHandler) handler;
+ if (handler instanceof PckGatewayHandler gatewayHandler) {
+ this.bridgeHandler = gatewayHandler;
}
}
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.NoSuchElementException;
import java.util.Optional;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
Object invertUpDown = channel.getConfiguration().get("invertUpDown");
// Initialize value converters
- if (unitObject instanceof String) {
- switch ((String) unitObject) {
+ if (unitObject instanceof String stringValue) {
+ switch (stringValue) {
case "power":
case "energy":
converters.put(channel.getUID(), new S0Converter(parameterObject));
if (command instanceof RefreshType) {
number.ifPresent(n -> subHandler.handleRefresh(channelGroup, n));
subHandler.handleRefresh(channelUid.getIdWithoutGroup());
- } else if (command instanceof OnOffType) {
- subHandler.handleCommandOnOff((OnOffType) command, channelGroup, number.get());
- } else if (command instanceof DimmerOutputCommand) {
- subHandler.handleCommandDimmerOutput((DimmerOutputCommand) command, number.get());
- } else if (command instanceof PercentType && number.isPresent()) {
- subHandler.handleCommandPercent((PercentType) command, channelGroup, number.get());
- } else if (command instanceof HSBType) {
- subHandler.handleCommandHsb((HSBType) command, channelUid.getIdWithoutGroup());
- } else if (command instanceof PercentType) {
- subHandler.handleCommandPercent((PercentType) command, channelGroup, channelUid.getIdWithoutGroup());
- } else if (command instanceof StringType) {
- subHandler.handleCommandString((StringType) command, number.orElse(0));
- } else if (command instanceof DecimalType) {
- DecimalType decimalType = (DecimalType) command;
- DecimalType nativeValue = getConverter(channelUid).onCommandFromItem(decimalType.doubleValue());
+ } else if (command instanceof OnOffType onOffCommand) {
+ subHandler.handleCommandOnOff(onOffCommand, channelGroup, number.get());
+ } else if (command instanceof DimmerOutputCommand outputCommand) {
+ subHandler.handleCommandDimmerOutput(outputCommand, number.get());
+ } else if (command instanceof PercentType percentCommand && number.isPresent()) {
+ subHandler.handleCommandPercent(percentCommand, channelGroup, number.get());
+ } else if (command instanceof HSBType hsbCommand) {
+ subHandler.handleCommandHsb(hsbCommand, channelUid.getIdWithoutGroup());
+ } else if (command instanceof PercentType percentCommand) {
+ subHandler.handleCommandPercent(percentCommand, channelGroup, channelUid.getIdWithoutGroup());
+ } else if (command instanceof StringType stringCommand) {
+ subHandler.handleCommandString(stringCommand, number.orElse(0));
+ } else if (command instanceof DecimalType decimalCommand) {
+ DecimalType nativeValue = getConverter(channelUid).onCommandFromItem(decimalCommand.doubleValue());
subHandler.handleCommandDecimal(nativeValue, channelGroup, number.get());
- } else if (command instanceof QuantityType) {
- QuantityType<?> quantityType = (QuantityType<?>) command;
- DecimalType nativeValue = getConverter(channelUid).onCommandFromItem(quantityType);
+ } else if (command instanceof QuantityType quantityCommand) {
+ DecimalType nativeValue = getConverter(channelUid).onCommandFromItem(quantityCommand);
subHandler.handleCommandDecimal(nativeValue, channelGroup, number.get());
- } else if (command instanceof UpDownType) {
+ } else if (command instanceof UpDownType upDownCommand) {
Channel channel = thing.getChannel(channelUid);
if (channel != null) {
Object invertConfig = channel.getConfiguration().get("invertUpDown");
- boolean invertUpDown = invertConfig instanceof Boolean && (boolean) invertConfig;
- subHandler.handleCommandUpDown((UpDownType) command, channelGroup, number.get(), invertUpDown);
+ boolean invertUpDown = invertConfig instanceof Boolean bool && bool;
+ subHandler.handleCommandUpDown(upDownCommand, channelGroup, number.get(), invertUpDown);
}
- } else if (command instanceof StopMoveType) {
- subHandler.handleCommandStopMove((StopMoveType) command, channelGroup, number.get());
+ } else if (command instanceof StopMoveType stopMoveCommand) {
+ subHandler.handleCommandStopMove(stopMoveCommand, channelGroup, number.get());
} else {
throw new LcnException("Unsupported command type");
}
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(LcnModuleActions.class);
+ return Set.of(LcnModuleActions.class);
}
/**
package org.openhab.binding.lcn.internal;
import java.util.Collection;
-import java.util.Collections;
import java.util.Locale;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
@Override
public Collection<ProfileTypeUID> getSupportedProfileTypeUIDs() {
- return Collections.singleton(DimmerOutputProfile.UID);
+ return Set.of(DimmerOutputProfile.UID);
}
@Override
public Collection<ProfileType> getProfileTypes(@Nullable Locale locale) {
- return Collections.singleton(ProfileTypeBuilder.newState(DimmerOutputProfile.UID, "Dimmer Output (%)")
+ return Set.of(ProfileTypeBuilder.newState(DimmerOutputProfile.UID, "Dimmer Output (%)")
.withSupportedItemTypes(CoreItemFactory.DIMMER, CoreItemFactory.COLOR)
.withSupportedChannelTypeUIDs(
new ChannelTypeUID(LcnBindingConstants.BINDING_ID, LcnChannelGroup.OUTPUT.name().toLowerCase()))
package org.openhab.binding.lcn.internal;
import java.util.Collection;
-import java.util.Collections;
import java.util.Optional;
+import java.util.Set;
import java.util.function.Consumer;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(LcnModuleDiscoveryService.class);
+ return Set.of(LcnModuleDiscoveryService.class);
}
@Override
OFF,
ON,
BLINK,
- FLICKER;
+ FLICKER
}
/** Possible states for LCN logic-operations. */
public enum LogicOpStatus {
NOT,
OR, // Note: Actually not correct since AND won't be OR also
- AND;
+ AND
}
/** Time units used for several LCN commands. */
SECONDS,
MINUTES,
HOURS,
- DAYS;
+ DAYS
}
/** Relay-state modifiers used in LCN commands. */
writeInProgress = false;
- if (sendQueue.size() > 0) {
+ if (!sendQueue.isEmpty()) {
/**
* This could lead to stack overflows, since the CompletionHandler may run in
* the same Thread as triggerWriteToSocket() is invoked (see
if (parameter == null) {
pulsesPerKwh = 1000;
logger.debug("Pulses per kWh not set. Assuming 1000 imp./kWh.");
- } else if (parameter instanceof BigDecimal) {
- pulsesPerKwh = ((BigDecimal) parameter).doubleValue();
+ } else if (parameter instanceof BigDecimal decimalValue) {
+ pulsesPerKwh = decimalValue.doubleValue();
} else {
logger.warn("Could not parse 'pulses', unexpected type, should be float or integer: {}", parameter);
}
*/
@Override
public State onStateUpdateFromHandler(State state) throws LcnException {
- if (state instanceof DecimalType) {
+ if (state instanceof DecimalType decimalValue) {
Unit<?> localUnit = unit;
if (localUnit != null) {
- return QuantityType.valueOf(toHumanReadable(((DecimalType) state).longValue()), localUnit);
+ return QuantityType.valueOf(toHumanReadable(decimalValue.longValue()), localUnit);
}
return state;
package org.openhab.binding.lcn.internal.subhandler;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Override
public Collection<Pattern> getPckStatusMessagePatterns() {
- return Collections.singleton(PATTERN);
+ return Set.of(PATTERN);
}
}
package org.openhab.binding.lcn.internal.subhandler;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.IntStream;
@Override
public Collection<Pattern> getPckStatusMessagePatterns() {
- return Collections.singleton(PATTERN);
+ return Set.of(PATTERN);
}
}
package org.openhab.binding.lcn.internal.subhandler;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Override
public Collection<Pattern> getPckStatusMessagePatterns() {
- return Collections.singleton(SEND_KEY_PATTERN);
+ return Set.of(SEND_KEY_PATTERN);
}
}
import java.util.Arrays;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.IntStream;
@Override
public Collection<Pattern> getPckStatusMessagePatterns() {
- return Collections.singleton(PATTERN);
+ return Set.of(PATTERN);
}
}
package org.openhab.binding.lcn.internal.subhandler;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Override
public Collection<Pattern> getPckStatusMessagePatterns() {
- return Collections.singleton(PATTERN);
+ return Set.of(PATTERN);
}
}
package org.openhab.binding.lcn.internal.subhandler;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.IntStream;
@Override
public Collection<Pattern> getPckStatusMessagePatterns() {
- return Collections.singleton(PATTERN);
+ return Set.of(PATTERN);
}
}
package org.openhab.binding.lcn.internal.subhandler;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Override
public Collection<Pattern> getPckStatusMessagePatterns() {
- return Collections.singleton(PATTERN);
+ return Set.of(PATTERN);
}
}
@Override
public void onStateUpdateFromItem(State state) {
- if (state instanceof HSBType) {
- lastState = (HSBType) state;
+ if (state instanceof HSBType hsbState) {
+ lastState = hsbState;
} else {
PercentType currentBrightness = state.as(PercentType.class);
if (currentBrightness != null) {
int hue = clockwise ? (color.getHue().toBigDecimal().intValue() - 20 + 360) % 360
: (color.getHue().toBigDecimal().intValue() + 20 + 360) % 360;
logger.debug("New hue value: {}", hue);
- HSBType newState = new HSBType(new DecimalType(hue), color.getSaturation(), color.getBrightness());
- return newState;
+ return new HSBType(new DecimalType(hue), color.getSaturation(), color.getBrightness());
}
}
import static org.openhab.binding.leapmotion.internal.LeapMotionBindingConstants.THING_TYPE_CONTROLLER;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@NonNullByDefault
public class LeapMotionHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_CONTROLLER);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_CONTROLLER);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
*/
package org.openhab.binding.leapmotion.internal.discovery;
-import java.util.Collections;
import java.util.Map;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
private @NonNullByDefault({}) Listener listener;
public LeapMotionDiscoveryService() throws IllegalArgumentException {
- super(Collections.singleton(LeapMotionBindingConstants.THING_TYPE_CONTROLLER), 10, true);
+ super(Set.of(LeapMotionBindingConstants.THING_TYPE_CONTROLLER), 10, true);
}
@Override
*/
package org.openhab.binding.lghombot.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_LGHOMBOT = new ThingTypeUID(BINDING_ID, "LGHomBot");
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_LGHOMBOT);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_LGHOMBOT);
// List of all Channel ids
static final String CHANNEL_STATE = "state";
import static org.openhab.binding.lghombot.internal.LGHomBotBindingConstants.THING_TYPE_LGHOMBOT;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.lghombot", service = ThingHandlerFactory.class)
public class LGHomBotHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_LGHOMBOT);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_LGHOMBOT);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
if (idx > 0) {
String name = msg.substring(0, idx);
- if (name.equalsIgnoreCase("JSON_NICKNAME")) {
- nickName = msg.substring(idx + 1).trim().replaceAll("\"", "");
- } else if (name.equalsIgnoreCase("JSON_VERSION")) {
- fwVersion = msg.substring(idx + 1).trim().replaceAll("\"", "");
- } else if (name.equalsIgnoreCase("LGSRV_VERSION")) {
- srvVersion = msg.substring(idx + 1).trim().replaceAll("\"", "");
+ if ("JSON_NICKNAME".equalsIgnoreCase(name)) {
+ nickName = msg.substring(idx + 1).trim().replace("\"", "");
+ } else if ("JSON_VERSION".equalsIgnoreCase(name)) {
+ fwVersion = msg.substring(idx + 1).trim().replace("\"", "");
+ } else if ("LGSRV_VERSION".equalsIgnoreCase(name)) {
+ srvVersion = msg.substring(idx + 1).trim().replace("\"", "");
}
}
this.success = success;
if (success) {
- state = data.equals("01") ? OnOffType.ON : OnOffType.OFF;
+ state = "01".equals(data) ? OnOffType.ON : OnOffType.OFF;
} else {
state = new StringType(data);
}
*/
package org.openhab.binding.lgwebos.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
public static final ThingTypeUID THING_TYPE_WEBOSTV = new ThingTypeUID(BINDING_ID, "WebOSTV");
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_WEBOSTV);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_WEBOSTV);
public static final ServiceType UPNP_SERVICE_TYPE = new ServiceType("lge-com", "webos-second-screen", 1);
case DISCONNECTED:
String macAddress = configProvider.getMacAddress();
if (macAddress.isEmpty()) {
- logger.debug("Received ON - Turning TV on via API is not supported by LG WebOS TVs. "
- + "You may succeed using wake on lan (WOL). "
- + "Please set the macAddress config value in Thing configuration to enable this.");
+ logger.debug("""
+ Received ON - Turning TV on via API is not supported by LG WebOS TVs. \
+ You may succeed using wake on lan (WOL). \
+ Please set the macAddress config value in Thing configuration to enable this.\
+ """);
handler.postUpdate(channelId, OnOffType.OFF);
} else {
for (int i = 0; i < WOL_PACKET_RETRY_COUNT; i++) {
handler.getSocket().getVolume(createResponseListener(channelId, handler));
return;
}
- if (command instanceof PercentType) {
- percent = (PercentType) command;
- } else if (command instanceof DecimalType) {
- percent = new PercentType(((DecimalType) command).toBigDecimal());
- } else if (command instanceof StringType) {
- percent = new PercentType(((StringType) command).toString());
+ if (command instanceof PercentType percentCommand) {
+ percent = percentCommand;
+ } else if (command instanceof DecimalType decimalCommand) {
+ percent = new PercentType(decimalCommand.toBigDecimal());
+ } else if (command instanceof StringType stringCommand) {
+ percent = new PercentType(stringCommand.toString());
} else {
percent = null;
}
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")) {
private List<AppInfo> getAppInfos() {
LGWebOSHandler lgWebOSHandler = getLGWebOSHandler();
- if (!this.getConnectedSocket().isPresent()) {
+ if (this.getConnectedSocket().isEmpty()) {
return Collections.emptyList();
}
LGWebOSHandler handler = null;
if (thing != null) {
thingHandler = thing.getHandler();
- if (thingHandler instanceof LGWebOSHandler) {
- handler = (LGWebOSHandler) thingHandler;
+ if (thingHandler instanceof LGWebOSHandler webOSHandler) {
+ handler = webOSHandler;
}
}
if (thing == null) {
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(LGWebOSActions.class);
+ return Set.of(LGWebOSActions.class);
}
/**
new Object[] { logId, packet.getClass().getSimpleName(), address.toString(),
packet.getTarget().getHex(), packet.getSequence(), Long.toString(packet.getSource(), 16) });
- if (packet instanceof StateServiceResponse) {
- StateServiceResponse response = (StateServiceResponse) packet;
+ if (packet instanceof StateServiceResponse response) {
MACAddress discoveredAddress = response.getTarget();
if (packetFromConfiguredHost && macAddress == null) {
macAddress = discoveredAddress;
try {
lock.lock();
- if (packet instanceof StateResponse) {
- handleLightStatus((StateResponse) packet);
- } else if (packet instanceof StatePowerResponse) {
- handlePowerStatus((StatePowerResponse) packet);
- } else if (packet instanceof StateLightPowerResponse) {
- handleLightPowerStatus((StateLightPowerResponse) packet);
- } else if (packet instanceof StateHevCycleResponse) {
- handleHevCycleStatus((StateHevCycleResponse) packet);
- } else if (packet instanceof StateLightInfraredResponse) {
- handleInfraredStatus((StateLightInfraredResponse) packet);
- } else if (packet instanceof StateMultiZoneResponse) {
- handleMultiZoneStatus((StateMultiZoneResponse) packet);
- } else if (packet instanceof StateTileEffectResponse) {
- handleTileEffectStatus((StateTileEffectResponse) packet);
- } else if (packet instanceof StateWifiInfoResponse) {
- handleWifiInfoStatus((StateWifiInfoResponse) packet);
+ if (packet instanceof StateResponse response) {
+ handleLightStatus(response);
+ } else if (packet instanceof StatePowerResponse response) {
+ handlePowerStatus(response);
+ } else if (packet instanceof StateLightPowerResponse response) {
+ handleLightPowerStatus(response);
+ } else if (packet instanceof StateHevCycleResponse response) {
+ handleHevCycleStatus(response);
+ } else if (packet instanceof StateLightInfraredResponse response) {
+ handleInfraredStatus(response);
+ } else if (packet instanceof StateMultiZoneResponse response) {
+ handleMultiZoneStatus(response);
+ } else if (packet instanceof StateTileEffectResponse response) {
+ handleTileEffectStatus(response);
+ } else if (packet instanceof StateWifiInfoResponse response) {
+ handleWifiInfoStatus(response);
}
currentLightState.setOnline();
MACAddress macAddress = packet.getTarget();
DiscoveredLight light = discoveredLights.get(macAddress);
- if (packet instanceof StateServiceResponse) {
- int port = (int) ((StateServiceResponse) packet).getPort();
+ if (packet instanceof StateServiceResponse response) {
+ int port = (int) response.getPort();
if (port != 0) {
try {
InetSocketAddress socketAddress = new InetSocketAddress(address.getAddress(), port);
}
}
} else if (light != null) {
- if (packet instanceof StateLabelResponse) {
- light.label = ((StateLabelResponse) packet).getLabel().trim();
- } else if (packet instanceof StateVersionResponse) {
+ if (packet instanceof StateLabelResponse response) {
+ light.label = response.getLabel().trim();
+ } else if (packet instanceof StateVersionResponse response) {
try {
- LifxProduct product = LifxProduct
- .getProductFromProductID(((StateVersionResponse) packet).getProduct());
+ LifxProduct product = LifxProduct.getProductFromProductID(response.getProduct());
light.product = product;
- light.productVersion = ((StateVersionResponse) packet).getVersion();
+ light.productVersion = response.getVersion();
light.supportedProduct = product.isLight();
} catch (IllegalArgumentException e) {
logger.debug("Discovered an unsupported light ({}): {}", light.macAddress.getAsLabel(),
return;
}
- if (packet instanceof StateVersionResponse) {
- long productId = ((StateVersionResponse) packet).getProduct();
+ if (packet instanceof StateVersionResponse response) {
+ long productId = response.getProduct();
properties.put(LifxBindingConstants.PROPERTY_PRODUCT_ID, Long.toString(productId));
- long productVersion = ((StateVersionResponse) packet).getVersion();
+ long productVersion = response.getVersion();
properties.put(LifxBindingConstants.PROPERTY_PRODUCT_VERSION, Long.toString(productVersion));
try {
}
receivedPacketTypes.add(packet.getPacketType());
- } else if (packet instanceof StateHostFirmwareResponse) {
- String hostVersion = ((StateHostFirmwareResponse) packet).getVersion().toString();
+ } else if (packet instanceof StateHostFirmwareResponse response) {
+ String hostVersion = response.getVersion().toString();
properties.put(LifxBindingConstants.PROPERTY_HOST_VERSION, hostVersion);
receivedPacketTypes.add(packet.getPacketType());
- } else if (packet instanceof StateWifiFirmwareResponse) {
- String wifiVersion = ((StateWifiFirmwareResponse) packet).getVersion().toString();
+ } else if (packet instanceof StateWifiFirmwareResponse response) {
+ String wifiVersion = response.getVersion().toString();
properties.put(LifxBindingConstants.PROPERTY_WIFI_VERSION, wifiVersion);
receivedPacketTypes.add(packet.getPacketType());
}
@Override
public Integer get() {
- return sequenceNumber.getAndUpdate((value) -> {
- return (value + 1) % SEQUENCE_NUMBER_DIVISOR;
- });
+ return sequenceNumber.getAndUpdate((value) -> (value + 1) % SEQUENCE_NUMBER_DIVISOR);
}
}
Optional<LightLastHevCycleResult> result = Arrays.stream(values()).filter((value) -> value.type == type)
.findFirst();
- if (!result.isPresent()) {
+ if (result.isEmpty()) {
throw new IllegalArgumentException("Invalid LightLastHevCycleResult type: " + type);
}
ByteBuffer flipped = flip(ByteBuffer.wrap(field));
- T value = wrapped.value(flipped);
-
- return value;
+ return wrapped.value(flipped);
}
@Override
switch (channelUID.getId()) {
case CHANNEL_ABS_TEMPERATURE:
case CHANNEL_TEMPERATURE:
- if (command instanceof DecimalType || (command instanceof QuantityType
- && ((QuantityType) command).toInvertibleUnit(Units.KELVIN) != null)) {
+ if (command instanceof DecimalType || (command instanceof QuantityType quantityCommand
+ && quantityCommand.toInvertibleUnit(Units.KELVIN) != null)) {
return () -> handleTemperatureCommand(command);
- } else if (command instanceof IncreaseDecreaseType) {
- return () -> handleIncreaseDecreaseTemperatureCommand((IncreaseDecreaseType) command);
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ return () -> handleIncreaseDecreaseTemperatureCommand(increaseDecreaseCommand);
}
case CHANNEL_BRIGHTNESS:
- if (command instanceof PercentType) {
- return () -> handlePercentCommand((PercentType) command);
- } else if (command instanceof OnOffType) {
- return () -> handleOnOffCommand((OnOffType) command);
- } else if (command instanceof IncreaseDecreaseType) {
- return () -> handleIncreaseDecreaseCommand((IncreaseDecreaseType) command);
+ if (command instanceof PercentType percentCommand) {
+ return () -> handlePercentCommand(percentCommand);
+ } else if (command instanceof OnOffType onOffCommand) {
+ return () -> handleOnOffCommand(onOffCommand);
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ return () -> handleIncreaseDecreaseCommand(increaseDecreaseCommand);
}
case CHANNEL_COLOR:
- if (command instanceof HSBType) {
- return () -> handleHSBCommand((HSBType) command);
- } else if (command instanceof PercentType) {
- return () -> handlePercentCommand((PercentType) command);
- } else if (command instanceof OnOffType) {
- return () -> handleOnOffCommand((OnOffType) command);
- } else if (command instanceof IncreaseDecreaseType) {
- return () -> handleIncreaseDecreaseCommand((IncreaseDecreaseType) command);
+ if (command instanceof HSBType hsbCommand) {
+ return () -> handleHSBCommand(hsbCommand);
+ } else if (command instanceof PercentType percentCommand) {
+ return () -> handlePercentCommand(percentCommand);
+ } else if (command instanceof OnOffType onOffCommand) {
+ return () -> handleOnOffCommand(onOffCommand);
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ return () -> handleIncreaseDecreaseCommand(increaseDecreaseCommand);
}
case CHANNEL_EFFECT:
- if (command instanceof StringType && features.hasFeature(TILE_EFFECT)) {
- return () -> handleTileEffectCommand((StringType) command);
+ if (command instanceof StringType stringCommand && features.hasFeature(TILE_EFFECT)) {
+ return () -> handleTileEffectCommand(stringCommand);
}
case CHANNEL_HEV_CYCLE:
- if (command instanceof OnOffType) {
- return () -> handleHevCycleCommand((OnOffType) command);
+ if (command instanceof OnOffType onOffCommand) {
+ return () -> handleHevCycleCommand(onOffCommand);
}
case CHANNEL_INFRARED:
- if (command instanceof PercentType) {
- return () -> handleInfraredCommand((PercentType) command);
- } else if (command instanceof IncreaseDecreaseType) {
- return () -> handleIncreaseDecreaseInfraredCommand((IncreaseDecreaseType) command);
+ if (command instanceof PercentType percentCommand) {
+ return () -> handleInfraredCommand(percentCommand);
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ return () -> handleIncreaseDecreaseInfraredCommand(increaseDecreaseCommand);
}
default:
try {
if (channelUID.getId().startsWith(CHANNEL_ABS_TEMPERATURE_ZONE)) {
int zoneIndex = Integer.parseInt(channelUID.getId().replace(CHANNEL_ABS_TEMPERATURE_ZONE, ""));
- if (command instanceof DecimalType || (command instanceof QuantityType
- && ((QuantityType) command).toInvertibleUnit(Units.KELVIN) != null)) {
+ if (command instanceof DecimalType || (command instanceof QuantityType quantityCommand
+ && quantityCommand.toInvertibleUnit(Units.KELVIN) != null)) {
return () -> handleTemperatureCommand(command, zoneIndex);
}
} else if (channelUID.getId().startsWith(CHANNEL_COLOR_ZONE)) {
int zoneIndex = Integer.parseInt(channelUID.getId().replace(CHANNEL_COLOR_ZONE, ""));
- if (command instanceof HSBType) {
- return () -> handleHSBCommand((HSBType) command, zoneIndex);
- } else if (command instanceof PercentType) {
- return () -> handlePercentCommand((PercentType) command, zoneIndex);
- } else if (command instanceof IncreaseDecreaseType) {
- return () -> handleIncreaseDecreaseCommand((IncreaseDecreaseType) command, zoneIndex);
+ if (command instanceof HSBType hsbCommand) {
+ return () -> handleHSBCommand(hsbCommand, zoneIndex);
+ } else if (command instanceof PercentType percentCommand) {
+ return () -> handlePercentCommand(percentCommand, zoneIndex);
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ return () -> handleIncreaseDecreaseCommand(increaseDecreaseCommand, zoneIndex);
}
} else if (channelUID.getId().startsWith(CHANNEL_TEMPERATURE_ZONE)) {
int zoneIndex = Integer.parseInt(channelUID.getId().replace(CHANNEL_TEMPERATURE_ZONE, ""));
- if (command instanceof PercentType) {
- return () -> handleTemperatureCommand((PercentType) command, zoneIndex);
- } else if (command instanceof IncreaseDecreaseType) {
- return () -> handleIncreaseDecreaseTemperatureCommand((IncreaseDecreaseType) command,
- zoneIndex);
+ if (command instanceof PercentType percentCommand) {
+ return () -> handleTemperatureCommand(percentCommand, zoneIndex);
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ return () -> handleIncreaseDecreaseTemperatureCommand(increaseDecreaseCommand, zoneIndex);
}
}
} catch (NumberFormatException e) {
}
public static int commandToKelvin(Command temperature, TemperatureRange temperatureRange) {
- if (temperature instanceof PercentType) {
- return percentTypeToKelvin((PercentType) temperature, temperatureRange);
- } else if (temperature instanceof QuantityType) {
- return quantityTypeToKelvin((QuantityType) temperature, temperatureRange);
- } else if (temperature instanceof DecimalType) {
- return decimalTypeToKelvin((DecimalType) temperature, temperatureRange);
+ if (temperature instanceof PercentType percentValue) {
+ return percentTypeToKelvin(percentValue, temperatureRange);
+ } else if (temperature instanceof QuantityType quantityValue) {
+ return quantityTypeToKelvin(quantityValue, temperatureRange);
+ } else if (temperature instanceof DecimalType decimalValue) {
+ return decimalTypeToKelvin(decimalValue, temperatureRange);
} else {
throw new IllegalStateException(
"Unexpected command type " + temperature.getClass().getName() + " for color temperature command.");
}
public static int getNewBroadcastPort() {
- int offset = BROADCAST_PORT_COUNTER.getAndUpdate((value) -> {
- return (value + 1) % Integer.MAX_VALUE;
- });
+ int offset = BROADCAST_PORT_COUNTER.getAndUpdate((value) -> (value + 1) % Integer.MAX_VALUE);
return BROADCAST_PORT + (offset % (PORT_MAX - BROADCAST_PORT));
}
}
readBuffer.rewind();
try {
- if (channel instanceof DatagramChannel) {
- InetSocketAddress address = (InetSocketAddress) ((DatagramChannel) channel).receive(readBuffer);
+ if (channel instanceof DatagramChannel datagramChannel) {
+ InetSocketAddress address = (InetSocketAddress) datagramChannel.receive(readBuffer);
if (address == null) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("{} : No datagram is available", logId);
} else if (isRemoteAddress(address.getAddress())) {
supplyParsedPacketToConsumer(readBuffer, address, packetConsumer, logId);
}
- } else if (channel instanceof SocketChannel) {
- ((SocketChannel) channel).read(readBuffer);
- InetSocketAddress address = (InetSocketAddress) ((SocketChannel) channel).getRemoteAddress();
+ } else if (channel instanceof SocketChannel socketChannel) {
+ socketChannel.read(readBuffer);
+ InetSocketAddress address = (InetSocketAddress) socketChannel.getRemoteAddress();
if (address == null) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("{} : Channel socket is not connected", logId);
if (key.isValid() && key.isWritable() && key.equals(castKey)) {
SelectableChannel channel = key.channel();
- if (channel instanceof DatagramChannel) {
+ if (channel instanceof DatagramChannel datagramChannel) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(
"{} : Sending packet type '{}' from '{}' to '{}' for '{}' with sequence '{}' and source '{}'",
new Object[] { context.getLogId(), packet.getClass().getSimpleName(),
- ((InetSocketAddress) ((DatagramChannel) channel).getLocalAddress())
- .toString(),
+ ((InetSocketAddress) datagramChannel.getLocalAddress()).toString(),
address.toString(), packet.getTarget().getHex(), packet.getSequence(),
Long.toString(packet.getSource(), 16) });
}
- ((DatagramChannel) channel).send(packet.bytes(), address);
+ datagramChannel.send(packet.bytes(), address);
return true;
- } else if (channel instanceof SocketChannel) {
- ((SocketChannel) channel).write(packet.bytes());
+ } else if (channel instanceof SocketChannel socketChannel) {
+ socketChannel.write(packet.bytes());
return true;
}
}
LinkyHandler handler = null;
if (thing != null) {
thingHandler = thing.getHandler();
- if (thingHandler instanceof LinkyHandler) {
- handler = (LinkyHandler) thingHandler;
+ if (thingHandler instanceof LinkyHandler linkyHandler) {
+ handler = linkyHandler;
}
}
if (thing == null) {
public @Nullable Object value;
public @Nullable String valueAsString() {
- return (value instanceof String) ? (String) value : null;
+ return (value instanceof String stringValue) ? stringValue : null;
}
}
}
private void checkData(Consumption consumption) throws LinkyException {
- if (consumption.aggregats.days.periodes.size() == 0) {
+ if (consumption.aggregats.days.periodes.isEmpty()) {
throw new LinkyException("Invalid consumptions data: no day period");
}
if (consumption.aggregats.days.periodes.size() != consumption.aggregats.days.datas.size()) {
throw new LinkyException("Invalid consumptions data: not any data for each day period");
}
- if (consumption.aggregats.weeks.periodes.size() == 0) {
+ if (consumption.aggregats.weeks.periodes.isEmpty()) {
throw new LinkyException("Invalid consumptions data: no week period");
}
if (consumption.aggregats.weeks.periodes.size() != consumption.aggregats.weeks.datas.size()) {
throw new LinkyException("Invalid consumptions data: not any data for each week period");
}
- if (consumption.aggregats.months.periodes.size() == 0) {
+ if (consumption.aggregats.months.periodes.isEmpty()) {
throw new LinkyException("Invalid consumptions data: no month period");
}
if (consumption.aggregats.months.periodes.size() != consumption.aggregats.months.datas.size()) {
throw new LinkyException("Invalid consumptions data: not any data for each month period");
}
- if (consumption.aggregats.years.periodes.size() == 0) {
+ if (consumption.aggregats.years.periodes.isEmpty()) {
throw new LinkyException("Invalid consumptions data: no year period");
}
if (consumption.aggregats.years.periodes.size() != consumption.aggregats.years.datas.size()) {
private boolean isDataFirstDayAvailable(Consumption consumption) {
Aggregate days = consumption.aggregats.days;
logData(days, "First day", false, DateTimeFormatter.ISO_LOCAL_DATE, Target.FIRST);
- return days.datas != null && days.datas.size() > 0 && !days.datas.get(0).isNaN();
+ return days.datas != null && !days.datas.isEmpty() && !days.datas.get(0).isNaN();
}
private boolean isDataLastDayAvailable(Consumption consumption) {
Aggregate days = consumption.aggregats.days;
logData(days, "Last day", false, DateTimeFormatter.ISO_LOCAL_DATE, Target.LAST);
- return days.datas != null && days.datas.size() > 0 && !days.datas.get(days.datas.size() - 1).isNaN();
+ return days.datas != null && !days.datas.isEmpty() && !days.datas.get(days.datas.size() - 1).isNaN();
}
private void logData(Aggregate aggregate, String title, boolean withDateFin, DateTimeFormatter dateTimeFormatter,
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.time.Duration;
-import java.util.Collections;
+import java.util.Set;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
private @NonNullByDefault({}) Future<?> discoveryJob;
public LinuxInputDiscoveryService() {
- super(Collections.singleton(THING_TYPE_DEVICE), (int) TIMEOUT.getSeconds(), true);
+ super(Set.of(THING_TYPE_DEVICE), (int) TIMEOUT.getSeconds(), true);
}
@Override
if (selector.selectedKeys().remove(evdevReady)) {
while (true) {
Optional<EvdevDevice.InputEvent> ev = currentDevice.nextEvent();
- if (!ev.isPresent()) {
+ if (ev.isEmpty()) {
break;
}
handleEvent(ev.get());
import static org.openhab.binding.linuxinput.internal.LinuxInputBindingConstants.THING_TYPE_DEVICE;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@NonNullByDefault
@Component(configurationPid = "binding.linuxinput", service = ThingHandlerFactory.class)
public class LinuxInputHandlerFactory extends BaseThingHandlerFactory {
- 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);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
if (client != null && client.isConnected()) {
String response = client.measureCommand();
CommData commandResponse = new Gson().fromJson(response, CommData.class);
- if (commandResponse != null && !commandResponse.header.name.equals("")) {
+ if (commandResponse != null && !"".equals(commandResponse.header.name)) {
if (!"success".equals(commandResponse.context.status)) {
logger.warn("Starting the measurement was not successful!");
}
try {
String jsonString = client.pollData();
CommData response = new Gson().fromJson(jsonString, CommData.class);
- if (response != null && !response.header.messageId.equals("")) {
+ if (response != null && !"".equals(response.header.messageId)) {
Map<String, String> properties = response.createPropertyMap();
if (!oldProps.equals(properties)) {
oldProps = properties;
*/
package org.openhab.binding.lirc.internal;
-import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public static final String CHANNEL_TRANSMIT = "transmit";
// List of all supported thing types
- public static final Set<ThingTypeUID> SUPPORTED_DEVICE_TYPES = Collections.singleton(THING_TYPE_REMOTE);
- public static final Set<ThingTypeUID> SUPPORTED_BRIDGE_TYPES = Collections.singleton(THING_TYPE_BRIDGE);
+ public static final Set<ThingTypeUID> SUPPORTED_DEVICE_TYPES = Set.of(THING_TYPE_REMOTE);
+ public static final Set<ThingTypeUID> SUPPORTED_BRIDGE_TYPES = Set.of(THING_TYPE_BRIDGE);
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Stream.of(THING_TYPE_REMOTE, THING_TYPE_BRIDGE)
.collect(Collectors.toSet());
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof LivisiBridgeHandler) {
- bridgeHandler = (LivisiBridgeHandler) handler;
+ if (handler instanceof LivisiBridgeHandler livisiBridgeHandler) {
+ bridgeHandler = livisiBridgeHandler;
}
}
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Collection;
-import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledExecutorService;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(LivisiDeviceDiscoveryService.class);
+ return Set.of(LivisiDeviceDiscoveryService.class);
}
@Override
@Override
public void onError(final Throwable cause) {
- if (cause instanceof Exception) {
- handleClientException((Exception) cause);
+ if (cause instanceof Exception exception) {
+ handleClientException(exception);
}
}
}
private void commandSetDimLevel(Command command, LivisiBridgeHandler bridgeHandler) {
- if (command instanceof DecimalType) {
- final DecimalType dimLevel = (DecimalType) command;
+ if (command instanceof DecimalType dimLevel) {
bridgeHandler.commandSetDimLevel(deviceId, dimLevel.intValue());
} else if (command instanceof OnOffType) {
if (OnOffType.ON.equals(command)) {
}
private void commandRollerShutter(Command command, LivisiBridgeHandler bridgeHandler) {
- if (command instanceof DecimalType) {
- final DecimalType rollerShutterLevel = (DecimalType) command;
+ if (command instanceof DecimalType rollerShutterLevel) {
bridgeHandler.commandSetRollerShutterLevel(deviceId,
invertRollerShutterValueIfConfigured(rollerShutterLevel.intValue()));
} else if (command instanceof OnOffType) {
}
private void commandUpdatePointTemperature(Command command, LivisiBridgeHandler bridgeHandler) {
- if (command instanceof QuantityType) {
- final QuantityType<?> pointTemperatureCommand = ((QuantityType<?>) command).toUnit(SIUnits.CELSIUS);
+ if (command instanceof QuantityType temperatureCommand) {
+ final QuantityType<?> pointTemperatureCommand = temperatureCommand.toUnit(SIUnits.CELSIUS);
if (pointTemperatureCommand != null) {
commandUpdatePointTemperature(pointTemperatureCommand.doubleValue(), bridgeHandler);
}
- } else if (command instanceof DecimalType) {
- commandUpdatePointTemperature(((DecimalType) command).doubleValue(), bridgeHandler);
+ } else if (command instanceof DecimalType temperatureCommand) {
+ commandUpdatePointTemperature(temperatureCommand.doubleValue(), bridgeHandler);
}
}
}
@Nullable
final ThingHandler handler = bridge.getHandler();
- if (handler instanceof LivisiBridgeHandler) {
- LivisiBridgeHandler bridgeHandler = (LivisiBridgeHandler) handler;
+ if (handler instanceof LivisiBridgeHandler bridgeHandler) {
bridgeHandler.registerDeviceStatusListener(deviceId, this);
this.bridgeHandler = bridgeHandler;
} else {
@Test
public void testRefreshStatusSHC2() throws Exception {
- mockRequest(STATUS_URL,
- "{\"gateway\": {\"serialNumber\": \"123\","
- + "\"appVersion\": \"1.2.37.430\",\"osVersion\": \"8.17\",\"configVersion\": 1200,"
- + "\"operationStatus\": \"active\",\"network\": "
- + "{\"ethCableAttached\": true,\"inUseAdapter\": \"eth\",\"hotspotActive\": false,"
- + "\"wpsActive\": false,\"backendAvailable\": true,\"ethMacAddress\": "
- + "[{\"id\": \"456\",\"config\": {\"name\": \"Arbeitszimmer\",\"type\": \"Other\"},"
- + "\"desc\": \"/desc/location\"}]}}}");
+ mockRequest(STATUS_URL, """
+ {"gateway": {"serialNumber": "123",\
+ "appVersion": "1.2.37.430","osVersion": "8.17","configVersion": 1200,\
+ "operationStatus": "active","network": \
+ {"ethCableAttached": true,"inUseAdapter": "eth","hotspotActive": false,\
+ "wpsActive": false,"backendAvailable": true,"ethMacAddress": \
+ [{"id": "456","config": {"name": "Arbeitszimmer","type": "Other"},\
+ "desc": "/desc/location"}]}}}\
+ """);
assertEquals("1200", client.refreshStatus());
}
assertTrue(device.isReachable());
assertFalse(device.hasLowBattery());
- device.setMessageList(Collections.singletonList(createMessage(MessageDTO.TYPE_DEVICE_LOW_BATTERY)));
+ device.setMessageList(List.of(createMessage(MessageDTO.TYPE_DEVICE_LOW_BATTERY)));
assertTrue(device.isReachable());
assertTrue(device.hasLowBattery());
assertTrue(device.isReachable());
assertFalse(device.hasLowBattery());
- device.setMessageList(Collections.singletonList(createMessage(MessageDTO.TYPE_DEVICE_UNREACHABLE)));
+ device.setMessageList(List.of(createMessage(MessageDTO.TYPE_DEVICE_UNREACHABLE)));
assertFalse(device.isReachable());
assertFalse(device.hasLowBattery());
assertFalse(device.isReachable());
assertTrue(device.hasLowBattery());
- messages = Collections.singletonList(createMessage("UNKNOWN"));
+ messages = List.of(createMessage("UNKNOWN"));
device.setMessageList(messages);
// Nothing should get changed.
assertTrue(device.isReachable());
assertFalse(device.hasLowBattery());
- device.setMessageList(Collections.singletonList(createMessage("UNKNOWN")));
+ device.setMessageList(List.of(createMessage("UNKNOWN")));
assertTrue(device.isReachable());
assertFalse(device.hasLowBattery());
import static org.openhab.binding.livisismarthome.internal.client.api.entity.link.LinkDTO.LINK_TYPE_DEVICE;
import java.io.IOException;
-import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
+import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
livisiClientMock = mock(LivisiClient.class);
fullDeviceManagerMock = mock(FullDeviceManager.class);
- when(fullDeviceManagerMock.getFullDevices()).thenReturn(Collections.singletonList(bridgeDevice));
+ when(fullDeviceManagerMock.getFullDevices()).thenReturn(List.of(bridgeDevice));
schedulerMock = mock(ScheduledExecutorService.class);
ThingUID thingUID = new ThingUID(thingTypeUID, device.getId());
Configuration thingConfiguration = new Configuration();
- thingConfiguration.setProperties(Collections.singletonMap(PROPERTY_ID, device.getId()));
+ thingConfiguration.setProperties(Map.of(PROPERTY_ID, device.getId()));
Thing thingMock = mock(Thing.class);
when(thingMock.getBridgeUID()).thenReturn(bridgeThingUID);
/**
* Buffer on top of RandomAccessFile.
*/
- private final byte inbuf[];
+ private final byte[] inbuf;
/**
* The file which will be tailed.
return;
}
- if (!(thing.getStatus() == ThingStatus.ONLINE)) {
+ if (thing.getStatus() != ThingStatus.ONLINE) {
updateStatus(ThingStatus.ONLINE);
}
private List<Pattern> compilePatterns(@Nullable String patterns) throws PatternSyntaxException {
List<Pattern> patternsList = new ArrayList<>();
if (patterns != null && !patterns.isEmpty()) {
- String list[] = patterns.split("\\|");
+ String[] list = patterns.split("\\|");
if (list.length > 0) {
for (String patternStr : list) {
patternsList.add(Pattern.compile(patternStr));
*/
package org.openhab.binding.loxone.internal;
-import java.util.Collections;
import java.util.Set;
import org.openhab.core.thing.Thing;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.loxone")
public class LxHandlerFactory extends BaseThingHandlerFactory {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .singleton(LxBindingConstants.THING_TYPE_MINISERVER);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(LxBindingConstants.THING_TYPE_MINISERVER);
private LxDynamicStateDescriptionProvider dynamicStateDescriptionProvider;
protected ThingHandler createHandler(Thing thing) {
ThingTypeUID uid = thing.getThingTypeUID();
if (uid.equals(LxBindingConstants.THING_TYPE_MINISERVER)) {
- LxServerHandler handler = new LxServerHandler(thing, dynamicStateDescriptionProvider);
- return handler;
+ return new LxServerHandler(thing, dynamicStateDescriptionProvider);
}
return null;
}
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
private final Logger logger = LoggerFactory.getLogger(LxServerHandler.class);
private static AtomicInteger staticDebugId = new AtomicInteger(1);
- static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .singleton(LxBindingConstants.THING_TYPE_MINISERVER);
+ static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(LxBindingConstants.THING_TYPE_MINISERVER);
private QueuedThreadPool jettyThreadPool;
@Override
public String getSetting(String name) {
Object value = getConfig().get(name);
- return (value instanceof String) ? (String) value : null;
+ return (value instanceof String s) ? s : null;
}
/*
}
@OnWebSocketMessage
- public void onBinaryMessage(byte data[], int msgOffset, int msgLength) {
+ public void onBinaryMessage(byte[] data, int msgOffset, int msgLength) {
int offset = msgOffset;
int length = msgLength;
if (logger.isTraceEnabled()) {
LxState state = states.get(name);
if (state != null) {
Object value = state.getStateValue();
- if (value instanceof String) {
- return (String) value;
+ if (value instanceof String str) {
+ return str;
}
}
return null;
if (STATE_START_TIME.equals(stateName)) {
startTime = UnDefType.UNDEF;
Object obj = state.getStateValue();
- if (obj instanceof String && !((String) obj).isEmpty()) {
+ if (obj instanceof String str && !str.isEmpty()) {
try {
- LocalDateTime ldt = LocalDateTime.parse((String) obj, dateTimeFormatter);
+ LocalDateTime ldt = LocalDateTime.parse(str, dateTimeFormatter);
ZonedDateTime dt = ldt.atZone(ZoneId.systemDefault());
startTime = new DateTimeType(dt);
} catch (DateTimeParseException e) {
}
private void handleCommands(Command command) throws IOException {
- if (command instanceof HSBType) {
- setColor((HSBType) command);
+ if (command instanceof HSBType hsbCommand) {
+ setColor(hsbCommand);
} else if (command instanceof OnOffType) {
if (command == OnOffType.ON) {
on();
} else {
off();
}
- } else if (command instanceof DecimalType) {
- setBrightness((DecimalType) command);
- } else if (command instanceof PercentType) {
- setBrightness((PercentType) command);
- } else if (command instanceof IncreaseDecreaseType) {
- if (((IncreaseDecreaseType) command).equals(IncreaseDecreaseType.INCREASE)) {
+ } else if (command instanceof DecimalType decimalCommand) {
+ setBrightness(decimalCommand);
+ } else if (command instanceof PercentType percentCommand) {
+ setBrightness(percentCommand);
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ if (increaseDecreaseCommand.equals(IncreaseDecreaseType.INCREASE)) {
increaseDecreaseBrightness(1);
} else {
increaseDecreaseBrightness(-1);
} else {
sendAction(CMD_OFF);
}
- } else if (command instanceof PercentType) {
- PercentType percentCmd = (PercentType) command;
- setPosition(percentCmd.doubleValue());
- } else if (command instanceof IncreaseDecreaseType) {
+ } else if (command instanceof PercentType percentCommand) {
+ setPosition(percentCommand.doubleValue());
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
Double value = getStateDoubleValue(STATE_POSITION);
Double min = getMin();
Double max = getMax();
Double step = getStep();
if (value != null && max != null && min != null && step != null && min >= 0 && max >= 0 && max > min) {
- if ((IncreaseDecreaseType) command == IncreaseDecreaseType.INCREASE) {
+ if (increaseDecreaseCommand == IncreaseDecreaseType.INCREASE) {
value += step;
if (value > max) {
value = max;
Double max = getMax();
Double min = getMin();
if (max != null && min != null) {
- double value = min + ohValue * (max - min) / 100;
- return value; // no rounding to integer value is needed as loxone is accepting floating point values
+ return min + ohValue * (max - min) / 100; // no rounding to integer value is needed as loxone is
+ // accepting floating point values
}
}
return null;
}
private void setOperatingMode(Command command) throws IOException {
- if (command instanceof DecimalType) {
- DecimalType mode = (DecimalType) command;
- sendAction(CMD_SET_OPERATING_MODE + String.valueOf(mode.intValue()));
+ if (command instanceof DecimalType mode) {
+ sendAction(CMD_SET_OPERATING_MODE + mode.intValue());
}
}
private void setTemperature(Command command, String prefix) throws IOException {
- if (command instanceof DecimalType) {
- DecimalType temp = (DecimalType) command;
- sendAction(prefix + String.valueOf(temp.doubleValue()));
+ if (command instanceof DecimalType temp) {
+ sendAction(prefix + temp.doubleValue());
}
}
}
private void handleOperateCommands(Command command) throws IOException {
logger.debug("Command input {}", command);
- if (command instanceof PercentType) {
+ if (command instanceof PercentType percentCommand) {
if (PercentType.ZERO.equals(command)) {
sendAction(CMD_FULL_UP);
} else if (PercentType.HUNDRED.equals(command)) {
sendAction(CMD_FULL_DOWN);
} else {
- moveToPosition(((PercentType) command).doubleValue() / 100);
+ moveToPosition(percentCommand.doubleValue() / 100);
}
- } else if (command instanceof UpDownType) {
- if ((UpDownType) command == UpDownType.UP) {
+ } else if (command instanceof UpDownType upDownCommand) {
+ if (upDownCommand == UpDownType.UP) {
sendAction(CMD_FULL_UP);
} else {
sendAction(CMD_FULL_DOWN);
}
- } else if (command instanceof StopMoveType) {
- if ((StopMoveType) command == StopMoveType.STOP) {
+ } else if (command instanceof StopMoveType stopMoveCommand) {
+ if (stopMoveCommand == StopMoveType.STOP) {
sendAction(CMD_STOP);
}
}
}
private void handleShadeCommands(Command command) throws IOException {
- if (command instanceof OnOffType) {
- if ((OnOffType) command == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
sendAction(CMD_SHADE);
}
}
}
private void handleAutoShadeCommands(Command command) throws IOException {
- if (command instanceof OnOffType) {
- if ((OnOffType) command == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
sendAction(CMD_AUTO);
} else {
sendAction(CMD_NO_AUTO);
}
private void handleCommands(Command command) throws IOException {
- if (command instanceof OnOffType) {
- if ((OnOffType) command == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
sendAction(CMD_ON);
} else {
sendAction(CMD_OFF);
}
- } else if (command instanceof UpDownType) {
- if ((UpDownType) command == UpDownType.UP) {
+ } else if (command instanceof UpDownType upDownCommand) {
+ if (upDownCommand == UpDownType.UP) {
sendAction(CMD_NEXT_SCENE);
} else {
sendAction(CMD_PREVIOUS_SCENE);
}
- } else if (command instanceof DecimalType) {
- int scene = ((DecimalType) command).intValue();
+ } else if (command instanceof DecimalType decimalCommand) {
+ int scene = decimalCommand.intValue();
if (scene == SCENE_ALL_ON) {
sendAction(CMD_ON);
} else if (scene >= 0 && scene < NUM_OF_SCENES) {
public void onStateChange(LxState state) {
if (STATE_SCENE_LIST.equals(state.getName()) && channelId != null) {
Object value = state.getStateValue();
- if (value instanceof String) {
+ if (value instanceof String str) {
sceneNames.clear();
- String[] scenes = ((String) value).split(",");
+ String[] scenes = str.split(",");
for (String line : scenes) {
- line = line.replaceAll("\"", "");
+ line = line.replace("\"", "");
String[] params = line.split("=");
if (params.length == 2) {
sceneNames.add(new StateOption(params[0], params[1]));
}
private void handleCommands(Command command) throws IOException {
- if (command instanceof UpDownType) {
- if ((UpDownType) command == UpDownType.UP) {
+ if (command instanceof UpDownType upDownCommand) {
+ if (upDownCommand == UpDownType.UP) {
sendAction(CMD_NEXT_MOOD);
} else {
sendAction(CMD_PREVIOUS_MOOD);
}
- } else if (command instanceof DecimalType) {
- int moodId = ((DecimalType) command).intValue();
+ } else if (command instanceof DecimalType decimalCommand) {
+ int moodId = decimalCommand.intValue();
if (isMoodOk(moodId)) {
sendAction(CMD_CHANGE_TO_MOOD + "/" + moodId);
}
String stateName = state.getName();
Object value = state.getStateValue();
try {
- if (STATE_MOODS_LIST.equals(stateName) && value instanceof String) {
- onMoodsListChange((String) value);
- } else if (STATE_ACTIVE_MOODS_LIST.equals(stateName) && value instanceof String) {
+ if (STATE_MOODS_LIST.equals(stateName) && value instanceof String string) {
+ onMoodsListChange(string);
+ } else if (STATE_ACTIVE_MOODS_LIST.equals(stateName) && value instanceof String string) {
// this state can be received before list of moods, but it contains a valid list of IDs
- Integer[] array = getGson().fromJson((String) value, Integer[].class);
+ Integer[] array = getGson().fromJson(string, Integer[].class);
activeMoods = Arrays.asList(array).stream().filter(id -> isMoodOk(id)).collect(Collectors.toList());
// update all moods states - this will force update of channels too
moodList.values().forEach(mood -> mood.onStateChange(null));
}
private void handleResetCommands(Command command) throws IOException {
- if (command instanceof OnOffType && (OnOffType) command == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand && onOffCommand == OnOffType.ON) {
sendAction(CMD_RESET);
}
}
@Override
void handleSwitchCommands(Command command) throws IOException {
- if (command instanceof OnOffType) {
- if ((OnOffType) command == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
sendAction(CMD_PULSE);
} else {
off();
}
private void handleCommands(Command command) throws IOException {
- if (((command instanceof OnOffType && (OnOffType) command == OnOffType.OFF) || DecimalType.ZERO.equals(command))
- && outputsMap.containsKey("0")) {
+ if (((command instanceof OnOffType onOffCommand && onOffCommand == OnOffType.OFF)
+ || DecimalType.ZERO.equals(command)) && outputsMap.containsKey("0")) {
sendAction(CMD_RESET);
- } else if (command instanceof DecimalType) {
- DecimalType output = (DecimalType) command;
+ } else if (command instanceof DecimalType output) {
if (outputsMap.containsKey(output.toString())) {
sendAction(String.valueOf(output.intValue()));
}
}
private void handleSaunaActivateCommands(Command command) throws IOException {
- if (command instanceof OnOffType) {
- if ((OnOffType) command == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
sendAction(CMD_ON);
} else {
sendAction(CMD_OFF);
}
private void handleSetNumberCommands(Command command, String prefix) throws IOException {
- if (command instanceof DecimalType) {
- Double value = ((DecimalType) command).doubleValue();
+ if (command instanceof DecimalType decimalCommand) {
+ Double value = decimalCommand.doubleValue();
sendAction(prefix + value.toString());
}
}
private void handleFanCommands(Command command) throws IOException {
- if (command instanceof OnOffType) {
- if ((OnOffType) command == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
sendAction(CMD_FAN_ON);
} else {
sendAction(CMD_FAN_OFF);
}
private void handleTriggerCommands(Command command, String prefix) throws IOException {
- if (command instanceof OnOffType && (OnOffType) command == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand && onOffCommand == OnOffType.ON) {
sendAction(prefix);
}
}
private void handleModeCommands(Command command) throws IOException {
- if (command instanceof DecimalType) {
- Double value = ((DecimalType) command).doubleValue();
+ if (command instanceof DecimalType decimalCommand) {
+ Double value = decimalCommand.doubleValue();
// per API there are 7 evaporator modes selected with number 0-6
if (value % 1 == 0 && value >= 0.0 && value <= 6.0) {
sendAction(CMD_SET_EVAPORATOR_MODE + value.toString());
}
void handleSwitchCommands(Command command) throws IOException {
- if (command instanceof OnOffType) {
- if ((OnOffType) command == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
on();
} else {
off();
}
private void handleCommands(Command command) throws IOException {
- if (command instanceof DecimalType) {
- Double value = ((DecimalType) command).doubleValue();
+ if (command instanceof DecimalType decimalCommand) {
+ Double value = decimalCommand.doubleValue();
if (minValue != null && maxValue != null && value >= minValue && value <= maxValue) {
sendAction(value.toString());
} else {
}
private void handleUpCommands(Command command) throws IOException {
- if (command instanceof OnOffType) {
- if ((OnOffType) command == OnOffType.ON && upState == OnOffType.OFF) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON && upState == OnOffType.OFF) {
setStates(OnOffType.ON, OnOffType.OFF);
sendAction(CMD_UP_ON);
} else if (upState == OnOffType.ON) {
}
private void handleDownCommands(Command command) throws IOException {
- if (command instanceof OnOffType) {
- if ((OnOffType) command == OnOffType.ON && downState == OnOffType.OFF) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON && downState == OnOffType.OFF) {
setStates(OnOffType.OFF, OnOffType.ON);
sendAction(CMD_DOWN_ON);
} else if (downState == OnOffType.ON) {
logger.debug("Value selector min or max value missing or min>max.");
return;
}
- if (command instanceof OnOffType) {
- if ((OnOffType) command == OnOffType.ON) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.ON) {
sendAction(maxValue.toString());
} else {
sendAction(minValue.toString());
}
- } else if (command instanceof IncreaseDecreaseType) {
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
if (stepValue == null) {
logger.debug("Value selector step value missing.");
return;
}
- IncreaseDecreaseType type = (IncreaseDecreaseType) command;
- if (increaseOnly != null && type == IncreaseDecreaseType.DECREASE && increaseOnly) {
+ if (increaseOnly != null && increaseDecreaseCommand == IncreaseDecreaseType.DECREASE && increaseOnly) {
logger.debug("Value selector configured to allow increase only.");
return;
}
Double currentValue = getStateDoubleValue(STATE_VALUE);
if (currentValue != null) {
- Double nextValue = currentValue + (type == IncreaseDecreaseType.INCREASE ? stepValue : -stepValue);
+ Double nextValue = currentValue
+ + (increaseDecreaseCommand == IncreaseDecreaseType.INCREASE ? stepValue : -stepValue);
if (nextValue > maxValue) {
nextValue = maxValue;
}
}
sendAction(nextValue.toString());
}
- } else if (command instanceof PercentType) {
- Double value = ((PercentType) command).doubleValue() * (maxValue - minValue) / 100.0 + minValue;
+ } else if (command instanceof PercentType percentCommand) {
+ Double value = percentCommand.doubleValue() * (maxValue - minValue) / 100.0 + minValue;
sendAction(value.toString());
}
}
logger.debug("Value selector min or max value missing or min>max.");
return;
}
- if (command instanceof DecimalType) {
- Double value = ((DecimalType) command).doubleValue();
+ if (command instanceof DecimalType decimalCommand) {
+ Double value = decimalCommand.doubleValue();
if (value < minValue || value > maxValue) {
logger.debug("Value {} out of {}-{} range", value, minValue, maxValue);
return;
*/
package org.openhab.binding.loxone.internal.types;
-import java.util.Collections;
import java.util.Set;
import org.openhab.binding.loxone.internal.controls.LxControl;
*
*/
public class LxTags {
- public static final Set<String> SCENE = Collections.singleton("Scene");
- public static final Set<String> LIGHTING = Collections.singleton("Lighting");
- public static final Set<String> SWITCHABLE = Collections.singleton("Switchable");
- public static final Set<String> TEMPERATURE = Collections.singleton("CurrentTemperature");
+ public static final Set<String> SCENE = Set.of("Scene");
+ public static final Set<String> LIGHTING = Set.of("Lighting");
+ public static final Set<String> SWITCHABLE = Set.of("Switchable");
+ public static final Set<String> TEMPERATURE = Set.of("CurrentTemperature");
}
this.uuid = init(uuid);
}
- public LxUuid(byte data[], int offset) {
+ public LxUuid(byte[] data, int offset) {
String id = String.format("%08x-%04x-%04x-%02x%02x%02x%02x%02x%02x%02x%02x",
ByteBuffer.wrap(data, offset, 4).order(ByteOrder.LITTLE_ENDIAN).getInt(),
ByteBuffer.wrap(data, offset + 4, 2).order(ByteOrder.LITTLE_ENDIAN).getShort(),
static final String SENSORS_CHANNEL = " / Sensors";
static final String QUIT_CHANNEL = " / Acknowledge";
- private static final String NUMBER_CHANNELS[] = { NEXT_LEVEL_CHANNEL, NEXT_LEVEL_DELAY_CHANNEL,
+ private static final String[] NUMBER_CHANNELS = { NEXT_LEVEL_CHANNEL, NEXT_LEVEL_DELAY_CHANNEL,
NEXT_LEVEL_DELAY_TOTAL_CHANNEL, LEVEL_CHANNEL, ARMED_DELAY_CHANNEL, ARMED_TOTAL_DELAY_CHANNEL };
@BeforeEach
*/
package org.openhab.binding.loxone.internal.controls;
-import java.util.Collections;
+import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@Test
public void testChannels() {
- testChannel("Number", null, null, null, null, "%.1f", true, null, Collections.singleton("CurrentTemperature"));
+ testChannel("Number", null, null, null, null, "%.1f", true, null, Set.of("CurrentTemperature"));
}
}
*/
package org.openhab.binding.loxone.internal.controls;
-import java.util.Collections;
import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
@Test
public void testChannels() {
- testChannel("Rollershutter", Collections.singleton("Blinds"));
- Set<String> tags = Collections.singleton("Switchable");
+ testChannel("Rollershutter", Set.of("Blinds"));
+ Set<String> tags = Set.of("Switchable");
testChannel("Switch", SHADE_CHANNEL, tags);
testChannel("Switch", AUTO_SHADE_CHANNEL, tags);
}
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
+import java.util.Set;
import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeEach;
@Test
public void testChannels() {
- testChannel("Number", Collections.singleton("Scene"));
+ testChannel("Number", Set.of("Scene"));
}
@Test
assertNotNull(min);
assertNotNull(max);
testChannel("Number", null, new BigDecimal(min), new BigDecimal(max), BigDecimal.ONE, null, false, options,
- Collections.singleton("Scene"));
+ Set.of("Scene"));
}
private void testMood(String name, String id, boolean isStatic) {
assertEquals(0, mood.getChannels().size());
} else {
assertEquals(1, mood.getChannels().size());
- testChannel(mood, "Switch", Collections.singleton("Lighting"));
+ testChannel(mood, "Switch", Set.of("Lighting"));
}
}
*/
package org.openhab.binding.loxone.internal.controls;
-import java.util.Collections;
+import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@Override
@Test
public void testChannels() {
- testChannel("Switch", Collections.singleton("Switchable"));
+ testChannel("Switch", Set.of("Switchable"));
}
@Override
*/
package org.openhab.binding.loxone.internal.controls;
-import java.util.Collections;
+import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@Test
public void testChannels() {
- testChannel("Switch", Collections.singleton("Lighting"));
+ testChannel("Switch", Set.of("Lighting"));
}
@Test
package org.openhab.binding.loxone.internal.controls;
import java.math.BigDecimal;
-import java.util.Collections;
+import java.util.Set;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@Test
public void testChannels() {
- testChannel("Switch", Collections.singleton("Switchable"));
+ testChannel("Switch", Set.of("Switchable"));
testChannel("Number", DELAY_CHANNEL, new BigDecimal(-1), null, null, null, true, null);
}
// Used by the HwDiscoveryService
public static final Set<ThingTypeUID> HW_DISCOVERABLE_DEVICE_TYPES_UIDS = Collections
- .unmodifiableSet(Collections.singleton(HwConstants.THING_TYPE_HWDIMMER));
+ .unmodifiableSet(Set.of(HwConstants.THING_TYPE_HWDIMMER));
// Other types that can be initiated but not discovered
private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
registerDiscoveryService(bridgeHandler);
return bridgeHandler;
} else if (thingTypeUID.equals(THING_TYPE_LEAPBRIDGE)) {
- LeapBridgeHandler bridgeHandler = new LeapBridgeHandler((Bridge) thing);
- return bridgeHandler;
+ return new LeapBridgeHandler((Bridge) thing);
} else if (thingTypeUID.equals(THING_TYPE_DIMMER)) {
return new DimmerHandler(thing);
} else if (thingTypeUID.equals(THING_TYPE_SHADE)) {
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof DimmerHandler) {
- this.handler = (DimmerHandler) handler;
+ if (handler instanceof DimmerHandler dimmerHandler) {
+ this.handler = dimmerHandler;
}
}
@Override
public void setThingHandler(ThingHandler handler) {
- if (handler instanceof LeapBridgeHandler) {
- bridgeHandler = (LeapBridgeHandler) handler;
+ if (handler instanceof LeapBridgeHandler leapBridgeHandler) {
+ bridgeHandler = leapBridgeHandler;
bridgeHandler.setDiscoveryService(this);
}
}
context.push(area.getName());
for (DeviceNode deviceNode : area.getDeviceNodes()) {
- if (deviceNode instanceof DeviceGroup) {
- processDeviceGroup(area, (DeviceGroup) deviceNode, context);
- } else if (deviceNode instanceof Device) {
- processDevice(area, (Device) deviceNode, context);
+ if (deviceNode instanceof DeviceGroup group) {
+ processDeviceGroup(area, group, context);
+ } else if (deviceNode instanceof Device device) {
+ processDevice(area, device, context);
}
}
import java.net.MulticastSocket;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
private static final int SCAN_INTERVAL_MINUTES = 30;
private static final int SCAN_TIMEOUT_MS = 2000;
- private static final Set<ThingTypeUID> BRIDGE_TYPE_UID = Collections.singleton(THING_TYPE_IPBRIDGE);
+ private static final Set<ThingTypeUID> BRIDGE_TYPE_UID = Set.of(THING_TYPE_IPBRIDGE);
private static final String GROUP_ADDRESS = "224.0.37.42";
private static final byte[] QUERY_DATA = "<LUTRON=1>".getBytes(StandardCharsets.US_ASCII);
import static org.openhab.binding.lutron.internal.LutronBindingConstants.*;
import java.net.InetAddress;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(THING_TYPE_IPBRIDGE);
+ return Set.of(THING_TYPE_IPBRIDGE);
}
@Override
}
if (id.equals(PrgConstants.CHANNEL_SCENE)) {
- if (command instanceof DecimalType) {
- final int scene = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType sceneCommand) {
+ final int scene = sceneCommand.intValue();
getProtocolHandler().selectScene(config.getControlUnit(), scene);
} else {
logger.error("Received a SCENE command with a non DecimalType: {}", command);
getProtocolHandler().setZoneRaise(config.getControlUnit(), zone);
}
} else if (id.equals(PrgConstants.CHANNEL_ZONEFADE)) {
- if (command instanceof DecimalType) {
- setFade(((DecimalType) command).intValue());
+ if (command instanceof DecimalType zoneFade) {
+ setFade(zoneFade.intValue());
} else {
logger.error("Received a ZONEFADE command with a non DecimalType: {}", command);
}
final Integer zone = getTrailingNbr(id, PrgConstants.CHANNEL_ZONEINTENSITY);
if (zone != null) {
- if (command instanceof PercentType) {
- final int intensity = ((PercentType) command).intValue();
+ if (command instanceof PercentType intensityPercent) {
+ final int intensity = intensityPercent.intValue();
getProtocolHandler().setZoneIntensity(config.getControlUnit(), zone, fade, intensity);
} else if (command instanceof OnOffType) {
getProtocolHandler().setZoneIntensity(config.getControlUnit(), zone, fade,
} else if (id.equals(PrgConstants.CHANNEL_ZONERAISESTOP)) {
protocolHandler.setZoneRaiseStop();
} else if (id.equals(PrgConstants.CHANNEL_TIMECLOCK)) {
- if (command instanceof DateTimeType) {
- final ZonedDateTime zdt = ((DateTimeType) command).getZonedDateTime();
+ if (command instanceof DateTimeType dateTime) {
+ final ZonedDateTime zdt = dateTime.getZonedDateTime();
protocolHandler.setTime(GregorianCalendar.from(zdt));
} else {
logger.error("Received a TIMECLOCK channel command with a non DateTimeType: {}", command);
}
} else if (id.startsWith(PrgConstants.CHANNEL_SCHEDULE)) {
- if (command instanceof DecimalType) {
- final int schedule = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType scheduleCommand) {
+ final int schedule = scheduleCommand.intValue();
protocolHandler.selectSchedule(schedule);
} else {
logger.error("Received a SCHEDULE channel command with a non DecimalType: {}", command);
session.setCallback(callback);
String response = callback.getResponse();
- if (response.equals("login")) {
+ if ("login".equals(response)) {
session.sendCommand(username);
} else {
return "Protocol violation - wasn't initially a command failure or login prompt: " + response;
response = callback.getResponse();
// Burn the empty response if we got one (
- if (response.equals("")) {
+ if ("".equals(response)) {
response = callback.getResponse();
}
throw new IllegalArgumentException("m (matcher) cannot be null");
}
if (m.groupCount() == 5) {
- if (m.group(1).equals("255")) {
+ if ("255".equals(m.group(1))) {
logger.warn("Sunrise/Sunset needs to be enabled via Liason Software");
return;
}
final int controlUnit = Integer.parseInt(m.group(1));
for (int z = 1; z <= 8; z++) {
final String zi = m.group(z + 1);
- if (zi.equals("*") || zi.equals(Integer.toString(z - 1))) {
+ if ("*".equals(zi) || zi.equals(Integer.toString(z - 1))) {
continue; // not present
}
final int zid = convertIntensity(controlUnit, z, zi);
*/
String getResponse() throws Exception {
final Object lastResponse = responses.poll(5, TimeUnit.SECONDS);
- if (lastResponse instanceof String) {
- return (String) lastResponse;
- } else if (lastResponse instanceof Exception) {
- throw (Exception) lastResponse;
+ if (lastResponse instanceof String str) {
+ return str;
+ } else if (lastResponse instanceof Exception exception) {
+ throw exception;
} else if (lastResponse == null) {
throw new Exception("Didn't receive response in time");
} else {
final Object response = responsesQueue.poll(1, TimeUnit.SECONDS);
if (response != null) {
- if (response instanceof String) {
+ if (response instanceof String str) {
try {
logger.debug("Dispatching response: {}", response);
- ssCallback.responseReceived((String) response);
+ ssCallback.responseReceived(str);
} catch (Exception e) {
logger.warn("Exception occurred processing the response '{}': ", response, e);
}
- } else if (response instanceof Exception) {
+ } else if (response instanceof Exception exception) {
logger.debug("Dispatching exception: {}", response);
- ssCallback.responseException((Exception) response);
+ ssCallback.responseException(exception);
} else {
logger.error("Unknown response class: {}", response);
}
}
private void handleLiftCommand(Command command) {
- if (command instanceof PercentType) {
- int level = ((PercentType) command).intValue();
+ if (command instanceof PercentType liftPercent) {
+ int level = liftPercent.intValue();
output(TargetType.BLIND, OutputCommand.ACTION_LIFTLEVEL, level, null, null);
} else if (command.equals(UpDownType.UP)) {
output(TargetType.BLIND, OutputCommand.ACTION_STARTRAISINGLIFT, null, null, null);
}
private void handleTiltCommand(Command command) {
- if (command instanceof PercentType) {
- int level = ((PercentType) command).intValue();
+ if (command instanceof PercentType tiltPercent) {
+ int level = tiltPercent.intValue();
output(TargetType.BLIND, OutputCommand.ACTION_TILTLEVEL, Math.min(level, tiltMax), null, null);
} else if (command.equals(UpDownType.UP)) {
output(TargetType.BLIND, OutputCommand.ACTION_STARTRAISINGTILT, null, null, null);
import java.math.BigDecimal;
import java.util.Collection;
-import java.util.Collections;
+import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import org.openhab.binding.lutron.internal.action.DimmerActions;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singletonList(DimmerActions.class);
+ return List.of(DimmerActions.class);
}
@Override
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
if (channelUID.getId().equals(CHANNEL_LIGHTLEVEL)) {
- if (command instanceof Number) {
- int level = ((Number) command).intValue();
+ if (command instanceof Number number) {
+ int level = number.intValue();
output(TargetType.DIMMER, OutputCommand.ACTION_ZONELEVEL, level, new LutronDuration("0.25"), null);
} else if (command.equals(OnOffType.ON)) {
if (config.onToLast) {
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
if (channelUID.getId().equals(CHANNEL_FANLEVEL)) {
- if (command instanceof Number) {
- int level = ((Number) command).intValue();
+ if (command instanceof Number number) {
+ int level = number.intValue();
FanSpeedType speed = FanSpeedType.toFanSpeedType(level);
// output(TargetType.FAN, LutronCommand.ACTION_ZONELEVEL, level, null, null);
sendCommand(new OutputCommand(TargetType.FAN, LutronOperation.EXECUTE, getIntegrationId(),
greenMode(ModeCommand.ACTION_STEP, 2);
} else if (command == OnOffType.OFF) {
greenMode(ModeCommand.ACTION_STEP, 1);
- } else if (command instanceof Number) {
- Integer step = ((Number) command).intValue();
+ } else if (command instanceof Number number) {
+ Integer step = number.intValue();
if (step.intValue() >= GREENSTEP_MIN) {
greenMode(ModeCommand.ACTION_STEP, step);
}
String scrubbedLine;
for (String line : this.session.readLines()) {
- if (line.trim().equals("")) {
+ if ("".equals(line.trim())) {
// Sometimes we get an empty line (possibly only when prompts are disabled). Ignore them.
continue;
}
@NonNullByDefault
public class QSIOHandler extends BaseKeypadHandler {
- private static enum Component implements KeypadComponent {
+ private enum Component implements KeypadComponent {
CCI1(1, "cci1", "CCI 1", ComponentType.CCI),
CCI2(2, "cci2", "CCI 2", ComponentType.CCI),
CCI3(3, "cci3", "CCI 3", ComponentType.CCI),
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
if (channelUID.getId().equals(CHANNEL_SHADELEVEL)) {
- if (command instanceof PercentType) {
- int level = ((PercentType) command).intValue();
+ if (command instanceof PercentType shadePercent) {
+ int level = shadePercent.intValue();
output(TargetType.SHADE, OutputCommand.ACTION_ZONELEVEL, level, null, null);
if (leap) {
// LEAP may not send back a position update
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
if (channelUID.getId().equals(CHANNEL_VARSTATE)) {
- if (command instanceof Number) {
- int state = ((Number) command).intValue();
+ if (command instanceof Number number) {
+ int state = number.intValue();
sysvar(SysvarCommand.ACTION_GETSETSYSVAR, state);
}
}
logger.debug("Handling timeclock command {} on channel {}", command, channelID);
if (channelUID.getId().equals(CHANNEL_CLOCKMODE)) {
- if (command instanceof DecimalType) {
- Integer mode = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ Integer mode = decimalCommand.intValue();
timeclock(TimeclockCommand.ACTION_CLOCKMODE, mode, null);
} else if (command instanceof RefreshType) {
queryTimeclock(TimeclockCommand.ACTION_CLOCKMODE);
logger.debug("Invalid command type for clockmode channnel");
}
} else if (channelUID.getId().equals(CHANNEL_EXECEVENT)) {
- if (command instanceof DecimalType) {
- Integer index = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ Integer index = decimalCommand.intValue();
timeclock(TimeclockCommand.ACTION_EXECEVENT, index, null);
} else {
logger.debug("Invalid command type for execevent channnel");
logger.debug("Invalid command type for sunset channnel");
}
} else if (channelUID.getId().equals(CHANNEL_ENABLEEVENT)) {
- if (command instanceof DecimalType) {
- Integer index = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ Integer index = decimalCommand.intValue();
timeclock(TimeclockCommand.ACTION_SETEVENT, index, true);
} else {
logger.debug("Invalid command type for enableevent channnel");
}
} else if (channelUID.getId().equals(CHANNEL_DISABLEEVENT)) {
- if (command instanceof DecimalType) {
- Integer index = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ Integer index = decimalCommand.intValue();
timeclock(TimeclockCommand.ACTION_SETEVENT, index, false);
} else {
logger.debug("Invalid command type for disableevent channnel");
@NonNullByDefault
public class VcrxHandler extends BaseKeypadHandler {
- private static enum Component implements KeypadComponent {
+ private enum Component implements KeypadComponent {
BUTTON1(1, "button1", "Button 1", ComponentType.BUTTON),
BUTTON2(2, "button2", "Button 2", ComponentType.BUTTON),
BUTTON3(3, "button3", "Button 3", ComponentType.BUTTON),
@NonNullByDefault
public class WciHandler extends BaseKeypadHandler {
- private static enum Component implements KeypadComponent {
+ private enum Component implements KeypadComponent {
BUTTON1(1, "button1", "Button 1", ComponentType.BUTTON),
BUTTON2(2, "button2", "Button 2", ComponentType.BUTTON),
BUTTON3(3, "button3", "Button 3", ComponentType.BUTTON),
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
if (channelUID.getId().equals(CHANNEL_LIGHTLEVEL)) {
- if (command instanceof Number) {
- int level = ((Number) command).intValue();
+ if (command instanceof Number number) {
+ int level = number.intValue();
outputLevel(level);
} else if (command.equals(OnOffType.ON)) {
outputLevel(defaultLevel);
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof HwSerialBridgeHandler) {
- this.handler = (HwSerialBridgeHandler) handler;
+ if (handler instanceof HwSerialBridgeHandler bridgeHandler) {
+ this.handler = bridgeHandler;
this.handler.setDiscoveryService(this);
}
}
logger.info("Discovered HomeWorks dimmer with no address");
return;
}
- String addressUid = address.replaceAll("[\\[\\]]", "").replaceAll(":", "-");
+ String addressUid = address.replaceAll("[\\[\\]]", "").replace(":", "-");
ThingUID bridgeUID = this.handler.getThing().getUID();
ThingUID uid = new ThingUID(HwConstants.THING_TYPE_HWDIMMER, bridgeUID, addressUid);
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
-import java.util.Collections;
+import java.util.Set;
import java.util.TooManyListenersException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(HwDiscoveryService.class);
+ return Set.of(HwDiscoveryService.class);
}
@Override
* @return Concatenated list
*/
@SafeVarargs
- protected static final List<KeypadComponent> combinedList(final List<KeypadComponent>... lists) {
+ protected static List<KeypadComponent> combinedList(final List<KeypadComponent>... lists) {
List<KeypadComponent> newlist = new LinkedList<>();
for (List<KeypadComponent> list : lists) {
newlist.addAll(list);
@NonNullByDefault
public final class KeypadConfigGrafikEye extends KeypadConfig {
- private static enum Component implements KeypadComponent {
+ private enum Component implements KeypadComponent {
BUTTON1(70, "button1", "Button 1", ComponentType.BUTTON), // Scene button 1
BUTTON2(71, "button2", "Button 2", ComponentType.BUTTON), // Scene button 2
BUTTON3(76, "button3", "Button 3", ComponentType.BUTTON), // Scene button 3
@NonNullByDefault
public final class KeypadConfigIntlSeetouch extends KeypadConfig {
- private static enum Component implements KeypadComponent {
+ private enum Component implements KeypadComponent {
BUTTON1(1, "button1", "Button 1", ComponentType.BUTTON),
BUTTON2(2, "button2", "Button 2", ComponentType.BUTTON),
BUTTON3(3, "button3", "Button 3", ComponentType.BUTTON),
@NonNullByDefault
public final class KeypadConfigPalladiom extends KeypadConfig {
- private static enum Component implements KeypadComponent {
+ private enum Component implements KeypadComponent {
BUTTON1(1, "button1", "Button 1", ComponentType.BUTTON),
BUTTON2(2, "button2", "Button 2", ComponentType.BUTTON),
BUTTON3(3, "button3", "Button 3", ComponentType.BUTTON),
public static final Map<Integer, Integer> LEAPBUTTONS_4B = Map.of(8, 1, 9, 2, 10, 3, 11, 4);
public static final Map<Integer, Integer> LEAPBUTTONS_3BRL = Map.of(2, 1, 3, 2, 4, 3, 5, 4, 6, 5);
- private static enum Component implements KeypadComponent {
+ private enum Component implements KeypadComponent {
// Buttons for 2B, 2BRL, 3B, and 3BRL models
BUTTON1(2, "button1", "Button 1", ComponentType.BUTTON),
BUTTON2(3, "button2", "Button 2", ComponentType.BUTTON),
@NonNullByDefault
public final class KeypadConfigSeetouch extends KeypadConfig {
- private static enum Component implements KeypadComponent {
+ private enum Component implements KeypadComponent {
BUTTON1(1, "button1", "Button 1", ComponentType.BUTTON),
BUTTON2(2, "button2", "Button 2", ComponentType.BUTTON),
BUTTON3(3, "button3", "Button 3", ComponentType.BUTTON),
@NonNullByDefault
public final class KeypadConfigTabletopSeetouch extends KeypadConfig {
- private static enum Component implements KeypadComponent {
+ private enum Component implements KeypadComponent {
BUTTON1(1, "button1", "Button 1", ComponentType.BUTTON),
BUTTON2(2, "button2", "Button 2", ComponentType.BUTTON),
BUTTON3(3, "button3", "Button 3", ComponentType.BUTTON),
}
public int getNumberParameter(int position) {
- if (parameters.length > position && parameters[position] instanceof Number) {
- Number num = (Number) parameters[position];
+ if (parameters.length > position && parameters[position] instanceof Number num) {
return num.intValue();
} else {
throw new IllegalArgumentException("Invalid command parameter");
* @param msg String containing the LEAP message
*/
public void handleMessage(String msg) {
- if (msg.trim().equals("")) {
+ if ("".equals(msg.trim())) {
return; // Ignore empty lines
}
logger.trace("Received message: {}", msg);
public static final String BUTTON_GROUP_URL = "/buttongroup";
public static String goToLevel(int zone, int value) {
- String request = "{\"CommuniqueType\": \"CreateRequest\","
- + "\"Header\": {\"Url\": \"/zone/%d/commandprocessor\"}," + "\"Body\": {" + "\"Command\": {"
- + "\"CommandType\": \"GoToLevel\"," + "\"Parameter\": [{\"Type\": \"Level\", \"Value\": %d}]}}}";
+ String request = """
+ {"CommuniqueType": "CreateRequest",\
+ "Header": {"Url": "/zone/%d/commandprocessor"},\
+ "Body": {\
+ "Command": {\
+ "CommandType": "GoToLevel",\
+ "Parameter": [{"Type": "Level", "Value": %d}]}}}\
+ """;
return String.format(request, zone, value);
}
/** fadeTime must be in the format hh:mm:ss **/
public static String goToDimmedLevel(int zone, int value, String fadeTime) {
- String request = "{\"CommuniqueType\": \"CreateRequest\","
- + "\"Header\": {\"Url\": \"/zone/%d/commandprocessor\"},\"Body\": {\"Command\": {"
- + "\"CommandType\": \"GoToDimmedLevel\","
- + "\"DimmedLevelParameters\": {\"Level\": %d, \"FadeTime\": \"%s\"}}}}";
+ String request = """
+ {"CommuniqueType": "CreateRequest",\
+ "Header": {"Url": "/zone/%d/commandprocessor"},"Body": {"Command": {\
+ "CommandType": "GoToDimmedLevel",\
+ "DimmedLevelParameters": {"Level": %d, "FadeTime": "%s"}}}}\
+ """;
return String.format(request, zone, value, fadeTime);
}
/** fadeTime and delayTime must be in the format hh:mm:ss **/
public static String goToDimmedLevel(int zone, int value, String fadeTime, String delayTime) {
- String request = "{\"CommuniqueType\": \"CreateRequest\","
- + "\"Header\": {\"Url\": \"/zone/%d/commandprocessor\"},\"Body\": {\"Command\": {"
- + "\"CommandType\": \"GoToDimmedLevel\","
- + "\"DimmedLevelParameters\": {\"Level\": %d, \"FadeTime\": \"%s\", \"DelayTime\": \"%s\"}}}}";
+ String request = """
+ {"CommuniqueType": "CreateRequest",\
+ "Header": {"Url": "/zone/%d/commandprocessor"},"Body": {"Command": {\
+ "CommandType": "GoToDimmedLevel",\
+ "DimmedLevelParameters": {"Level": %d, "FadeTime": "%s", "DelayTime": "%s"}}}}\
+ """;
return String.format(request, zone, value, fadeTime, delayTime);
}
public static String goToFanSpeed(int zone, FanSpeedType fanSpeed) {
- String request = "{\"CommuniqueType\": \"CreateRequest\","
- + "\"Header\": {\"Url\": \"/zone/%d/commandprocessor\"}," + "\"Body\": {"
- + "\"Command\": {\"CommandType\": \"GoToFanSpeed\","
- + "\"FanSpeedParameters\": {\"FanSpeed\": \"%s\"}}}}";
+ String request = """
+ {"CommuniqueType": "CreateRequest",\
+ "Header": {"Url": "/zone/%d/commandprocessor"},\
+ "Body": {\
+ "Command": {"CommandType": "GoToFanSpeed",\
+ "FanSpeedParameters": {"FanSpeed": "%s"}}}}\
+ """;
return String.format(request, zone, fanSpeed.leapValue());
}
public static String buttonCommand(int button, CommandType command) {
- String request = "{\"CommuniqueType\": \"CreateRequest\","
- + "\"Header\": {\"Url\": \"/button/%d/commandprocessor\"},"
- + "\"Body\": {\"Command\": {\"CommandType\": \"%s\"}}}";
+ String request = """
+ {"CommuniqueType": "CreateRequest",\
+ "Header": {"Url": "/button/%d/commandprocessor"},\
+ "Body": {"Command": {"CommandType": "%s"}}}\
+ """;
return String.format(request, button, command.toString());
}
public static String virtualButtonCommand(int virtualbutton, CommandType command) {
- String request = "{\"CommuniqueType\": \"CreateRequest\","
- + "\"Header\": {\"Url\": \"/virtualbutton/%d/commandprocessor\"},"
- + "\"Body\": {\"Command\": {\"CommandType\": \"%s\"}}}";
+ String request = """
+ {"CommuniqueType": "CreateRequest",\
+ "Header": {"Url": "/virtualbutton/%d/commandprocessor"},\
+ "Body": {"Command": {"CommandType": "%s"}}}\
+ """;
return String.format(request, virtualbutton, command.toString());
}
public static String zoneCommand(int zone, CommandType commandType) {
- String request = "{\"CommuniqueType\": \"CreateRequest\","
- + "\"Header\": {\"Url\": \"/zone/%d/commandprocessor\"}," + "\"Body\": {" + "\"Command\": {"
- + "\"CommandType\": \"%s\"}}}";
+ String request = """
+ {"CommuniqueType": "CreateRequest",\
+ "Header": {"Url": "/zone/%d/commandprocessor"},\
+ "Body": {\
+ "Command": {\
+ "CommandType": "%s"}}}\
+ """;
return String.format(request, zone, commandType.toString());
}
SWITCH,
SYSVAR,
TIMECLOCK,
- VIRTUALKEYPAD;
+ VIRTUALKEYPAD
}
@Override
public void write(String command) {
- logger.debug("Writing to serial port: {}", command.toString());
+ logger.debug("Writing to serial port: {}", command);
SerialPort serialPort = this.serialPort;
try {
}
if (LutronBindingConstants.CHANNEL_LIGHTLEVEL.equals(channelUID.getId())) {
- if (command instanceof PercentType) {
- int intensity = ((PercentType) command).intValue();
+ if (command instanceof PercentType percentCommand) {
+ int intensity = percentCommand.intValue();
SetDimmerLevelCommand cmd = new SetDimmerLevelCommand(config.getZoneNumber(), intensity, config.system);
bridgeHandler.sendCommand(cmd);
updateInternalState(intensity);
}
- if (command instanceof OnOffType) {
- OnOffType onOffCmd = (OnOffType) command;
-
+ if (command instanceof OnOffType onOffCmd) {
SetSwitchLevelCommand cmd = new SetSwitchLevelCommand(config.getZoneNumber(), onOffCmd, config.system);
bridgeHandler.sendCommand(cmd);
@Override
public void handleFeedback(RadioRAFeedback feedback) {
- if (feedback instanceof LocalZoneChangeFeedback) {
- handleLocalZoneChangeFeedback((LocalZoneChangeFeedback) feedback);
- } else if (feedback instanceof ZoneMapFeedback) {
- handleZoneMapFeedback((ZoneMapFeedback) feedback);
+ if (feedback instanceof LocalZoneChangeFeedback localZoneChangeFeedback) {
+ handleLocalZoneChangeFeedback(localZoneChangeFeedback);
+ } else if (feedback instanceof ZoneMapFeedback zoneMapFeedback) {
+ handleZoneMapFeedback(zoneMapFeedback);
}
}
return null;
}
ThingHandler th = bridge.getHandler();
- if (th instanceof RS232Handler) {
- return (RS232Handler) th;
+ if (th instanceof RS232Handler handler) {
+ return handler;
} else {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Bridge not properly configured.");
return null;
@Override
public void handleFeedback(RadioRAFeedback feedback) {
- if (feedback instanceof LEDMapFeedback) {
- handleLEDMapFeedback((LEDMapFeedback) feedback);
+ if (feedback instanceof LEDMapFeedback ledMapFeedback) {
+ handleLEDMapFeedback(ledMapFeedback);
}
}
public void handleRadioRAFeedback(RadioRAFeedback feedback) {
for (Thing thing : getThing().getThings()) {
ThingHandler handler = thing.getHandler();
- if (handler instanceof LutronHandler) {
- ((LutronHandler) handler).handleFeedback(feedback);
+ if (handler instanceof LutronHandler lutronHandler) {
+ lutronHandler.handleFeedback(feedback);
} else {
logger.debug("Unexpected - Thing {} is not a LutronHandler", thing.getClass());
}
public void handleCommand(ChannelUID channelUID, Command command) {
RS232Handler bridgeHandler = getRS232Handler();
if (LutronBindingConstants.CHANNEL_SWITCH.equals(channelUID.getId())) {
- if (command instanceof OnOffType) {
- SetSwitchLevelCommand cmd = new SetSwitchLevelCommand(config.getZoneNumber(), (OnOffType) command,
+ if (command instanceof OnOffType onOffCommand) {
+ SetSwitchLevelCommand cmd = new SetSwitchLevelCommand(config.getZoneNumber(), onOffCommand,
config.system);
if (bridgeHandler != null) {
@Override
public void handleFeedback(RadioRAFeedback feedback) {
- if (feedback instanceof LocalZoneChangeFeedback) {
- handleLocalZoneChangeFeedback((LocalZoneChangeFeedback) feedback);
- } else if (feedback instanceof ZoneMapFeedback) {
- handleZoneMapFeedback((ZoneMapFeedback) feedback);
+ if (feedback instanceof LocalZoneChangeFeedback localZoneChangeFeedback) {
+ handleLocalZoneChangeFeedback(localZoneChangeFeedback);
+ } else if (feedback instanceof ZoneMapFeedback zoneMapFeedback) {
+ handleZoneMapFeedback(zoneMapFeedback);
}
}
}
if (system == 1 || system == 2) {
- args.add("S" + String.valueOf(system));
+ args.add("S" + system);
}
return args;
}
if (system == 1 || system == 2) {
- args.add("S" + String.valueOf(system));
+ args.add("S" + system);
}
return args;
}
if (system == 1 || system == 2) {
- args.add("S" + String.valueOf(system));
+ args.add("S" + system);
}
return args;
clear();
}
} else if (LuxomBindingConstants.CHANNEL_BRIGHTNESS.equals(channelUID.getId()) && config != null) {
- if (command instanceof Number) {
- int level = ((Number) command).intValue();
+ if (command instanceof Number number) {
+ int level = number.intValue();
logger.trace("dimmer at address {} just setting dimmer level", getAddress());
dim(level);
- } else if (command instanceof IncreaseDecreaseType) {
- IncreaseDecreaseType s = (IncreaseDecreaseType) command;
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
int currentValue = lastLightLevel.get();
int newValue;
- if (IncreaseDecreaseType.INCREASE.equals(s)) {
+ if (IncreaseDecreaseType.INCREASE.equals(increaseDecreaseCommand)) {
newValue = currentValue + config.stepPercentage;
// round down to step multiple
newValue = newValue - newValue % config.stepPercentage;
if (bridgeStatusInfo.getStatus() == ThingStatus.ONLINE
&& getThing().getStatusInfo().getStatusDetail() == ThingStatusDetail.BRIDGE_OFFLINE) {
initDeviceState();
-
} else if (bridgeStatusInfo.getStatus() == ThingStatus.OFFLINE) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE);
thingOfflineNotify();
// IP-interface.
(new Thread(this::runLuxomEvents,
"OH-binding-" + bridgeHandler.getThing().getBridgeUID() + "-listen-for-events")).start();
-
} catch (IOException | InterruptedException e) {
throw new LuxomConnectionException(e);
}
*/
package org.openhab.binding.luxtronikheatpump.internal;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
public static final ThingTypeUID THING_TYPE_HEATPUMP = new ThingTypeUID(BINDING_ID, "heatpump");
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_HEATPUMP);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_HEATPUMP);
}
return;
}
- if (command instanceof QuantityType) {
- QuantityType<?> value = (QuantityType<?>) command;
-
+ if (command instanceof QuantityType value) {
Unit<?> unit = channel.getUnit();
if (unit != null) {
value = value.toUnit(unit);
command = new DecimalType(value.floatValue());
}
- if (command instanceof OnOffType) {
- command = ((OnOffType) command) == OnOffType.ON ? new DecimalType(1) : DecimalType.ZERO;
+ if (command instanceof OnOffType onOffCommand) {
+ command = onOffCommand == OnOffType.ON ? new DecimalType(1) : DecimalType.ZERO;
}
if (!(command instanceof DecimalType)) {
this.name = name;
}
- public static final HeatpumpType fromCode(Integer code) {
+ public static HeatpumpType fromCode(Integer code) {
for (HeatpumpType error : HeatpumpType.values()) {
if (error.code.equals(code)) {
return error;
*/
package org.openhab.binding.magentatv.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_RECEIVER = new ThingTypeUID(BINDING_ID, "receiver");
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_RECEIVER);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_RECEIVER);
/**
* Property names for config/status properties
}
public void setPort(String port) {
- if (modelId.contains(MODEL_MR400) && port.equals("49153")) {
+ if (modelId.contains(MODEL_MR400) && "49153".equals(port)) {
// overwrite port returned by discovery (invalid for this model)
this.port = MR400_DEF_REMOTE_PORT;
} else {
public String getDescriptionUrl() {
if (descriptionUrl.equals(MR400_DEF_DESCRIPTION_URL)
- && !(port.equals(MR400_DEF_REMOTE_PORT) || port.equals("49153"))) {
+ && !(port.equals(MR400_DEF_REMOTE_PORT) || "49153".equals(port))) {
// MR401B returns the wrong URL
return MR401B_DEF_DESCRIPTION_URL;
}
import static org.openhab.binding.magentatv.internal.MagentaTVUtil.*;
import static org.openhab.core.thing.Thing.*;
-import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(THING_TYPE_RECEIVER);
+ return Set.of(THING_TYPE_RECEIVER);
}
/**
.substring(device.getIdentity().getUdn().getIdentifierString().length() - 12);
String mac = hex.substring(0, 2) + ":" + hex.substring(2, 4) + ":" + hex.substring(4, 6) + ":"
+ hex.substring(6, 8) + ":" + hex.substring(8, 10) + ":" + hex.substring(10, 12);
- if (port.equals("49153")) { // MR400 reports the rong
+ if ("49153".equals(port)) { // MR400 reports the rong
port = MR400_DEF_REMOTE_PORT;
}
properties.put(PROPERTY_VENDOR, VENDOR + "(" + manufacturer + ")");
if (result.contains("<X_wakeOnLan>")) {
String wol = substringBetween(result, "<X_wakeOnLan>", "</X_wakeOnLan>");
config.setWakeOnLAN(wol);
- logger.debug("{}: Wake-on-LAN is {}", thingId, wol.equals("0") ? "disabled" : "enabled");
+ logger.debug("{}: Wake-on-LAN is {}", thingId, "0".equals(wol) ? "disabled" : "enabled");
}
if (result.contains("<productVersionNumber>")) {
String version;
}
String result = substringBetween(response, "<result>", "</result>");
- if (!result.equals("0")) {
+ if (!"0".equals(result)) {
throw new MagentaTVException("Pairing failed, result=" + result);
}
}
String result = getXmlValue(response, "pairingResult");
- if (!result.equals("0")) {
+ if (!"0".equals(result)) {
logger.debug("{}: Pairing failed or pairing no longer valid, result={}", thingId, result);
resetPairing();
// let the caller decide how to proceed
}
try {
- if (!isOnline() || command.toString().equalsIgnoreCase("PAIR")) {
+ if (!isOnline() || "PAIR".equalsIgnoreCase(command.toString())) {
logger.debug("{}: Receiver {} is offline, try to (re-)connect", thingId, deviceName());
connectReceiver(); // reconnect to MR, throws an exception if this fails
}
}
break;
case CHANNEL_KEY:
- if (command.toString().equalsIgnoreCase("PAIR")) { // special key to re-pair receiver (already done
+ if ("PAIR".equalsIgnoreCase(command.toString())) { // special key to re-pair receiver (already done
// above)
logger.debug("{}: PAIRing key received, reconnect receiver {}", thingId, deviceName());
} else {
* @throws IOException
*/
public String sendData(String remoteIp, String remotePort, String data) throws MagentaTVException {
-
String errorMessage = "";
StringBuffer response = new StringBuffer();
try (Socket socket = new Socket()) {
*/
public void initLocalNet(String localIP, String localPort) throws MagentaTVException {
try {
- if (localIP.isEmpty() || localIP.equals("0.0.0.0") || localIP.equals("127.0.0.1")) {
+ if (localIP.isEmpty() || "0.0.0.0".equals(localIP) || "127.0.0.1".equals(localIP)) {
throw new MagentaTVException("Unable to detect local IP address!");
}
this.localPort = localPort;
@Override
protected void service(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response)
throws ServletException, IOException {
-
String data = inputStreamToString(request);
try {
if ((request == null) || (response == null)) {
}
} else {
if (data.contains("STB_")) {
- data = data.replaceAll(""", "\"");
+ data = data.replace(""", "\"");
String stbMac = substringBetween(data, "<STB_Mac>", "</STB_Mac>");
String stbEvent = "";
if (data.contains("<STB_playContent>")) {
if (cred.sam3Para != null) {
for (OauthKeyValue si : cred.sam3Para) {
logger.trace("sam3Para.{} = {}", si.key, si.value);
- if (si.key.equalsIgnoreCase("oAuthScope")) {
+ if ("oAuthScope".equalsIgnoreCase(si.key)) {
oAuthScope = si.value;
- } else if (si.key.equalsIgnoreCase("SAM3ServiceURL")) {
+ } else if ("SAM3ServiceURL".equalsIgnoreCase(si.key)) {
oAuthService = si.value;
}
}
// validate response, API errors are reported as Json
HttpFields responseHeaders = contentResponse.getHeaders();
for (HttpField f : responseHeaders) {
- if (f.getName().equals("Set-Cookie")) {
+ if ("Set-Cookie".equals(f.getName())) {
HttpCookie c = new HttpCookie(f.getName(), f.getValue());
cookies.add(c);
}
if (fieldName.startsWith("x-java-") && fieldName.length() > 7) {
String command = fieldName.substring(7);
value = value.trim();
- if (command.equals("fallback-entry")) {
- if (value.equals("true")) {
+ if ("fallback-entry".equals(command)) {
+ if ("true".equals(value)) {
fallback = true;
}
}
}
Object rawContent = message.getContent();
String contentAsString;
- if (rawContent instanceof String) {
+ if (rawContent instanceof String str) {
logger.trace("Detected plain text message");
- contentAsString = (String) rawContent;
+ contentAsString = str;
} else if (rawContent instanceof MimeMessage mimeMessage) {
logger.trace("Detected MIME message");
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
Field dataField = dataSource.getClass().getDeclaredField("data");
dataField.setAccessible(true);
Object data = dataField.get(dataSource);
- if (data instanceof MimeMultipart) {
- MimeMultipart mimeMultipart = (MimeMultipart) data;
+ if (data instanceof MimeMultipart mimeMultipart) {
for (int i = 0; i < mimeMultipart.getCount(); i++) {
Part mimePart = mimeMultipart.getBodyPart(i);
mimePart.getDataHandler().setCommandMap(commandMap);
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof SMTPHandler) {
- this.handler = (SMTPHandler) handler;
+ if (handler instanceof SMTPHandler smtpHandler) {
+ this.handler = smtpHandler;
}
}
* the hex value to be parsed into an integer
* @return the given hex value as integer
*/
- public static final int fromHex(String hex) {
+ public static int fromHex(String hex) {
return Integer.parseInt(hex, 16);
}
* the integer values to be converted into hexadecimal numbers
* @return the given numbers as hexadecimal number
*/
- public static final String toHex(int... values) {
+ public static String toHex(int... values) {
String returnValue = "";
for (int v : values) {
returnValue += v < 16 ? "0" + Integer.toHexString(v).toUpperCase() : Integer.toHexString(v).toUpperCase();
* hexadecimal numbers
* @return the hexadecimal number
*/
- public static final String toHex(boolean[] bits) {
+ public static String toHex(boolean[] bits) {
int retVal = 0;
for (int i = 0; i < bits.length; ++i) {
retVal |= (bits[i] ? 1 : 0) << i;
* the byte to be converted into its integer value
* @return the integer value represented by the given byte
*/
- public static final int fromByte(byte b) {
+ public static int fromByte(byte b) {
return b & 0xFF;
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof MaxCubeBridgeHandler) {
- this.handler = (MaxCubeBridgeHandler) handler;
+ if (handler instanceof MaxCubeBridgeHandler bridgeHandler) {
+ this.handler = bridgeHandler;
}
}
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof MaxDevicesHandler) {
- this.handler = (MaxDevicesHandler) handler;
+ if (handler instanceof MaxDevicesHandler devicesHandler) {
+ this.handler = devicesHandler;
}
}
@Override
public String getCommandString() {
- String cmd = "c:" + rfAddress + '\r' + '\n';
- return cmd;
+ return "c:" + rfAddress + '\r' + '\n';
}
@Override
// Check if the message is correct
if (message.startsWith("eQ3Max") && !message.equals(MAXCUBE_COMMAND_STRING)) {
- commandResponse.put("maxCubeIP", receivePacket.getAddress().getHostAddress().toString());
+ commandResponse.put("maxCubeIP", receivePacket.getAddress().getHostAddress());
commandResponse.put("maxCubeState", message.substring(0, 8));
commandResponse.put("serialNumber", message.substring(8, 18));
commandResponse.put("msgValidid", message.substring(18, 19));
String requestType = message.substring(19, 20);
commandResponse.put("requestType", requestType);
- if (requestType.equals("I")) {
+ if ("I".equals(requestType)) {
commandResponse.put("rfAddress",
Utils.getHex(message.substring(21, 24).getBytes(StandardCharsets.UTF_8))
.replace(" ", "").toLowerCase());
logger.trace("Msg Valid : {}", msgValidid);
logger.trace("Msg Type : {}", requestType);
- if (requestType.equals("I")) {
+ if ("I".equals(requestType)) {
rfAddress = Utils.getHex(Arrays.copyOfRange(messageBuf, 21, 24)).replace(" ", "").toLowerCase();
String firmwareVersion = Utils.getHex(Arrays.copyOfRange(messageBuf, 24, 26)).replace(" ", ".");
logger.debug("RF Address: {}", rfAddress);
@Override
public void setThingHandler(@NonNullByDefault({}) ThingHandler handler) {
- if (handler instanceof MaxCubeBridgeHandler) {
- this.maxCubeBridgeHandler = (MaxCubeBridgeHandler) handler;
+ if (handler instanceof MaxCubeBridgeHandler maxCubeBridgeHandler) {
+ this.maxCubeBridgeHandler = maxCubeBridgeHandler;
}
}
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(MaxDevicesActions.class);
+ return Set.of(MaxDevicesActions.class);
}
private void sendPropertyUpdate(Map<String, Object> configurationParameters, Map<String, Object> deviceProperties) {
configuration.put(PROPERTY_ROOMNAME, device.getRoomName());
config_changed = true;
}
- if (getConfig().get(PROPERTY_ROOMID) == null || !(new BigDecimal(device.getRoomId())
- .compareTo((BigDecimal) getConfig().get(PROPERTY_ROOMID)) == 0)) {
+ if (getConfig().get(PROPERTY_ROOMID) == null || new BigDecimal(device.getRoomId())
+ .compareTo((BigDecimal) getConfig().get(PROPERTY_ROOMID)) != 0) {
configuration.put(PROPERTY_ROOMID, new BigDecimal(device.getRoomId()));
config_changed = true;
}
* This is can be used to find duplicated commands in the queue
*/
private static String getKey(String serialNumber, CubeCommand cubeCommand) {
- String key = serialNumber + "-" + cubeCommand.getClass().getSimpleName();
- return key;
+ return serialNumber + "-" + cubeCommand.getClass().getSimpleName();
}
/**
}
}
} else {
- if ((!counter.equals(this.numberOfRequiredLines)) || (!(index == this.receivedLines.size()))) {
+ if (!counter.equals(this.numberOfRequiredLines) || index != this.receivedLines.size()) {
throw new IncorrectMultilineIndexException();
}
private List<Device> devices = new ArrayList<>();
private List<RoomInformation> rooms = new ArrayList<>();
- String deviceCMsg[] = {
+ String[] deviceCMsg = {
"C:0b0da3,0gsNowIBEABLRVEwNTQ0MjQyLCQ9CQcYAzAM/wBIYViRSP1ZFE0gTSBNIEUgRSBFIEUgRSBFIEhhWJFQ/VkVUSBRIFEgRSBFIEUgRSBFIEUgSFBYWkj+WRRNIE0gTSBFIEUgRSBFIEUgRSBIUFhaSP5ZFE0gTSBNIEUgRSBFIEUgRSBFIEhQWFpI/lkUTSBNIE0gRSBFIEUgRSBFIEUgSFBYWkj+WRRNIE0gTSBFIEUgRSBFIEUgRSBIUFhaSP5ZFE0gTSBNIEUgRSBFIEUgRSBFIA==",
"C:08c1d6,0gjB1gEFGP9LRVEwNjQ5MzEyKyE9CQcYAzAM/wBEeFUgVSBVIFUgVSBVIEUgRSBFIEUgRSBFIER4VRZFIEUgRSBFIEUgRSBFIEUgRSBFIEUgRFFEYkTkTQ9FIEUgRSBFIEUgRSBFIEUgRSBEUURiRORND0UgRSBFIEUgRSBFIEUgRSBFIERRRGJE5E0PRSBFIEUgRSBFIEUgRSBFIEUgRFFEYkTkTQ9FIEUgRSBFIEUgRSBFIEUgRSBEUURiRORRGEUgRSBFIEUgRSBFIEUgRSBFIA==",
"C:0e75f6,EQ519gQCEABLRVExMTA0Mzgw",
@Test
public void getBitsTest() {
- boolean b1[] = Utils.getBits(0xFF);
+ boolean[] b1 = Utils.getBits(0xFF);
assertEquals(b1.length, 8);
for (int i = 0; i < 8; i++) {
assertEquals(true, b1[i]);
}
- boolean b2[] = Utils.getBits(0x5A);
+ boolean[] b2 = Utils.getBits(0x5A);
assertEquals(b2.length, 8);
assertEquals(false, b2[0]);
JsonArray array = deviceInfo.getAsJsonArray("PatientDevices");
JsonObject patient = array.get(0).getAsJsonObject();
if (patient.has("UuidPerson") && !patient.get("UuidPerson").isJsonNull()) {
- return "https://cunds-syncapi.azurewebsites.net/api/ApiSensor/GetLatestApiSensorEvents"
- + "?UuidPatient=" + patient.get("UuidPerson").getAsString() + "&SerialNumber="
- + serialNumber + "&Count=1";
+ return """
+ https://cunds-syncapi.azurewebsites.net/api/ApiSensor/GetLatestApiSensorEvents\
+ ?UuidPatient=\
+ """ + patient.get("UuidPerson").getAsString() + "&SerialNumber=" + serialNumber
+ + "&Count=1";
}
} else if (deviceInfo.has("OrganisationUnitDevices")
&& deviceInfo.getAsJsonArray("OrganisationUnitDevices").size() != 0) {
JsonArray array = deviceInfo.getAsJsonArray("OrganisationUnitDevices");
JsonObject orgUnit = array.get(0).getAsJsonObject();
if (orgUnit.has("UuidOrganisationUnit") && !orgUnit.get("UuidOrganisationUnit").isJsonNull()) {
- return "https://cunds-syncapi.azurewebsites.net/api/ApiSensor/GetLatestApiSensorEvents"
- + "?UuidOrganisationUnit=" + orgUnit.get("UuidOrganisationUnit").getAsString()
- + "&SerialNumber=" + serialNumber + "&Count=1";
+ return """
+ https://cunds-syncapi.azurewebsites.net/api/ApiSensor/GetLatestApiSensorEvents\
+ ?UuidOrganisationUnit=\
+ """ + orgUnit.get("UuidOrganisationUnit").getAsString() + "&SerialNumber="
+ + serialNumber + "&Count=1";
}
}
} else {
@Test
public void getLatestValueFromJsonObjectTest() {
- String arrayString = "[\n" + " {\n" + " \"IdPatient\": 1,\n" + " \"LastName\": \"Mustermann\",\n"
- + " \"FirstName\": \"Max\",\n" + " \"Devices\": [\n" + " {\n" + " \"IdDevice\": 2,\n"
- + " \"SerialNumber\": \"001\",\n" + " \"Name\": \"Test Sitzkissen\",\n"
- + " \"Events\": [\n" + " {\n" + " \"EventDef\": \"Alarm\",\n"
- + " \"DateEntry\": \"2021-11-22T10:17:56.2866667\"\n" + " }\n" + " ]\n"
- + " }\n" + " ]\n" + " }\n" + "]";
+ String arrayString = """
+ [
+ {
+ "IdPatient": 1,
+ "LastName": "Mustermann",
+ "FirstName": "Max",
+ "Devices": [
+ {
+ "IdDevice": 2,
+ "SerialNumber": "001",
+ "Name": "Test Sitzkissen",
+ "Events": [
+ {
+ "EventDef": "Alarm",
+ "DateEntry": "2021-11-22T10:17:56.2866667"
+ }
+ ]
+ }
+ ]
+ }
+ ]\
+ """;
JsonArray array = gson.fromJson(arrayString, JsonArray.class);
JsonObject object = SensorThingHandler.getLatestValueFromJsonArray(array);
String string = object != null ? object.toString() : null;
assertEquals("{\"EventDef\":\"Alarm\",\"DateEntry\":\"2021-11-22T10:17:56.2866667\"}", string);
- arrayString = "[\n" + " {\n" + " \"IdPatient\": 1,\n" + " \"LastName\": \"Mustermann\",\n"
- + " \"FirstName\": \"Max\",\n" + " \"Devices\": [\n" + " {\n" + " \"IdDevice\": 2,\n"
- + " \"SerialNumber\": \"001\",\n" + " \"Name\": \"Test Sitzkissen\"\n" + " }\n"
- + " ]\n" + " }\n" + "]";
+ arrayString = """
+ [
+ {
+ "IdPatient": 1,
+ "LastName": "Mustermann",
+ "FirstName": "Max",
+ "Devices": [
+ {
+ "IdDevice": 2,
+ "SerialNumber": "001",
+ "Name": "Test Sitzkissen"
+ }
+ ]
+ }
+ ]\
+ """;
array = gson.fromJson(arrayString, JsonArray.class);
assertNull(SensorThingHandler.getLatestValueFromJsonArray(array));
}
import static org.openhab.binding.mcp23017.internal.Mcp23017BindingConstants.THING_TYPE_MCP23017;
-import java.util.Collections;
import java.util.Set;
import org.openhab.binding.mcp23017.internal.handler.Mcp23017Handler;
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.mcp23017")
public class Mcp23017HandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_MCP23017);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_MCP23017);
private final Logger logger = LoggerFactory.getLogger(Mcp23017HandlerFactory.class);
@Override
throw new MeaterException("Failed to fetch from API!");
} catch (ExecutionException e) {
Throwable cause = e.getCause();
- if (cause != null && cause instanceof HttpResponseException) {
- Response response = ((HttpResponseException) cause).getResponse();
+ if (cause instanceof HttpResponseException httpResponseException) {
+ Response response = httpResponseException.getResponse();
if (response.getStatus() == HttpStatus.UNAUTHORIZED_401) {
/*
* When contextId is not valid, the service will respond with HTTP code 401 without
for (Thing thing : thingRegistry.getAll()) {
ThingHandler thingHandler = thing.getHandler();
- if (thingHandler instanceof MeaterBridgeHandler) {
+ if (thingHandler instanceof MeaterBridgeHandler bridgeHandler) {
console.println("API bridge: " + thing.getLabel());
- ((MeaterBridgeHandler) thingHandler).getMeaterThings().entrySet().stream().forEach(t -> {
+ bridgeHandler.getMeaterThings().entrySet().stream().forEach(t -> {
console.println(" - ID: " + t.getKey() + " (ambient temperature: "
+ t.getValue().temperature.ambient + ")");
});
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof MeaterBridgeHandler) {
- this.handler = (MeaterBridgeHandler) handler;
- i18nProvider = ((MeaterBridgeHandler) handler).getI18nProvider();
- localeProvider = ((MeaterBridgeHandler) handler).getLocaleProvider();
+ if (handler instanceof MeaterBridgeHandler bridgeHandler) {
+ this.handler = bridgeHandler;
+ i18nProvider = bridgeHandler.getI18nProvider();
+ localeProvider = bridgeHandler.getLocaleProvider();
}
}
import static org.openhab.binding.meater.internal.MeaterBindingConstants.*;
import java.util.Collection;
-import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
private final Logger logger = LoggerFactory.getLogger(MeaterBridgeHandler.class);
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_BRIDGE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BRIDGE);
private final Gson gson;
private final HttpClient httpClient;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(MeaterDiscoveryService.class);
+ return Set.of(MeaterDiscoveryService.class);
}
@Override
ThingTypeUID thingTypeUID = thing.getThingTypeUID();
if (THING_TYPE_MELCLOUD_ACCOUNT.equals(thingTypeUID)) {
- MelCloudAccountHandler handler = new MelCloudAccountHandler((Bridge) thing);
- return handler;
+ return new MelCloudAccountHandler((Bridge) thing);
} else if (THING_TYPE_ACDEVICE.equals(thingTypeUID)) {
- MelCloudDeviceHandler handler = new MelCloudDeviceHandler(thing);
- return handler;
+ return new MelCloudDeviceHandler(thing);
} else if (THING_TYPE_HEATPUMPDEVICE.equals(thingTypeUID)) {
- MelCloudHeatpumpDeviceHandler handler = new MelCloudHeatpumpDeviceHandler(thing);
- return handler;
+ return new MelCloudHeatpumpDeviceHandler(thing);
}
return null;
try {
String response = HttpUtil.executeUrl("GET", url, getHeaderProperties(), null, null, TIMEOUT_MILLISECONDS);
logger.debug("Device status response: {}", response);
- DeviceStatus deviceStatus = gson.fromJson(response, DeviceStatus.class);
- return deviceStatus;
+ return gson.fromJson(response, DeviceStatus.class);
} catch (IOException | JsonSyntaxException e) {
setConnected(false);
throw new MelCloudCommException("Error occurred during device status fetch", e);
try {
String response = HttpUtil.executeUrl("GET", url, getHeaderProperties(), null, null, TIMEOUT_MILLISECONDS);
logger.debug("Device heatpump status response: {}", response);
- HeatpumpDeviceStatus heatpumpDeviceStatus = gson.fromJson(response, HeatpumpDeviceStatus.class);
- return heatpumpDeviceStatus;
+ return gson.fromJson(response, HeatpumpDeviceStatus.class);
} catch (IOException | JsonSyntaxException e) {
setConnected(false);
throw new MelCloudCommException("Error occurred during heatpump device status fetch", e);
Map<String, Object> deviceProperties = new HashMap<>();
deviceProperties.put(PROPERTY_DEVICE_ID, device.getDeviceID().toString());
- deviceProperties.put(Thing.PROPERTY_SERIAL_NUMBER, device.getSerialNumber().toString());
- deviceProperties.put(Thing.PROPERTY_MAC_ADDRESS, device.getMacAddress().toString());
- deviceProperties.put("deviceName", device.getDeviceName().toString());
+ deviceProperties.put(Thing.PROPERTY_SERIAL_NUMBER, device.getSerialNumber());
+ deviceProperties.put(Thing.PROPERTY_MAC_ADDRESS, device.getMacAddress());
+ deviceProperties.put("deviceName", device.getDeviceName());
deviceProperties.put("buildingID", device.getBuildingID().toString());
String label = createLabel(device);
} else if (device.getType() == 1) {
sb.append("Heatpump Device - ");
}
- if (device.getBuildingName() != null && device.getBuildingName() instanceof String) {
+ if (device.getBuildingName() instanceof String) {
sb.append(device.getBuildingName()).append(" - ");
}
sb.append(device.getDeviceName());
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof MelCloudAccountHandler) {
- melCloudHandler = (MelCloudAccountHandler) handler;
+ if (handler instanceof MelCloudAccountHandler accountHandler) {
+ melCloudHandler = accountHandler;
}
}
import java.util.Collections;
import java.util.List;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(MelCloudDiscoveryService.class);
+ return Set.of(MelCloudDiscoveryService.class);
}
@Override
@Override
public void dispose() {
- if (!server.isEmpty()) {
+ if (server.isPresent()) {
CallbackServer serv = server.get();
serv.stop();
serv.dispose();
logger.debug("Image {} is empty", key);
}
}
- } else if (channelUID.getIdWithoutGroup().equals("clear-cache") && command.equals(OnOffType.ON)) {
+ } else if ("clear-cache".equals(channelUID.getIdWithoutGroup()) && command.equals(OnOffType.ON)) {
List<String> removals = new ArrayList<String>();
imageStorage.get().getKeys().forEach(entry -> {
if (entry.contains("_" + config.get().vin)) {
public boolean start() {
LOGGER.debug("Start Callback Server for port {}", config.callbackPort);
- if (!server.isEmpty()) {
+ if (server.isPresent()) {
LOGGER.debug("Callback server for port {} already started", config.callbackPort);
return true;
}
public void stop() {
LOGGER.debug("Stop Callback Server");
try {
- if (!server.isEmpty()) {
+ if (server.isPresent()) {
server.get().stop();
server = Optional.empty();
}
AlertLevel alertLevel = ordinal < AlertLevel.values().length ? AlertLevel.values()[ordinal]
: AlertLevel.UNKNOWN;
icon = icon.replaceAll(AlertLevel.UNKNOWN.color, alertLevel.color);
-
} catch (NumberFormatException e) {
logger.debug("{} is not a valid DecimalType", state);
}
@NonNullByDefault
public class MeteoAlerteHandler extends BaseThingHandler {
private static final int TIMEOUT_MS = 30000;
- private static final String URL = "https://public.opendatasoft.com/api/records/1.0/search/?dataset=risques-meteorologiques-copy&"
- + "facet=etat_vent&facet=etat_pluie_inondation&facet=etat_orage&facet=etat_inondation&facet=etat_neige&facet=etat_canicule&"
- + "facet=etat_grand_froid&facet=etat_avalanches&refine.nom_dept=%s";
+ private static final String URL = """
+ https://public.opendatasoft.com/api/records/1.0/search/?dataset=risques-meteorologiques-copy&\
+ facet=etat_vent&facet=etat_pluie_inondation&facet=etat_orage&facet=etat_inondation&facet=etat_neige&facet=etat_canicule&\
+ facet=etat_grand_froid&facet=etat_avalanches&refine.nom_dept=%s\
+ """;
private final Logger logger = LoggerFactory.getLogger(MeteoAlerteHandler.class);
private final MeteoAlertIconProvider iconProvider;
// generic getter
public Object getDatapoint(String datapointName) {
- if (datapointName.equals("condition")) {
+ if ("condition".equals(datapointName)) {
return String.valueOf(pictocode);
}
package org.openhab.binding.meteoblue.internal;
import java.util.Arrays;
-import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public static final ThingTypeUID THING_TYPE_WEATHER = new ThingTypeUID(BINDING_ID, "weather");
public static final ThingTypeUID THING_TYPE_BRIDGE = new ThingTypeUID(BINDING_ID, "bridge");
- public static final Set<ThingTypeUID> BRIDGE_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_BRIDGE);
+ public static final Set<ThingTypeUID> BRIDGE_THING_TYPES_UIDS = Set.of(THING_TYPE_BRIDGE);
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = new HashSet<>(Arrays.asList(THING_TYPE_WEATHER));
// Bridge configuration settings
import static org.openhab.binding.meteoblue.internal.MeteoBlueBindingConstants.THING_TYPE_BRIDGE;
-import java.util.Collections;
import java.util.Set;
import org.openhab.binding.meteoblue.internal.MeteoBlueBridgeConfig;
* @author Chris Carman - Initial contribution
*/
public class MeteoBlueBridgeHandler extends BaseBridgeHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_BRIDGE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BRIDGE);
private final Logger logger = LoggerFactory.getLogger(MeteoBlueBridgeHandler.class);
private String apiKey;
// Build a State from this value
State state = null;
- if (datapoint instanceof Calendar) {
- state = new DateTimeType(
- ZonedDateTime.ofInstant(((Calendar) datapoint).toInstant(), ZoneId.systemDefault()));
+ if (datapoint instanceof Calendar calendar) {
+ state = new DateTimeType(ZonedDateTime.ofInstant(calendar.toInstant(), ZoneId.systemDefault()));
} else if (datapoint instanceof Integer) {
state = getStateForType(channel.getAcceptedItemType(), (Integer) datapoint);
} else if (datapoint instanceof Number) {
state = getStateForType(channel.getAcceptedItemType(), decimalValue);
} else if (datapoint instanceof String) {
state = new StringType(datapoint.toString());
- } else if (datapoint instanceof BufferedImage) {
+ } else if (datapoint instanceof BufferedImage image) {
ImageItem item = new ImageItem("rain area");
- state = new RawType(renderImage((BufferedImage) datapoint), "image/png");
+ state = new RawType(renderImage(image), "image/png");
item.setState(state);
} else {
logger.debug("Unsupported value type {}", datapoint.getClass().getSimpleName());
private State getStateForType(String type, BigDecimal value) {
State state = new DecimalType(value);
- if (type.equals("Number:Temperature")) {
+ if ("Number:Temperature".equals(type)) {
state = new QuantityType<>(value, SIUnits.CELSIUS);
- } else if (type.equals("Number:Length")) {
+ } else if ("Number:Length".equals(type)) {
state = new QuantityType<>(value, MILLI(SIUnits.METRE));
- } else if (type.equals("Number:Pressure")) {
+ } else if ("Number:Pressure".equals(type)) {
state = new QuantityType<>(value, HECTO(SIUnits.PASCAL));
- } else if (type.equals("Number:Speed")) {
+ } else if ("Number:Speed".equals(type)) {
state = new QuantityType<>(value, Units.METRE_PER_SECOND);
}
String errorMessage = jsonResult.getErrorMessage();
if (errorMessage != null) {
- if (errorMessage.equals("MB_REQUEST::DISPATCH: Invalid api key")) {
+ if ("MB_REQUEST::DISPATCH: Invalid api key".equals(errorMessage)) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Invalid API Key");
- } else if (errorMessage.equals("MB_REQUEST::DISPATCH: This datafeed is not authorized for your api key")) {
+ } else if ("MB_REQUEST::DISPATCH: This datafeed is not authorized for your api key".equals(errorMessage)) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
"API Key not authorized for this datafeed");
} else {
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
-import java.util.Collections;
import java.util.Date;
import java.util.Set;
import java.util.TooManyListenersException;
* @author Chris Jackson - Initial contribution
*/
public class MeteostickBridgeHandler extends BaseBridgeHandler {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_BRIDGE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BRIDGE);
private final Logger logger = LoggerFactory.getLogger(MeteostickBridgeHandler.class);
if (rxByte == 13 && rxCnt > 0) {
String inputString = new String(rxPacket, 0, rxCnt);
logger.debug("MeteoStick received: {}", inputString);
- String p[] = inputString.split("\\s+");
+ String[] p = inputString.split("\\s+");
switch (p[0]) {
case "B": // Barometer
*
* @param data a line of data from the meteoStick
*/
- void onDataReceived(String data[]);
+ void onDataReceived(String[] data);
}
* @author John Cocula - Added variable spoon size, UoM, wind stats, bug fixes
*/
public class MeteostickSensorHandler extends BaseThingHandler implements MeteostickEventListener {
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_DAVIS);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_DAVIS);
private final Logger logger = LoggerFactory.getLogger(MeteostickSensorHandler.class);
ThingTypeUID thingTypeUID = getThingTypeUidFromModelId(modelId);
if (getSupportedThingTypes().contains(thingTypeUID)) {
- ThingUID thingUID = new ThingUID(thingTypeUID, bridgeUID, appliance.getApplianceIdentifier().getId());
- return thingUID;
+ return new ThingUID(thingTypeUID, bridgeUID, appliance.getApplianceIdentifier().getId());
} else {
return null;
}
}
}
+ @Override
public State getState(String s) {
try {
Method valueOf = typeClass.getMethod("valueOf", String.class);
}
}
+ @Override
public State getState(String s) {
try {
Method valueOf = typeClass.getMethod("valueOf", String.class);
updateSwitchStartStopFromState(dp);
}
+ @Override
public void onApplianceExtendedStateChanged(byte[] extendedDeviceState) {
if (extendedDeviceState.length < EXTENDED_STATE_MIN_SIZE_BYTES) {
logger.debug("Insufficient extended state data to extract consumption values: {}", extendedDeviceState);
}
}
+ @Override
public State getState(String s) {
try {
Method valueOf = typeClass.getMethod("valueOf", String.class);
}
}
+ @Override
public State getState(String s) {
try {
Method valueOf = typeClass.getMethod("valueOf", String.class);
}
}
+ @Override
public State getState(String s) {
try {
Method valueOf = typeClass.getMethod("valueOf", String.class);
}
}
+ @Override
public State getState(String s) {
try {
Method valueOf = typeClass.getMethod("valueOf", String.class);
byte[] extendedStateBytes = DeviceUtil.stringToBytes(dp.Value);
logger.trace("Extended device state for {}: {}", getThing().getUID(),
DeviceUtil.bytesToHex(extendedStateBytes));
- if (this instanceof ExtendedDeviceStateListener) {
- ((ExtendedDeviceStateListener) this).onApplianceExtendedStateChanged(extendedStateBytes);
+ if (this instanceof ExtendedDeviceStateListener listener) {
+ listener.onApplianceExtendedStateChanged(extendedStateBytes);
}
}
return;
return null;
}
ThingHandler handler = bridge.getHandler();
- if (handler instanceof MieleBridgeHandler) {
- this.bridgeHandler = (MieleBridgeHandler) handler;
+ if (handler instanceof MieleBridgeHandler mieleBridgeHandler) {
+ this.bridgeHandler = mieleBridgeHandler;
}
}
return this.bridgeHandler;
}
}
+ @Override
public State getState(String s) {
try {
Method valueOf = typeClass.getMethod("valueOf", String.class);
}
}
+ @Override
public State getState(String s) {
try {
Method valueOf = typeClass.getMethod("valueOf", String.class);
}
}
+ @Override
public State getState(String s) {
try {
Method valueOf = typeClass.getMethod("valueOf", String.class);
updateSwitchStartStopFromState(dp);
}
+ @Override
public void onApplianceExtendedStateChanged(byte[] extendedDeviceState) {
if (extendedDeviceState.length < EXTENDED_STATE_MIN_SIZE_BYTES) {
logger.debug("Insufficient extended state data to extract consumption values: {}", extendedDeviceState);
private String getLocale(Bridge bridge) {
var locale = bridge.getConfiguration().get(MieleCloudBindingConstants.CONFIG_PARAM_LOCALE);
- if (locale instanceof String) {
- return (String) locale;
+ if (locale instanceof String str) {
+ return str;
} else {
return "en";
}
private String renderSslWarning(HttpServletRequest request, String skeleton) {
if (!request.isSecure()) {
- return skeleton.replace(NO_SSL_WARNING_PLACEHOLDER, "<div class=\"alert alert-danger\" role=\"alert\">\n"
- + " Warning: We strongly advice to proceed only with SSL enabled for a secure data exchange.\n"
- + " See <a href=\"https://www.openhab.org/docs/installation/security.html\">Securing access to openHAB</a> for details.\n"
- + " </div>");
+ return skeleton.replace(NO_SSL_WARNING_PLACEHOLDER,
+ """
+ <div class="alert alert-danger" role="alert">
+ Warning: We strongly advice to proceed only with SSL enabled for a secure data exchange.
+ See <a href="https://www.openhab.org/docs/installation/security.html">Securing access to openHAB</a> for details.
+ </div>\
+ """);
} else {
return skeleton.replace(NO_SSL_WARNING_PLACEHOLDER, "");
}
@Override
public void setThingHandler(ThingHandler handler) {
- if (handler instanceof MieleBridgeHandler) {
- var bridgeHandler = (MieleBridgeHandler) handler;
+ if (handler instanceof MieleBridgeHandler bridgeHandler) {
bridgeHandler.setDiscoveryService(this);
this.bridgeHandler = bridgeHandler;
}
if (deviceType.isPresent() && techType.isPresent()) {
return Optional.of(deviceType.get() + " " + techType.get());
}
- if (!deviceType.isPresent() && techType.isPresent()) {
+ if (deviceType.isEmpty() && techType.isPresent()) {
return techType;
}
- if (deviceType.isPresent() && !techType.isPresent()) {
+ if (deviceType.isPresent() && techType.isEmpty()) {
return deviceType;
}
return Optional.empty();
}
BridgeHandler handler = bridge.getHandler();
- if (handler == null || !(handler instanceof MieleBridgeHandler)) {
+ if (!(handler instanceof MieleBridgeHandler)) {
return Optional.empty();
}
package org.openhab.binding.mielecloud.internal.handler;
import java.util.Collection;
-import java.util.Collections;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledExecutorService;
private void tryInitializeWebservice() {
Optional<String> accessToken = tokenRefresher.getAccessTokenFromStorage(getOAuthServiceHandle());
- if (!accessToken.isPresent()) {
+ if (accessToken.isEmpty()) {
logger.debug("No OAuth2 access token available. Retrying later.");
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING,
I18NKeys.BRIDGE_STATUS_DESCRIPTION_ACCESS_TOKEN_NOT_CONFIGURED);
@Override
public Optional<String> getLanguage() {
Object languageObject = thing.getConfiguration().get(MieleCloudBindingConstants.CONFIG_PARAM_LOCALE);
- if (languageObject instanceof String) {
- String language = (String) languageObject;
+ if (languageObject instanceof String language) {
if (language.isEmpty() || !LocaleValidator.isValidLanguage(language)) {
return Optional.empty();
} else {
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(ThingDiscoveryService.class);
+ return Set.of(ThingDiscoveryService.class);
}
}
* Converts an {@link Optional} of {@link String} to {@link State}.
*/
public static State stringToState(Optional<String> value) {
- return value.filter(v -> !v.isEmpty()).filter(v -> !v.equals("null")).map(v -> (State) new StringType(v))
+ return value.filter(v -> !v.isEmpty()).filter(v -> !"null".equals(v)).map(v -> (State) new StringType(v))
.orElse(UnDefType.UNDEF);
}
@Nullable
private Request createSseRequest(String endpoint) {
Optional<String> accessToken = this.accessToken;
- if (!accessToken.isPresent()) {
+ if (accessToken.isEmpty()) {
logger.warn("No access token present.");
return null;
}
@Override
public void logout() {
Optional<String> accessToken = this.accessToken;
- if (!accessToken.isPresent()) {
+ if (accessToken.isEmpty()) {
logger.debug("No access token present.");
return;
}
*/
private Actions getActions(String deviceId) {
Optional<String> accessToken = this.accessToken;
- if (!accessToken.isPresent()) {
+ if (accessToken.isEmpty()) {
throw new MieleWebserviceException("Missing access token.", ConnectionError.AUTHORIZATION_FAILED);
}
private void putActions(String deviceId, String json) {
retryStrategy.performRetryableOperation(() -> {
Optional<String> accessToken = this.accessToken;
- if (!accessToken.isPresent()) {
+ if (accessToken.isEmpty()) {
throw new MieleWebserviceException("Missing access token.", ConnectionError.AUTHORIZATION_FAILED);
}
private static String getHttpErrorMessageFromCloudResponse(Response response) {
String exceptionMessage = "HTTP error " + response.getStatus() + ": " + response.getReason();
- if (response instanceof ContentResponse) {
+ if (response instanceof ContentResponse contentResponse) {
try {
- ErrorMessage errorMessage = ErrorMessage.fromJson(((ContentResponse) response).getContentAsString());
+ ErrorMessage errorMessage = ErrorMessage.fromJson(contentResponse.getContentAsString());
exceptionMessage += "\nCloud returned message: " + errorMessage.getMessage();
} catch (MieleSyntaxException e) {
exceptionMessage += "\nCloud returned invalid message.";
Optional<Integer> targetTemperature = getTargetTemperature(0);
Optional<Integer> currentTemperature = getTemperature(0);
- if (!targetTemperature.isPresent() || !currentTemperature.isPresent()) {
+ if (targetTemperature.isEmpty() || currentTemperature.isEmpty()) {
return Optional.empty();
}
Optional<Boolean> doorState = getDoorState();
Optional<Boolean> failure = device.flatMap(Device::getState).flatMap(State::getSignalFailure);
- if (!doorState.isPresent() || !failure.isPresent()) {
+ if (doorState.isEmpty() || failure.isEmpty()) {
return Optional.empty();
}
}
private Optional<Boolean> hasFinishedFromPreviousState(DeviceState prevState) {
- if (!prevState.getStateType().isPresent()) {
+ if (prevState.getStateType().isEmpty()) {
return Optional.empty();
}
} catch (MieleWebserviceException e) {
// Workaround for HTML response from cloud in case of a 401 HTTP error.
var cause = e.getCause();
- if (cause == null || !(cause instanceof ExecutionException)) {
+ if (!(cause instanceof ExecutionException)) {
throw e;
}
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
+import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
when(discoveryResult.getThingTypeUID()).thenReturn(thingTypeUid);
when(discoveryResult.getThingUID()).thenReturn(new ThingUID(thingTypeUid, id, bridgeId));
when(discoveryResult.getProperties())
- .thenReturn(Collections.singletonMap(MieleCloudBindingConstants.CONFIG_PARAM_DEVICE_IDENTIFIER, id));
+ .thenReturn(Map.of(MieleCloudBindingConstants.CONFIG_PARAM_DEVICE_IDENTIFIER, id));
return discoveryResult;
}
Collections.emptyList());
// then:
- assertEquals("Bridge mielecloud:account:mielebridge [ email=\"everyone@openhab.org\", locale=\"de\" ] {\n"
- + " Thing oven 000137439123 \"Oven H7860XY\" [ deviceIdentifier=\"000137439123\" ]\n"
- + " Thing hob 000160106123 [ deviceIdentifier=\"000160106123\" ]\n}", template);
+ assertEquals("""
+ Bridge mielecloud:account:mielebridge [ email="everyone@openhab.org", locale="de" ] {
+ Thing oven 000137439123 "Oven H7860XY" [ deviceIdentifier="000137439123" ]
+ Thing hob 000160106123 [ deviceIdentifier="000160106123" ]
+ }\
+ """, template);
}
@Test
discoveredThings);
// then:
- assertEquals("Bridge mielecloud:account:mielebridge [ email=\"everyone@openhab.org\", locale=\"de\" ] {\n"
- + " Thing fridge_freezer 000154106123 \"Fridge-Freezer Kitchen\" [ deviceIdentifier=\"000154106123\" ]\n"
- + " Thing washing_machine 000189106123 \"Washing Machine\" [ deviceIdentifier=\"000189106123\" ]\n}",
- template);
+ assertEquals("""
+ Bridge mielecloud:account:mielebridge [ email="everyone@openhab.org", locale="de" ] {
+ Thing fridge_freezer 000154106123 "Fridge-Freezer Kitchen" [ deviceIdentifier="000154106123" ]
+ Thing washing_machine 000189106123 "Washing Machine" [ deviceIdentifier="000189106123" ]
+ }\
+ """, template);
}
@Test
discoveredThings);
// then:
- assertEquals("Bridge mielecloud:account:mielebridge [ email=\"openhab@openhab.org\", locale=\"de\" ] {\n"
- + " Thing oven 000137439123 \"Oven H7860XY\" [ deviceIdentifier=\"000137439123\" ]\n"
- + " Thing hob 000160106123 [ deviceIdentifier=\"000160106123\" ]\n"
- + " Thing fridge_freezer 000154106123 \"Fridge-Freezer Kitchen\" [ deviceIdentifier=\"000154106123\" ]\n"
- + " Thing washing_machine 000189106123 \"Washing Machine\" [ deviceIdentifier=\"000189106123\" ]\n}",
- template);
+ assertEquals("""
+ Bridge mielecloud:account:mielebridge [ email="openhab@openhab.org", locale="de" ] {
+ Thing oven 000137439123 "Oven H7860XY" [ deviceIdentifier="000137439123" ]
+ Thing hob 000160106123 [ deviceIdentifier="000160106123" ]
+ Thing fridge_freezer 000154106123 "Fridge-Freezer Kitchen" [ deviceIdentifier="000154106123" ]
+ Thing washing_machine 000189106123 "Washing Machine" [ deviceIdentifier="000189106123" ]
+ }\
+ """, template);
}
@Test
try (DefaultMieleWebservice webservice = new DefaultMieleWebservice(requestFactory, retryStrategy,
new DeviceStateDispatcher(), scheduler)) {
-
// when:
assertThrows(IllegalArgumentException.class, () -> {
webservice.putProcessAction(DEVICE_IDENTIFIER, ProcessAction.UNKNOWN);
// given:
Actions actions = mock(Actions.class);
ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions);
- when(actions.getProcessAction()).thenReturn(Collections.singletonList(ProcessAction.START));
+ when(actions.getProcessAction()).thenReturn(List.of(ProcessAction.START));
// when:
boolean canBeStarted = actionState.canBeStarted();
// given:
Actions actions = mock(Actions.class);
ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions);
- when(actions.getProcessAction()).thenReturn(Collections.singletonList(ProcessAction.STOP));
+ when(actions.getProcessAction()).thenReturn(List.of(ProcessAction.STOP));
// when:
boolean canBeStarted = actionState.canBeStarted();
// given:
Actions actions = mock(Actions.class);
ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions);
- when(actions.getProcessAction()).thenReturn(Collections.singletonList(ProcessAction.START_SUPERCOOLING));
+ when(actions.getProcessAction()).thenReturn(List.of(ProcessAction.START_SUPERCOOLING));
// when:
boolean canStartSupercooling = actionState.canStartSupercooling();
// given:
Actions actions = mock(Actions.class);
ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions);
- when(actions.getProcessAction()).thenReturn(Collections.singletonList(ProcessAction.START_SUPERFREEZING));
+ when(actions.getProcessAction()).thenReturn(List.of(ProcessAction.START_SUPERFREEZING));
// when:
boolean canStartSuperfreezing = actionState.canStartSuperfreezing();
// given:
Actions actions = mock(Actions.class);
ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions);
- when(actions.getLight()).thenReturn(Collections.singletonList(Light.ENABLE));
+ when(actions.getLight()).thenReturn(List.of(Light.ENABLE));
// when:
boolean canEnableLight = actionState.canEnableLight();
// given:
Actions actions = mock(Actions.class);
ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions);
- when(actions.getLight()).thenReturn(Collections.singletonList(Light.DISABLE));
+ when(actions.getLight()).thenReturn(List.of(Light.DISABLE));
// when:
boolean canDisableLight = actionState.canDisableLight();
public void testCanControlLightReturnsTrueWhenLightCanBeEnabled() {
// given:
Actions actions = mock(Actions.class);
- when(actions.getLight()).thenReturn(Collections.singletonList(Light.ENABLE));
+ when(actions.getLight()).thenReturn(List.of(Light.ENABLE));
ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions);
public void testCanControlLightReturnsTrueWhenLightCanBeDisabled() {
// given:
Actions actions = mock(Actions.class);
- when(actions.getLight()).thenReturn(Collections.singletonList(Light.DISABLE));
+ when(actions.getLight()).thenReturn(List.of(Light.DISABLE));
ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions);
public void testProgramIdCanBeSetWhenProgramIdIsPresent() {
// given:
Actions actions = mock(Actions.class);
- when(actions.getProgramId()).thenReturn(Collections.singletonList(1));
+ when(actions.getProgramId()).thenReturn(List.of(1));
ActionsState actionState = new ActionsState(DEVICE_IDENTIFIER, actions);
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
+import java.util.List;
import java.util.Optional;
import org.eclipse.jdt.annotation.NonNullByDefault;
when(plateStepMock.getValueLocalized()).thenReturn(Optional.empty());
State state = mock(State.class);
- when(state.getPlateStep()).thenReturn(Collections.singletonList(plateStepMock));
+ when(state.getPlateStep()).thenReturn(List.of(plateStepMock));
when(state.getStatus()).thenReturn(Optional.of(status));
Device device = mock(Device.class);
State state = mock(State.class);
when(state.getStatus()).thenReturn(Optional.of(status));
- when(state.getElapsedTime()).thenReturn(Optional.of(Collections.singletonList(2)));
+ when(state.getElapsedTime()).thenReturn(Optional.of(List.of(2)));
Device device = mock(Device.class);
when(device.getState()).thenReturn(Optional.of(state));
// Test TargetTemperature:
Temperature targetTemperatureMock = mock(Temperature.class);
- when(state.getTargetTemperature()).thenReturn(Collections.singletonList(targetTemperatureMock));
+ when(state.getTargetTemperature()).thenReturn(List.of(targetTemperatureMock));
when(targetTemperatureMock.getValueLocalized()).thenReturn(Optional.of(200));
// when:
Optional<Integer> targetTemperature = deviceState.getTargetTemperature(0);
// Test Temperature:
Temperature temperature = mock(Temperature.class);
- when(state.getTemperature()).thenReturn(Collections.singletonList(temperature));
+ when(state.getTemperature()).thenReturn(List.of(temperature));
when(temperature.getValueLocalized()).thenReturn(Optional.of(200));
// when:
Optional<Integer> t = deviceState.getTemperature(0);
import static org.openhab.binding.mielecloud.internal.util.ResourceUtil.getResourceAsString;
import java.io.IOException;
-import java.util.Collections;
import java.util.List;
import java.util.Optional;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
ActionsCollection collection = ActionsCollection.fromJson(json);
// then:
- assertEquals(Collections.singleton("000123456789"), collection.getDeviceIdentifiers());
+ assertEquals(Set.of("000123456789"), collection.getDeviceIdentifiers());
Actions actions = collection.getActions("000123456789");
assertEquals(List.of(ProcessAction.START, ProcessAction.STOP), actions.getProcessAction());
- assertEquals(Collections.singletonList(Light.DISABLE), actions.getLight());
+ assertEquals(List.of(Light.DISABLE), actions.getLight());
assertEquals(Optional.empty(), actions.getStartTime());
- assertEquals(Collections.singletonList(123), actions.getProgramId());
+ assertEquals(List.of(123), actions.getProgramId());
assertEquals(Optional.of(true), actions.getPowerOn());
assertEquals(Optional.of(false), actions.getPowerOff());
}
DeviceCollection collection = DeviceCollection.fromJson(json);
// then:
- assertEquals(Collections.singleton("mac-00124B000AE539D6"), collection.getDeviceIdentifiers());
+ assertEquals(Set.of("mac-00124B000AE539D6"), collection.getDeviceIdentifiers());
}
}
import java.io.IOException;
import java.util.Arrays;
-import java.util.Collections;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
Actions actions = new Gson().fromJson(json, Actions.class);
// then:
- assertEquals(Collections.singletonList(ProcessAction.START), actions.getProcessAction());
+ assertEquals(List.of(ProcessAction.START), actions.getProcessAction());
}
@Test
import static org.openhab.binding.mihome.internal.XiaomiGatewayBindingConstants.*;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Component(service = DiscoveryService.class, configurationPid = "discovery.mihome")
public class XiaomiBridgeDiscoveryService extends AbstractDiscoveryService implements XiaomiSocketListener {
- 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 DISCOVERY_TIMEOUT_SEC = 30;
private final Logger logger = LoggerFactory.getLogger(XiaomiBridgeDiscoveryService.class);
@Override
public void onDataReceived(JsonObject data) {
logger.debug("Received message {}", data);
- if (data.get("cmd").getAsString().equals("iam")) {
+ if ("iam".equals(data.get("cmd").getAsString())) {
getGatewayInfo(data);
}
}
@Override
public void onItemUpdate(String sid, String command, JsonObject data) {
- if (command.equals("read_ack") || command.equals("report") || command.equals("heartbeat")) {
+ if ("read_ack".equals(command) || "report".equals(command) || "heartbeat".equals(command)) {
String model = data.get("model").getAsString();
ThingTypeUID thingType = getThingTypeForModel(model);
void execute(ChannelUID channelUID, Command command) {
switch (channelUID.getId()) {
case CHANNEL_BRIGHTNESS:
- if (command instanceof PercentType) {
- int newBright = ((PercentType) command).intValue();
+ if (command instanceof PercentType percentCommand) {
+ int newBright = percentCommand.intValue();
if (lastBrigthness != newBright) {
lastBrigthness = newBright;
logger.debug("Set brigthness to {}", lastBrigthness);
}
break;
case CHANNEL_COLOR:
- if (command instanceof HSBType) {
- lastColor = ((HSBType) command).getRGB() & 0xffffff;
+ if (command instanceof HSBType hsbCommand) {
+ lastColor = hsbCommand.getRGB() & 0xffffff;
writeBridgeLightColor(lastColor, lastBrigthness);
return;
}
break;
case CHANNEL_COLOR_TEMPERATURE:
- if (command instanceof PercentType) {
- PercentType colorTemperature = (PercentType) command;
- int kelvin = (COLOR_TEMPERATURE_MAX - COLOR_TEMPERATURE_MIN) / 100 * colorTemperature.intValue()
+ if (command instanceof PercentType percentCommand) {
+ int kelvin = (COLOR_TEMPERATURE_MAX - COLOR_TEMPERATURE_MIN) / 100 * percentCommand.intValue()
+ COLOR_TEMPERATURE_MIN;
int color = ColorUtil.getRGBFromK(kelvin);
writeBridgeLightColor(color, lastBrigthness);
}
break;
case CHANNEL_GATEWAY_SOUND:
- if (command instanceof DecimalType) {
- writeBridgeRingtone(((DecimalType) command).intValue(), lastVolume);
+ if (command instanceof DecimalType decimalCommand) {
+ writeBridgeRingtone(decimalCommand.intValue(), lastVolume);
updateState(CHANNEL_GATEWAY_SOUND_SWITCH, OnOffType.ON);
return;
}
break;
case CHANNEL_GATEWAY_SOUND_SWITCH:
- if (command instanceof OnOffType) {
- if (((OnOffType) command) == OnOffType.OFF) {
+ if (command instanceof OnOffType onOffCommand) {
+ if (onOffCommand == OnOffType.OFF) {
stopRingtone();
}
return;
}
break;
case CHANNEL_GATEWAY_VOLUME:
- if (command instanceof DecimalType) {
- updateLastVolume((DecimalType) command);
+ if (command instanceof DecimalType decimalCommand) {
+ updateLastVolume(decimalCommand);
}
return;
}
private static final String YES = "yes";
private static final String NO = "no";
- public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(THING_TYPE_BRIDGE);
+ public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_BRIDGE);
private static final EncryptionHelper CRYPTER = new EncryptionHelper();
private static Map<String, JsonObject> retentionInbox = new ConcurrentHashMap<>();
}
private String escapeQuotes(String string) {
- return string.replaceAll("\"", "\\\\\"");
+ return string.replace("\"", "\\\\\"");
}
private int getConfigInteger(Configuration config, String key) {
Object value = config.get(key);
- if (value instanceof BigDecimal) {
- return ((BigDecimal) value).intValue();
- } else if (value instanceof String) {
- return Integer.parseInt((String) value);
+ if (value instanceof BigDecimal decimal) {
+ return decimal.intValue();
+ } else if (value instanceof String str) {
+ return Integer.parseInt(str);
} else {
return (Integer) value;
}
void execute(ChannelUID channelUID, Command command) {
if (CHANNEL_WRITE_MSG.equals(channelUID.getId())) {
- if (command instanceof StringType) {
- getXiaomiBridgeHandler().writeToDevice(itemId, ((StringType) command).toFullString());
+ if (command instanceof StringType str) {
+ getXiaomiBridgeHandler().writeToDevice(itemId, str.toFullString());
} else {
logger.debug("Command \"{}\" has to be of StringType", command);
}
return null;
}
ThingHandler handler = bridge.getHandler();
- if (handler instanceof XiaomiBridgeHandler) {
- this.bridgeHandler = (XiaomiBridgeHandler) handler;
+ if (handler instanceof XiaomiBridgeHandler xiaomiBridgeHandler) {
+ this.bridgeHandler = xiaomiBridgeHandler;
this.bridgeHandler.registerItemListener(this);
} else {
return null;
@Override
void execute(ChannelUID channelUID, Command command) {
if (CHANNEL_OPEN_ALARM_TIMER.equals(channelUID.getId())) {
- if (command != null && command instanceof DecimalType) {
- setTimerFromDecimalType((DecimalType) command);
+ if (command instanceof DecimalType decimalCommand) {
+ setTimerFromDecimalType(decimalCommand);
return;
}
// Only gets here, if no condition was met
@Override
void execute(ChannelUID channelUID, Command command) {
if (CHANNEL_MOTION_OFF_TIMER.equals(channelUID.getId())) {
- if (command != null && command instanceof DecimalType) {
- setTimerFromDecimalType((DecimalType) command);
+ if (command instanceof DecimalType decimalCommand) {
+ setTimerFromDecimalType(decimalCommand);
return;
}
// Only gets here, if no condition was met
*/
private void notifyListeners(JsonObject message, InetAddress address) {
for (XiaomiSocketListener listener : listeners) {
- if (listener instanceof XiaomiBridgeHandler) {
- if (((XiaomiBridgeHandler) listener).getHost().equals(address)) {
+ if (listener instanceof XiaomiBridgeHandler handler) {
+ if (handler.getHost().equals(address)) {
listener.onDataReceived(message);
}
} else if (listener instanceof XiaomiBridgeDiscoveryService) {
* @return RGB value + brightness as first byte
*/
private static @Nullable JsonElement hsvToBRGB(@Nullable Command command, @Nullable JsonElement value) {
- if (command != null && command instanceof HSBType) {
+ if (command instanceof HSBType) {
HSBType hsb = (HSBType) command;
Color color = Color.getHSBColor(hsb.getHue().floatValue() / 360, hsb.getSaturation().floatValue() / 100,
hsb.getBrightness().floatValue() / 100);
* @return
*/
private static @Nullable JsonElement hsbOnly(@Nullable Command command, @Nullable JsonElement value) {
- if (command != null && command instanceof HSBType) {
+ if (command instanceof HSBType) {
return value;
}
return null;
public class InterfaceThingConfig implements ConfigValidation {
public String name = "";
+ @Override
public boolean isValid() {
return !name.isBlank();
}
public String password = "";
public int refresh = 10;
+ @Override
public boolean isValid() {
return !host.isBlank() && !login.isBlank() && !password.isBlank() && refresh > 0 && port > 0;
}
public String ssid = "";
public int considerContinuous = 180;
+ @Override
public boolean isValid() {
return !mac.isBlank() && considerContinuous > 0;
}
// refresh all the client things below
getThing().getThings().forEach(thing -> {
ThingHandler handler = thing.getHandler();
- if (handler instanceof MikrotikBaseThingHandler<?>) {
- ((MikrotikBaseThingHandler<?>) handler).refresh();
+ if (handler instanceof MikrotikBaseThingHandler<?> thingHandler) {
+ thingHandler.refresh();
}
});
} catch (ChannelUpdateException e) {
}
public boolean isMaster() {
- return getProp("slave", "").equals("false");
+ return "false".equals(getProp("slave", ""));
}
public boolean isDynamic() {
- return getProp("dynamic", "").equals("true");
+ return "true".equals(getProp("dynamic", ""));
}
public boolean isBound() {
- return getProp("bound", "").equals("true");
+ return "true".equals(getProp("bound", ""));
}
public boolean isActive() {
- return getProp("inactive", "").equals("false");
+ return "false".equals(getProp("inactive", ""));
}
public @Nullable String getCurrentState() {
}
public boolean isEnabled() {
- return getProp("disabled", "").equals("false");
+ return "false".equals(getProp("disabled", ""));
}
public boolean isConnected() {
- return getProp("running", "").equals("true");
+ return "true".equals(getProp("running", ""));
}
public @Nullable Integer getLinkDowns() {
return typeName.equals(otherType);
}
+ @Override
public String toString() {
return this.typeName;
}
return true;
}
+ @Override
public @Nullable String getMacAddress() {
return null;
}
return true;
}
+ @Override
public @Nullable String getMacAddress() {
return getProp("ac-mac");
}
}
public boolean isRouterboard() {
- return getProp("routerboard", "").equals("true");
+ return "true".equals(getProp("routerboard", ""));
}
public String getModel() {
try (MilightV6SessionManager session = new MilightV6SessionManager(bridgeID, sessionState, addressOfBridge,
MilightBindingConstants.PORT_VER6, MilightV6SessionManager.TIMEOUT_MS, new byte[] { 0, 0 })) {
session.start();
- boolean success = s.tryAcquire(1, 1300, TimeUnit.MILLISECONDS);
- return success;
+ return s.tryAcquire(1, 1300, TimeUnit.MILLISECONDS);
} catch (IOException e) {
logger.debug("checkForV6Bridge failed", e);
}
switch (channelUID.getId()) {
case MilightBindingConstants.CHANNEL_COLOR: {
- if (command instanceof HSBType) {
- HSBType hsb = (HSBType) command;
+ if (command instanceof HSBType hsb) {
this.setHSB(hsb.getHue().intValue(), hsb.getSaturation().intValue(), hsb.getBrightness().intValue(),
state);
updateState(MilightBindingConstants.CHANNEL_SATURATION, new PercentType(state.saturation));
- } else if (command instanceof OnOffType) {
- OnOffType hsb = (OnOffType) command;
+ } else if (command instanceof OnOffType hsb) {
this.setPower(hsb == OnOffType.ON, state);
- } else if (command instanceof PercentType) {
- PercentType p = (PercentType) command;
+ } else if (command instanceof PercentType p) {
this.setBrightness(p.intValue(), state);
- } else if (command instanceof IncreaseDecreaseType) {
- this.changeBrightness((IncreaseDecreaseType) command == IncreaseDecreaseType.INCREASE ? 1 : -1,
- state);
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ this.changeBrightness(increaseDecreaseCommand == IncreaseDecreaseType.INCREASE ? 1 : -1, state);
} else {
logger.error(
"CHANNEL_COLOR channel only supports OnOffType/IncreaseDecreaseType/HSBType/PercentType");
break;
}
case MilightBindingConstants.CHANNEL_BRIGHTNESS: {
- if (command instanceof OnOffType) {
- OnOffType hsb = (OnOffType) command;
- this.setPower(hsb == OnOffType.ON, state);
- } else if (command instanceof DecimalType) {
- DecimalType d = (DecimalType) command;
- this.setBrightness(d.intValue(), state);
- } else if (command instanceof IncreaseDecreaseType) {
- this.changeBrightness((IncreaseDecreaseType) command == IncreaseDecreaseType.INCREASE ? 1 : -1,
- state);
+ if (command instanceof OnOffType onOffCommand) {
+ this.setPower(onOffCommand == OnOffType.ON, state);
+ } else if (command instanceof DecimalType decimalCommand) {
+ this.setBrightness(decimalCommand.intValue(), state);
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ this.changeBrightness(increaseDecreaseCommand == IncreaseDecreaseType.INCREASE ? 1 : -1, state);
} else {
logger.error("CHANNEL_BRIGHTNESS channel only supports OnOffType/IncreaseDecreaseType/DecimalType");
}
break;
}
case MilightBindingConstants.CHANNEL_SATURATION: {
- if (command instanceof OnOffType) {
- OnOffType s = (OnOffType) command;
- this.setSaturation((s == OnOffType.ON) ? 100 : 0, state);
- } else if (command instanceof DecimalType) {
- DecimalType d = (DecimalType) command;
- this.setSaturation(d.intValue(), state);
- } else if (command instanceof IncreaseDecreaseType) {
- this.changeSaturation((IncreaseDecreaseType) command == IncreaseDecreaseType.INCREASE ? 1 : -1,
- state);
+ if (command instanceof OnOffType onOffCommand) {
+ this.setSaturation((onOffCommand == OnOffType.ON) ? 100 : 0, state);
+ } else if (command instanceof DecimalType decimalCommand) {
+ this.setSaturation(decimalCommand.intValue(), state);
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ this.changeSaturation(increaseDecreaseCommand == IncreaseDecreaseType.INCREASE ? 1 : -1, state);
} else {
logger.error("CHANNEL_SATURATION channel only supports OnOffType/IncreaseDecreaseType/DecimalType");
}
break;
}
case MilightBindingConstants.CHANNEL_TEMP: {
- if (command instanceof OnOffType) {
- OnOffType s = (OnOffType) command;
- this.setColorTemperature((s == OnOffType.ON) ? 100 : 0, state);
- } else if (command instanceof IncreaseDecreaseType) {
- this.changeColorTemperature(
- (IncreaseDecreaseType) command == IncreaseDecreaseType.INCREASE ? 1 : -1, state);
- } else if (command instanceof DecimalType) {
- DecimalType d = (DecimalType) command;
+ if (command instanceof OnOffType onOffCommand) {
+ this.setColorTemperature((onOffCommand == OnOffType.ON) ? 100 : 0, state);
+ } else if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ this.changeColorTemperature(increaseDecreaseCommand == IncreaseDecreaseType.INCREASE ? 1 : -1,
+ state);
+ } else if (command instanceof DecimalType d) {
this.setColorTemperature(d.intValue(), state);
} else {
logger.error("CHANNEL_TEMP channel only supports OnOffType/IncreaseDecreaseType/DecimalType");
break;
}
case MilightBindingConstants.CHANNEL_SPEED_REL: {
- if (command instanceof IncreaseDecreaseType) {
- IncreaseDecreaseType id = (IncreaseDecreaseType) command;
- if (id == IncreaseDecreaseType.INCREASE) {
+ if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ if (increaseDecreaseCommand == IncreaseDecreaseType.INCREASE) {
this.changeSpeed(1, state);
- } else if (id == IncreaseDecreaseType.DECREASE) {
+ } else if (increaseDecreaseCommand == IncreaseDecreaseType.DECREASE) {
this.changeSpeed(-1, state);
}
} else {
break;
}
case MilightBindingConstants.CHANNEL_ANIMATION_MODE: {
- if (command instanceof DecimalType) {
- DecimalType d = (DecimalType) command;
- this.setLedMode(d.intValue(), state);
+ if (command instanceof DecimalType decimalCommand) {
+ this.setLedMode(decimalCommand.intValue(), state);
} else {
logger.error("Animation mode channel only supports DecimalType");
}
break;
}
case MilightBindingConstants.CHANNEL_ANIMATION_MODE_REL: {
- if (command instanceof IncreaseDecreaseType) {
- IncreaseDecreaseType id = (IncreaseDecreaseType) command;
- if (id == IncreaseDecreaseType.INCREASE) {
+ if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ if (increaseDecreaseCommand == IncreaseDecreaseType.INCREASE) {
this.nextAnimationMode(state);
- } else if (id == IncreaseDecreaseType.DECREASE) {
+ } else if (increaseDecreaseCommand == IncreaseDecreaseType.DECREASE) {
this.previousAnimationMode(state);
}
} else {
public void setPower(boolean on, MilightThingState state) {
if (on) {
logger.debug("milight: sendOn");
- byte messageBytes[] = null;
+ byte[] messageBytes = null;
// message rgb bulbs ON
messageBytes = new byte[] { 0x22, 0x00, 0x55 };
sendQueue.queue(createRepeatable(uidc(ProtocolConstants.CAT_POWER_MODE), messageBytes));
} else {
logger.debug("milight: sendOff");
- byte messageBytes[] = null;
+ byte[] messageBytes = null;
// message rgb bulbs OFF
messageBytes = new byte[] { 0x21, 0x00, 0x55 };
public class MilightV3RGBWHandler extends AbstractLedV3Handler {
protected static final int BRIGHTNESS_LEVELS = 26;
- private static final byte COMMAND_ON[] = { (byte) 0x42, (byte) 0x45, (byte) 0x47, (byte) 0x49, (byte) 0x4B };
- private static final byte COMMAND_OFF[] = { (byte) 0x41, (byte) 0x46, (byte) 0x48, (byte) 0x4A, (byte) 0x4C };
- private static final byte COMMAND_WHITEMODE[] = { (byte) 0xC2, (byte) 0xC5, (byte) 0xC7, (byte) 0xC9, (byte) 0xCB };
- private static final byte NIGHTMODE_FIRST[] = { 0x41, 0x46, 0x48, 0x4A, 0x4C };
- private static final byte NIGHTMODE_SECOND[] = { (byte) 0xC1, (byte) 0xC6, (byte) 0xC8, (byte) 0xCA, (byte) 0xCC };
- private static final byte NEXT_ANIMATION_MODE[] = { 0x4D, 0x00, 0x55 };
+ private static final byte[] COMMAND_ON = { (byte) 0x42, (byte) 0x45, (byte) 0x47, (byte) 0x49, (byte) 0x4B };
+ private static final byte[] COMMAND_OFF = { (byte) 0x41, (byte) 0x46, (byte) 0x48, (byte) 0x4A, (byte) 0x4C };
+ private static final byte[] COMMAND_WHITEMODE = { (byte) 0xC2, (byte) 0xC5, (byte) 0xC7, (byte) 0xC9, (byte) 0xCB };
+ private static final byte[] NIGHTMODE_FIRST = { 0x41, 0x46, 0x48, 0x4A, 0x4C };
+ private static final byte[] NIGHTMODE_SECOND = { (byte) 0xC1, (byte) 0xC6, (byte) 0xC8, (byte) 0xCA, (byte) 0xCC };
+ private static final byte[] NEXT_ANIMATION_MODE = { 0x4D, 0x00, 0x55 };
public MilightV3RGBWHandler(Thing thing, QueuedSend sendQueue) {
super(thing, sendQueue, 10);
whiteMode(state);
} else {
state.hue360 = hue;
- final byte messageBytes[] = new byte[] { 0x40, makeColor(hue), 0x55 };
- final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 };
+ final byte[] messageBytes = new byte[] { 0x40, makeColor(hue), 0x55 };
+ final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 };
sendQueue.queue(createRepeatable(uidc(ProtocolConstants.CAT_COLOR_SET), cOn).addRepeatable(messageBytes));
}
@Override
public void whiteMode(MilightThingState state) {
- final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 };
- final byte cWhite[] = { COMMAND_WHITEMODE[config.zone], 0x00, 0x55 };
+ final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 };
+ final byte[] cWhite = { COMMAND_WHITEMODE[config.zone], 0x00, 0x55 };
sendQueue.queue(createRepeatable(uidc(ProtocolConstants.CAT_WHITEMODE), cOn).addRepeatable(cWhite));
}
@Override
public void nightMode(MilightThingState state) {
- final byte cN1[] = { NIGHTMODE_FIRST[config.zone], 0x00, 0x55 };
- final byte cN2[] = { NIGHTMODE_SECOND[config.zone], 0x00, 0x55 };
+ final byte[] cN1 = { NIGHTMODE_FIRST[config.zone], 0x00, 0x55 };
+ final byte[] cN2 = { NIGHTMODE_SECOND[config.zone], 0x00, 0x55 };
sendQueue.queue(createRepeatable(uidc(ProtocolConstants.CAT_POWER_MODE), cN1).addRepeatable(cN2));
}
int br = (int) Math.ceil((value * BRIGHTNESS_LEVELS) / 100.0) + 1;
- final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 };
+ final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 };
sendQueue.queue(createRepeatable(uidc(ProtocolConstants.CAT_BRIGHTNESS_SET), cOn)
.addRepeatable(new byte[] { 0x4E, (byte) br, 0x55 }));
return;
}
- final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 };
- final byte cSpeed[] = { (byte) (relativeSpeed > 0 ? 0x44 : 0x43), 0x00, 0x55 };
+ final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 };
+ final byte[] cSpeed = { (byte) (relativeSpeed > 0 ? 0x44 : 0x43), 0x00, 0x55 };
sendQueue.queue(createRepeatable(cOn).addNonRepeatable(cSpeed));
}
// instead.
@Override
public void previousAnimationMode(MilightThingState state) {
- final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 };
+ final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 };
sendQueue.queue(createRepeatable(cOn).addNonRepeatable(NEXT_ANIMATION_MODE));
state.animationMode = (state.animationMode + 1) % (MAX_ANIM_MODES + 1);
}
@Override
public void nextAnimationMode(MilightThingState state) {
- final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 };
+ final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 };
sendQueue.queue(createRepeatable(cOn).addNonRepeatable(NEXT_ANIMATION_MODE));
state.animationMode = (state.animationMode + 1) % (MAX_ANIM_MODES + 1);
}
super(thing, sendQueue, 0);
}
- private static final byte COMMAND_FULL[] = { (byte) 0xB5, (byte) 0xB8, (byte) 0xBD, (byte) 0xB7, (byte) 0xB2 };
- private static final byte COMMAND_ON[] = { (byte) 0x35, (byte) 0x38, (byte) 0x3D, (byte) 0x37, (byte) 0x32 };
- private static final byte COMMAND_OFF[] = { (byte) 0x39, (byte) 0x3B, (byte) 0x33, (byte) 0x3A, (byte) 0x36 };
- private static final byte COMMAND_NIGHTMODE[] = { (byte) 0xB9, (byte) 0xBB, (byte) 0xB3, (byte) 0xBA, (byte) 0xB6 };
- private static final byte PREV_ANIMATION_MODE[] = { 0x27, 0x00, 0x55 };
- private static final byte NEXT_ANIMATION_MODE[] = { 0x27, 0x00, 0x55 };
+ private static final byte[] COMMAND_FULL = { (byte) 0xB5, (byte) 0xB8, (byte) 0xBD, (byte) 0xB7, (byte) 0xB2 };
+ private static final byte[] COMMAND_ON = { (byte) 0x35, (byte) 0x38, (byte) 0x3D, (byte) 0x37, (byte) 0x32 };
+ private static final byte[] COMMAND_OFF = { (byte) 0x39, (byte) 0x3B, (byte) 0x33, (byte) 0x3A, (byte) 0x36 };
+ private static final byte[] COMMAND_NIGHTMODE = { (byte) 0xB9, (byte) 0xBB, (byte) 0xB3, (byte) 0xBA, (byte) 0xB6 };
+ private static final byte[] PREV_ANIMATION_MODE = { 0x27, 0x00, 0x55 };
+ private static final byte[] NEXT_ANIMATION_MODE = { 0x27, 0x00, 0x55 };
protected void setFull(int zone, MilightThingState state) {
sendQueue.queue(createRepeatable(uidc(ProtocolConstants.CAT_BRIGHTNESS_SET),
@Override
public void nightMode(MilightThingState state) {
- final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 };
- final byte cNight[] = { COMMAND_NIGHTMODE[config.zone], 0x00, 0x55 };
+ final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 };
+ final byte[] cNight = { COMMAND_NIGHTMODE[config.zone], 0x00, 0x55 };
sendQueue.queue(createRepeatable(uidc(ProtocolConstants.CAT_POWER_MODE), cOn).addRepeatable(cNight));
}
@Override
public void changeColorTemperature(int colorTempRelative, MilightThingState state) {
state.colorTemperature = Math.min(100, Math.max(state.colorTemperature + colorTempRelative, 0));
- final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 };
- final byte cTemp[] = { (byte) (colorTempRelative > 0 ? 0x3E : 0x3F), 0x00, 0x55 };
+ final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 };
+ final byte[] cTemp = { (byte) (colorTempRelative > 0 ? 0x3E : 0x3F), 0x00, 0x55 };
sendQueue.queue(createRepeatable(cOn).addNonRepeatable(cTemp));
}
// When turning on start from full brightness
int oldLevel;
- final byte cFull[] = { COMMAND_FULL[config.zone], 0x00, 0x55 };
+ final byte[] cFull = { COMMAND_FULL[config.zone], 0x00, 0x55 };
QueueItem item = createRepeatable(cFull);
boolean skipFirst = false;
String.valueOf(value), repeatCount);
int op = newLevel > oldLevel ? +1 : -1;
- final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 };
+ final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 };
for (int i = 0; i < repeatCount; i++) {
final byte[] cBr = { (byte) (op < 0 ? 0x34 : 0x3C), 0x00, 0x55 };
item = item.addRepeatable(cOn).addNonRepeatable(cBr);
sendQueue.queue(createRepeatable(uidc(ProtocolConstants.CAT_POWER_MODE),
new byte[] { COMMAND_OFF[config.zone], 0x00, 0x55 }));
} else {
- final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 };
- final byte cBr[] = { (byte) (relativeBrightness < 0 ? 0x34 : 0x3C), 0x00, 0x55 };
+ final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 };
+ final byte[] cBr = { (byte) (relativeBrightness < 0 ? 0x34 : 0x3C), 0x00, 0x55 };
sendQueue.queue(createRepeatable(cOn).addNonRepeatable(cBr));
}
}
@Override
public void previousAnimationMode(MilightThingState state) {
- final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 };
+ final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 };
sendQueue.queue(createRepeatable(cOn).addNonRepeatable(PREV_ANIMATION_MODE));
state.animationMode = Math.max(state.animationMode - 1, 0);
}
@Override
public void nextAnimationMode(MilightThingState state) {
- final byte cOn[] = { COMMAND_ON[config.zone], 0x00, 0x55 };
+ final byte[] cOn = { COMMAND_ON[config.zone], 0x00, 0x55 };
sendQueue.queue(createRepeatable(cOn).addNonRepeatable(NEXT_ANIMATION_MODE));
state.animationMode = Math.min(state.animationMode + 1, MAX_ANIM_MODES);
}
private int sequenceNo = 0;
// Password bytes 1 and 2
- public byte pw[] = { 0, 0 };
+ public byte[] pw = { 0, 0 };
// Session bytes 1 and 2
- public byte sid[] = { 0, 0 };
+ public byte[] sid = { 0, 0 };
// Client session bytes 1 and 2. Those are fixed for now.
public final byte clientSID1 = (byte) 0xab;
(byte) 0xD4 };
// Send to the network by clients to find V6 bridges
- private byte searchBroadcast[] = new byte[] { 0x10, 0, 0, 0, 0x24, 0x02, cls1, cls2, 0x02, 0x39, 0x38, 0x35, 0x62,
+ private byte[] searchBroadcast = new byte[] { 0x10, 0, 0, 0, 0x24, 0x02, cls1, cls2, 0x02, 0x39, 0x38, 0x35, 0x62,
0x31, 0x35, 0x37, 0x62, 0x66, 0x36, 0x66, 0x63, 0x34, 0x33, 0x33, 0x36, 0x38, 0x61, 0x36, 0x33, 0x34, 0x36,
0x37, 0x65, 0x61, 0x33, 0x62, 0x31, 0x39, 0x64, 0x30, 0x64 };
// Send to broadcast address by the client usually and used to test if the client with the contained bridge id
// is present on the network. If the IP of the bridge is known already, then SESSION_REQUEST is used usually.
- private byte sessionRequestFindBroadcast[] = new byte[] { 0x10, 0, 0, 0, 0x0A, 2, cls1, cls2, 1, FAKE_MAC[0],
+ private byte[] sessionRequestFindBroadcast = new byte[] { 0x10, 0, 0, 0, 0x0A, 2, cls1, cls2, 1, FAKE_MAC[0],
FAKE_MAC[1], FAKE_MAC[2], FAKE_MAC[3], FAKE_MAC[4], FAKE_MAC[5] };
// Some clients send this as first command to get a session id, especially if the bridge IP is already known.
- private byte sessionRequest[] = new byte[] { (byte) 0x20, 0, 0, 0, (byte) 0x16, 2, (byte) 0x62, (byte) 0x3A,
+ private byte[] sessionRequest = new byte[] { (byte) 0x20, 0, 0, 0, (byte) 0x16, 2, (byte) 0x62, (byte) 0x3A,
(byte) 0xD5, (byte) 0xED, (byte) 0xA3, 1, (byte) 0xAE, (byte) 0x08, (byte) 0x2D, (byte) 0x46, (byte) 0x61,
(byte) 0x41, (byte) 0xA7, (byte) 0xF6, (byte) 0xDC, (byte) 0xAF, cls1, cls2, 0, 0, (byte) 0x1E };
- private byte sessionResponse[] = { (byte) 0x28, 0, 0, 0, (byte) 0x11, 0, 2, (byte) 0xAC, (byte) 0xCF, (byte) 0x23,
+ private byte[] sessionResponse = { (byte) 0x28, 0, 0, 0, (byte) 0x11, 0, 2, (byte) 0xAC, (byte) 0xCF, (byte) 0x23,
(byte) 0xF5, (byte) 0x7A, (byte) 0xD4, (byte) 0x69, (byte) 0xF0, (byte) 0x3C, (byte) 0x23, 0, 1, SID1, SID2,
0 };
// Some clients call this as second command to establish a session.
- private static final byte ESTABLISH_SESSION_REQUEST[] = new byte[] { (byte) 0x30, 0, 0, 0, 3, SID1, SID2, 0 };
+ private static final byte[] ESTABLISH_SESSION_REQUEST = new byte[] { (byte) 0x30, 0, 0, 0, 3, SID1, SID2, 0 };
// In response to SEARCH, ESTABLISH_SESSION_REQUEST but also to SESSION_REQUEST_FIND_BROADCAST
- private static final byte REESTABLISH_SESSION_RESPONSE[] = new byte[] { (byte) 0x18, 0, 0, 0, (byte) 0x40, 2,
+ private static final byte[] REESTABLISH_SESSION_RESPONSE = new byte[] { (byte) 0x18, 0, 0, 0, (byte) 0x40, 2,
FAKE_MAC[0], FAKE_MAC[1], FAKE_MAC[2], FAKE_MAC[3], FAKE_MAC[4], FAKE_MAC[5], 0, (byte) 0x20, (byte) 0x39,
(byte) 0x38, (byte) 0x35, (byte) 0x62, (byte) 0x31, (byte) 0x35, (byte) 0x37, (byte) 0x62, (byte) 0x66,
(byte) 0x36, (byte) 0x66, (byte) 0x63, (byte) 0x34, (byte) 0x33, (byte) 0x33, (byte) 0x36, (byte) 0x38,
(byte) 0x6E, (byte) 0x6B, (byte) 0x5F, (byte) 0x64, (byte) 0x65, (byte) 0x76, (byte) 0x07, (byte) 0x5B,
(byte) 0xCD, (byte) 0x15 };
- private static final byte REGISTRATION_REQUEST[] = { (byte) 0x80, 0, 0, 0, 0x11, SID1, SID2, SEQ1, SEQ2, 0, 0x33,
+ private static final byte[] REGISTRATION_REQUEST = { (byte) 0x80, 0, 0, 0, 0x11, SID1, SID2, SEQ1, SEQ2, 0, 0x33,
PW1, PW2, 0, 0, 0, 0, 0, 0, 0, 0, 0x33 };
// 80:00:00:00:15:(f0:fe:6b:16:b0:8a):05:02:00:34:00:00:00:00:00:00:00:00:00:00:34
- private static final byte REGISTRATION_REQUEST_RESPONSE[] = { (byte) 0x80, 0, 0, 0, 0x15, FAKE_MAC[0], FAKE_MAC[1],
+ private static final byte[] REGISTRATION_REQUEST_RESPONSE = { (byte) 0x80, 0, 0, 0, 0x15, FAKE_MAC[0], FAKE_MAC[1],
FAKE_MAC[2], FAKE_MAC[3], FAKE_MAC[4], FAKE_MAC[5], 5, 2, 0, 0x34, PW1, PW2, 0, 0, 0, 0, 0, 0, 0, 0, 0x34 };
private static final byte[] KEEP_ALIVE_REQUEST = { (byte) 0xD0, 0, 0, 0, 2, SID1, SID2 };
new Thread(this::runBrigde).start();
}
- private void replaceWithMac(byte data[], int offset) {
+ private void replaceWithMac(byte[] data, int offset) {
data[offset + 0] = FAKE_MAC[0];
data[offset + 1] = FAKE_MAC[1];
data[offset + 2] = FAKE_MAC[2];
}
public void runDiscovery() {
- final byte discover[] = "HF-A11ASSISTHREAD".getBytes();
+ final byte[] discover = "HF-A11ASSISTHREAD".getBytes();
try {
byte[] a = new byte[0];
debugStr.append("iBox ");
}
- debugStr.append("Zone " + String.valueOf(buffer[19]) + " ");
+ debugStr.append("Zone " + buffer[19] + " ");
for (int i = 13; i < 19; ++i) {
debugStr.append(String.format("%02X ", buffer[i]));
}
}
- byte response[] = { (byte) 0x88, 0, 0, 0, (byte) 0x03, 0, seq, 0 };
+ byte[] response = { (byte) 0x88, 0, 0, 0, (byte) 0x03, 0, seq, 0 };
sendMessage(sPacket, datagramSocket, response);
continue;
}
logger.error("{}: {}", reason, s);
}
- protected void sendMessage(DatagramPacket packet, DatagramSocket datagramSocket, byte buffer[]) {
+ protected void sendMessage(DatagramPacket packet, DatagramSocket datagramSocket, byte[] buffer) {
packet.setData(buffer);
try {
datagramSocket.send(packet);
}
}
- private void debugSessionSend(byte buffer[], InetAddress address) {
+ private void debugSessionSend(byte[] buffer, InetAddress address) {
StringBuilder s = new StringBuilder();
for (int i = 0; i < buffer.length; ++i) {
s.append(String.format("%02X ", buffer[i]));
*/
public class GetIndependentDevicesByHomeResponse extends AbstractResponse {
@SerializedName("deviceInfo")
- public DeviceDTO devices[] = new DeviceDTO[0];
+ public DeviceDTO[] devices = new DeviceDTO[0];
}
final Optional<Room> optionalRoom = model.findRoomById(roomId);
if (optionalHome.isPresent() && optionalRoom.isPresent()) {
final SetRoomTempRequest req = new SetRoomTempRequest(optionalHome.get(), optionalRoom.get());
- if (command instanceof QuantityType<?>) {
- final int newTemp = (int) ((QuantityType<?>) command).longValue();
+ if (command instanceof QuantityType<?> quantityCommand) {
+ final int newTemp = (int) quantityCommand.longValue();
switch (mode) {
case SLEEP:
req.sleepTemp = newTemp;
@Nullable final Command fanCommand) {
model.findHeaterByMacOrId(macAddress, heaterId).ifPresent(heater -> {
int setTemp = heater.getTargetTemp();
- if (temperatureCommand instanceof QuantityType<?>) {
- setTemp = (int) ((QuantityType<?>) temperatureCommand).longValue();
+ if (temperatureCommand instanceof QuantityType<?> temperature) {
+ setTemp = (int) temperature.longValue();
}
boolean masterOnOff = heater.powerStatus();
if (masterOnOffCommand != null) {
updateState(channelUID, new QuantityType<>(home.getHolidayTemp(), SIUnits.CELSIUS));
} else if (command instanceof QuantityType<?>) {
updateVacationModeProperty(home, SetHolidayParameterRequest.PROP_TEMP, command);
- } else if (command instanceof DecimalType) {
+ } else if (command instanceof DecimalType decimalCommand) {
updateVacationModeProperty(home, SetHolidayParameterRequest.PROP_TEMP,
- new QuantityType<>((DecimalType) command, SIUnits.CELSIUS));
+ new QuantityType<>(decimalCommand, SIUnits.CELSIUS));
}
} else if (CHANNEL_HOME_VACATION_MODE.equals(channelUID.getId())) {
if (command instanceof RefreshType) {
if (macAddress != null) {
heater = findHeaterByMac(macAddress);
}
- if (!heater.isPresent() && id != null) {
+ if (heater.isEmpty() && id != null) {
heater = findHeaterById(id);
}
return heater;
minecraftServers.add(serverHandler);
return serverHandler;
} else if (thingTypeUID.equals(MinecraftBindingConstants.THING_TYPE_PLAYER)) {
- MinecraftPlayerHandler playerHandler = new MinecraftPlayerHandler(thing);
- return playerHandler;
+ return new MinecraftPlayerHandler(thing);
} else if (thingTypeUID.equals(MinecraftBindingConstants.THING_TYPE_SIGN)) {
- MinecraftSignHandler signHandler = new MinecraftSignHandler(thing);
- return signHandler;
+ return new MinecraftSignHandler(thing);
}
return null;
*/
package org.openhab.binding.minecraft.internal.discovery;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
+import java.util.Set;
import org.openhab.binding.minecraft.internal.MinecraftBindingConstants;
import org.openhab.binding.minecraft.internal.MinecraftHandlerFactory;
private CompositeSubscription subscription;
public MinecraftDiscoveryService() {
- super(Collections.singleton(MinecraftBindingConstants.THING_TYPE_SERVER), DISCOVER_TIMEOUT_SECONDS, false);
+ super(Set.of(MinecraftBindingConstants.THING_TYPE_SERVER), DISCOVER_TIMEOUT_SECONDS, false);
}
@Override
* @return subscription for listening to sign events.
*/
private Subscription subscribeSignsRx(Observable<ServerConnection> serverRx) {
- return serverRx
- .flatMap(connection -> connection.getSocketHandler().getSignsRx().distinct(), (connection, signs) -> {
- return new Pair<>(connection, signs);
- }).subscribe(conectionSignPair -> {
+ return serverRx.flatMap(connection -> connection.getSocketHandler().getSignsRx().distinct(),
+ (connection, signs) -> new Pair<>(connection, signs)).subscribe(conectionSignPair -> {
for (SignData sign : conectionSignPair.second) {
submitSignDiscoveryResults(conectionSignPair.first.getThingUID(), sign);
}
*/
package org.openhab.binding.minecraft.internal.discovery;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(MinecraftBindingConstants.THING_TYPE_SERVER);
+ return Set.of(MinecraftBindingConstants.THING_TYPE_SERVER);
}
@Override
@Override
public DiscoveryResult createResult(ServiceInfo service) {
- if (service.getName().equals("wc-minecraft")) {
+ if ("wc-minecraft".equals(service.getName())) {
ThingUID uid = getThingUID(service);
if (uid != null) {
MinecraftServerHandler bridgeHandler = null;
ThingHandler handler = bridge.getHandler();
- if (handler instanceof MinecraftServerHandler) {
- bridgeHandler = (MinecraftServerHandler) handler;
+ if (handler instanceof MinecraftServerHandler serverHandler) {
+ bridgeHandler = serverHandler;
} else {
logger.debug("No available bridge handler found yet. Bridge: {} .", bridge.getUID());
bridgeHandler = null;
MinecraftServerHandler bridgeHandler = null;
ThingHandler handler = bridge.getHandler();
- if (handler instanceof MinecraftServerHandler) {
- bridgeHandler = (MinecraftServerHandler) handler;
+ if (handler instanceof MinecraftServerHandler serverHandler) {
+ bridgeHandler = serverHandler;
} else {
logger.debug("No available bridge handler found yet. Bridge: {} .", bridge.getUID());
bridgeHandler = null;
return null;
}
- if (handler instanceof ModbusEndpointThingHandler) {
- ModbusEndpointThingHandler slaveEndpoint = (ModbusEndpointThingHandler) handler;
- return slaveEndpoint;
+ if (handler instanceof ModbusEndpointThingHandler thingHandler) {
+ return thingHandler;
} else {
logger.debug("Unexpected bridge handler: {}", handler);
return null;
private void triggerSwitch(String variableName) {
try {
if (handler != null) {
-
handler.writeValue(variableName, "1");
}
} catch (HeliosException e) {
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.Semaphore;
return null;
}
- if (handler instanceof ModbusEndpointThingHandler) {
- return (ModbusEndpointThingHandler) handler;
+ if (handler instanceof ModbusEndpointThingHandler thingHandler) {
+ return thingHandler;
} else {
logger.debug("Unexpected bridge handler: {}", handler);
return null;
String value = null;
if (command instanceof OnOffType) {
value = command == OnOffType.ON ? "1" : "0";
- } else if (command instanceof DateTimeType) {
+ } else if (command instanceof DateTimeType dateTimeCommand) {
try {
- ZonedDateTime d = ((DateTimeType) command).getZonedDateTime();
+ ZonedDateTime d = dateTimeCommand.getZonedDateTime();
if (channelId.equals(HeliosEasyControlsBindingConstants.SYS_DATE)) {
setSysDateTime(d);
} else if (channelId.equals(HeliosEasyControlsBindingConstants.BYPASS_FROM)) {
} else if (channelId.equals(HeliosEasyControlsBindingConstants.BYPASS_TO)) {
this.setBypass(false, d.getDayOfMonth(), d.getMonthValue());
} else {
- value = formatDate(channelId, ((DateTimeType) command).getZonedDateTime());
+ value = formatDate(channelId, dateTimeCommand.getZonedDateTime());
}
} catch (InterruptedException e) {
logger.debug(
}
} else if ((command instanceof DecimalType) || (command instanceof StringType)) {
value = command.toString();
- } else if (command instanceof QuantityType<?>) {
+ } else if (command instanceof QuantityType<?> val) {
// convert item's unit to the Helios device's unit
Map<String, HeliosVariable> variableMap = this.variableMap;
if (variableMap != null) {
HeliosVariable v = variableMap.get(channelId);
if (v != null) {
String unit = v.getUnit();
- QuantityType<?> val = (QuantityType<?>) command;
if (unit != null) {
switch (unit) {
case HeliosVariable.UNIT_DAY:
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(HeliosEasyControlsActions.class);
+ return Set.of(HeliosEasyControlsActions.class);
}
/**
switch (itemType) {
case "Number":
if (((HeliosVariable.TYPE_INTEGER.equals(variableType))
- || (HeliosVariable.TYPE_FLOAT.equals(variableType))) && (!value.equals("-"))) {
+ || (HeliosVariable.TYPE_FLOAT.equals(variableType))) && (!"-".equals(value))) {
State state = null;
if (v.getUnit() == null) {
state = DecimalType.valueOf(value);
break;
case "Switch":
if (variableType.equals(HeliosVariable.TYPE_INTEGER)) {
- updateState(v.getGroupAndName(), value.equals("1") ? OnOffType.ON : OnOffType.OFF);
+ updateState(v.getGroupAndName(), "1".equals(value) ? OnOffType.ON : OnOffType.OFF);
}
break;
case "String":
import static org.openhab.binding.modbus.helioseasycontrols.internal.HeliosEasyControlsBindingConstants.THING_TYPE_HELIOS_VENTILATION_EASY_CONTROLS;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.helioseasycontrols", service = ThingHandlerFactory.class)
public class HeliosEasyControlsHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections
- .singleton(THING_TYPE_HELIOS_VENTILATION_EASY_CONTROLS);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set
+ .of(THING_TYPE_HELIOS_VENTILATION_EASY_CONTROLS);
private final HeliosEasyControlsTranslationProvider translationProvider;
@Activate
import static org.openhab.binding.modbus.stiebeleltron.internal.StiebelEltronBindingConstants.THING_TYPE_HEATPUMP;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.stiebeleltron", service = ThingHandlerFactory.class)
public class StiebelEltronHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_HEATPUMP);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_HEATPUMP);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
* Register poll task This is where we set up our regular poller
*/
public synchronized void registerPollTask(int address, int length, ModbusReadFunctionCode readFunctionCode) {
-
logger.debug("Setting up regular polling");
ModbusCommunicationInterface mycomms = StiebelEltronHandler.this.comms;
* the stiebel eltron modbus documentation)
*/
private short getScaledInt16Value(Command command) throws StiebelEltronException {
- if (command instanceof QuantityType) {
- QuantityType<?> c = ((QuantityType<?>) command).toUnit(CELSIUS);
+ if (command instanceof QuantityType quantityCommand) {
+ QuantityType<?> c = quantityCommand.toUnit(CELSIUS);
if (c != null) {
return (short) (c.doubleValue() * 10);
} else {
throw new StiebelEltronException("Unsupported unit");
}
}
- if (command instanceof DecimalType) {
- DecimalType c = (DecimalType) command;
+ if (command instanceof DecimalType c) {
return (short) (c.doubleValue() * 10);
}
throw new StiebelEltronException("Unsupported command type");
* @return short the value of the command as short
*/
private short getInt16Value(Command command) throws StiebelEltronException {
- if (command instanceof DecimalType) {
- DecimalType c = (DecimalType) command;
+ if (command instanceof DecimalType c) {
return c.shortValue();
}
throw new StiebelEltronException("Unsupported command type");
* Start the periodic polling1
*/
private void startUp() {
-
if (comms != null) {
return;
}
return null;
}
- if (handler instanceof ModbusEndpointThingHandler) {
- ModbusEndpointThingHandler slaveEndpoint = (ModbusEndpointThingHandler) handler;
- return slaveEndpoint;
+ if (handler instanceof ModbusEndpointThingHandler thingHandler) {
+ return thingHandler;
} else {
throw new IllegalStateException("Unexpected bridge handler: " + handler.toString());
}
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
-
// Currently we do not support any commands
}
* Start the periodic polling
*/
private void startUp() {
-
connectEndpoint();
if (comms == null || config == null) {
return null;
}
- if (handler instanceof ModbusEndpointThingHandler) {
- ModbusEndpointThingHandler slaveEndpoint = (ModbusEndpointThingHandler) handler;
- return slaveEndpoint;
+ if (handler instanceof ModbusEndpointThingHandler thingHandler) {
+ return thingHandler;
} else {
logger.debug("Unexpected bridge handler: {}", handler);
return null;
* @return the converted float
*/
public @Nullable Float hexToFloat(String hex) {
- String t = hex.replaceAll(" ", "");
+ String t = hex.replace(" ", "");
float f = Float.intBitsToFloat((int) Long.parseLong(t, 16));
if (Float.isNaN(f)) {
return null;
Optional<DecimalType> id = ModbusBitUtilities.extractStateFromRegisters(registers, 0, ValueType.UINT32);
- if (!id.isPresent() || id.get().longValue() != SUNSPEC_ID) {
+ if (id.isEmpty() || id.get().longValue() != SUNSPEC_ID) {
logger.debug("Could not find SunSpec DID at address {}, received: {}, expected: {}", baseAddress, id,
SUNSPEC_ID);
detectModel();
Optional<DecimalType> blockLength = ModbusBitUtilities.extractStateFromRegisters(registers, 1,
ValueType.UINT16);
- if (!moduleID.isPresent() || !blockLength.isPresent()) {
+ if (moduleID.isEmpty() || blockLength.isEmpty()) {
logger.info("Could not find valid module id or block length field.");
parsingFinished();
return;
return null;
}
- if (handler instanceof ModbusEndpointThingHandler) {
- ModbusEndpointThingHandler slaveEndpoint = (ModbusEndpointThingHandler) handler;
- return slaveEndpoint;
+ if (handler instanceof ModbusEndpointThingHandler thingHandler) {
+ return thingHandler;
} else {
logger.debug("Unexpected bridge handler: {}", handler);
return null;
* @return the scaled value as a DecimalType
*/
protected State getScaled(Optional<? extends Number> value, Optional<Short> scaleFactor, Unit<?> unit) {
- if (!value.isPresent() || !scaleFactor.isPresent()) {
+ if (value.isEmpty() || scaleFactor.isEmpty()) {
return UnDefType.UNDEF;
}
return getScaled(value.get().longValue(), scaleFactor.get(), unit);
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof ModbusEndpointThingHandler) {
- this.handler = (ModbusEndpointThingHandler) handler;
+ if (handler instanceof ModbusEndpointThingHandler thingHandler) {
+ this.handler = thingHandler;
}
}
BridgeHandler handler = bridge.getHandler();
- if (handler instanceof ModbusEndpointThingHandler) {
- return (ModbusEndpointThingHandler) handler;
+ if (handler instanceof ModbusEndpointThingHandler thingHandler) {
+ return thingHandler;
} else {
throw new IllegalStateException("Not a Modbus Bridge: " + handler);
}
return null;
}
- if (handler instanceof ModbusEndpointThingHandler) {
- ModbusEndpointThingHandler slaveEndpoint = (ModbusEndpointThingHandler) handler;
- return slaveEndpoint;
+ if (handler instanceof ModbusEndpointThingHandler thingHandler) {
+ return thingHandler;
} else {
logger.debug("Unexpected bridge handler: {}", handler);
return null;
@Override
public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
- if (childHandler instanceof ModbusDataThingHandler) {
- this.childCallbacks.add((ModbusDataThingHandler) childHandler);
+ if (childHandler instanceof ModbusDataThingHandler modbusDataThingHandler) {
+ this.childCallbacks.add(modbusDataThingHandler);
}
}
package org.openhab.binding.modbus.internal;
import java.util.Arrays;
-import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
.filter(s -> !s.isEmpty()).map(transformation -> new SingleValueTransformation(transformation))
.collect(Collectors.toList());
if (localTransformations.isEmpty()) {
- localTransformations = Collections.singletonList(new SingleValueTransformation(transformationString));
+ localTransformations = List.of(new SingleValueTransformation(transformationString));
}
transformations = localTransformations;
}
}
public static Optional<Command> tryConvertToCommand(String transformed) {
- Optional<Command> transformedCommand = Optional.ofNullable(TypeParser.parseCommand(DEFAULT_TYPES, transformed));
- return transformedCommand;
+ return Optional.ofNullable(TypeParser.parseCommand(DEFAULT_TYPES, transformed));
}
@Override
return;
}
- if (!transformedCommand.isPresent()) {
+ if (transformedCommand.isEmpty()) {
// transformation failed, return
logger.warn("Cannot process command {} (of type {}) with channel {} since transformation was unsuccessful",
command, command.getClass().getSimpleName(), channelUID);
}
if (writeType.equals(WRITE_TYPE_COIL)) {
Optional<Boolean> commandAsBoolean = ModbusBitUtilities.translateCommand2Boolean(transformedCommand);
- if (!commandAsBoolean.isPresent()) {
+ if (commandAsBoolean.isEmpty()) {
logger.warn(
"Cannot process command {} with channel {} since command is not OnOffType, OpenClosedType or Decimal trying to write to coil. Do not know how to convert to 0/1. Transformed command was '{}'",
origCommand, channelUID, transformedCommand);
bridge.getLabel());
throw new ModbusConfigurationException(errmsg);
}
- if (bridgeHandler instanceof ModbusEndpointThingHandler) {
- // Write-only thing, parent is endpoint
- ModbusEndpointThingHandler endpointHandler = (ModbusEndpointThingHandler) bridgeHandler;
+ if (bridgeHandler instanceof ModbusEndpointThingHandler endpointHandler) {
slaveId = endpointHandler.getSlaveId();
comms = endpointHandler.getCommunicationInterface();
childOfEndpoint = true;
@Nullable
ModbusReadRequestBlueprint readRequest = this.readRequest;
ValueType readValueType = this.readValueType;
- if (!readIndex.isPresent() || readRequest == null) {
+ if (readIndex.isEmpty() || readRequest == null) {
return;
}
assert readValueType != null;
String errmsg = String.format(
"readStart=X.Y notation is not allowed to be used with value types larger than 16bit! Use readStart=X instead.");
throw new ModbusConfigurationException(errmsg);
- } else if (!bitQuery && valueTypeBitCount < 16 && !readSubIndex.isPresent()) {
+ } else if (!bitQuery && valueTypeBitCount < 16 && readSubIndex.isEmpty()) {
// User has specified value type which is less than register width (16 bits).
// readStart=X.Y notation must be used to define which data to extract from the 16 bit register.
String errmsg = String
private void validateWriteIndex() throws ModbusConfigurationException {
@Nullable
ModbusReadRequestBlueprint readRequest = this.readRequest;
- if (!writeStart.isPresent() || !writeSubIndex.isPresent()) {
+ if (writeStart.isEmpty() || writeSubIndex.isEmpty()) {
//
// this validation is really about writeStart=X.Y validation
//
}
private boolean containsOnOff(List<Class<? extends State>> channelAcceptedDataTypes) {
- return channelAcceptedDataTypes.stream().anyMatch(clz -> {
- return clz.equals(OnOffType.class);
- });
+ return channelAcceptedDataTypes.stream().anyMatch(clz -> clz.equals(OnOffType.class));
}
private boolean containsOpenClosed(List<Class<? extends State>> acceptedDataTypes) {
- return acceptedDataTypes.stream().anyMatch(clz -> {
- return clz.equals(OpenClosedType.class);
- });
+ return acceptedDataTypes.stream().anyMatch(clz -> clz.equals(OpenClosedType.class));
}
public synchronized void onReadResult(AsyncModbusReadResult result) {
package org.openhab.binding.modbus.internal.handler;
import java.util.Collection;
-import java.util.Collections;
import java.util.Optional;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.modbus.discovery.internal.ModbusEndpointDiscoveryService;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(ModbusEndpointDiscoveryService.class);
+ return Set.of(ModbusEndpointDiscoveryService.class);
}
}
package org.openhab.binding.modbus.internal.handler;
import java.util.Collection;
-import java.util.Collections;
import java.util.Optional;
+import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.modbus.discovery.internal.ModbusEndpointDiscoveryService;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(ModbusEndpointDiscoveryService.class);
+ return Set.of(ModbusEndpointDiscoveryService.class);
}
}
@Override
public void onCommandFromItem(Command command) {
Type result = applyGainOffset(command, false);
- if (result instanceof Command) {
+ if (result instanceof Command cmd) {
logger.trace("Command '{}' from item, sending converted '{}' state towards handler.", command, result);
- callback.handleCommand((Command) result);
+ callback.handleCommand(cmd);
}
}
@Override
public void onCommandFromHandler(Command command) {
Type result = applyGainOffset(command, true);
- if (result instanceof Command) {
+ if (result instanceof Command cmd) {
logger.trace("Command '{}' from handler, sending converted '{}' command towards item.", command, result);
- callback.sendCommand((Command) result);
+ callback.sendCommand(cmd);
}
}
QuantityType<Dimensionless> pregainOffsetQt = localPregainOffset.get();
String formula = towardsItem ? String.format("( '%s' + '%s') * '%s'", state, pregainOffsetQt, gain)
: String.format("'%s'/'%s' - '%s'", state, gain, pregainOffsetQt);
- if (state instanceof QuantityType) {
+ if (state instanceof QuantityType quantityState) {
try {
if (towardsItem) {
@SuppressWarnings("unchecked") // xx.toUnit(ONE) returns null or QuantityType<Dimensionless>
@Nullable
- QuantityType<Dimensionless> qtState = (QuantityType<Dimensionless>) (((QuantityType<?>) state)
+ QuantityType<Dimensionless> qtState = (QuantityType<Dimensionless>) (quantityState
.toUnit(Units.ONE));
if (qtState == null) {
logger.warn("Profile can only process plain numbers from handler. Got unit {}. Returning UNDEF",
- ((QuantityType<?>) state).getUnit());
+ quantityState.getUnit());
return UnDefType.UNDEF;
}
QuantityType<Dimensionless> offsetted = qtState.add(pregainOffsetQt);
result = applyGainTowardsItem(offsetted, gain);
} else {
- final QuantityType<?> qtState = (QuantityType<?>) state;
- result = applyGainTowardsHandler(qtState, gain).subtract(pregainOffsetQt);
+ result = applyGainTowardsHandler(quantityState, gain).subtract(pregainOffsetQt);
}
} catch (UnconvertibleException | UnsupportedOperationException e) {
gain, pregainOffsetQt, state, formula, towardsItem, e.getMessage());
return UnDefType.UNDEF;
}
- } else if (state instanceof DecimalType) {
- DecimalType decState = (DecimalType) state;
+ } else if (state instanceof DecimalType decState) {
return applyGainOffset(new QuantityType<>(decState, Units.ONE), towardsItem);
} else if (state instanceof RefreshType) {
result = state;
Object parameterValue, @Nullable Unit<QU> assertUnit) {
Optional<QuantityType<QU>> result = Optional.empty();
Unit<QU> sourceUnit = null;
- if (parameterValue instanceof String) {
+ if (parameterValue instanceof String str) {
try {
- QuantityType<QU> qt = new QuantityType<>((String) parameterValue);
+ QuantityType<QU> qt = new QuantityType<>(str);
result = Optional.of(qt);
sourceUnit = qt.getUnit();
} catch (IllegalArgumentException e) {
logger.error("Cannot convert value '{}' of parameter '{}' into a QuantityType.", parameterValue,
parameterName);
}
- } else if (parameterValue instanceof BigDecimal) {
- BigDecimal parameterBigDecimal = (BigDecimal) parameterValue;
+ } else if (parameterValue instanceof BigDecimal parameterBigDecimal) {
result = Optional.of(new QuantityType<QU>(parameterBigDecimal.toString()));
} else {
logger.error("Parameter '{}' is not of type String or BigDecimal", parameterName);
private static Object orDefault(Object defaultValue, @Nullable Object value) {
if (value == null) {
return defaultValue;
- } else if (value instanceof String && ((String) value).isBlank()) {
+ } else if (value instanceof String str && str.isBlank()) {
return defaultValue;
} else {
return value;
final Type actualStateUpdateTowardsItem;
if (stateUpdateFromHandler) {
final State updateFromHandler;
- if (updateFromHandlerObj instanceof String) {
- updateFromHandler = new QuantityType((String) updateFromHandlerObj);
+ if (updateFromHandlerObj instanceof String str) {
+ updateFromHandler = new QuantityType(str);
} else {
assertTrue(updateFromHandlerObj instanceof State);
updateFromHandler = (State) updateFromHandlerObj;
actualStateUpdateTowardsItem = capture.getValue();
} else {
final Command updateFromHandler;
- if (updateFromHandlerObj instanceof String) {
- updateFromHandler = new QuantityType((String) updateFromHandlerObj);
+ if (updateFromHandlerObj instanceof String str) {
+ updateFromHandler = new QuantityType(str);
} else {
assertTrue(updateFromHandlerObj instanceof State);
updateFromHandler = (Command) updateFromHandlerObj;
actualStateUpdateTowardsItem = capture.getValue();
}
- Type expectedStateUpdateTowardsItem = (expectedUpdateTowardsItemObj instanceof String)
- ? new QuantityType((String) expectedUpdateTowardsItemObj)
+ Type expectedStateUpdateTowardsItem = (expectedUpdateTowardsItemObj instanceof String s) ? new QuantityType(s)
: (Type) expectedUpdateTowardsItemObj;
assertEquals(expectedStateUpdateTowardsItem, actualStateUpdateTowardsItem);
verifyNoMoreInteractions(callback);
ProfileCallback callback = mock(ProfileCallback.class);
ModbusGainOffsetProfile profile = createProfile(callback, gain, preGainOffset);
- Command commandFromItem = (commandFromItemObj instanceof String) ? new QuantityType((String) commandFromItemObj)
+ Command commandFromItem = (commandFromItemObj instanceof String str) ? new QuantityType(str)
: (Command) commandFromItemObj;
profile.onCommandFromItem(commandFromItem);
ArgumentCaptor<Command> capture = ArgumentCaptor.forClass(Command.class);
verify(callback, times(1)).handleCommand(capture.capture());
Command actualCommandTowardsHandler = capture.getValue();
- Command expectedCommandTowardsHandler = (expectedCommandTowardsHandlerObj instanceof String)
- ? new QuantityType((String) expectedCommandTowardsHandlerObj)
+ Command expectedCommandTowardsHandler = (expectedCommandTowardsHandlerObj instanceof String str)
+ ? new QuantityType(str)
: (Command) expectedCommandTowardsHandlerObj;
assertEquals(expectedCommandTowardsHandler, actualCommandTowardsHandler);
verifyNoMoreInteractions(callback);
}
break;
case CHANNEL_TYPE_SOURCE:
- if (command instanceof DecimalType) {
- final int value = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ final int value = decimalCommand.intValue();
if (value >= ONE && value <= amp.getNumSources()) {
logger.debug("Got source command {} zone {}", value, zoneId);
connector.sendCommand(zoneId, amp.getSourceCmd(), value);
}
break;
case CHANNEL_TYPE_VOLUME:
- if (command instanceof PercentType) {
- final int value = (int) Math.round(
- ((PercentType) command).doubleValue() / 100.0 * (amp.getMaxVol() - MIN_VOLUME))
+ if (command instanceof PercentType percentCommand) {
+ final int value = (int) Math
+ .round(percentCommand.doubleValue() / 100.0 * (amp.getMaxVol() - MIN_VOLUME))
+ MIN_VOLUME;
logger.debug("Got volume command {} zone {}", value, zoneId);
connector.sendCommand(zoneId, amp.getVolumeCmd(), value);
}
break;
case CHANNEL_TYPE_TREBLE:
- if (command instanceof DecimalType) {
- final int value = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ final int value = decimalCommand.intValue();
if (value >= amp.getMinTone() && value <= amp.getMaxTone()) {
logger.debug("Got treble command {} zone {}", value, zoneId);
connector.sendCommand(zoneId, amp.getTrebleCmd(), value + amp.getToneOffset());
}
break;
case CHANNEL_TYPE_BASS:
- if (command instanceof DecimalType) {
- final int value = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ final int value = decimalCommand.intValue();
if (value >= amp.getMinTone() && value <= amp.getMaxTone()) {
logger.debug("Got bass command {} zone {}", value, zoneId);
connector.sendCommand(zoneId, amp.getBassCmd(), value + amp.getToneOffset());
}
break;
case CHANNEL_TYPE_BALANCE:
- if (command instanceof DecimalType) {
- final int value = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ final int value = decimalCommand.intValue();
if (value >= amp.getMinBal() && value <= amp.getMaxBal()) {
logger.debug("Got balance command {} zone {}", value, zoneId);
connector.sendCommand(zoneId, amp.getBalanceCmd(), value + amp.getBalOffset());
}
break;
case CHANNEL_TYPE_ALLSOURCE:
- if (command instanceof DecimalType) {
- final int value = ((DecimalType) command).intValue();
+ if (command instanceof DecimalType decimalCommand) {
+ final int value = decimalCommand.intValue();
if (value >= ONE && value <= amp.getNumSources()) {
zoneStream.forEach((streamZoneId) -> {
if (!ignoreZones.contains(amp.getZoneName(streamZoneId))) {
}
break;
case CHANNEL_TYPE_ALLVOLUME:
- if (command instanceof PercentType) {
- allVolume = (int) Math.round(
- ((PercentType) command).doubleValue() / 100.0 * (amp.getMaxVol() - MIN_VOLUME))
+ if (command instanceof PercentType percentCommand) {
+ allVolume = (int) Math
+ .round(percentCommand.doubleValue() / 100.0 * (amp.getMaxVol() - MIN_VOLUME))
+ MIN_VOLUME;
zoneStream.forEach((streamZoneId) -> {
if (!ignoreZones.contains(amp.getZoneName(streamZoneId))) {
import static org.openhab.binding.mpd.internal.MPDBindingConstants.THING_TYPE_MPD;
-import java.util.Collections;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@Component(configurationPid = "binding.mpd", service = ThingHandlerFactory.class)
public class MPDHandlerFactory extends BaseThingHandlerFactory {
- private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Collections.singleton(THING_TYPE_MPD);
+ private static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = Set.of(THING_TYPE_MPD);
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
@Override
public void setThingHandler(@Nullable ThingHandler handler) {
- if (handler instanceof MPDHandler) {
- this.handler = (MPDHandler) handler;
+ if (handler instanceof MPDHandler mpdHandler) {
+ this.handler = mpdHandler;
}
}
package org.openhab.binding.mpd.internal.discovery;
import java.net.Inet4Address;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
@Override
public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
- return Collections.singleton(MPDBindingConstants.THING_TYPE_MPD);
+ return Set.of(MPDBindingConstants.THING_TYPE_MPD);
}
@Override
String name = service.getName();
- final DiscoveryResult result = DiscoveryResultBuilder.create(uid).withLabel(name).withProperties(properties)
+ return DiscoveryResultBuilder.create(uid).withLabel(name).withProperties(properties)
.withRepresentationProperty(MPDBindingConstants.UNIQUE_ID).build();
- return result;
}
@Nullable
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(MPDActions.class);
+ return Set.of(MPDActions.class);
}
/**
} else if (command == OnOffType.OFF) {
newValue = 0;
}
- } else if (command instanceof DecimalType) {
- newValue = ((DecimalType) command).intValue();
- } else if (command instanceof PercentType) {
- newValue = ((PercentType) command).intValue();
+ } else if (command instanceof DecimalType decimalCommand) {
+ newValue = decimalCommand.intValue();
+ } else if (command instanceof PercentType percentCommand) {
+ newValue = percentCommand.intValue();
} else {
logger.debug("Command {} is not supported to change volume", command);
return;
for (String param : parameters) {
builder.append(" ");
builder.append("\"");
- builder.append(param.replaceAll("\"", "\\\\\"").replaceAll("'", "\\\\'"));
+ builder.append(param.replace("\"", "\\\\\"").replace("'", "\\\\'"));
builder.append("\"");
}
if ("password".equals(command)) {
builder.append(param.replaceAll(".", "."));
} else {
- builder.append(param.replaceAll("\"", "\\\\\"").replaceAll("'", "\\\\'"));
+ builder.append(param.replace("\"", "\\\\\"").replace("'", "\\\\'"));
}
builder.append("\"");
}
bulbSaturation = "100";
}
// 360 isn't allowed by OpenHAB
- if (bulbHue.equals("360")) {
+ if ("360".equals(bulbHue)) {
bulbHue = "0";
}
var hsb = new HSBType(new DecimalType(Integer.valueOf(bulbHue)),
}
sendMQTT("{\"state\":\"ON\",\"level\":" + savedLevel.intValue() + "}");
return;
- } else if (command instanceof HSBType) {
- HSBType hsb = (HSBType) command;
+ } else if (command instanceof HSBType hsb) {
// This feature allows google home or Echo to trigger white mode when asked to turn color to white.
if (hsb.getHue().intValue() == config.whiteHue && hsb.getSaturation().intValue() == config.whiteSat) {
if (hasCCT()) {
}
savedLevel = hsb.getBrightness().toBigDecimal();
return;
- } else if (command instanceof PercentType) {
- PercentType percentType = (PercentType) command;
+ } else if (command instanceof PercentType percentType) {
if (percentType.intValue() == 0) {
turnOff();
return;
return;
}
ThingHandler handler = localBridge.getHandler();
- if (handler instanceof AbstractBrokerHandler) {
- AbstractBrokerHandler abh = (AbstractBrokerHandler) handler;
+ if (handler instanceof AbstractBrokerHandler abh) {
final MqttBrokerConnection connection;
try {
connection = abh.getConnectionAsync().get(500, TimeUnit.MILLISECONDS);
// Handle the conversion case of BigDecimal to Float,Double,Long,Integer and the respective
// primitive types
String typeName = type.getSimpleName();
- if (value instanceof BigDecimal && !type.equals(BigDecimal.class)) {
- BigDecimal bdValue = (BigDecimal) value;
+ if (value instanceof BigDecimal bdValue && !type.equals(BigDecimal.class)) {
if (type.equals(Float.class) || "float".equals(typeName)) {
result = bdValue.floatValue();
} else if (type.equals(Double.class) || "double".equals(typeName)) {
} else
// Handle the conversion case of String to Float,Double,Long,Integer,BigDecimal and the respective
// primitive types
- if (value instanceof String && !type.equals(String.class)) {
- String bdValue = (String) value;
+ if (value instanceof String bdValue && !type.equals(String.class)) {
if (type.equals(Float.class) || "float".equals(typeName)) {
result = Float.valueOf(bdValue);
} else if (type.equals(Double.class) || "double".equals(typeName)) {
@Override
public HSBType parseCommand(Command command) throws IllegalArgumentException {
HSBType oldvalue = (state == UnDefType.UNDEF) ? new HSBType() : (HSBType) state;
- if (command instanceof HSBType) {
- return (HSBType) command;
- } else if (command instanceof OnOffType) {
- OnOffType boolValue = ((OnOffType) command);
+ if (command instanceof HSBType hsbCommand) {
+ return hsbCommand;
+ } else if (command instanceof OnOffType onOffCommand) {
PercentType minOn = new PercentType(Math.max(oldvalue.getBrightness().intValue(), onBrightness));
return new HSBType(oldvalue.getHue(), oldvalue.getSaturation(),
- boolValue == OnOffType.ON ? minOn : new PercentType(0));
- } else if (command instanceof PercentType) {
- return new HSBType(oldvalue.getHue(), oldvalue.getSaturation(), (PercentType) command);
+ onOffCommand == OnOffType.ON ? minOn : new PercentType(0));
+ } else if (command instanceof PercentType percentCommand) {
+ return new HSBType(oldvalue.getHue(), oldvalue.getSaturation(), percentCommand);
} else {
final String updatedValue = command.toString();
if (onValue.equals(updatedValue)) {
@Override
public DateTimeType parseCommand(Command command) throws IllegalArgumentException {
- if (command instanceof DateTimeType) {
- return ((DateTimeType) command);
+ if (command instanceof DateTimeType dateTimeCommand) {
+ return dateTimeCommand;
} else {
return DateTimeType.valueOf(command.toString());
}
@Override
public PointType parseCommand(Command command) throws IllegalArgumentException {
- if (command instanceof PointType) {
- return ((PointType) command);
+ if (command instanceof PointType point) {
+ return point;
} else {
return PointType.valueOf(command.toString());
}
@Override
public Command parseCommand(Command command) throws IllegalArgumentException {
BigDecimal newValue = null;
- if (command instanceof DecimalType) {
- newValue = ((DecimalType) command).toBigDecimal();
+ if (command instanceof DecimalType decimalCommand) {
+ newValue = decimalCommand.toBigDecimal();
} else if (command instanceof IncreaseDecreaseType || command instanceof UpDownType) {
BigDecimal oldValue = getOldValue();
if (command == IncreaseDecreaseType.INCREASE || command == UpDownType.UP) {
} else {
newValue = oldValue.subtract(step);
}
- } else if (command instanceof QuantityType<?>) {
- newValue = getQuantityTypeAsDecimal((QuantityType<?>) command);
+ } else if (command instanceof QuantityType<?> quantityCommand) {
+ newValue = getQuantityTypeAsDecimal(quantityCommand);
} else {
newValue = new BigDecimal(command.toString());
}
private BigDecimal getOldValue() {
BigDecimal val = BigDecimal.ZERO;
- if (state instanceof DecimalType) {
- val = ((DecimalType) state).toBigDecimal();
- } else if (state instanceof QuantityType<?>) {
- val = ((QuantityType<?>) state).toBigDecimal();
+ if (state instanceof DecimalType decimalCommand) {
+ val = decimalCommand.toBigDecimal();
+ } else if (state instanceof QuantityType<?> quantityCommand) {
+ val = quantityCommand.toBigDecimal();
}
return val;
}
@Override
public OnOffType parseCommand(Command command) throws IllegalArgumentException {
- if (command instanceof OnOffType) {
- return (OnOffType) command;
+ if (command instanceof OnOffType onOffCommand) {
+ return onOffCommand;
} else {
final String updatedValue = command.toString();
if (onState.equals(updatedValue)) {
@Override
public OpenClosedType parseCommand(Command command) throws IllegalArgumentException {
- if (command instanceof OpenClosedType) {
- return (OpenClosedType) command;
+ if (command instanceof OpenClosedType openClosed) {
+ return openClosed;
} else {
final String updatedValue = command.toString();
if (openString.equals(updatedValue)) {
public PercentType parseCommand(Command command) throws IllegalArgumentException {
PercentType oldvalue = (state == UnDefType.UNDEF) ? new PercentType() : (PercentType) state;
// Nothing do to -> We have received a percentage
- if (command instanceof PercentType) {
- return (PercentType) command;
+ if (command instanceof PercentType percent) {
+ return percent;
} else //
// A decimal type need to be converted according to the current min/max values
- if (command instanceof DecimalType) {
- BigDecimal v = ((DecimalType) command).toBigDecimal();
+ if (command instanceof DecimalType decimal) {
+ BigDecimal v = decimal.toBigDecimal();
v = v.subtract(min).multiply(HUNDRED).divide(max.subtract(min), MathContext.DECIMAL128);
return new PercentType(v);
} else //
// A quantity type need to be converted according to the current min/max values
- if (command instanceof QuantityType) {
- QuantityType<?> qty = ((QuantityType<?>) command).toUnit(Units.PERCENT);
+ if (command instanceof QuantityType quantity) {
+ QuantityType<?> qty = quantity.toUnit(Units.PERCENT);
if (qty != null) {
BigDecimal v = qty.toBigDecimal();
v = v.subtract(min).multiply(HUNDRED).divide(max.subtract(min), MathContext.DECIMAL128);
return oldvalue;
} else //
// Increase or decrease by "step"
- if (command instanceof IncreaseDecreaseType) {
- if (((IncreaseDecreaseType) command) == IncreaseDecreaseType.INCREASE) {
+ if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
+ if (increaseDecreaseCommand == IncreaseDecreaseType.INCREASE) {
final BigDecimal v = oldvalue.toBigDecimal().add(stepPercent);
return v.compareTo(HUNDRED) <= 0 ? new PercentType(v) : PercentType.HUNDRED;
} else {
}
} else //
// On/Off equals 100 or 0 percent
- if (command instanceof OnOffType) {
- return ((OnOffType) command) == OnOffType.ON ? PercentType.HUNDRED : PercentType.ZERO;
+ if (command instanceof OnOffType increaseDecreaseCommand) {
+ return increaseDecreaseCommand == OnOffType.ON ? PercentType.HUNDRED : PercentType.ZERO;
} else//
// Increase or decrease by "step"
- if (command instanceof UpDownType) {
- if (((UpDownType) command) == UpDownType.UP) {
+ if (command instanceof UpDownType upDownCommand) {
+ if (upDownCommand == UpDownType.UP) {
final BigDecimal v = oldvalue.toBigDecimal().add(stepPercent);
return v.compareTo(HUNDRED) <= 0 ? new PercentType(v) : PercentType.HUNDRED;
} else {
return PercentType.HUNDRED;
}
}
- } else if (command instanceof PercentType) {
- return (PercentType) command;
+ } else if (command instanceof PercentType percentage) {
+ return percentage;
} else if (command instanceof StringType) {
final String updatedValue = command.toString();
if (updatedValue.equals(upString)) {
} else {
return ((StopMoveType) command).name();
}
- } else if (command instanceof PercentType) {
+ } else if (command instanceof PercentType percentage) {
if (command.equals(PercentType.HUNDRED) && downString != null) {
return downString;
} else if (command.equals(PercentType.ZERO) && upString != null) {
return upString;
} else {
- return String.valueOf(((PercentType) command).intValue());
+ return String.valueOf(percentage.intValue());
}
} else {
throw new IllegalArgumentException("Invalid command type for Rollershutter item");
* @param data The binary payload to update the internal value.
* @exception IllegalArgumentException Thrown if for example a text is assigned to a number type.
*/
- public void update(byte data[]) throws IllegalArgumentException {
+ public void update(byte[] data) throws IllegalArgumentException {
String mimeType = null;
// URLConnection.guessContentTypeFromStream(input) is not sufficient to detect all JPEG files
ChannelStateTransformation transformation = channelConfig.transformationsIn.get(0);
- byte payload[] = JSON_PATH_JSON.getBytes();
+ byte[] payload = JSON_PATH_JSON.getBytes();
assertThat(transformation.pattern, is(JSON_PATH_PATTERN));
// Test process message
channelConfig.processMessage(channelConfig.getStateTopic(), payload);
textValue, thingHandler));
doReturn(channelConfig).when(thingHandler).createChannelState(any(), any(), any());
thingHandler.initialize();
- byte payload[] = "UPDATE".getBytes();
+ byte[] payload = "UPDATE".getBytes();
// Test process message
channelConfig.processMessage("test/state", payload);
if (newState.getBrightness().equals(PercentType.ZERO)) {
newState = new HSBType(newState.getHue(), newState.getSaturation(), PercentType.HUNDRED);
}
- } else if (command instanceof HSBType) {
- newState = (HSBType) command;
- } else if (command instanceof PercentType) {
- newState = new HSBType(newState.getHue(), newState.getSaturation(), (PercentType) command);
+ } else if (command instanceof HSBType hsb) {
+ newState = hsb;
+ } else if (command instanceof PercentType brightness) {
+ newState = new HSBType(newState.getHue(), newState.getSaturation(), brightness);
} else {
return false;
}
public static final String TEMPERATURE_LOW_CH_ID = "temperatureLow";
public static final String POWER_CH_ID = "power";
- public static enum TemperatureUnit {
+ public enum TemperatureUnit {
@SerializedName("C")
CELSIUS(SIUnits.CELSIUS, new BigDecimal("0.1")),
@SerializedName("F")
private boolean handleColorCommand(Command command) {
if (!handleOnOffCommand(command)) {
return false;
- } else if (command instanceof HSBType) {
- HSBType color = (HSBType) command;
+ } else if (command instanceof HSBType color) {
if (channelConfiguration.hsCommandTopic != null) {
// If we don't have a brightness channel, something is probably busted
// but don't choke
String xyString = String.format("%f,%f", xy[0].doubleValue(), xy[1].doubleValue());
xyChannel.getState().publishValue(new StringType(xyString));
}
- } else if (command instanceof PercentType) {
+ } else if (command instanceof PercentType brightness) {
if (channelConfiguration.brightnessCommandTopic != null) {
brightnessChannel.getState().publishValue(command);
} else {
color = HSBType.WHITE;
}
HSBType existingColor = (HSBType) color;
- HSBType newCommand = new HSBType(existingColor.getHue(), existingColor.getSaturation(),
- (PercentType) command);
+ HSBType newCommand = new HSBType(existingColor.getHue(), existingColor.getSaturation(), brightness);
// re-process
handleColorCommand(newCommand);
}
public DeviceTrigger(ComponentFactory.ComponentConfiguration componentConfiguration) {
super(componentConfiguration, ChannelConfiguration.class);
- if (!channelConfiguration.automationType.equals("trigger")) {
+ if (!"trigger".equals(channelConfiguration.automationType)) {
throw new ConfigurationException("Component:DeviceTrigger must have automation_type 'trigger'");
}
if (channelConfiguration.type.isBlank()) {
rawChannel.getState().publishValue(new StringType(command));
}
+ @Override
protected boolean handleCommand(Command command) {
JSONState json = new JSONState();
if (command.getClass().equals(OnOffType.class)) {
@Override
public @Nullable T read(JsonReader in) throws IOException {
/* read the object using the default adapter, but translate the names in the reader */
- T result = delegate.read(MappingJsonReader.getDeviceMapper(in));
- return result;
+ return delegate.read(MappingJsonReader.getDeviceMapper(in));
}
@Override
try {
list = json.getAsJsonArray();
} catch (IllegalStateException e) {
- throw new JsonParseException("Cannot parse JSON array. Each connection must be defined as array with two "
- + "elements: connection_type, connection identifier. For example: \"connections\": [[\"mac\", "
- + "\"02:5b:26:a8:dc:12\"]]", e);
+ throw new JsonParseException("""
+ Cannot parse JSON array. Each connection must be defined as array with two \
+ elements: connection_type, connection identifier. For example: "connections": [["mac", \
+ "02:5b:26:a8:dc:12"]]\
+ """, e);
}
if (list.size() != 2) {
throw new JsonParseException("Connection information must be a tuple, but has " + list.size()
import java.io.IOException;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
import java.util.Objects;
in.nextNull();
return null;
case STRING:
- return Collections.singletonList(in.nextString());
+ return List.of(in.nextString());
case BEGIN_ARRAY:
return readList(in);
default:
import static org.hamcrest.core.IsIterableContaining.hasItem;
import java.util.Collection;
-import java.util.Collections;
+import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
assertThat(restore, is(subject));
- HandlerConfiguration haConfig = new HandlerConfiguration(subject.baseTopic,
- Collections.singletonList(subject.toShortTopic()));
+ HandlerConfiguration haConfig = new HandlerConfiguration(subject.baseTopic, List.of(subject.toShortTopic()));
Collection<HaID> restoreList = HaID.fromConfig(haConfig);
assertThat(restoreList, hasItem(new HaID("homeassistant/switch/name/config")));
assertThat(restore, is(subject));
- HandlerConfiguration haConfig = new HandlerConfiguration(subject.baseTopic,
- Collections.singletonList(subject.toShortTopic()));
+ HandlerConfiguration haConfig = new HandlerConfiguration(subject.baseTopic, List.of(subject.toShortTopic()));
Collection<HaID> restoreList = HaID.fromConfig(haConfig);
assertThat(restoreList, hasItem(new HaID("homeassistant/switch/node/name/config")));
public void testAlarmControlPanel() {
// @formatter:off
var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "{ " +
- " \"availability\": [ " +
- " { " +
- " \"topic\": \"zigbee2mqtt/bridge/state\" " +
- " } " +
- " ], " +
- " \"code\": \"12345\", " +
- " \"command_topic\": \"zigbee2mqtt/alarm/set/state\", " +
- " \"device\": { " +
- " \"identifiers\": [ " +
- " \"zigbee2mqtt_0x0000000000000000\" " +
- " ], " +
- " \"manufacturer\": \"BestAlarmEver\", " +
- " \"model\": \"Heavy duty super duper alarm\", " +
- " \"name\": \"Alarm\", " +
- " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " +
- " }, " +
- " \"name\": \"alarm\", " +
- " \"payload_arm_away\": \"ARM_AWAY_\", " +
- " \"payload_arm_home\": \"ARM_HOME_\", " +
- " \"payload_arm_night\": \"ARM_NIGHT_\", " +
- " \"payload_arm_custom_bypass\": \"ARM_CUSTOM_BYPASS_\", " +
- " \"payload_disarm\": \"DISARM_\", " +
- " \"state_topic\": \"zigbee2mqtt/alarm/state\" " +
- "} ");
+ """
+ { \
+ "availability": [ \
+ { \
+ "topic": "zigbee2mqtt/bridge/state" \
+ } \
+ ], \
+ "code": "12345", \
+ "command_topic": "zigbee2mqtt/alarm/set/state", \
+ "device": { \
+ "identifiers": [ \
+ "zigbee2mqtt_0x0000000000000000" \
+ ], \
+ "manufacturer": "BestAlarmEver", \
+ "model": "Heavy duty super duper alarm", \
+ "name": "Alarm", \
+ "sw_version": "Zigbee2MQTT 1.18.2" \
+ }, \
+ "name": "alarm", \
+ "payload_arm_away": "ARM_AWAY_", \
+ "payload_arm_home": "ARM_HOME_", \
+ "payload_arm_night": "ARM_NIGHT_", \
+ "payload_arm_custom_bypass": "ARM_CUSTOM_BYPASS_", \
+ "payload_disarm": "DISARM_", \
+ "state_topic": "zigbee2mqtt/alarm/state" \
+ } \
+ """);
// @formatter:on
assertThat(component.channels.size(), is(4));
public void test() throws InterruptedException {
// @formatter:off
var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "{ " +
- " \"availability\": [ " +
- " { " +
- " \"topic\": \"zigbee2mqtt/bridge/state\" " +
- " } " +
- " ], " +
- " \"device\": { " +
- " \"identifiers\": [ " +
- " \"zigbee2mqtt_0x0000000000000000\" " +
- " ], " +
- " \"manufacturer\": \"Sensors inc\", " +
- " \"model\": \"On Off Sensor\", " +
- " \"name\": \"OnOffSensor\", " +
- " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " +
- " }, " +
- " \"name\": \"onoffsensor\", " +
- " \"force_update\": \"true\", " +
- " \"payload_off\": \"OFF_\", " +
- " \"payload_on\": \"ON_\", " +
- " \"state_topic\": \"zigbee2mqtt/sensor/state\", " +
- " \"unique_id\": \"sn1\", " +
- " \"value_template\": \"{{ value_json.state }}\" " +
- "}");
+ """
+ { \
+ "availability": [ \
+ { \
+ "topic": "zigbee2mqtt/bridge/state" \
+ } \
+ ], \
+ "device": { \
+ "identifiers": [ \
+ "zigbee2mqtt_0x0000000000000000" \
+ ], \
+ "manufacturer": "Sensors inc", \
+ "model": "On Off Sensor", \
+ "name": "OnOffSensor", \
+ "sw_version": "Zigbee2MQTT 1.18.2" \
+ }, \
+ "name": "onoffsensor", \
+ "force_update": "true", \
+ "payload_off": "OFF_", \
+ "payload_on": "ON_", \
+ "state_topic": "zigbee2mqtt/sensor/state", \
+ "unique_id": "sn1", \
+ "value_template": "{{ value_json.state }}" \
+ }\
+ """);
// @formatter:on
assertThat(component.channels.size(), is(1));
public void offDelayTest() {
// @formatter:off
var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "{ " +
- " \"availability\": [ " +
- " { " +
- " \"topic\": \"zigbee2mqtt/bridge/state\" " +
- " } " +
- " ], " +
- " \"device\": { " +
- " \"identifiers\": [ " +
- " \"zigbee2mqtt_0x0000000000000000\" " +
- " ], " +
- " \"manufacturer\": \"Sensors inc\", " +
- " \"model\": \"On Off Sensor\", " +
- " \"name\": \"OnOffSensor\", " +
- " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " +
- " }, " +
- " \"name\": \"onoffsensor\", " +
- " \"force_update\": \"true\", " +
- " \"off_delay\": \"1\", " +
- " \"payload_off\": \"OFF_\", " +
- " \"payload_on\": \"ON_\", " +
- " \"state_topic\": \"zigbee2mqtt/sensor/state\", " +
- " \"unique_id\": \"sn1\", " +
- " \"value_template\": \"{{ value_json.state }}\" " +
- "}");
+ """
+ { \
+ "availability": [ \
+ { \
+ "topic": "zigbee2mqtt/bridge/state" \
+ } \
+ ], \
+ "device": { \
+ "identifiers": [ \
+ "zigbee2mqtt_0x0000000000000000" \
+ ], \
+ "manufacturer": "Sensors inc", \
+ "model": "On Off Sensor", \
+ "name": "OnOffSensor", \
+ "sw_version": "Zigbee2MQTT 1.18.2" \
+ }, \
+ "name": "onoffsensor", \
+ "force_update": "true", \
+ "off_delay": "1", \
+ "payload_off": "OFF_", \
+ "payload_on": "ON_", \
+ "state_topic": "zigbee2mqtt/sensor/state", \
+ "unique_id": "sn1", \
+ "value_template": "{{ value_json.state }}" \
+ }\
+ """);
// @formatter:on
publishMessage("zigbee2mqtt/sensor/state", "{ \"state\": \"ON_\" }");
public void expireAfterTest() {
// @formatter:off
var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "{ " +
- " \"availability\": [ " +
- " { " +
- " \"topic\": \"zigbee2mqtt/bridge/state\" " +
- " } " +
- " ], " +
- " \"device\": { " +
- " \"identifiers\": [ " +
- " \"zigbee2mqtt_0x0000000000000000\" " +
- " ], " +
- " \"manufacturer\": \"Sensors inc\", " +
- " \"model\": \"On Off Sensor\", " +
- " \"name\": \"OnOffSensor\", " +
- " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " +
- " }, " +
- " \"name\": \"onoffsensor\", " +
- " \"expire_after\": \"1\", " +
- " \"force_update\": \"true\", " +
- " \"payload_off\": \"OFF_\", " +
- " \"payload_on\": \"ON_\", " +
- " \"state_topic\": \"zigbee2mqtt/sensor/state\", " +
- " \"unique_id\": \"sn1\", " +
- " \"value_template\": \"{{ value_json.state }}\" " +
- "}");
+ """
+ { \
+ "availability": [ \
+ { \
+ "topic": "zigbee2mqtt/bridge/state" \
+ } \
+ ], \
+ "device": { \
+ "identifiers": [ \
+ "zigbee2mqtt_0x0000000000000000" \
+ ], \
+ "manufacturer": "Sensors inc", \
+ "model": "On Off Sensor", \
+ "name": "OnOffSensor", \
+ "sw_version": "Zigbee2MQTT 1.18.2" \
+ }, \
+ "name": "onoffsensor", \
+ "expire_after": "1", \
+ "force_update": "true", \
+ "payload_off": "OFF_", \
+ "payload_on": "ON_", \
+ "state_topic": "zigbee2mqtt/sensor/state", \
+ "unique_id": "sn1", \
+ "value_template": "{{ value_json.state }}" \
+ }\
+ """);
// @formatter:on
publishMessage("zigbee2mqtt/sensor/state", "{ \"state\": \"OFF_\" }");
public void test() throws InterruptedException {
// @formatter:off
var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "{ " +
- " \"availability\": [ " +
- " { " +
- " \"topic\": \"zigbee2mqtt/bridge/state\" " +
- " } " +
- " ], " +
- " \"device\": { " +
- " \"identifiers\": [ " +
- " \"zigbee2mqtt_0x0000000000000000\" " +
- " ], " +
- " \"manufacturer\": \"Cameras inc\", " +
- " \"model\": \"Camera\", " +
- " \"name\": \"camera\", " +
- " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " +
- " }, " +
- " \"name\": \"cam1\", " +
- " \"topic\": \"zigbee2mqtt/cam1/state\"" +
- "}");
+ """
+ { \
+ "availability": [ \
+ { \
+ "topic": "zigbee2mqtt/bridge/state" \
+ } \
+ ], \
+ "device": { \
+ "identifiers": [ \
+ "zigbee2mqtt_0x0000000000000000" \
+ ], \
+ "manufacturer": "Cameras inc", \
+ "model": "Camera", \
+ "name": "camera", \
+ "sw_version": "Zigbee2MQTT 1.18.2" \
+ }, \
+ "name": "cam1", \
+ "topic": "zigbee2mqtt/cam1/state"\
+ }\
+ """);
// @formatter:on
assertThat(component.channels.size(), is(1));
@SuppressWarnings("null")
@Test
public void testTS0601Climate() {
- var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), "{"
- + " \"action_template\": \"{% set values = {'idle':'off','heat':'heating','cool':'cooling','fan only':'fan'} %}{{ values[value_json.running_state] }}\","
- + " \"action_topic\": \"zigbee2mqtt/th1\", \"availability\": [ {"
- + " \"topic\": \"zigbee2mqtt/bridge/state\" } ],"
- + " \"away_mode_command_topic\": \"zigbee2mqtt/th1/set/away_mode\","
- + " \"away_mode_state_template\": \"{{ value_json.away_mode }}\","
- + " \"away_mode_state_topic\": \"zigbee2mqtt/th1\","
- + " \"current_temperature_template\": \"{{ value_json.local_temperature }}\","
- + " \"current_temperature_topic\": \"zigbee2mqtt/th1\", \"device\": {"
- + " \"identifiers\": [ \"zigbee2mqtt_0x847127fffe11dd6a\" ], \"manufacturer\": \"TuYa\","
- + " \"model\": \"Radiator valve with thermostat (TS0601_thermostat)\","
- + " \"name\": \"th1\", \"sw_version\": \"Zigbee2MQTT 1.18.2\" },"
- + " \"hold_command_topic\": \"zigbee2mqtt/th1/set/preset\", \"hold_modes\": ["
- + " \"schedule\", \"manual\", \"boost\", \"complex\", \"comfort\", \"eco\" ],"
- + " \"hold_state_template\": \"{{ value_json.preset }}\","
- + " \"hold_state_topic\": \"zigbee2mqtt/th1\","
- + " \"json_attributes_topic\": \"zigbee2mqtt/th1\", \"max_temp\": \"35\","
- + " \"min_temp\": \"5\", \"mode_command_topic\": \"zigbee2mqtt/th1/set/system_mode\","
- + " \"mode_state_template\": \"{{ value_json.system_mode }}\","
- + " \"mode_state_topic\": \"zigbee2mqtt/th1\", \"modes\": [ \"heat\","
- + " \"auto\", \"off\" ], \"name\": \"th1\", \"temp_step\": 0.5,"
- + " \"temperature_command_topic\": \"zigbee2mqtt/th1/set/current_heating_setpoint\","
- + " \"temperature_state_template\": \"{{ value_json.current_heating_setpoint }}\","
- + " \"temperature_state_topic\": \"zigbee2mqtt/th1\", \"temperature_unit\": \"C\","
- + " \"unique_id\": \"0x847127fffe11dd6a_climate_zigbee2mqtt\"}");
+ var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
+ """
+ {\
+ "action_template": "{% set values = {'idle':'off','heat':'heating','cool':'cooling','fan only':'fan'} %}{{ values[value_json.running_state] }}",\
+ "action_topic": "zigbee2mqtt/th1", "availability": [ {\
+ "topic": "zigbee2mqtt/bridge/state" } ],\
+ "away_mode_command_topic": "zigbee2mqtt/th1/set/away_mode",\
+ "away_mode_state_template": "{{ value_json.away_mode }}",\
+ "away_mode_state_topic": "zigbee2mqtt/th1",\
+ "current_temperature_template": "{{ value_json.local_temperature }}",\
+ "current_temperature_topic": "zigbee2mqtt/th1", "device": {\
+ "identifiers": [ "zigbee2mqtt_0x847127fffe11dd6a" ], "manufacturer": "TuYa",\
+ "model": "Radiator valve with thermostat (TS0601_thermostat)",\
+ "name": "th1", "sw_version": "Zigbee2MQTT 1.18.2" },\
+ "hold_command_topic": "zigbee2mqtt/th1/set/preset", "hold_modes": [\
+ "schedule", "manual", "boost", "complex", "comfort", "eco" ],\
+ "hold_state_template": "{{ value_json.preset }}",\
+ "hold_state_topic": "zigbee2mqtt/th1",\
+ "json_attributes_topic": "zigbee2mqtt/th1", "max_temp": "35",\
+ "min_temp": "5", "mode_command_topic": "zigbee2mqtt/th1/set/system_mode",\
+ "mode_state_template": "{{ value_json.system_mode }}",\
+ "mode_state_topic": "zigbee2mqtt/th1", "modes": [ "heat",\
+ "auto", "off" ], "name": "th1", "temp_step": 0.5,\
+ "temperature_command_topic": "zigbee2mqtt/th1/set/current_heating_setpoint",\
+ "temperature_state_template": "{{ value_json.current_heating_setpoint }}",\
+ "temperature_state_topic": "zigbee2mqtt/th1", "temperature_unit": "C",\
+ "unique_id": "0x847127fffe11dd6a_climate_zigbee2mqtt"}\
+ """);
assertThat(component.channels.size(), is(6));
assertThat(component.getName(), is("th1"));
assertChannel(component, Climate.TEMPERATURE_CH_ID, "zigbee2mqtt/th1",
"zigbee2mqtt/th1/set/current_heating_setpoint", "th1", NumberValue.class);
- publishMessage("zigbee2mqtt/th1",
- "{\"running_state\": \"idle\", \"away_mode\": \"ON\", "
- + "\"local_temperature\": \"22.2\", \"preset\": \"schedule\", \"system_mode\": \"heat\", "
- + "\"current_heating_setpoint\": \"24\"}");
+ publishMessage("zigbee2mqtt/th1", """
+ {"running_state": "idle", "away_mode": "ON", \
+ "local_temperature": "22.2", "preset": "schedule", "system_mode": "heat", \
+ "current_heating_setpoint": "24"}\
+ """);
assertState(component, Climate.ACTION_CH_ID, new StringType("off"));
assertState(component, Climate.AWAY_MODE_CH_ID, OnOffType.ON);
assertState(component, Climate.CURRENT_TEMPERATURE_CH_ID, new QuantityType<>(22.2, SIUnits.CELSIUS));
@SuppressWarnings("null")
@Test
public void testTS0601ClimateNotSendIfOff() {
- var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), "{"
- + " \"action_template\": \"{% set values = {'idle':'off','heat':'heating','cool':'cooling','fan only':'fan'} %}{{ values[value_json.running_state] }}\","
- + " \"action_topic\": \"zigbee2mqtt/th1\", \"availability\": [ {"
- + " \"topic\": \"zigbee2mqtt/bridge/state\" } ],"
- + " \"away_mode_command_topic\": \"zigbee2mqtt/th1/set/away_mode\","
- + " \"away_mode_state_template\": \"{{ value_json.away_mode }}\","
- + " \"away_mode_state_topic\": \"zigbee2mqtt/th1\","
- + " \"current_temperature_template\": \"{{ value_json.local_temperature }}\","
- + " \"current_temperature_topic\": \"zigbee2mqtt/th1\", \"device\": {"
- + " \"identifiers\": [ \"zigbee2mqtt_0x847127fffe11dd6a\" ], \"manufacturer\": \"TuYa\","
- + " \"model\": \"Radiator valve with thermostat (TS0601_thermostat)\","
- + " \"name\": \"th1\", \"sw_version\": \"Zigbee2MQTT 1.18.2\" },"
- + " \"hold_command_topic\": \"zigbee2mqtt/th1/set/preset\", \"hold_modes\": ["
- + " \"schedule\", \"manual\", \"boost\", \"complex\", \"comfort\", \"eco\" ],"
- + " \"hold_state_template\": \"{{ value_json.preset }}\","
- + " \"hold_state_topic\": \"zigbee2mqtt/th1\","
- + " \"json_attributes_topic\": \"zigbee2mqtt/th1\", \"max_temp\": \"35\","
- + " \"min_temp\": \"5\", \"mode_command_topic\": \"zigbee2mqtt/th1/set/system_mode\","
- + " \"mode_state_template\": \"{{ value_json.system_mode }}\","
- + " \"mode_state_topic\": \"zigbee2mqtt/th1\", \"modes\": [ \"heat\","
- + " \"auto\", \"off\" ], \"name\": \"th1\", \"temp_step\": 0.5,"
- + " \"temperature_command_topic\": \"zigbee2mqtt/th1/set/current_heating_setpoint\","
- + " \"temperature_state_template\": \"{{ value_json.current_heating_setpoint }}\","
- + " \"temperature_state_topic\": \"zigbee2mqtt/th1\", \"temperature_unit\": \"C\","
- + " \"power_command_topic\": \"zigbee2mqtt/th1/power\","
- + " \"unique_id\": \"0x847127fffe11dd6a_climate_zigbee2mqtt\", \"send_if_off\": \"false\"}");
+ var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
+ """
+ {\
+ "action_template": "{% set values = {'idle':'off','heat':'heating','cool':'cooling','fan only':'fan'} %}{{ values[value_json.running_state] }}",\
+ "action_topic": "zigbee2mqtt/th1", "availability": [ {\
+ "topic": "zigbee2mqtt/bridge/state" } ],\
+ "away_mode_command_topic": "zigbee2mqtt/th1/set/away_mode",\
+ "away_mode_state_template": "{{ value_json.away_mode }}",\
+ "away_mode_state_topic": "zigbee2mqtt/th1",\
+ "current_temperature_template": "{{ value_json.local_temperature }}",\
+ "current_temperature_topic": "zigbee2mqtt/th1", "device": {\
+ "identifiers": [ "zigbee2mqtt_0x847127fffe11dd6a" ], "manufacturer": "TuYa",\
+ "model": "Radiator valve with thermostat (TS0601_thermostat)",\
+ "name": "th1", "sw_version": "Zigbee2MQTT 1.18.2" },\
+ "hold_command_topic": "zigbee2mqtt/th1/set/preset", "hold_modes": [\
+ "schedule", "manual", "boost", "complex", "comfort", "eco" ],\
+ "hold_state_template": "{{ value_json.preset }}",\
+ "hold_state_topic": "zigbee2mqtt/th1",\
+ "json_attributes_topic": "zigbee2mqtt/th1", "max_temp": "35",\
+ "min_temp": "5", "mode_command_topic": "zigbee2mqtt/th1/set/system_mode",\
+ "mode_state_template": "{{ value_json.system_mode }}",\
+ "mode_state_topic": "zigbee2mqtt/th1", "modes": [ "heat",\
+ "auto", "off" ], "name": "th1", "temp_step": 0.5,\
+ "temperature_command_topic": "zigbee2mqtt/th1/set/current_heating_setpoint",\
+ "temperature_state_template": "{{ value_json.current_heating_setpoint }}",\
+ "temperature_state_topic": "zigbee2mqtt/th1", "temperature_unit": "C",\
+ "power_command_topic": "zigbee2mqtt/th1/power",\
+ "unique_id": "0x847127fffe11dd6a_climate_zigbee2mqtt", "send_if_off": "false"}\
+ """);
assertThat(component.channels.size(), is(7));
assertThat(component.getName(), is("th1"));
assertChannel(component, Climate.TEMPERATURE_CH_ID, "zigbee2mqtt/th1",
"zigbee2mqtt/th1/set/current_heating_setpoint", "th1", NumberValue.class);
- publishMessage("zigbee2mqtt/th1",
- "{\"running_state\": \"idle\", \"away_mode\": \"ON\", "
- + "\"local_temperature\": \"22.2\", \"preset\": \"schedule\", \"system_mode\": \"heat\", "
- + "\"current_heating_setpoint\": \"24\"}");
+ publishMessage("zigbee2mqtt/th1", """
+ {"running_state": "idle", "away_mode": "ON", \
+ "local_temperature": "22.2", "preset": "schedule", "system_mode": "heat", \
+ "current_heating_setpoint": "24"}\
+ """);
assertState(component, Climate.ACTION_CH_ID, new StringType("off"));
assertState(component, Climate.AWAY_MODE_CH_ID, OnOffType.ON);
assertState(component, Climate.CURRENT_TEMPERATURE_CH_ID, new QuantityType<>(22.2, SIUnits.CELSIUS));
assertPublished("zigbee2mqtt/th1/power", "ON");
// Enabled
- publishMessage("zigbee2mqtt/th1",
- "{\"running_state\": \"heat\", \"away_mode\": \"ON\", "
- + "\"local_temperature\": \"22.2\", \"preset\": \"schedule\", \"system_mode\": \"heat\", "
- + "\"current_heating_setpoint\": \"24\"}");
+ publishMessage("zigbee2mqtt/th1", """
+ {"running_state": "heat", "away_mode": "ON", \
+ "local_temperature": "22.2", "preset": "schedule", "system_mode": "heat", \
+ "current_heating_setpoint": "24"}\
+ """);
// Climate is in ON state
component.getChannel(Climate.AWAY_MODE_CH_ID).getState().publishValue(OnOffType.OFF);
@SuppressWarnings("null")
@Test
public void testClimate() {
- var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "{\"action_template\": \"{{ value_json.action }}\", \"action_topic\": \"zigbee2mqtt/th1\","
- + " \"aux_command_topic\": \"zigbee2mqtt/th1/aux\","
- + " \"aux_state_template\": \"{{ value_json.aux }}\", \"aux_state_topic\": \"zigbee2mqtt/th1\","
- + " \"away_mode_command_topic\": \"zigbee2mqtt/th1/away_mode\","
- + " \"away_mode_state_template\": \"{{ value_json.away_mode }}\","
- + " \"away_mode_state_topic\": \"zigbee2mqtt/th1\","
- + " \"current_temperature_template\": \"{{ value_json.current_temperature }}\","
- + " \"current_temperature_topic\": \"zigbee2mqtt/th1\","
- + " \"fan_mode_command_template\": \"fan_mode={{ value }}\","
- + " \"fan_mode_command_topic\": \"zigbee2mqtt/th1/fan_mode\","
- + " \"fan_mode_state_template\": \"{{ value_json.fan_mode }}\","
- + " \"fan_mode_state_topic\": \"zigbee2mqtt/th1\", \"fan_modes\": [ \"p1\","
- + " \"p2\" ], \"hold_command_template\": \"hold={{ value }}\","
- + " \"hold_command_topic\": \"zigbee2mqtt/th1/hold\","
- + " \"hold_state_template\": \"{{ value_json.hold }}\","
- + " \"hold_state_topic\": \"zigbee2mqtt/th1\", \"hold_modes\": [ \"u1\", \"u2\","
- + " \"u3\" ], \"json_attributes_template\": \"{{ value_json.attrs }}\","
- + " \"json_attributes_topic\": \"zigbee2mqtt/th1\","
- + " \"mode_command_template\": \"mode={{ value }}\","
- + " \"mode_command_topic\": \"zigbee2mqtt/th1/mode\","
- + " \"mode_state_template\": \"{{ value_json.mode }}\","
- + " \"mode_state_topic\": \"zigbee2mqtt/th1\", \"modes\": [ \"B1\", \"B2\""
- + " ], \"swing_command_template\": \"swing={{ value }}\","
- + " \"swing_command_topic\": \"zigbee2mqtt/th1/swing\","
- + " \"swing_state_template\": \"{{ value_json.swing }}\","
- + " \"swing_state_topic\": \"zigbee2mqtt/th1\", \"swing_modes\": [ \"G1\","
- + " \"G2\" ], \"temperature_command_template\": \"temperature={{ value }}\","
- + " \"temperature_command_topic\": \"zigbee2mqtt/th1/temperature\","
- + " \"temperature_state_template\": \"{{ value_json.temperature }}\","
- + " \"temperature_state_topic\": \"zigbee2mqtt/th1\","
- + " \"temperature_high_command_template\": \"temperature_high={{ value }}\","
- + " \"temperature_high_command_topic\": \"zigbee2mqtt/th1/temperature_high\","
- + " \"temperature_high_state_template\": \"{{ value_json.temperature_high }}\","
- + " \"temperature_high_state_topic\": \"zigbee2mqtt/th1\","
- + " \"temperature_low_command_template\": \"temperature_low={{ value }}\","
- + " \"temperature_low_command_topic\": \"zigbee2mqtt/th1/temperature_low\","
- + " \"temperature_low_state_template\": \"{{ value_json.temperature_low }}\","
- + " \"temperature_low_state_topic\": \"zigbee2mqtt/th1\","
- + " \"power_command_topic\": \"zigbee2mqtt/th1/power\", \"initial\": \"10\","
- + " \"max_temp\": \"40\", \"min_temp\": \"0\", \"temperature_unit\": \"F\","
- + " \"temp_step\": \"1\", \"precision\": \"0.5\", \"send_if_off\": \"false\" }");
+ var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), """
+ {"action_template": "{{ value_json.action }}", "action_topic": "zigbee2mqtt/th1",\
+ "aux_command_topic": "zigbee2mqtt/th1/aux",\
+ "aux_state_template": "{{ value_json.aux }}", "aux_state_topic": "zigbee2mqtt/th1",\
+ "away_mode_command_topic": "zigbee2mqtt/th1/away_mode",\
+ "away_mode_state_template": "{{ value_json.away_mode }}",\
+ "away_mode_state_topic": "zigbee2mqtt/th1",\
+ "current_temperature_template": "{{ value_json.current_temperature }}",\
+ "current_temperature_topic": "zigbee2mqtt/th1",\
+ "fan_mode_command_template": "fan_mode={{ value }}",\
+ "fan_mode_command_topic": "zigbee2mqtt/th1/fan_mode",\
+ "fan_mode_state_template": "{{ value_json.fan_mode }}",\
+ "fan_mode_state_topic": "zigbee2mqtt/th1", "fan_modes": [ "p1",\
+ "p2" ], "hold_command_template": "hold={{ value }}",\
+ "hold_command_topic": "zigbee2mqtt/th1/hold",\
+ "hold_state_template": "{{ value_json.hold }}",\
+ "hold_state_topic": "zigbee2mqtt/th1", "hold_modes": [ "u1", "u2",\
+ "u3" ], "json_attributes_template": "{{ value_json.attrs }}",\
+ "json_attributes_topic": "zigbee2mqtt/th1",\
+ "mode_command_template": "mode={{ value }}",\
+ "mode_command_topic": "zigbee2mqtt/th1/mode",\
+ "mode_state_template": "{{ value_json.mode }}",\
+ "mode_state_topic": "zigbee2mqtt/th1", "modes": [ "B1", "B2"\
+ ], "swing_command_template": "swing={{ value }}",\
+ "swing_command_topic": "zigbee2mqtt/th1/swing",\
+ "swing_state_template": "{{ value_json.swing }}",\
+ "swing_state_topic": "zigbee2mqtt/th1", "swing_modes": [ "G1",\
+ "G2" ], "temperature_command_template": "temperature={{ value }}",\
+ "temperature_command_topic": "zigbee2mqtt/th1/temperature",\
+ "temperature_state_template": "{{ value_json.temperature }}",\
+ "temperature_state_topic": "zigbee2mqtt/th1",\
+ "temperature_high_command_template": "temperature_high={{ value }}",\
+ "temperature_high_command_topic": "zigbee2mqtt/th1/temperature_high",\
+ "temperature_high_state_template": "{{ value_json.temperature_high }}",\
+ "temperature_high_state_topic": "zigbee2mqtt/th1",\
+ "temperature_low_command_template": "temperature_low={{ value }}",\
+ "temperature_low_command_topic": "zigbee2mqtt/th1/temperature_low",\
+ "temperature_low_state_template": "{{ value_json.temperature_low }}",\
+ "temperature_low_state_topic": "zigbee2mqtt/th1",\
+ "power_command_topic": "zigbee2mqtt/th1/power", "initial": "10",\
+ "max_temp": "40", "min_temp": "0", "temperature_unit": "F",\
+ "temp_step": "1", "precision": "0.5", "send_if_off": "false" }\
+ """);
assertThat(component.channels.size(), is(12));
assertThat(component.getName(), is("MQTT HVAC"));
"MQTT HVAC", NumberValue.class);
assertChannel(component, Climate.POWER_CH_ID, "", "zigbee2mqtt/th1/power", "MQTT HVAC", OnOffValue.class);
- publishMessage("zigbee2mqtt/th1",
- "{ \"action\": \"fan\", \"aux\": \"ON\", \"away_mode\": \"OFF\", "
- + "\"current_temperature\": \"35.5\", \"fan_mode\": \"p2\", \"hold\": \"u2\", "
- + "\"mode\": \"B1\", \"swing\": \"G1\", \"temperature\": \"30\", "
- + "\"temperature_high\": \"37\", \"temperature_low\": \"20\" }");
+ publishMessage("zigbee2mqtt/th1", """
+ { "action": "fan", "aux": "ON", "away_mode": "OFF", \
+ "current_temperature": "35.5", "fan_mode": "p2", "hold": "u2", \
+ "mode": "B1", "swing": "G1", "temperature": "30", \
+ "temperature_high": "37", "temperature_low": "20" }\
+ """);
assertState(component, Climate.ACTION_CH_ID, new StringType("fan"));
assertState(component, Climate.AUX_CH_ID, OnOffType.ON);
public void test() throws InterruptedException {
// @formatter:off
var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "{ " +
- " \"availability\": [ " +
- " { " +
- " \"topic\": \"zigbee2mqtt/bridge/state\" " +
- " } " +
- " ], " +
- " \"device\": { " +
- " \"identifiers\": [ " +
- " \"zigbee2mqtt_0x0000000000000000\" " +
- " ], " +
- " \"manufacturer\": \"Covers inc\", " +
- " \"model\": \"cover v1\", " +
- " \"name\": \"Cover\", " +
- " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " +
- " }, " +
- " \"name\": \"cover\", " +
- " \"payload_open\": \"OPEN_\", " +
- " \"payload_close\": \"CLOSE_\", " +
- " \"payload_stop\": \"STOP_\", " +
- " \"state_topic\": \"zigbee2mqtt/cover/state\", " +
- " \"command_topic\": \"zigbee2mqtt/cover/set/state\" " +
- "}");
+ """
+ { \
+ "availability": [ \
+ { \
+ "topic": "zigbee2mqtt/bridge/state" \
+ } \
+ ], \
+ "device": { \
+ "identifiers": [ \
+ "zigbee2mqtt_0x0000000000000000" \
+ ], \
+ "manufacturer": "Covers inc", \
+ "model": "cover v1", \
+ "name": "Cover", \
+ "sw_version": "Zigbee2MQTT 1.18.2" \
+ }, \
+ "name": "cover", \
+ "payload_open": "OPEN_", \
+ "payload_close": "CLOSE_", \
+ "payload_stop": "STOP_", \
+ "state_topic": "zigbee2mqtt/cover/state", \
+ "command_topic": "zigbee2mqtt/cover/set/state" \
+ }\
+ """);
// @formatter:on
assertThat(component.channels.size(), is(1));
public void testRgb() throws InterruptedException {
// @formatter:off
var component = (Light) discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "{ " +
- " \"availability\": [ " +
- " { " +
- " \"topic\": \"zigbee2mqtt/bridge/state\" " +
- " } " +
- " ], " +
- " \"device\": { " +
- " \"identifiers\": [ " +
- " \"zigbee2mqtt_0x0000000000000000\" " +
- " ], " +
- " \"manufacturer\": \"Lights inc\", " +
- " \"model\": \"light v1\", " +
- " \"name\": \"Light\", " +
- " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " +
- " }, " +
- " \"name\": \"light\", " +
- " \"state_topic\": \"zigbee2mqtt/light/state\", " +
- " \"command_topic\": \"zigbee2mqtt/light/set/state\", " +
- " \"state_value_template\": \"{{ value_json.power }}\", " +
- " \"payload_on\": \"ON_\", " +
- " \"payload_off\": \"OFF_\", " +
- " \"rgb_state_topic\": \"zigbee2mqtt/light/rgb\", " +
- " \"rgb_command_topic\": \"zigbee2mqtt/light/set/rgb\", " +
- " \"rgb_value_template\": \"{{ value_json.rgb }}\", " +
- " \"brightness_state_topic\": \"zigbee2mqtt/light/brightness\", " +
- " \"brightness_command_topic\": \"zigbee2mqtt/light/set/brightness\", " +
- " \"brightness_value_template\": \"{{ value_json.br }}\" " +
- "}");
+ """
+ { \
+ "availability": [ \
+ { \
+ "topic": "zigbee2mqtt/bridge/state" \
+ } \
+ ], \
+ "device": { \
+ "identifiers": [ \
+ "zigbee2mqtt_0x0000000000000000" \
+ ], \
+ "manufacturer": "Lights inc", \
+ "model": "light v1", \
+ "name": "Light", \
+ "sw_version": "Zigbee2MQTT 1.18.2" \
+ }, \
+ "name": "light", \
+ "state_topic": "zigbee2mqtt/light/state", \
+ "command_topic": "zigbee2mqtt/light/set/state", \
+ "state_value_template": "{{ value_json.power }}", \
+ "payload_on": "ON_", \
+ "payload_off": "OFF_", \
+ "rgb_state_topic": "zigbee2mqtt/light/rgb", \
+ "rgb_command_topic": "zigbee2mqtt/light/set/rgb", \
+ "rgb_value_template": "{{ value_json.rgb }}", \
+ "brightness_state_topic": "zigbee2mqtt/light/brightness", \
+ "brightness_command_topic": "zigbee2mqtt/light/set/brightness", \
+ "brightness_value_template": "{{ value_json.br }}" \
+ }\
+ """);
// @formatter:on
assertThat(component.channels.size(), is(1));
public void testRgbWithoutBrightness() throws InterruptedException {
// @formatter:off
var component = (Light) discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "{ " +
- " \"name\": \"light\", " +
- " \"state_topic\": \"zigbee2mqtt/light/state\", " +
- " \"command_topic\": \"zigbee2mqtt/light/set/state\", " +
- " \"state_value_template\": \"{{ value_json.power }}\", " +
- " \"payload_on\": \"ON_\", " +
- " \"payload_off\": \"OFF_\", " +
- " \"rgb_state_topic\": \"zigbee2mqtt/light/rgb\", " +
- " \"rgb_command_topic\": \"zigbee2mqtt/light/set/rgb\", " +
- " \"rgb_value_template\": \"{{ value_json.rgb }}\"" +
- "}");
+ """
+ { \
+ "name": "light", \
+ "state_topic": "zigbee2mqtt/light/state", \
+ "command_topic": "zigbee2mqtt/light/set/state", \
+ "state_value_template": "{{ value_json.power }}", \
+ "payload_on": "ON_", \
+ "payload_off": "OFF_", \
+ "rgb_state_topic": "zigbee2mqtt/light/rgb", \
+ "rgb_command_topic": "zigbee2mqtt/light/set/rgb", \
+ "rgb_value_template": "{{ value_json.rgb }}"\
+ }\
+ """);
// @formatter:on
publishMessage("zigbee2mqtt/light/rgb", "{\"rgb\": \"255,255,255\"}");
public void testHsb() throws InterruptedException {
// @formatter:off
var component = (Light) discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "{ " +
- " \"name\": \"light\", " +
- " \"state_topic\": \"zigbee2mqtt/light/state\", " +
- " \"command_topic\": \"zigbee2mqtt/light/set/state\", " +
- " \"state_value_template\": \"{{ value_json.power }}\", " +
- " \"payload_on\": \"ON_\", " +
- " \"payload_off\": \"OFF_\", " +
- " \"hs_state_topic\": \"zigbee2mqtt/light/hs\", " +
- " \"hs_command_topic\": \"zigbee2mqtt/light/set/hs\", " +
- " \"hs_value_template\": \"{{ value_json.hs }}\", " +
- " \"brightness_state_topic\": \"zigbee2mqtt/light/brightness\", " +
- " \"brightness_command_topic\": \"zigbee2mqtt/light/set/brightness\", " +
- " \"brightness_value_template\": \"{{ value_json.br }}\" " +
- "}");
+ """
+ { \
+ "name": "light", \
+ "state_topic": "zigbee2mqtt/light/state", \
+ "command_topic": "zigbee2mqtt/light/set/state", \
+ "state_value_template": "{{ value_json.power }}", \
+ "payload_on": "ON_", \
+ "payload_off": "OFF_", \
+ "hs_state_topic": "zigbee2mqtt/light/hs", \
+ "hs_command_topic": "zigbee2mqtt/light/set/hs", \
+ "hs_value_template": "{{ value_json.hs }}", \
+ "brightness_state_topic": "zigbee2mqtt/light/brightness", \
+ "brightness_command_topic": "zigbee2mqtt/light/set/brightness", \
+ "brightness_value_template": "{{ value_json.br }}" \
+ }\
+ """);
// @formatter:on
assertThat(component.channels.size(), is(1));
public void testBrightnessAndOnOff() throws InterruptedException {
// @formatter:off
var component = (Light) discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "{ " +
- " \"name\": \"light\", " +
- " \"state_topic\": \"zigbee2mqtt/light/state\", " +
- " \"command_topic\": \"zigbee2mqtt/light/set/state\", " +
- " \"state_value_template\": \"{{ value_json.power }}\", " +
- " \"brightness_state_topic\": \"zigbee2mqtt/light/brightness\", " +
- " \"brightness_command_topic\": \"zigbee2mqtt/light/set/brightness\", " +
- " \"payload_on\": \"ON_\", " +
- " \"payload_off\": \"OFF_\" " +
- "}");
+ """
+ { \
+ "name": "light", \
+ "state_topic": "zigbee2mqtt/light/state", \
+ "command_topic": "zigbee2mqtt/light/set/state", \
+ "state_value_template": "{{ value_json.power }}", \
+ "brightness_state_topic": "zigbee2mqtt/light/brightness", \
+ "brightness_command_topic": "zigbee2mqtt/light/set/brightness", \
+ "payload_on": "ON_", \
+ "payload_off": "OFF_" \
+ }\
+ """);
// @formatter:on
assertThat(component.channels.size(), is(1));
public void testOnOffOnly() throws InterruptedException {
// @formatter:off
var component = (Light) discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "{ " +
- " \"name\": \"light\", " +
- " \"state_topic\": \"zigbee2mqtt/light/state\", " +
- " \"command_topic\": \"zigbee2mqtt/light/set/state\", " +
- " \"state_value_template\": \"{{ value_json.power }}\", " +
- " \"payload_on\": \"ON_\", " +
- " \"payload_off\": \"OFF_\" " +
- "}");
+ """
+ { \
+ "name": "light", \
+ "state_topic": "zigbee2mqtt/light/state", \
+ "command_topic": "zigbee2mqtt/light/set/state", \
+ "state_value_template": "{{ value_json.power }}", \
+ "payload_on": "ON_", \
+ "payload_off": "OFF_" \
+ }\
+ """);
// @formatter:on
assertThat(component.channels.size(), is(1));
public void test() throws InterruptedException {
// @formatter:off
var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "{ " +
- " \"availability\": [ " +
- " { " +
- " \"topic\": \"zigbee2mqtt/bridge/state\" " +
- " } " +
- " ], " +
- " \"device\": { " +
- " \"identifiers\": [ " +
- " \"zigbee2mqtt_0x0000000000000000\" " +
- " ], " +
- " \"manufacturer\": \"Fans inc\", " +
- " \"model\": \"Fan\", " +
- " \"name\": \"FanBlower\", " +
- " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " +
- " }, " +
- " \"name\": \"fan\", " +
- " \"payload_off\": \"OFF_\", " +
- " \"payload_on\": \"ON_\", " +
- " \"state_topic\": \"zigbee2mqtt/fan/state\", " +
- " \"command_topic\": \"zigbee2mqtt/fan/set/state\" " +
- "}");
+ """
+ { \
+ "availability": [ \
+ { \
+ "topic": "zigbee2mqtt/bridge/state" \
+ } \
+ ], \
+ "device": { \
+ "identifiers": [ \
+ "zigbee2mqtt_0x0000000000000000" \
+ ], \
+ "manufacturer": "Fans inc", \
+ "model": "Fan", \
+ "name": "FanBlower", \
+ "sw_version": "Zigbee2MQTT 1.18.2" \
+ }, \
+ "name": "fan", \
+ "payload_off": "OFF_", \
+ "payload_on": "ON_", \
+ "state_topic": "zigbee2mqtt/fan/state", \
+ "command_topic": "zigbee2mqtt/fan/set/state" \
+ }\
+ """);
// @formatter:on
assertThat(component.channels.size(), is(1));
public void testRgb() throws InterruptedException {
// @formatter:off
var component = (Light) discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "{ " +
- " \"availability\": [ " +
- " { " +
- " \"topic\": \"zigbee2mqtt/bridge/state\" " +
- " } " +
- " ], " +
- " \"device\": { " +
- " \"identifiers\": [ " +
- " \"zigbee2mqtt_0x0000000000000000\" " +
- " ], " +
- " \"manufacturer\": \"Lights inc\", " +
- " \"model\": \"light v1\", " +
- " \"name\": \"Light\", " +
- " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " +
- " }, " +
- " \"name\": \"light\", " +
- " \"schema\": \"json\", " +
- " \"state_topic\": \"zigbee2mqtt/light/state\", " +
- " \"command_topic\": \"zigbee2mqtt/light/set/state\", " +
- " \"brightness\": true, " +
- " \"color_mode\": true, " +
- " \"supported_color_modes\": [\"onoff\", \"brightness\", \"rgb\"]" +
- "}");
+ """
+ { \
+ "availability": [ \
+ { \
+ "topic": "zigbee2mqtt/bridge/state" \
+ } \
+ ], \
+ "device": { \
+ "identifiers": [ \
+ "zigbee2mqtt_0x0000000000000000" \
+ ], \
+ "manufacturer": "Lights inc", \
+ "model": "light v1", \
+ "name": "Light", \
+ "sw_version": "Zigbee2MQTT 1.18.2" \
+ }, \
+ "name": "light", \
+ "schema": "json", \
+ "state_topic": "zigbee2mqtt/light/state", \
+ "command_topic": "zigbee2mqtt/light/set/state", \
+ "brightness": true, \
+ "color_mode": true, \
+ "supported_color_modes": ["onoff", "brightness", "rgb"]\
+ }\
+ """);
// @formatter:on
assertThat(component.channels.size(), is(1));
public void testBrightnessAndOnOff() throws InterruptedException {
// @formatter:off
var component = (Light) discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "{ " +
- " \"name\": \"light\", " +
- " \"schema\": \"json\", " +
- " \"state_topic\": \"zigbee2mqtt/light/state\", " +
- " \"command_topic\": \"zigbee2mqtt/light/set/state\", " +
- " \"brightness\": true" +
- "}");
+ """
+ { \
+ "name": "light", \
+ "schema": "json", \
+ "state_topic": "zigbee2mqtt/light/state", \
+ "command_topic": "zigbee2mqtt/light/set/state", \
+ "brightness": true\
+ }\
+ """);
// @formatter:on
assertThat(component.channels.size(), is(1));
public void testOnOffOnly() throws InterruptedException {
// @formatter:off
var component = (Light) discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "{ " +
- " \"name\": \"light\", " +
- " \"schema\": \"json\", " +
- " \"state_topic\": \"zigbee2mqtt/light/state\", " +
- " \"command_topic\": \"zigbee2mqtt/light/set/state\"" +
- "}");
+ """
+ { \
+ "name": "light", \
+ "schema": "json", \
+ "state_topic": "zigbee2mqtt/light/state", \
+ "command_topic": "zigbee2mqtt/light/set/state"\
+ }\
+ """);
// @formatter:on
assertThat(component.channels.size(), is(1));
public void test() throws InterruptedException {
// @formatter:off
var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "{ " +
- " \"availability\": [ " +
- " { " +
- " \"topic\": \"zigbee2mqtt/bridge/state\" " +
- " } " +
- " ], " +
- " \"device\": { " +
- " \"identifiers\": [ " +
- " \"zigbee2mqtt_0x0000000000000000\" " +
- " ], " +
- " \"manufacturer\": \"Locks inc\", " +
- " \"model\": \"Lock\", " +
- " \"name\": \"LockBlower\", " +
- " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " +
- " }, " +
- " \"name\": \"lock\", " +
- " \"payload_unlock\": \"UNLOCK_\", " +
- " \"payload_lock\": \"LOCK_\", " +
- " \"state_topic\": \"zigbee2mqtt/lock/state\", " +
- " \"command_topic\": \"zigbee2mqtt/lock/set/state\" " +
- "}");
+ """
+ { \
+ "availability": [ \
+ { \
+ "topic": "zigbee2mqtt/bridge/state" \
+ } \
+ ], \
+ "device": { \
+ "identifiers": [ \
+ "zigbee2mqtt_0x0000000000000000" \
+ ], \
+ "manufacturer": "Locks inc", \
+ "model": "Lock", \
+ "name": "LockBlower", \
+ "sw_version": "Zigbee2MQTT 1.18.2" \
+ }, \
+ "name": "lock", \
+ "payload_unlock": "UNLOCK_", \
+ "payload_lock": "LOCK_", \
+ "state_topic": "zigbee2mqtt/lock/state", \
+ "command_topic": "zigbee2mqtt/lock/set/state" \
+ }\
+ """);
// @formatter:on
assertThat(component.channels.size(), is(1));
public void forceOptimisticIsNotSupported() {
// @formatter:off
publishMessage(configTopicToMqtt(CONFIG_TOPIC),
- "{ " +
- " \"availability\": [ " +
- " { " +
- " \"topic\": \"zigbee2mqtt/bridge/state\" " +
- " } " +
- " ], " +
- " \"device\": { " +
- " \"identifiers\": [ " +
- " \"zigbee2mqtt_0x0000000000000000\" " +
- " ], " +
- " \"manufacturer\": \"Locks inc\", " +
- " \"model\": \"Lock\", " +
- " \"name\": \"LockBlower\", " +
- " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " +
- " }, " +
- " \"name\": \"lock\", " +
- " \"payload_unlock\": \"UNLOCK_\", " +
- " \"payload_lock\": \"LOCK_\", " +
- " \"optimistic\": \"true\", " +
- " \"state_topic\": \"zigbee2mqtt/lock/state\", " +
- " \"command_topic\": \"zigbee2mqtt/lock/set/state\" " +
- "}");
+ """
+ { \
+ "availability": [ \
+ { \
+ "topic": "zigbee2mqtt/bridge/state" \
+ } \
+ ], \
+ "device": { \
+ "identifiers": [ \
+ "zigbee2mqtt_0x0000000000000000" \
+ ], \
+ "manufacturer": "Locks inc", \
+ "model": "Lock", \
+ "name": "LockBlower", \
+ "sw_version": "Zigbee2MQTT 1.18.2" \
+ }, \
+ "name": "lock", \
+ "payload_unlock": "UNLOCK_", \
+ "payload_lock": "LOCK_", \
+ "optimistic": "true", \
+ "state_topic": "zigbee2mqtt/lock/state", \
+ "command_topic": "zigbee2mqtt/lock/set/state" \
+ }\
+ """);
// @formatter:on
}
public void test() throws InterruptedException {
// @formatter:off
var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "{ " +
- " \"availability_topic\": \"zigbee2mqtt/bridge/state\", " +
- " \"availability_template\": \"{{value_json.state}}\", " +
- " \"device\": { " +
- " \"identifiers\": [ " +
- " \"zigbee2mqtt_0x0000000000000000\" " +
- " ], " +
- " \"manufacturer\": \"Sensors inc\", " +
- " \"model\": \"Sensor\", " +
- " \"name\": \"Sensor\", " +
- " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " +
- " }, " +
- " \"name\": \"sensor1\", " +
- " \"expire_after\": \"1\", " +
- " \"force_update\": \"true\", " +
- " \"unit_of_measurement\": \"W\", " +
- " \"state_topic\": \"zigbee2mqtt/sensor/state\", " +
- " \"unique_id\": \"sn1\" " +
- "}");
+ """
+ { \
+ "availability_topic": "zigbee2mqtt/bridge/state", \
+ "availability_template": "{{value_json.state}}", \
+ "device": { \
+ "identifiers": [ \
+ "zigbee2mqtt_0x0000000000000000" \
+ ], \
+ "manufacturer": "Sensors inc", \
+ "model": "Sensor", \
+ "name": "Sensor", \
+ "sw_version": "Zigbee2MQTT 1.18.2" \
+ }, \
+ "name": "sensor1", \
+ "expire_after": "1", \
+ "force_update": "true", \
+ "unit_of_measurement": "W", \
+ "state_topic": "zigbee2mqtt/sensor/state", \
+ "unique_id": "sn1" \
+ }\
+ """);
// @formatter:on
assertThat(component.channels.size(), is(1));
public void testMeasurementStateClass() throws InterruptedException {
// @formatter:off
var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "{ " +
- " \"device\": { " +
- " \"identifiers\": [ " +
- " \"zigbee2mqtt_0x0000000000000000\" " +
- " ], " +
- " \"manufacturer\": \"Sensors inc\", " +
- " \"model\": \"Sensor\", " +
- " \"name\": \"Sensor\", " +
- " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " +
- " }, " +
- " \"name\": \"sensor1\", " +
- " \"expire_after\": \"1\", " +
- " \"force_update\": \"true\", " +
- " \"state_class\": \"measurement\", " +
- " \"state_topic\": \"zigbee2mqtt/sensor/state\", " +
- " \"unique_id\": \"sn1\" " +
- "}");
+ """
+ { \
+ "device": { \
+ "identifiers": [ \
+ "zigbee2mqtt_0x0000000000000000" \
+ ], \
+ "manufacturer": "Sensors inc", \
+ "model": "Sensor", \
+ "name": "Sensor", \
+ "sw_version": "Zigbee2MQTT 1.18.2" \
+ }, \
+ "name": "sensor1", \
+ "expire_after": "1", \
+ "force_update": "true", \
+ "state_class": "measurement", \
+ "state_topic": "zigbee2mqtt/sensor/state", \
+ "unique_id": "sn1" \
+ }\
+ """);
// @formatter:on
assertChannel(component, Sensor.SENSOR_CHANNEL_ID, "zigbee2mqtt/sensor/state", "", "sensor1",
public void testNonNumericSensor() throws InterruptedException {
// @formatter:off
var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "{ " +
- " \"device\": { " +
- " \"identifiers\": [ " +
- " \"zigbee2mqtt_0x0000000000000000\" " +
- " ], " +
- " \"manufacturer\": \"Sensors inc\", " +
- " \"model\": \"Sensor\", " +
- " \"name\": \"Sensor\", " +
- " \"sw_version\": \"Zigbee2MQTT 1.18.2\" " +
- " }, " +
- " \"name\": \"sensor1\", " +
- " \"expire_after\": \"1\", " +
- " \"force_update\": \"true\", " +
- " \"state_topic\": \"zigbee2mqtt/sensor/state\", " +
- " \"unique_id\": \"sn1\" " +
- "}");
+ """
+ { \
+ "device": { \
+ "identifiers": [ \
+ "zigbee2mqtt_0x0000000000000000" \
+ ], \
+ "manufacturer": "Sensors inc", \
+ "model": "Sensor", \
+ "name": "Sensor", \
+ "sw_version": "Zigbee2MQTT 1.18.2" \
+ }, \
+ "name": "sensor1", \
+ "expire_after": "1", \
+ "force_update": "true", \
+ "state_topic": "zigbee2mqtt/sensor/state", \
+ "unique_id": "sn1" \
+ }\
+ """);
// @formatter:on
assertChannel(component, Sensor.SENSOR_CHANNEL_ID, "zigbee2mqtt/sensor/state", "", "sensor1", TextValue.class);
@SuppressWarnings("null")
@Test
public void testSwitchWithStateAndCommand() {
- var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "" + "{\n" + " \"availability\": [\n" + " {\n" + " \"topic\": \"zigbee2mqtt/bridge/state\"\n"
- + " }\n" + " ],\n" + " \"command_topic\": \"zigbee2mqtt/th1/set/auto_lock\",\n"
- + " \"device\": {\n" + " \"identifiers\": [\n"
- + " \"zigbee2mqtt_0x847127fffe11dd6a\"\n" + " ],\n"
- + " \"manufacturer\": \"TuYa\",\n"
- + " \"model\": \"Radiator valve with thermostat (TS0601_thermostat)\",\n"
- + " \"name\": \"th1\",\n" + " \"sw_version\": \"Zigbee2MQTT 1.18.2\"\n" + " },\n"
- + " \"json_attributes_topic\": \"zigbee2mqtt/th1\",\n" + " \"name\": \"th1 auto lock\",\n"
- + " \"payload_off\": \"MANUAL\",\n" + " \"payload_on\": \"AUTO\",\n"
- + " \"state_off\": \"MANUAL\",\n" + " \"state_on\": \"AUTO\",\n"
- + " \"state_topic\": \"zigbee2mqtt/th1\",\n"
- + " \"unique_id\": \"0x847127fffe11dd6a_auto_lock_zigbee2mqtt\",\n"
- + " \"value_template\": \"{{ value_json.auto_lock }}\"\n" + "}");
+ var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), """
+ {
+ "availability": [
+ {
+ "topic": "zigbee2mqtt/bridge/state"
+ }
+ ],
+ "command_topic": "zigbee2mqtt/th1/set/auto_lock",
+ "device": {
+ "identifiers": [
+ "zigbee2mqtt_0x847127fffe11dd6a"
+ ],
+ "manufacturer": "TuYa",
+ "model": "Radiator valve with thermostat (TS0601_thermostat)",
+ "name": "th1",
+ "sw_version": "Zigbee2MQTT 1.18.2"
+ },
+ "json_attributes_topic": "zigbee2mqtt/th1",
+ "name": "th1 auto lock",
+ "payload_off": "MANUAL",
+ "payload_on": "AUTO",
+ "state_off": "MANUAL",
+ "state_on": "AUTO",
+ "state_topic": "zigbee2mqtt/th1",
+ "unique_id": "0x847127fffe11dd6a_auto_lock_zigbee2mqtt",
+ "value_template": "{{ value_json.auto_lock }}"
+ }\
+ """);
assertThat(component.channels.size(), is(1));
assertThat(component.getName(), is("th1 auto lock"));
@Test
public void testSwitchWithState() {
- var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "" + "{\n" + " \"availability\": [\n" + " {\n" + " \"topic\": \"zigbee2mqtt/bridge/state\"\n"
- + " }\n" + " ],\n" + " \"device\": {\n" + " \"identifiers\": [\n"
- + " \"zigbee2mqtt_0x847127fffe11dd6a\"\n" + " ],\n"
- + " \"manufacturer\": \"TuYa\",\n"
- + " \"model\": \"Radiator valve with thermostat (TS0601_thermostat)\",\n"
- + " \"name\": \"th1\",\n" + " \"sw_version\": \"Zigbee2MQTT 1.18.2\"\n" + " },\n"
- + " \"json_attributes_topic\": \"zigbee2mqtt/th1\",\n" + " \"name\": \"th1 auto lock\",\n"
- + " \"state_off\": \"MANUAL\",\n" + " \"state_on\": \"AUTO\",\n"
- + " \"state_topic\": \"zigbee2mqtt/th1\",\n"
- + " \"unique_id\": \"0x847127fffe11dd6a_auto_lock_zigbee2mqtt\",\n"
- + " \"value_template\": \"{{ value_json.auto_lock }}\"\n" + "}");
+ var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), """
+ {
+ "availability": [
+ {
+ "topic": "zigbee2mqtt/bridge/state"
+ }
+ ],
+ "device": {
+ "identifiers": [
+ "zigbee2mqtt_0x847127fffe11dd6a"
+ ],
+ "manufacturer": "TuYa",
+ "model": "Radiator valve with thermostat (TS0601_thermostat)",
+ "name": "th1",
+ "sw_version": "Zigbee2MQTT 1.18.2"
+ },
+ "json_attributes_topic": "zigbee2mqtt/th1",
+ "name": "th1 auto lock",
+ "state_off": "MANUAL",
+ "state_on": "AUTO",
+ "state_topic": "zigbee2mqtt/th1",
+ "unique_id": "0x847127fffe11dd6a_auto_lock_zigbee2mqtt",
+ "value_template": "{{ value_json.auto_lock }}"
+ }\
+ """);
assertThat(component.channels.size(), is(1));
assertThat(component.getName(), is("th1 auto lock"));
@SuppressWarnings("null")
@Test
public void testSwitchWithCommand() {
- var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC),
- "" + "{\n" + " \"availability\": [\n" + " {\n" + " \"topic\": \"zigbee2mqtt/bridge/state\"\n"
- + " }\n" + " ],\n" + " \"command_topic\": \"zigbee2mqtt/th1/set/auto_lock\",\n"
- + " \"device\": {\n" + " \"identifiers\": [\n"
- + " \"zigbee2mqtt_0x847127fffe11dd6a\"\n" + " ],\n"
- + " \"manufacturer\": \"TuYa\",\n"
- + " \"model\": \"Radiator valve with thermostat (TS0601_thermostat)\",\n"
- + " \"name\": \"th1\",\n" + " \"sw_version\": \"Zigbee2MQTT 1.18.2\"\n" + " },\n"
- + " \"json_attributes_topic\": \"zigbee2mqtt/th1\",\n" + " \"name\": \"th1 auto lock\",\n"
- + " \"payload_off\": \"MANUAL\",\n" + " \"payload_on\": \"AUTO\",\n"
- + " \"unique_id\": \"0x847127fffe11dd6a_auto_lock_zigbee2mqtt\",\n"
- + " \"value_template\": \"{{ value_json.auto_lock }}\"\n" + "}");
+ var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), """
+ {
+ "availability": [
+ {
+ "topic": "zigbee2mqtt/bridge/state"
+ }
+ ],
+ "command_topic": "zigbee2mqtt/th1/set/auto_lock",
+ "device": {
+ "identifiers": [
+ "zigbee2mqtt_0x847127fffe11dd6a"
+ ],
+ "manufacturer": "TuYa",
+ "model": "Radiator valve with thermostat (TS0601_thermostat)",
+ "name": "th1",
+ "sw_version": "Zigbee2MQTT 1.18.2"
+ },
+ "json_attributes_topic": "zigbee2mqtt/th1",
+ "name": "th1 auto lock",
+ "payload_off": "MANUAL",
+ "payload_on": "AUTO",
+ "unique_id": "0x847127fffe11dd6a_auto_lock_zigbee2mqtt",
+ "value_template": "{{ value_json.auto_lock }}"
+ }\
+ """);
assertThat(component.channels.size(), is(1));
assertThat(component.getName(), is("th1 auto lock"));
@Test
public void testRoborockValetudo() {
// @formatter:off
- var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), "{" +
- "\"name\":\"Rockrobo\"," +
- "\"unique_id\":\"rockrobo_vacuum\"," +
- "\"schema\":\"state\"," +
- "\"device\":{" +
- " \"manufacturer\":\"Roborock\"," +
- " \"model\":\"v1\"," +
- " \"name\":\"rockrobo\"," +
- " \"identifiers\":[\"rockrobo\"]," +
- " \"sw_version\":\"0.9.9\"" +
- "}," +
- "\"supported_features\":[\"start\",\"pause\",\"stop\",\"return_home\",\"battery\",\"status\"," +
- " \"locate\",\"clean_spot\",\"fan_speed\",\"send_command\"]," +
- "\"command_topic\":\"valetudo/rockrobo/command\"," +
- "\"state_topic\":\"valetudo/rockrobo/state\"," +
- "\"set_fan_speed_topic\":\"valetudo/rockrobo/set_fan_speed\"," +
- "\"fan_speed_list\":[\"min\",\"medium\",\"high\",\"max\",\"mop\"]," +
- "\"send_command_topic\":\"valetudo/rockrobo/custom_command\"," +
- "\"json_attributes_topic\":\"valetudo/rockrobo/attributes\"" +
- "}");
+ var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), """
+ {\
+ "name":"Rockrobo",\
+ "unique_id":"rockrobo_vacuum",\
+ "schema":"state",\
+ "device":{\
+ "manufacturer":"Roborock",\
+ "model":"v1",\
+ "name":"rockrobo",\
+ "identifiers":["rockrobo"],\
+ "sw_version":"0.9.9"\
+ },\
+ "supported_features":["start","pause","stop","return_home","battery","status",\
+ "locate","clean_spot","fan_speed","send_command"],\
+ "command_topic":"valetudo/rockrobo/command",\
+ "state_topic":"valetudo/rockrobo/state",\
+ "set_fan_speed_topic":"valetudo/rockrobo/set_fan_speed",\
+ "fan_speed_list":["min","medium","high","max","mop"],\
+ "send_command_topic":"valetudo/rockrobo/custom_command",\
+ "json_attributes_topic":"valetudo/rockrobo/attributes"\
+ }\
+ """);
// @formatter:on
assertThat(component.channels.size(), is(6)); // command, state, fan speed, send command, battery, json attrs
// @formatter:off
String jsonValue;
- publishMessage("valetudo/rockrobo/attributes", jsonValue = "{" +
- "\"mainBrush\":\"245.1\"," +
- "\"sideBrush\":\"145.1\"," +
- "\"filter\":\"95.1\"," +
- "\"sensor\":\"0.0\"," +
- "\"currentCleanTime\":\"52.0\"," +
- "\"currentCleanArea\":\"46.7\"," +
- "\"cleanTime\":\"54.9\"," +
- "\"cleanArea\":\"3280.9\"," +
- "\"cleanCount\":84," +
- "\"last_run_stats\":{" +
- " \"startTime\":1633257319000," +
- " \"endTime\":1633260439000," +
- " \"duration\":3120," +
- " \"area\":\"46.7\"," +
- " \"errorCode\":0," +
- " \"errorDescription\":\"No error\"," +
- " \"finishedFlag\":true" +
- "}," +
- "\"last_bin_out\":2147483647000," +
- "\"state\":\"docked\"," +
- "\"valetudo_state\":{" +
- " \"id\":8," +
- " \"name\":\"Charging\"" +
- "}," +
- "\"last_bin_full\":0" +
- "}");
+ publishMessage("valetudo/rockrobo/attributes", jsonValue = """
+ {\
+ "mainBrush":"245.1",\
+ "sideBrush":"145.1",\
+ "filter":"95.1",\
+ "sensor":"0.0",\
+ "currentCleanTime":"52.0",\
+ "currentCleanArea":"46.7",\
+ "cleanTime":"54.9",\
+ "cleanArea":"3280.9",\
+ "cleanCount":84,\
+ "last_run_stats":{\
+ "startTime":1633257319000,\
+ "endTime":1633260439000,\
+ "duration":3120,\
+ "area":"46.7",\
+ "errorCode":0,\
+ "errorDescription":"No error",\
+ "finishedFlag":true\
+ },\
+ "last_bin_out":2147483647000,\
+ "state":"docked",\
+ "valetudo_state":{\
+ "id":8,\
+ "name":"Charging"\
+ },\
+ "last_bin_full":0\
+ }\
+ """);
// @formatter:on
// @formatter:off
- publishMessage("valetudo/rockrobo/state", "{" +
- "\"state\":\"docked\"," +
- "\"battery_level\":100," +
- "\"fan_speed\":\"max\"" +
- "}");
+ publishMessage("valetudo/rockrobo/state", """
+ {\
+ "state":"docked",\
+ "battery_level":100,\
+ "fan_speed":"max"\
+ }\
+ """);
// @formatter:on
assertState(component, Vacuum.STATE_CH_ID, new StringType(Vacuum.STATE_DOCKED));
assertPublished("valetudo/rockrobo/command", "start");
// @formatter:off
- publishMessage("valetudo/rockrobo/state", "{" +
- "\"state\":\"cleaning\"," +
- "\"battery_level\":99," +
- "\"fan_speed\":\"max\"" +
- "}");
+ publishMessage("valetudo/rockrobo/state", """
+ {\
+ "state":"cleaning",\
+ "battery_level":99,\
+ "fan_speed":"max"\
+ }\
+ """);
// @formatter:on
assertState(component, Vacuum.STATE_CH_ID, new StringType(Vacuum.STATE_CLEANING));
assertPublished("valetudo/rockrobo/set_fan_speed", "medium");
// @formatter:off
- publishMessage("valetudo/rockrobo/state", "{" +
- "\"state\":\"returning\"," +
- "\"battery_level\":80," +
- "\"fan_speed\":\"medium\"" +
- "}");
+ publishMessage("valetudo/rockrobo/state", """
+ {\
+ "state":"returning",\
+ "battery_level":80,\
+ "fan_speed":"medium"\
+ }\
+ """);
// @formatter:on
assertState(component, Vacuum.STATE_CH_ID, new StringType(Vacuum.STATE_RETURNING));
@Test
public void testLegacySchema() {
// @formatter:off
- var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), "{" +
- "\"name\":\"Rockrobo\"," +
- "\"unique_id\":\"rockrobo_vacuum\"," +
- "\"device\":{" +
- " \"manufacturer\":\"Roborock\"," +
- " \"model\":\"v1\"," +
- " \"name\":\"rockrobo\"," +
- " \"identifiers\":[\"rockrobo\"]," +
- " \"sw_version\":\"0.9.9\"" +
- "}," +
- "\"supported_features\":[\"turn_on\", \"turn_off\",\"pause\",\"stop\",\"return_home\",\"battery\",\"status\"," +
- " \"locate\",\"clean_spot\",\"fan_speed\",\"send_command\"]," +
- "\"command_topic\":\"vacuum/command\"," +
- "\"battery_level_topic\":\"vacuum/state\"," +
- "\"battery_level_template\":\"{{ value_json.battery_level }}\"," +
- "\"charging_topic\":\"vacuum/state\"," +
- "\"charging_template\":\"{{ value_json.charging }}\"," +
- "\"cleaning_topic\":\"vacuum/state\"," +
- "\"cleaning_template\":\"{{ value_json.cleaning }}\"," +
- "\"docked_topic\":\"vacuum/state\"," +
- "\"docked_template\":\"{{ value_json.docked }}\"," +
- "\"error_topic\":\"vacuum/state\"," +
- "\"error_template\":\"{{ value_json.error }}\"," +
- "\"fan_speed_topic\":\"vacuum/state\"," +
- "\"set_fan_speed_topic\":\"vacuum/set_fan_speed\"," +
- "\"fan_speed_template\":\"{{ value_json.fan_speed }}\"," +
- "\"fan_speed_list\":[\"min\",\"medium\",\"high\",\"max\"]," +
- "\"send_command_topic\":\"vacuum/send_command\"" +
- "}");
+ var component = discoverComponent(configTopicToMqtt(CONFIG_TOPIC), """
+ {\
+ "name":"Rockrobo",\
+ "unique_id":"rockrobo_vacuum",\
+ "device":{\
+ "manufacturer":"Roborock",\
+ "model":"v1",\
+ "name":"rockrobo",\
+ "identifiers":["rockrobo"],\
+ "sw_version":"0.9.9"\
+ },\
+ "supported_features":["turn_on", "turn_off","pause","stop","return_home","battery","status",\
+ "locate","clean_spot","fan_speed","send_command"],\
+ "command_topic":"vacuum/command",\
+ "battery_level_topic":"vacuum/state",\
+ "battery_level_template":"{{ value_json.battery_level }}",\
+ "charging_topic":"vacuum/state",\
+ "charging_template":"{{ value_json.charging }}",\
+ "cleaning_topic":"vacuum/state",\
+ "cleaning_template":"{{ value_json.cleaning }}",\
+ "docked_topic":"vacuum/state",\
+ "docked_template":"{{ value_json.docked }}",\
+ "error_topic":"vacuum/state",\
+ "error_template":"{{ value_json.error }}",\
+ "fan_speed_topic":"vacuum/state",\
+ "set_fan_speed_topic":"vacuum/set_fan_speed",\
+ "fan_speed_template":"{{ value_json.fan_speed }}",\
+ "fan_speed_list":["min","medium","high","max"],\
+ "send_command_topic":"vacuum/send_command"\
+ }\
+ """);
// @formatter:on
assertThat(component.channels.size(), is(8)); // command, battery, charging, cleaning, docked, error,
assertChannel(component, Vacuum.CUSTOM_COMMAND_CH_ID, "", "vacuum/send_command", "Rockrobo", TextValue.class);
// @formatter:off
- publishMessage("vacuum/state", "{" +
- "\"battery_level\": 61," +
- "\"docked\": true," +
- "\"cleaning\": false," +
- "\"charging\": true," +
- "\"fan_speed\": \"off\"," +
- "\"error\": \"Error message\"" +
- "}");
+ publishMessage("vacuum/state", """
+ {\
+ "battery_level": 61,\
+ "docked": true,\
+ "cleaning": false,\
+ "charging": true,\
+ "fan_speed": "off",\
+ "error": "Error message"\
+ }\
+ """);
// @formatter:on
assertState(component, Vacuum.BATTERY_LEVEL_CH_ID, new PercentType(61));
assertPublished("vacuum/command", "turn_on");
// @formatter:off
- publishMessage("vacuum/state", "{" +
- "\"battery_level\": 55," +
- "\"docked\": false," +
- "\"cleaning\": true," +
- "\"charging\": false," +
- "\"fan_speed\": \"medium\"," +
- "\"error\": \"\"" +
- "}");
+ publishMessage("vacuum/state", """
+ {\
+ "battery_level": 55,\
+ "docked": false,\
+ "cleaning": true,\
+ "charging": false,\
+ "fan_speed": "medium",\
+ "error": ""\
+ }\
+ """);
// @formatter:on
assertState(component, Vacuum.BATTERY_LEVEL_CH_ID, new PercentType(55));
package org.openhab.binding.mqtt.homie.internal.discovery;
import java.nio.charset.StandardCharsets;
-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;
@Activate
public Homie300Discovery(@Reference MQTTTopicDiscoveryService discoveryService) {
- super(Collections.singleton(MqttBindingConstants.HOMIE300_MQTT_THING), 3, true, "+/+/$homie");
+ super(Set.of(MqttBindingConstants.HOMIE300_MQTT_THING), 3, true, "+/+/$homie");
this.discoveryService = discoveryService;
}
"Homie devices require QoS 1 but Qos 0/2 is configured. Using override. Please check the configuration");
connection.setQos(1);
}
- return device.subscribe(connection, scheduler, attributeReceiveTimeout).thenCompose((Void v) -> {
- return device.startChannels(connection, scheduler, attributeReceiveTimeout, this);
- }).thenRun(() -> {
- logger.debug("Homie device {} fully attached (start)", config.deviceid);
- });
+ return device.subscribe(connection, scheduler, attributeReceiveTimeout)
+ .thenCompose((Void v) -> device.startChannels(connection, scheduler, attributeReceiveTimeout, this))
+ .thenRun(() -> {
+ logger.debug("Homie device {} fully attached (start)", config.deviceid);
+ });
}
@Override
logger.warn("couldn't remove retained topics for {} because connection is null", thing.getUID());
return;
}
- device.getRetainedTopics().stream().map(d -> {
- return String.format("%s/%s", config.basetopic, d);
- }).collect(Collectors.toList()).forEach(t -> connection.publish(t, new byte[0], 1, true));
+ device.getRetainedTopics().stream().map(d -> String.format("%s/%s", config.basetopic, d))
+ .collect(Collectors.toList()).forEach(t -> connection.publish(t, new byte[0], 1, true));
}
@Override
value = new OnOffValue("true", "false");
break;
case color_:
- if (attributes.format.equals("hsv")) {
+ if ("hsv".equals(attributes.format)) {
value = new ColorValue(ColorMode.HSB, null, null, 100);
- } else if (attributes.format.equals("rgb")) {
+ } else if ("rgb".equals(attributes.format)) {
value = new ColorValue(ColorMode.RGB, null, null, 100);
} else {
logger.warn("Non supported color format: '{}'. Only 'hsv' and 'rgb' are supported",
}
break;
case enum_:
- String enumValues[] = attributes.format.split(",");
+ String[] enumValues = attributes.format.split(",");
value = new TextValue(enumValues);
break;
case float_:
case integer_:
isDecimal = attributes.datatype == DataTypeEnum.float_;
- String s[] = attributes.format.split("\\:");
+ String[] s = attributes.format.split("\\:");
BigDecimal min = s.length == 2 ? convertFromString(s[0]) : null;
BigDecimal max = s.length == 2 ? convertFromString(s[1]) : null;
BigDecimal step = (min != null && max != null)
public List<String> getRetainedTopics() {
List<String> topics = new ArrayList<>();
- topics.addAll(Stream.of(this.attributes.getClass().getDeclaredFields()).map(f -> {
- return String.format("%s/$%s", this.propertyID, f.getName());
- }).collect(Collectors.toList()));
+ topics.addAll(Stream.of(this.attributes.getClass().getDeclaredFields())
+ .map(f -> String.format("%s/$%s", this.propertyID, f.getName())).collect(Collectors.toList()));
// All exceptions can be ignored because the 'retained' attribute of the PropertyAttributes class
// is public, is a boolean variable and has a default value (true)
if (payloadIntermediate == null) {
throw new JsonSyntaxException("JSON parsing failed");
}
- GatewayPayload payload = new GatewayPayload(payloadIntermediate);
- return payload;
+ return new GatewayPayload(payloadIntermediate);
}
}
}));
assertTrue(//
- discoveryResults.stream().anyMatch(result -> {
- return "DE:EA:DB:BE:FF:00"
- .equals(result.getProperties().get(RuuviGatewayBindingConstants.PROPERTY_TAG_ID))
- && "ruuvi/foo/bar/de:ea:DB:be:ff:00".equals(result.getProperties()
- .get(RuuviGatewayBindingConstants.CONFIGURATION_PROPERTY_TOPIC));
- }) && //
- discoveryResults.stream().anyMatch(result -> {
- return "DE:EA:DB:BE:FF:01"
- .equals(result.getProperties().get(RuuviGatewayBindingConstants.PROPERTY_TAG_ID))
- && "ruuvi/foo/bar/de:ea:DB:be:ff:01".equals(result.getProperties()
- .get(RuuviGatewayBindingConstants.CONFIGURATION_PROPERTY_TOPIC));
- })
+ discoveryResults.stream().anyMatch(result -> "DE:EA:DB:BE:FF:00"
+ .equals(result.getProperties().get(RuuviGatewayBindingConstants.PROPERTY_TAG_ID))
+ && "ruuvi/foo/bar/de:ea:DB:be:ff:00".equals(
+ result.getProperties().get(RuuviGatewayBindingConstants.CONFIGURATION_PROPERTY_TOPIC)))
+ && //
+ discoveryResults.stream()
+ .anyMatch(result -> "DE:EA:DB:BE:FF:01".equals(
+ result.getProperties().get(RuuviGatewayBindingConstants.PROPERTY_TAG_ID))
+ && "ruuvi/foo/bar/de:ea:DB:be:ff:01".equals(result.getProperties()
+ .get(RuuviGatewayBindingConstants.CONFIGURATION_PROPERTY_TOPIC)))
, "Failed to match: " + discoveryResults.toString());
}
public void testUnexpectedTypes3() {
assertThrows(JsonSyntaxException.class, () -> {
GatewayPayloadParser.parse(bytes(//
- "{\"gw_mac\": \"DE:AD:BE:EF:00:00\","//
- + " \"rssi\": \"foobar\","// should be number
- + " \"aoa\": [],"//
- + " \"gwts\": \"1659365438\","//
- + " \"ts\": \"1659365438\","//
- + " \"data\": \"0201061BFF99040512FC5394C37C0004FFFC040CAC364200CDCBB8334C884F\","
- + " \"coords\": \"\"" + "}"));
+ """
+ {"gw_mac": "DE:AD:BE:EF:00:00",\
+ "rssi": "foobar",\
+ "aoa": [],\
+ "gwts": "1659365438",\
+ "ts": "1659365438",\
+ "data": "0201061BFF99040512FC5394C37C0004FFFC040CAC364200CDCBB8334C884F",\
+ "coords": ""\
+ }\
+ """));
});
}
public void testUnexpectedManufacturer() {
assertThrows(IllegalArgumentException.class, () -> {
GatewayPayloadParser.parse(bytes(//
- "{\"gw_mac\": \"DE:AD:BE:EF:00:00\","//
- + " \"rssi\": -83,"//
- + " \"aoa\": [],"//
- + " \"gwts\": \"1659365438\","//
- + " \"ts\": \"1659365438\","//
- // manufacturer is not 99 04 (Ruuvi) but 99 99
- + " \"data\": \"0201061BFF99990512FC5394C37C0004FFFC040CAC364200CDCBB8334C884F\","
- + " \"coords\": \"\"" + "}"));
+ """
+ {"gw_mac": "DE:AD:BE:EF:00:00",\
+ "rssi": -83,\
+ "aoa": [],\
+ "gwts": "1659365438",\
+ "ts": "1659365438",\
+ "data": "0201061BFF99990512FC5394C37C0004FFFC040CAC364200CDCBB8334C884F",\
+ "coords": ""\
+ }\
+ """));
});
}
public void testDataNotBluetoothAdvertisement() {
assertThrows(IllegalArgumentException.class, () -> {
GatewayPayloadParser.parse(bytes(//
- "{\"gw_mac\": \"DE:AD:BE:EF:00:00\","//
- + " \"rssi\": -83,"//
- + " \"aoa\": [],"//
- + " \"gwts\": \"1659365438\","//
- + " \"ts\": \"1659365438\","//
- // not advertisement (FF) but AA
- + " \"data\": \"0201061BAA99040512FC5394C37C0004FFFC040CAC364200CDCBB8334C884F\","
- + " \"coords\": \"\"" + "}"));
+ """
+ {"gw_mac": "DE:AD:BE:EF:00:00",\
+ "rssi": -83,\
+ "aoa": [],\
+ "gwts": "1659365438",\
+ "ts": "1659365438",\
+ "data": "0201061BAA99040512FC5394C37C0004FFFC040CAC364200CDCBB8334C884F",\
+ "coords": ""\
+ }\
+ """));
});
}
}
package org.openhab.binding.mqtt.handler;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(MQTTActions.class);
+ return Set.of(MQTTActions.class);
}
/**
* for creating a ThingUID with that string (tcp_122_123_111_123_1883).
*/
public static String getThingID(String host, int port) {
- return host.replace('.', '_').replace("://", "_") + "_" + String.valueOf(port);
+ return host.replace('.', '_').replace("://", "_") + "_" + port;
}
/**
if (THING_TYPE_CONNECTED_DRIVE_ACCOUNT.equals(thingTypeUID)) {
return new MyBMWBridgeHandler((Bridge) thing, httpClientFactory, localeLanguage);
} else if (SUPPORTED_THING_SET.contains(thingTypeUID)) {
- VehicleHandler vh = new VehicleHandler(thing, commandOptionProvider, locationProvider,
- thingTypeUID.getId());
- return vh;
+ return new VehicleHandler(thing, commandOptionProvider, locationProvider, thingTypeUID.getId());
}
return null;
}
@Override
public void setThingHandler(ThingHandler handler) {
- if (handler instanceof MyBMWBridgeHandler) {
- bridgeHandler = Optional.of((MyBMWBridgeHandler) handler);
+ if (handler instanceof MyBMWBridgeHandler bmwBridgeHandler) {
+ bridgeHandler = Optional.of(bmwBridgeHandler);
bridgeHandler.get().setDiscoveryService(this);
}
}
package org.openhab.binding.mybmw.internal.handler;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(VehicleDiscovery.class);
+ return Set.of(VehicleDiscovery.class);
}
public Optional<MyBMWProxy> getProxy() {
logger.debug("HTTP Error {}", error.toString());
callback.onError(error);
} else {
- if (callback instanceof StringResponseCallback) {
- ((StringResponseCallback) callback).onResponse(getContentAsString());
- } else if (callback instanceof ByteResponseCallback) {
- ((ByteResponseCallback) callback).onResponse(getContent());
+ if (callback instanceof StringResponseCallback responseCallback) {
+ responseCallback.onResponse(getContentAsString());
+ } else if (callback instanceof ByteResponseCallback responseCallback) {
+ responseCallback.onResponse(getContent());
} else {
logger.error("unexpected reponse type {}", callback.getClass().getName());
}
UrlEncoded.decodeTo(encodedUrl, tokenMap, StandardCharsets.US_ASCII);
final StringBuilder codeFound = new StringBuilder();
tokenMap.forEach((key, value) -> {
- if (value.size() > 0) {
+ if (!value.isEmpty()) {
String val = value.get(0);
if (key.endsWith(CODE)) {
- codeFound.append(val.toString());
+ codeFound.append(val);
}
}
});
// Check for Channel Group and corresponding Actions
} else if (CHANNEL_GROUP_REMOTE.equals(group)) {
// Executing Remote Services
- if (command instanceof StringType) {
- String serviceCommand = ((StringType) command).toFullString();
+ if (command instanceof StringType str) {
+ String serviceCommand = str.toFullString();
remote.ifPresent(remot -> {
switch (serviceCommand) {
case REMOTE_SERVICE_LIGHT_FLASH:
prox.requestChargeStatistics(config, chargeStatisticsCallback);
prox.requestChargeSessions(config, chargeSessionCallback);
}
- if (!imageCache.isPresent() && !imageProperties.failLimitReached()) {
+ if (imageCache.isEmpty() && !imageProperties.failLimitReached()) {
prox.requestImage(config, imageProperties, imageCallback);
}
}, () -> {
int rightLimit = 122; // letter 'z'
Random random = new SecureRandom();
- String generatedString = random.ints(leftLimit, rightLimit + 1).limit(size)
+ return random.ints(leftLimit, rightLimit + 1).limit(size)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();
-
- return generatedString;
}
public static State getLockState(boolean lock) {
if (serviceDate.equals(farFuture)) {
return UnDefType.UNDEF;
} else {
- DateTimeType dt = DateTimeType.valueOf(serviceDate.format(Converter.DATE_INPUT_PATTERN));
- return dt;
+ return DateTimeType.valueOf(serviceDate.format(Converter.DATE_INPUT_PATTERN));
}
}
assertEquals(expected.toString(), dtt.toString(), "Last Update");
break;
case GPS:
- if (state instanceof PointType) {
- pt = (PointType) state;
+ if (state instanceof PointType point) {
+ pt = point;
assertNotNull(vehicle.properties.vehicleLocation);
assertEquals(
PointType.valueOf(Double.toString(vehicle.properties.vehicleLocation.coordinates.latitude)
} // else no check needed
break;
case HEADING:
- if (state instanceof QuantityType) {
- qt = ((QuantityType) state);
+ if (state instanceof QuantityType quantityCommand) {
+ qt = quantityCommand;
assertEquals(Units.DEGREE_ANGLE, qt.getUnit(), "Angle Unit");
assertNotNull(vehicle.properties.vehicleLocation);
assertEquals(vehicle.properties.vehicleLocation.heading, qt.intValue(), 0.01, "Heading");
}
break;
case ADDRESS:
- if (state instanceof StringType) {
- st = (StringType) state;
+ if (state instanceof StringType str) {
+ st = str;
assertEquals(st.toFullString(), vehicle.properties.vehicleLocation.address.formatted,
"Location Address");
} // else no check needed
break;
case HOME_DISTANCE:
- if (state instanceof QuantityType) {
- qt = (QuantityType) state;
+ if (state instanceof QuantityType quantity) {
+ qt = quantity;
PointType vehicleLocation = PointType
.valueOf(Double.toString(vehicle.properties.vehicleLocation.coordinates.latitude) + ","
+ Double.toString(vehicle.properties.vehicleLocation.coordinates.longitude));
UrlEncoded.decodeTo(encodedUrl, tokenMap, StandardCharsets.US_ASCII);
final StringBuilder codeFound = new StringBuilder();
tokenMap.forEach((key, value) -> {
- if (value.size() > 0) {
+ if (!value.isEmpty()) {
String val = value.get(0);
if (key.endsWith(CODE)) {
- codeFound.append(val.toString());
+ codeFound.append(val);
}
}
});
public class FileReader {
public static String readFileInString(String filename) {
- try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8"));) {
+ try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8"))) {
StringBuilder buf = new StringBuilder();
String sCurrentLine;
listeners.getOrDefault(mycroftMessage.type, new HashSet<>()).stream()).forEach(listener -> {
listener.baseMessageReceived(finalMessage);
});
-
} catch (RuntimeException e) {
// we need to catch all processing exceptions, otherwise they could affect the connection
logger.debug("{} encountered an error while processing the message {}: {}", socketName, message,
@OnWebSocketError
public void onError(@Nullable Session session, Throwable cause) {
-
if (session == null || !session.equals(this.session)) {
handleWrongSession(session, "Connection error: " + cause.getMessage());
return;
@Override
public void handleCommand(Command command) {
- if (command instanceof PlayPauseType) {
- if (((PlayPauseType) command) == PlayPauseType.PAUSE) {
+ if (command instanceof PlayPauseType playPauseCommand) {
+ if (playPauseCommand == PlayPauseType.PAUSE) {
if (handler.sendMessage(new MessageAudioPause())) {
updateMyState(PlayPauseType.PAUSE);
}
}
- if (((PlayPauseType) command) == PlayPauseType.PLAY) {
+ if (playPauseCommand == PlayPauseType.PLAY) {
handler.sendMessage(new MessageAudioPlay());
if (handler.sendMessage(new MessageAudioResume())) {
updateMyState(PlayPauseType.PLAY);
}
}
}
- if (command instanceof NextPreviousType) {
- if (((NextPreviousType) command) == NextPreviousType.NEXT) {
+ if (command instanceof NextPreviousType nextPreviousCommand) {
+ if (nextPreviousCommand == NextPreviousType.NEXT) {
if (handler.sendMessage(new MessageAudioNext())) {
updateMyState(PlayPauseType.PLAY);
}
}
- if (((NextPreviousType) command) == NextPreviousType.PREVIOUS) {
+ if (nextPreviousCommand == NextPreviousType.PREVIOUS) {
if (handler.sendMessage(new MessageAudioPrev())) {
updateMyState(PlayPauseType.PLAY);
}
}
private boolean sendVolumeSetMessage(float volume) {
- String messageToSend = VolumeChannel.VOLUME_SETTER_MESSAGE.replaceAll("\\$\\$VOLUME",
- Float.valueOf(volume).toString());
+ String messageToSend = VolumeChannel.VOLUME_SETTER_MESSAGE.replaceAll("\\$\\$VOLUME", Float.toString(volume));
return handler.sendMessage(messageToSend);
}
@Override
public void messageReceived(BaseMessage message) {
-
if (message.type == MessageType.mycroft_volume_get_response) {
float volumeGet = ((MessageVolumeGetResponse) message).data.percent;
updateAndSaveMyState(normalizeVolume(volumeGet));
}
protected final void updateAndSaveMyState(State state) {
- if (state instanceof PercentType) {
- this.lastVolume = ((PercentType) state);
- if (((PercentType) state).intValue() > 0) {
- this.lastNonZeroVolume = ((PercentType) state);
+ if (state instanceof PercentType volume) {
+ this.lastVolume = volume;
+ if (volume.intValue() > 0) {
+ this.lastNonZeroVolume = volume;
}
}
super.updateMyState(state);
}
private boolean sendSetMessage(float volume) {
- String messageToSend = VOLUME_SETTER_MESSAGE.replaceAll("\\$\\$VOLUME", Float.valueOf(volume).toString());
+ String messageToSend = VOLUME_SETTER_MESSAGE.replaceAll("\\$\\$VOLUME", Float.toString(volume));
return handler.sendMessage(messageToSend);
}
handler.sendMessage(new MessageVolumeDecrease());
updateAndSaveMyState(computeNewVolume(-10));
}
- } else if (command instanceof PercentType) {
- sendSetMessage(toMycroftVolume((PercentType) command));
- updateAndSaveMyState((PercentType) command);
+ } else if (command instanceof PercentType volume) {
+ sendSetMessage(toMycroftVolume(volume));
+ updateAndSaveMyState(volume);
} else if (command instanceof RefreshType) {
handler.sendMessage(new MessageVolumeGet());
}
@Test
public void testConnectionOK() throws IOException {
-
MycroftConnection mycroftConnection = new MycroftConnection(mycroftConnectionListener, new WebSocketClient());
Mockito.when(sessionMock.getRemoteAddress()).thenReturn(new InetSocketAddress(1234));
mycroftConnection.onConnect(sessionMock);
@Test
public void testSpeakListener() throws IOException {
-
MycroftConnection mycroftConnection = new MycroftConnection(mycroftConnectionListener, new WebSocketClient());
Mockito.when(sessionMock.getRemoteAddress()).thenReturn(new InetSocketAddress(1234));
public enum UserPerm {
wait,
user,
- admin;
+ admin
}
@XStreamAsAttribute
UP_AND_OVER,
SLIDING,
BARRIER,
- SWING;
+ SWING
}
@XStreamAsAttribute
*/
@XStreamAlias("Properties")
public class Properties {
- public static enum DoorStatus {
+ public enum DoorStatus {
OPEN(false),
CLOSED(false),
OPENING(true),
@Override
public void setThingHandler(ThingHandler handler) {
- if (handler instanceof MyQAccountHandler) {
- accountHandler = (MyQAccountHandler) handler;
+ if (handler instanceof MyQAccountHandler myqAccountHandler) {
+ accountHandler = myqAccountHandler;
}
}
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
+import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
@Override
public Collection<Class<? extends ThingHandlerService>> getServices() {
- return Collections.singleton(MyQDiscoveryService.class);
+ return Set.of(MyQDiscoveryService.class);
}
@Override
public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
List<DeviceDTO> localDeviceCaches = devicesCache;
- if (childHandler instanceof MyQDeviceHandler) {
- MyQDeviceHandler handler = (MyQDeviceHandler) childHandler;
- localDeviceCaches.stream()
- .filter(d -> ((MyQDeviceHandler) childHandler).getSerialNumber().equalsIgnoreCase(d.serialNumber))
- .findFirst().ifPresent(handler::handleDeviceUpdate);
+ if (childHandler instanceof MyQDeviceHandler deviceHandler) {
+ localDeviceCaches.stream().filter(d -> deviceHandler.getSerialNumber().equalsIgnoreCase(d.serialNumber))
+ .findFirst().ifPresent(deviceHandler::handleDeviceUpdate);
}
}
if (command instanceof UpDownType) {
cmd = command == UpDownType.UP ? "open" : "close";
}
- if (command instanceof PercentType) {
- cmd = ((PercentType) command).as(UpDownType.class) == UpDownType.UP ? "open" : "close";
+ if (command instanceof PercentType percentage) {
+ cmd = percentage.as(UpDownType.class) == UpDownType.UP ? "open" : "close";
}
if (command instanceof StringType) {
cmd = command.toString();
}
break;
case CHANNEL_COLOR:
- if (command instanceof HSBType) {
- if (Objects.equals(((HSBType) command).as(OnOffType.class), OnOffType.OFF)) {
+ if (command instanceof HSBType hsb) {
+ if (Objects.equals(hsb.as(OnOffType.class), OnOffType.OFF)) {
sResp = sendToBulb("off", null, null, null);
} else {
- String hsv = command.toString().replaceAll(",", ";");
+ String hsv = command.toString().replace(",", ";");
sResp = sendToBulb("on", hsv, null, HSV);
}
}
break;
case CHANNEL_BRIGHTNESS:
- if (command instanceof PercentType) {
- if (Objects.equals(((PercentType) command).as(OnOffType.class), OnOffType.OFF)) {
+ if (command instanceof PercentType brightness) {
+ if (Objects.equals(brightness.as(OnOffType.class), OnOffType.OFF)) {
sResp = sendToBulb("off", null, null, null);
} else {
if (lastMode.equals(MONO)) {
}
break;
case CHANNEL_COLOR_TEMPERATURE:
- if (command instanceof PercentType) {
- String mono = convertPercentageToMyStromCT((PercentType) command) + ";"
- + lastBrightness.toString();
+ if (command instanceof PercentType temperature) {
+ String mono = convertPercentageToMyStromCT(temperature) + ";" + lastBrightness.toString();
sResp = sendToBulb("on", mono, null, MONO);
}
break;
if (deviceInfo != null) {
updateState(CHANNEL_SWITCH, deviceInfo.on ? OnOffType.ON : OnOffType.OFF);
updateState(CHANNEL_RAMP, QuantityType.valueOf(deviceInfo.ramp, MetricPrefix.MILLI(SECOND)));
- if (deviceInfo instanceof MyStromDeviceSpecificInfo) {
- updateState(CHANNEL_POWER, QuantityType.valueOf(((MyStromDeviceSpecificInfo) deviceInfo).power, WATT));
+ if (deviceInfo instanceof MyStromDeviceSpecificInfo info) {
+ updateState(CHANNEL_POWER, QuantityType.valueOf(info.power, WATT));
}
if (deviceInfo.on) {
try {
lastColor = new HSBType(lastColor.getHue() + ",0," + lastBrightness);
updateState(CHANNEL_COLOR_TEMPERATURE, lastColorTemperature);
} else if (numSemicolon == 2 && deviceInfo.mode.equals(HSV)) {
- lastColor = HSBType.valueOf(deviceInfo.color.replaceAll(";", ","));
+ lastColor = HSBType.valueOf(deviceInfo.color.replace(";", ","));
lastBrightness = lastColor.getBrightness();
- } else if (!deviceInfo.color.equals("") && deviceInfo.mode.equals(RGB)) {
+ } else if (!"".equals(deviceInfo.color) && deviceInfo.mode.equals(RGB)) {
int r = Integer.parseInt(deviceInfo.color.substring(2, 4), 16);
int g = Integer.parseInt(deviceInfo.color.substring(4, 6), 16);
int b = Integer.parseInt(deviceInfo.color.substring(6, 8), 16);