[homekit] Checkstyle cleanup ()

* Remove package
* java 17 instanceofpattern
* EqualsAvoidNullCheck
* NoEmptyLineSeparatorCheck
* ConstantNameCheck

Signed-off-by: lsiepel <leosiepel@gmail.com>
This commit is contained in:
lsiepel 2023-08-21 20:12:49 +02:00 committed by GitHub
parent 24fa966dc3
commit a1b79b6b7b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 161 additions and 168 deletions

@ -230,8 +230,8 @@ public class HomekitChangeListener implements ItemRegistryChangeListener {
/*
* if metadata of a group item was changed, mark all group member as dirty.
*/
if (item instanceof GroupItem) {
((GroupItem) item).getMembers().forEach(groupMember -> pendingUpdates.add(groupMember.getName()));
if (item instanceof GroupItem itemAsGroupItem) {
itemAsGroupItem.getMembers().forEach(groupMember -> pendingUpdates.add(groupMember.getName()));
}
applyUpdatesDebouncer.call();
}
@ -386,10 +386,9 @@ public class HomekitChangeListener implements ItemRegistryChangeListener {
@Nullable Map<String, Object> configuration) {
if (accessoryTypes.size() > 1 && configuration != null) {
final @Nullable Object value = configuration.get(HomekitTaggedItem.PRIMARY_SERVICE);
if (value instanceof String) {
return accessoryTypes.stream()
.filter(aType -> ((String) value).equalsIgnoreCase(aType.getKey().getTag())).findAny()
.orElse(accessoryTypes.get(0)).getKey();
if (value instanceof String valueAsString) {
return accessoryTypes.stream().filter(aType -> valueAsString.equalsIgnoreCase(aType.getKey().getTag()))
.findAny().orElse(accessoryTypes.get(0)).getKey();
}
}
// no primary accessory found or there is only one type, so return the first type from the list
@ -513,8 +512,8 @@ public class HomekitChangeListener implements ItemRegistryChangeListener {
if (value == null) {
return (instance == 1);
}
if (value instanceof Number) {
return (instance == ((Number) value).intValue());
if (value instanceof Number valueAsNumber) {
return (instance == valueAsNumber.intValue());
}
logger.warn("Unrecognized instance tag {} ({}) for item {}; assigning to default instance.", value,
value.getClass(), item.getName());

@ -60,8 +60,7 @@ public class HomekitOHItemProxy {
private int delay = DEFAULT_DELAY;
public static Item getBaseItem(Item item) {
if (item instanceof GroupItem) {
final GroupItem groupItem = (GroupItem) item;
if (item instanceof GroupItem groupItem) {
final Item baseItem = groupItem.getBaseItem();
if (baseItem != null) {
return baseItem;
@ -110,8 +109,8 @@ public class HomekitOHItemProxy {
|| ((dimmerMode == DIMMER_MODE_FILTER_ON_EXCEPT_BRIGHTNESS_100) && (currentOnState != OnOffType.ON)
&& ((brightness == null) || (brightness.intValue() == 100)))) {
logger.trace("send OnOff command for item {} with value {}", item, on);
if (item instanceof GroupItem) {
((GroupItem) item).send(on);
if (item instanceof GroupItem groupItem) {
groupItem.send(on);
} else {
((DimmerItem) item).send(on);
}
@ -120,8 +119,8 @@ public class HomekitOHItemProxy {
// if hue or saturation present, send an HSBType state update. no filter applied for HUE & Saturation
if ((hue != null) || (saturation != null)) {
if (baseItem instanceof ColorItem) {
sendHSBCommand((ColorItem) item, hue, saturation, brightness);
if (baseItem instanceof ColorItem colorItem) {
sendHSBCommand(colorItem, hue, saturation, brightness);
}
} else if ((brightness != null) && (baseItem instanceof DimmerItem)) {
// sends brightness:
@ -132,10 +131,10 @@ public class HomekitOHItemProxy {
if ((dimmerMode == DIMMER_MODE_NORMAL) || (dimmerMode == DIMMER_MODE_FILTER_ON)
|| (brightness.intValue() < 100) || (currentOnState == OnOffType.ON)) {
logger.trace("send Brightness command for item {} with value {}", item, brightness);
if (item instanceof ColorItem) {
sendHSBCommand((ColorItem) item, hue, saturation, brightness);
} else if (item instanceof GroupItem) {
((GroupItem) item).send(brightness);
if (item instanceof ColorItem colorItem) {
sendHSBCommand(colorItem, hue, saturation, brightness);
} else if (item instanceof GroupItem groupItem) {
groupItem.send(brightness);
} else {
((DimmerItem) item).send(brightness);
}
@ -152,8 +151,8 @@ public class HomekitOHItemProxy {
final PercentType targetSaturation = saturation != null ? saturation : currentState.getSaturation();
final PercentType targetBrightness = brightness != null ? brightness : currentState.getBrightness();
final HSBType command = new HSBType(targetHue, targetSaturation, targetBrightness);
if (item instanceof GroupItem) {
((GroupItem) item).send(command);
if (item instanceof GroupItem groupItem) {
groupItem.send(command);
} else {
((ColorItem) item).send(command);
}

@ -112,8 +112,8 @@ public class HomekitTaggedItem {
}
public boolean isGroup() {
return (isAccessory() && (proxyItem.getItem() instanceof GroupItem)
&& ((GroupItem) proxyItem.getItem()).getBaseItem() == null);
return (isAccessory() && (proxyItem.getItem() instanceof GroupItem groupItem)
&& groupItem.getBaseItem() == null);
}
public HomekitAccessoryType getAccessoryType() {
@ -177,11 +177,11 @@ public class HomekitTaggedItem {
* @param command
*/
public void send(DecimalType command) {
if (getItem() instanceof GroupItem && getBaseItem() instanceof NumberItem) {
((GroupItem) getItem()).send(command);
if (getItem() instanceof GroupItem groupItem && getBaseItem() instanceof NumberItem) {
groupItem.send(command);
return;
} else if (getItem() instanceof NumberItem) {
((NumberItem) getItem()).send(command);
} else if (getItem() instanceof NumberItem numberItem) {
numberItem.send(command);
return;
}
logger.warn("Received DecimalType command for item {} that doesn't support it. This is probably a bug.",
@ -194,11 +194,11 @@ public class HomekitTaggedItem {
* @param command
*/
public void send(QuantityType command) {
if (getItem() instanceof GroupItem && getBaseItem() instanceof NumberItem) {
((GroupItem) getItem()).send(command);
if (getItem() instanceof GroupItem groupItem && getBaseItem() instanceof NumberItem) {
groupItem.send(command);
return;
} else if (getItem() instanceof NumberItem) {
((NumberItem) getItem()).send(command);
} else if (getItem() instanceof NumberItem numberItem) {
numberItem.send(command);
return;
}
logger.warn("Received QuantityType command for item {} that doesn't support it. This is probably a bug.",
@ -211,11 +211,11 @@ public class HomekitTaggedItem {
* @param command
*/
public void send(OnOffType command) {
if (getItem() instanceof GroupItem && getBaseItem() instanceof SwitchItem) {
((GroupItem) getItem()).send(command);
if (getItem() instanceof GroupItem groupItem && getBaseItem() instanceof SwitchItem) {
groupItem.send(command);
return;
} else if (getItem() instanceof SwitchItem) {
((SwitchItem) getItem()).send(command);
} else if (getItem() instanceof SwitchItem switchItem) {
switchItem.send(command);
return;
}
logger.warn("Received OnOffType command for item {} that doesn't support it. This is probably a bug.",
@ -226,11 +226,11 @@ public class HomekitTaggedItem {
* Send IncreaseDecreaseType command to a DimmerItem (or a Group:Dimmer)
*/
public void send(IncreaseDecreaseType command) {
if (getItem() instanceof GroupItem && getBaseItem() instanceof DimmerItem) {
((GroupItem) getItem()).send(command);
if (getItem() instanceof GroupItem groupItem && getBaseItem() instanceof DimmerItem) {
groupItem.send(command);
return;
} else if (getItem() instanceof DimmerItem) {
((DimmerItem) getItem()).send(command);
} else if (getItem() instanceof DimmerItem dimmerItem) {
dimmerItem.send(command);
return;
}
logger.warn(
@ -244,15 +244,15 @@ public class HomekitTaggedItem {
* @param command
*/
public void send(PercentType command) {
if (getItem() instanceof GroupItem
if (getItem() instanceof GroupItem groupItem
&& (getBaseItem() instanceof DimmerItem || getBaseItem() instanceof RollershutterItem)) {
((GroupItem) getItem()).send(command);
groupItem.send(command);
return;
} else if (getItem() instanceof DimmerItem) {
((DimmerItem) getItem()).send(command);
} else if (getItem() instanceof DimmerItem dimmerItem) {
dimmerItem.send(command);
return;
} else if (getItem() instanceof RollershutterItem) {
((RollershutterItem) getItem()).send(command);
} else if (getItem() instanceof RollershutterItem rollerShutterItem) {
rollerShutterItem.send(command);
return;
}
logger.warn("Received PercentType command for item {} that doesn't support it. This is probably a bug.",
@ -265,11 +265,11 @@ public class HomekitTaggedItem {
* @param command
*/
public void send(StringType command) {
if (getItem() instanceof GroupItem && getBaseItem() instanceof StringItem) {
((GroupItem) getItem()).send(command);
if (getItem() instanceof GroupItem groupItem && getBaseItem() instanceof StringItem) {
groupItem.send(command);
return;
} else if (getItem() instanceof StringItem) {
((StringItem) getItem()).send(command);
} else if (getItem() instanceof StringItem stringItem) {
stringItem.send(command);
return;
}
logger.warn("Received StringType command for item {} that doesn't support it. This is probably a bug.",
@ -350,8 +350,8 @@ public class HomekitTaggedItem {
return (T) value;
}
// fix for different handling of numbers via .items and via mainUI, see #1904
if ((value instanceof BigDecimal) && (defaultValue instanceof Double)) {
return (T) Double.valueOf(((BigDecimal) value).doubleValue());
if ((value instanceof BigDecimal valueAsBigDecimal) && (defaultValue instanceof Double)) {
return (T) Double.valueOf(valueAsBigDecimal.doubleValue());
}
if ((value instanceof Double) && (defaultValue instanceof BigDecimal)) {
return (T) BigDecimal.valueOf(((Double) value).doubleValue());
@ -386,12 +386,11 @@ public class HomekitTaggedItem {
if (value == null) {
return defaultValue;
}
if (value instanceof Boolean) {
return (Boolean) value;
if (value instanceof Boolean valueAsBoolean) {
return valueAsBoolean;
}
if (value instanceof String) {
final String valueString = (String) value;
return valueString.equalsIgnoreCase("yes") || valueString.equalsIgnoreCase("true");
if (value instanceof String valueString) {
return "yes".equalsIgnoreCase(valueString) || "true".equalsIgnoreCase(valueString);
}
return defaultValue;
}
@ -451,7 +450,7 @@ public class HomekitTaggedItem {
// not convertible? just assume it's in the item's unit
if (convertedValue == null) {
Unit unit;
if (getBaseItem() instanceof NumberItem && (unit = ((NumberItem) getBaseItem()).getUnit()) != null) {
if (getBaseItem() instanceof NumberItem numberItem && (unit = numberItem.getUnit()) != null) {
var bdValue = new BigDecimal(stringValue);
parsedValue = new QuantityType(bdValue, unit);
if (relativeConversion) {
@ -474,12 +473,12 @@ public class HomekitTaggedItem {
private void parseConfiguration() {
if (configuration != null) {
final @Nullable Object dimmerModeConfig = configuration.get(DIMMER_MODE);
if (dimmerModeConfig instanceof String) {
HomekitDimmerMode.valueOfTag((String) dimmerModeConfig).ifPresent(proxyItem::setDimmerMode);
if (dimmerModeConfig instanceof String dimmerModeConfigAsString) {
HomekitDimmerMode.valueOfTag(dimmerModeConfigAsString).ifPresent(proxyItem::setDimmerMode);
}
final @Nullable Object delayConfig = configuration.get(DELAY);
if (delayConfig instanceof Number) {
proxyItem.setDelay(((Number) delayConfig).intValue());
if (delayConfig instanceof Number delayConfigNumber) {
proxyItem.setDelay(delayConfigNumber.intValue());
}
}
}

@ -218,7 +218,6 @@ public abstract class AbstractHomekitAccessoryImpl implements HomekitAccessory {
} else {
logger.warn("Mandatory characteristic {} not found at accessory {}. ", characteristic,
accessory.getItem().getName());
}
return Optional.empty();
}

@ -87,20 +87,20 @@ abstract class AbstractHomekitPositionAccessoryImpl extends AbstractHomekitAcces
getCharacteristic(TARGET_POSITION).ifPresentOrElse(taggedItem -> {
final Item item = taggedItem.getItem();
final int targetPosition = convertPosition(value, openPosition);
if (item instanceof RollershutterItem) {
if (item instanceof RollershutterItem itemAsRollerShutterItem) {
// HomeKit home app never sends STOP. we emulate stop if we receive 100% or 0% while the blind is moving
if (emulateState && (targetPosition == 100 && emulatedState == PositionStateEnum.DECREASING)
|| ((targetPosition == 0 && emulatedState == PositionStateEnum.INCREASING))) {
if (emulateStopSameDirection) {
// some blinds devices do not support "STOP" but would stop if receive UP/DOWN while moving
((RollershutterItem) item)
itemAsRollerShutterItem
.send(emulatedState == PositionStateEnum.INCREASING ? UpDownType.UP : UpDownType.DOWN);
} else {
((RollershutterItem) item).send(StopMoveType.STOP);
itemAsRollerShutterItem.send(StopMoveType.STOP);
}
emulatedState = PositionStateEnum.STOPPED;
} else {
((RollershutterItem) item).send(new PercentType(targetPosition));
itemAsRollerShutterItem.send(new PercentType(targetPosition));
if (emulateState) {
@Nullable
PercentType currentPosition = item.getStateAs(PercentType.class);
@ -110,16 +110,19 @@ abstract class AbstractHomekitPositionAccessoryImpl extends AbstractHomekitAcces
: PositionStateEnum.DECREASING;
}
}
} else if (item instanceof DimmerItem) {
((DimmerItem) item).send(new PercentType(targetPosition));
} else if (item instanceof NumberItem) {
((NumberItem) item).send(new DecimalType(targetPosition));
} else if (item instanceof GroupItem && ((GroupItem) item).getBaseItem() instanceof RollershutterItem) {
((GroupItem) item).send(new PercentType(targetPosition));
} else if (item instanceof GroupItem && ((GroupItem) item).getBaseItem() instanceof DimmerItem) {
((GroupItem) item).send(new PercentType(targetPosition));
} else if (item instanceof GroupItem && ((GroupItem) item).getBaseItem() instanceof NumberItem) {
((GroupItem) item).send(new DecimalType(targetPosition));
} else if (item instanceof DimmerItem itemAsDimmerItem) {
itemAsDimmerItem.send(new PercentType(targetPosition));
} else if (item instanceof NumberItem itemAsNumberItem) {
itemAsNumberItem.send(new DecimalType(targetPosition));
} else if (item instanceof GroupItem itemAsGroupItem
&& itemAsGroupItem.getBaseItem() instanceof RollershutterItem) {
itemAsGroupItem.send(new PercentType(targetPosition));
} else if (item instanceof GroupItem itemAsGroupItem
&& itemAsGroupItem.getBaseItem() instanceof DimmerItem) {
itemAsGroupItem.send(new PercentType(targetPosition));
} else if (item instanceof GroupItem itemAsGroupItem
&& itemAsGroupItem.getBaseItem() instanceof NumberItem) {
itemAsGroupItem.send(new DecimalType(targetPosition));
} else {
logger.warn(
"Unsupported item type for characteristic {} at accessory {}. Expected Rollershutter, Dimmer or Number item, got {}",

@ -100,11 +100,11 @@ public class BooleanItemReader {
} else if (state instanceof StringType) {
return state.toString().equalsIgnoreCase("Open") || state.toString().equalsIgnoreCase("Opened");
} else if (localTrueThresheold != null) {
if (state instanceof DecimalType) {
final boolean result = ((DecimalType) state).toBigDecimal().compareTo(localTrueThresheold) > 0;
if (state instanceof DecimalType stateAsDecimalType) {
final boolean result = stateAsDecimalType.toBigDecimal().compareTo(localTrueThresheold) > 0;
return result ^ invertThreshold;
} else if (state instanceof QuantityType) {
final boolean result = ((QuantityType<?>) state).toBigDecimal().compareTo(localTrueThresheold) > 0;
} else if (state instanceof QuantityType stateAsQuantityType) {
final boolean result = stateAsQuantityType.toBigDecimal().compareTo(localTrueThresheold) > 0;
return result ^ invertThreshold;
}
}
@ -118,10 +118,10 @@ public class BooleanItemReader {
}
void setValue(Boolean value) {
if (item instanceof SwitchItem) {
((SwitchItem) item).send(value ? trueOnOffValue : getOffValue(trueOnOffValue));
} else if (item instanceof GroupItem) {
((GroupItem) item).send(value ? trueOnOffValue : getOffValue(trueOnOffValue));
if (item instanceof SwitchItem switchItem) {
switchItem.send(value ? trueOnOffValue : getOffValue(trueOnOffValue));
} else if (item instanceof GroupItem groupItem) {
groupItem.send(value ? trueOnOffValue : getOffValue(trueOnOffValue));
} else {
logger.debug("Cannot set value {} for item {}. Only Switch and Group items are supported.", value, item);
}

@ -62,7 +62,7 @@ import io.github.hapjava.characteristics.impl.common.NameCharacteristic;
*/
@NonNullByDefault
public class HomekitAccessoryFactory {
private static final Logger logger = LoggerFactory.getLogger(HomekitAccessoryFactory.class);
private static final Logger LOGGER = LoggerFactory.getLogger(HomekitAccessoryFactory.class);
public static final String METADATA_KEY = "homekit"; // prefix for HomeKit meta information in items.xml
/** List of mandatory attributes for each accessory type. **/
@ -192,12 +192,12 @@ public class HomekitAccessoryFactory {
HomekitAccessoryUpdater updater, HomekitSettings settings, Set<HomekitTaggedItem> ancestorServices)
throws HomekitException {
final HomekitAccessoryType accessoryType = taggedItem.getAccessoryType();
logger.trace("Constructing {} of accessory type {}", taggedItem.getName(), accessoryType.getTag());
LOGGER.trace("Constructing {} of accessory type {}", taggedItem.getName(), accessoryType.getTag());
final List<HomekitTaggedItem> foundCharacteristics = getMandatoryCharacteristicsFromItem(taggedItem,
metadataRegistry);
final List<HomekitCharacteristicType> mandatoryCharacteristics = getRequiredCharacteristics(taggedItem);
if (foundCharacteristics.size() < mandatoryCharacteristics.size()) {
logger.warn("Accessory of type {} must have following characteristics {}. Found only {}",
LOGGER.warn("Accessory of type {} must have following characteristics {}. Found only {}",
accessoryType.getTag(), mandatoryCharacteristics, foundCharacteristics);
throw new HomekitException("Missing mandatory characteristics");
}
@ -207,7 +207,7 @@ public class HomekitAccessoryFactory {
.get(accessoryType);
if (accessoryImplClass != null) {
if (ancestorServices.contains(taggedItem)) {
logger.warn("Item {} has already been created. Perhaps you have circular Homekit accessory groups?",
LOGGER.warn("Item {} has already been created. Perhaps you have circular Homekit accessory groups?",
taggedItem.getName());
throw new HomekitException("Circular accessory references");
}
@ -221,12 +221,12 @@ public class HomekitAccessoryFactory {
addLinkedServices(taggedItem, accessoryImpl, metadataRegistry, updater, settings, ancestorServices);
return accessoryImpl;
} else {
logger.warn("Unsupported HomeKit type: {}", accessoryType.getTag());
LOGGER.warn("Unsupported HomeKit type: {}", accessoryType.getTag());
throw new HomekitException("Unsupported HomeKit type: " + accessoryType);
}
} catch (NoSuchMethodException | IllegalAccessException | InstantiationException
| InvocationTargetException e) {
logger.warn("Cannot instantiate accessory implementation for accessory {}", accessoryType.getTag(), e);
LOGGER.warn("Cannot instantiate accessory implementation for accessory {}", accessoryType.getTag(), e);
throw new HomekitException("Cannot instantiate accessory implementation for accessory " + accessoryType);
}
}
@ -281,9 +281,9 @@ public class HomekitAccessoryFactory {
public static List<GroupItem> getAccessoryGroups(Item item, ItemRegistry itemRegistry,
MetadataRegistry metadataRegistry) {
return item.getGroupNames().stream().flatMap(name -> {
final @Nullable Item groupItem = itemRegistry.get(name);
if (groupItem instanceof GroupItem) {
return Stream.of((GroupItem) groupItem);
final @Nullable Item itemFromRegistry = itemRegistry.get(name);
if (itemFromRegistry instanceof GroupItem groupItem) {
return Stream.of(groupItem);
} else {
return Stream.empty();
}
@ -308,7 +308,7 @@ public class HomekitAccessoryFactory {
} else {
addMandatoryCharacteristics(taggedItem, collectedCharacteristics, taggedItem.getItem(), metadataRegistry);
}
logger.trace("Mandatory characteristics: {}", collectedCharacteristics);
LOGGER.trace("Mandatory characteristics: {}", collectedCharacteristics);
return collectedCharacteristics;
}
@ -391,7 +391,7 @@ public class HomekitAccessoryFactory {
accessory.getUpdater());
accessory.addCharacteristic(optionalItem, characteristic);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | HomekitException e) {
logger.warn("Unsupported optional HomeKit characteristic: type {}, characteristic type {}",
LOGGER.warn("Unsupported optional HomeKit characteristic: type {}, characteristic type {}",
accessory.getPrimaryService(), type.getTag());
}
});
@ -449,13 +449,13 @@ public class HomekitAccessoryFactory {
var accessoryTypes = characteristicTypes.stream().filter(HomekitAccessoryFactory::isRootAccessory)
.collect(Collectors.toList());
logger.trace("accessory types for {} are {}", groupMember.getName(), accessoryTypes);
LOGGER.trace("accessory types for {} are {}", groupMember.getName(), accessoryTypes);
if (accessoryTypes.isEmpty()) {
continue;
}
if (accessoryTypes.size() > 1) {
logger.warn("Item {} is a HomeKit sub-accessory, but multiple accessory types are not allowed.",
LOGGER.warn("Item {} is a HomeKit sub-accessory, but multiple accessory types are not allowed.",
groupMember.getName());
continue;
}
@ -463,7 +463,7 @@ public class HomekitAccessoryFactory {
final @Nullable Map<String, Object> itemConfiguration = getItemConfiguration(groupMember, metadataRegistry);
final var accessoryType = accessoryTypes.iterator().next().getKey();
logger.trace("Item {} is a HomeKit sub-accessory of type {}.", groupMember.getName(), accessoryType);
LOGGER.trace("Item {} is a HomeKit sub-accessory of type {}.", groupMember.getName(), accessoryType);
final var itemProxy = new HomekitOHItemProxy(groupMember);
final var subTaggedItem = new HomekitTaggedItem(itemProxy, accessoryType, itemConfiguration);
final var subAccessory = create(subTaggedItem, metadataRegistry, updater, settings, ancestorServices);
@ -507,7 +507,7 @@ public class HomekitAccessoryFactory {
.forEach(characteristic -> characteristicItems.put(characteristic.getValue(),
(GenericItem) taggedItem.getItem()));
}
logger.trace("Optional characteristics for item {}: {}", taggedItem.getName(), characteristicItems.values());
LOGGER.trace("Optional characteristics for item {}: {}", taggedItem.getName(), characteristicItems.values());
return Collections.unmodifiableMap(characteristicItems);
}

@ -151,7 +151,6 @@ import io.github.hapjava.characteristics.impl.windowcovering.CurrentVerticalTilt
import io.github.hapjava.characteristics.impl.windowcovering.HoldPositionCharacteristic;
import io.github.hapjava.characteristics.impl.windowcovering.TargetHorizontalTiltAngleCharacteristic;
import io.github.hapjava.characteristics.impl.windowcovering.TargetVerticalTiltAngleCharacteristic;
import tech.units.indriya.unit.UnitDimension;
/**
* Creates an optional characteristics .
@ -160,10 +159,10 @@ import tech.units.indriya.unit.UnitDimension;
*/
@NonNullByDefault
public class HomekitCharacteristicFactory {
private static final Logger logger = LoggerFactory.getLogger(HomekitCharacteristicFactory.class);
private static final Logger LOGGER = LoggerFactory.getLogger(HomekitCharacteristicFactory.class);
// List of optional characteristics and corresponding method to create them.
private static final Map<HomekitCharacteristicType, BiFunction<HomekitTaggedItem, HomekitAccessoryUpdater, Characteristic>> optional = new HashMap<HomekitCharacteristicType, BiFunction<HomekitTaggedItem, HomekitAccessoryUpdater, Characteristic>>() {
private static final Map<HomekitCharacteristicType, BiFunction<HomekitTaggedItem, HomekitAccessoryUpdater, Characteristic>> OPTIONAL = new HashMap<HomekitCharacteristicType, BiFunction<HomekitTaggedItem, HomekitAccessoryUpdater, Characteristic>>() {
{
put(NAME, HomekitCharacteristicFactory::createNameCharacteristic);
put(BATTERY_LOW_STATUS, HomekitCharacteristicFactory::createStatusLowBatteryCharacteristic);
@ -234,9 +233,9 @@ public class HomekitCharacteristicFactory {
public static @Nullable Characteristic createNullableCharacteristic(HomekitTaggedItem item,
HomekitAccessoryUpdater updater) {
final @Nullable HomekitCharacteristicType type = item.getCharacteristicType();
logger.trace("Create characteristic {}", item);
if (optional.containsKey(type)) {
return optional.get(type).apply(item, updater);
LOGGER.trace("Create characteristic {}", item);
if (OPTIONAL.containsKey(type)) {
return OPTIONAL.get(type).apply(item, updater);
}
return null;
}
@ -255,7 +254,7 @@ public class HomekitCharacteristicFactory {
return characteristic;
}
final @Nullable HomekitCharacteristicType type = item.getCharacteristicType();
logger.warn("Unsupported optional characteristic from item {}. Accessory type {}, characteristic type {}",
LOGGER.warn("Unsupported optional characteristic from item {}. Accessory type {}, characteristic type {}",
item.getName(), item.getAccessoryType(), type.getTag());
throw new HomekitException(
"Unsupported optional characteristic. Characteristic type \"" + type.getTag() + "\"");
@ -328,7 +327,7 @@ public class HomekitCharacteristicFactory {
}
});
}
logger.debug("Created {} mapping for item {} ({}): {}", klazz.getSimpleName(), item.getName(),
LOGGER.debug("Created {} mapping for item {} ({}): {}", klazz.getSimpleName(), item.getName(),
item.getBaseItem().getClass().getSimpleName(), map);
return map;
}
@ -355,7 +354,7 @@ public class HomekitCharacteristicFactory {
*/
public static <T> T getKeyFromMapping(HomekitTaggedItem item, Map<T, String> mapping, T defaultValue) {
final State state = item.getItem().getState();
logger.trace("getKeyFromMapping: characteristic {}, state {}, mapping {}", item.getAccessoryType().getTag(),
LOGGER.trace("getKeyFromMapping: characteristic {}, state {}, mapping {}", item.getAccessoryType().getTag(),
state, mapping);
String value;
@ -370,7 +369,7 @@ public class HomekitCharacteristicFactory {
// We specifically want DecimalType, but _not_ PercentType or HSBType, so don't use instanceof
value = Integer.toString(((DecimalType) state).intValue());
} else {
logger.warn(
LOGGER.warn(
"Wrong value type {} ({}) for {} characteristic of the item {}. Expected StringItem, NumberItem, or SwitchItem.",
state.toString(), state.getClass().getSimpleName(), item.getAccessoryType().getTag(),
item.getName());
@ -379,7 +378,7 @@ public class HomekitCharacteristicFactory {
return mapping.entrySet().stream().filter(entry -> value.equalsIgnoreCase(entry.getValue())).findAny()
.map(Map.Entry::getKey).orElseGet(() -> {
logger.warn(
LOGGER.warn(
"Wrong value {} for {} characteristic of the item {}. Expected one of following {}. Returning {}.",
state.toString(), item.getAccessoryType().getTag(), item.getName(), mapping.values(),
defaultValue);
@ -414,15 +413,15 @@ public class HomekitCharacteristicFactory {
private static int getIntFromItem(HomekitTaggedItem taggedItem, int defaultValue) {
int value = defaultValue;
final State state = taggedItem.getItem().getState();
if (state instanceof PercentType) {
value = ((PercentType) state).intValue();
} else if (state instanceof DecimalType) {
value = ((DecimalType) state).intValue();
if (state instanceof PercentType stateAsPercentType) {
value = stateAsPercentType.intValue();
} else if (state instanceof DecimalType stateAsDecimalType) {
value = stateAsDecimalType.intValue();
} else if (state instanceof UnDefType) {
logger.debug("Item state {} is UNDEF {}. Returning default value {}", state, taggedItem.getName(),
LOGGER.debug("Item state {} is UNDEF {}. Returning default value {}", state, taggedItem.getName(),
defaultValue);
} else {
logger.warn(
LOGGER.warn(
"Item state {} is not supported for {}. Only PercentType and DecimalType (0/100) are supported.",
state, taggedItem.getName());
}
@ -433,8 +432,8 @@ public class HomekitCharacteristicFactory {
private static int getAngleFromItem(HomekitTaggedItem taggedItem, int defaultValue) {
int value = defaultValue;
final State state = taggedItem.getItem().getState();
if (state instanceof PercentType) {
value = (int) ((((PercentType) state).intValue() * 90.0) / 50.0 - 90.0);
if (state instanceof PercentType stateAsPercentType) {
value = (int) ((stateAsPercentType.intValue() * 90.0) / 50.0 - 90.0);
} else {
value = getIntFromItem(taggedItem, defaultValue);
}
@ -451,9 +450,8 @@ public class HomekitCharacteristicFactory {
return null;
}
if (state instanceof QuantityType<?>) {
final QuantityType<?> qt = (QuantityType<?>) state;
if (qt.getDimension().equals(UnitDimension.TEMPERATURE)) {
if (state instanceof QuantityType<?> qt) {
if (qt.getDimension().equals(SIUnits.CELSIUS.getDimension())) {
return qt.toUnit(SIUnits.CELSIUS).doubleValue();
}
}
@ -488,7 +486,7 @@ public class HomekitCharacteristicFactory {
if (taggedItem.getBaseItem() instanceof NumberItem) {
taggedItem.send(new DecimalType(value));
} else {
logger.warn("Item type {} is not supported for {}. Only NumberItem is supported.",
LOGGER.warn("Item type {} is not supported for {}. Only NumberItem is supported.",
taggedItem.getBaseItem().getType(), taggedItem.getName());
}
};
@ -501,7 +499,7 @@ public class HomekitCharacteristicFactory {
} else if (taggedItem.getBaseItem() instanceof DimmerItem) {
taggedItem.send(new PercentType(value));
} else {
logger.warn("Item type {} is not supported for {}. Only DimmerItem and NumberItem are supported.",
LOGGER.warn("Item type {} is not supported for {}. Only DimmerItem and NumberItem are supported.",
taggedItem.getBaseItem().getType(), taggedItem.getName());
}
};
@ -515,7 +513,7 @@ public class HomekitCharacteristicFactory {
value = (int) (value * 50.0 / 90.0 + 50.0);
taggedItem.send(new PercentType(value));
} else {
logger.warn("Item type {} is not supported for {}. Only DimmerItem and NumberItem are supported.",
LOGGER.warn("Item type {} is not supported for {}. Only DimmerItem and NumberItem are supported.",
taggedItem.getBaseItem().getType(), taggedItem.getName());
}
};
@ -526,12 +524,12 @@ public class HomekitCharacteristicFactory {
return () -> {
final State state = taggedItem.getItem().getState();
double value = defaultValue;
if (state instanceof PercentType) {
value = ((PercentType) state).doubleValue();
} else if (state instanceof DecimalType) {
value = ((DecimalType) state).doubleValue();
} else if (state instanceof QuantityType) {
value = ((QuantityType) state).doubleValue();
if (state instanceof PercentType stateAsPercentType) {
value = stateAsPercentType.doubleValue();
} else if (state instanceof DecimalType stateAsDecimalType) {
value = stateAsDecimalType.doubleValue();
} else if (state instanceof QuantityType stateAsQuantityType) {
value = stateAsQuantityType.doubleValue();
}
return CompletableFuture.completedFuture(value);
};
@ -544,7 +542,7 @@ public class HomekitCharacteristicFactory {
} else if (taggedItem.getBaseItem() instanceof DimmerItem) {
taggedItem.send(new PercentType(value.intValue()));
} else {
logger.warn("Item type {} is not supported for {}. Only Number and Dimmer type are supported.",
LOGGER.warn("Item type {} is not supported for {}. Only Number and Dimmer type are supported.",
taggedItem.getBaseItem().getType(), taggedItem.getName());
}
};
@ -563,7 +561,7 @@ public class HomekitCharacteristicFactory {
if (taggedItem.getBaseItem() instanceof NumberItem) {
taggedItem.send(new DecimalType(convertFromCelsius(value)));
} else {
logger.warn("Item type {} is not supported for {}. Only Number type is supported.",
LOGGER.warn("Item type {} is not supported for {}. Only Number type is supported.",
taggedItem.getBaseItem().getType(), taggedItem.getName());
}
};
@ -638,7 +636,7 @@ public class HomekitCharacteristicFactory {
HomekitAccessoryUpdater updater) {
final Item item = taggedItem.getBaseItem();
if (!(item instanceof SwitchItem || item instanceof RollershutterItem)) {
logger.warn(
LOGGER.warn(
"Item {} cannot be used for the HoldPosition characteristic; only SwitchItem and RollershutterItem are supported. Hold requests will be ignored.",
item.getName());
}
@ -648,10 +646,10 @@ public class HomekitCharacteristicFactory {
return;
}
if (item instanceof SwitchItem) {
((SwitchItem) item).send(OnOffType.ON);
} else if (item instanceof RollershutterItem) {
((RollershutterItem) item).send(StopMoveType.STOP);
if (item instanceof SwitchItem switchItem) {
switchItem.send(OnOffType.ON);
} else if (item instanceof RollershutterItem rollerShutterItem) {
rollerShutterItem.send(StopMoveType.STOP);
}
});
}
@ -743,15 +741,15 @@ public class HomekitCharacteristicFactory {
return new HueCharacteristic(() -> {
double value = 0.0;
State state = taggedItem.getItem().getState();
if (state instanceof HSBType) {
value = ((HSBType) state).getHue().doubleValue();
if (state instanceof HSBType stateAsHSBType) {
value = stateAsHSBType.getHue().doubleValue();
}
return CompletableFuture.completedFuture(value);
}, (hue) -> {
if (taggedItem.getBaseItem() instanceof ColorItem) {
taggedItem.sendCommandProxy(HomekitCommandType.HUE_COMMAND, new DecimalType(hue));
} else {
logger.warn("Item type {} is not supported for {}. Only Color type is supported.",
LOGGER.warn("Item type {} is not supported for {}. Only Color type is supported.",
taggedItem.getBaseItem().getType(), taggedItem.getName());
}
}, getSubscriber(taggedItem, HUE, updater), getUnsubscriber(taggedItem, HUE, updater));
@ -762,17 +760,17 @@ public class HomekitCharacteristicFactory {
return new BrightnessCharacteristic(() -> {
int value = 0;
final State state = taggedItem.getItem().getState();
if (state instanceof HSBType) {
value = ((HSBType) state).getBrightness().intValue();
} else if (state instanceof PercentType) {
value = ((PercentType) state).intValue();
if (state instanceof HSBType stateAsHSBType) {
value = stateAsHSBType.getBrightness().intValue();
} else if (state instanceof PercentType stateAsPercentType) {
value = stateAsPercentType.intValue();
}
return CompletableFuture.completedFuture(value);
}, (brightness) -> {
if (taggedItem.getBaseItem() instanceof DimmerItem) {
taggedItem.sendCommandProxy(HomekitCommandType.BRIGHTNESS_COMMAND, new PercentType(brightness));
} else {
logger.warn("Item type {} is not supported for {}. Only ColorItem and DimmerItem are supported.",
LOGGER.warn("Item type {} is not supported for {}. Only ColorItem and DimmerItem are supported.",
taggedItem.getBaseItem().getType(), taggedItem.getName());
}
}, getSubscriber(taggedItem, BRIGHTNESS, updater), getUnsubscriber(taggedItem, BRIGHTNESS, updater));
@ -783,10 +781,10 @@ public class HomekitCharacteristicFactory {
return new SaturationCharacteristic(() -> {
double value = 0.0;
State state = taggedItem.getItem().getState();
if (state instanceof HSBType) {
value = ((HSBType) state).getSaturation().doubleValue();
} else if (state instanceof PercentType) {
value = ((PercentType) state).doubleValue();
if (state instanceof HSBType stateAsHSBType) {
value = stateAsHSBType.getSaturation().doubleValue();
} else if (state instanceof PercentType stateAsPercentType) {
value = stateAsPercentType.doubleValue();
}
return CompletableFuture.completedFuture(value);
}, (saturation) -> {
@ -794,7 +792,7 @@ public class HomekitCharacteristicFactory {
taggedItem.sendCommandProxy(HomekitCommandType.SATURATION_COMMAND,
new PercentType(saturation.intValue()));
} else {
logger.warn("Item type {} is not supported for {}. Only Color type is supported.",
LOGGER.warn("Item type {} is not supported for {}. Only Color type is supported.",
taggedItem.getBaseItem().getType(), taggedItem.getName());
}
}, getSubscriber(taggedItem, SATURATION, updater), getUnsubscriber(taggedItem, SATURATION, updater));
@ -826,17 +824,16 @@ public class HomekitCharacteristicFactory {
return new ColorTemperatureCharacteristic(minValue, maxValue, () -> {
int value = finalMinValue;
final State state = taggedItem.getItem().getState();
if (state instanceof QuantityType<?>) {
if (state instanceof QuantityType<?> qt) {
// Number:Temperature
QuantityType<?> qt = (QuantityType<?>) state;
qt = qt.toInvertibleUnit(Units.MIRED);
if (qt == null) {
logger.warn("Item {}'s state '{}' is not convertible to mireds.", taggedItem.getName(), state);
LOGGER.warn("Item {}'s state '{}' is not convertible to mireds.", taggedItem.getName(), state);
} else {
value = qt.intValue();
}
} else if (state instanceof PercentType) {
double percent = ((PercentType) state).doubleValue();
} else if (state instanceof PercentType stateAsPercentType) {
double percent = stateAsPercentType.doubleValue();
// invert so that 0% == coolest
if (inverted) {
percent = 100.0 - percent;
@ -845,8 +842,8 @@ public class HomekitCharacteristicFactory {
// Dimmer
// scale to the originally configured range
value = (int) (percent * range / 100) + finalMinValue;
} else if (state instanceof DecimalType) {
value = ((DecimalType) state).intValue();
} else if (state instanceof DecimalType stateAsDecimalType) {
value = stateAsDecimalType.intValue();
}
return CompletableFuture.completedFuture(value);
}, (value) -> {
@ -927,10 +924,10 @@ public class HomekitCharacteristicFactory {
final @Nullable Map<String, Object> itemConfiguration = taggedItem.getConfiguration();
if ((value == 0) && (itemConfiguration != null)) { // check for default duration
final Object duration = itemConfiguration.get(HomekitValveImpl.CONFIG_DEFAULT_DURATION);
if (duration instanceof BigDecimal) {
value = ((BigDecimal) duration).intValue();
if (taggedItem.getItem() instanceof NumberItem) {
((NumberItem) taggedItem.getItem()).setState(new DecimalType(value));
if (duration instanceof BigDecimal durationAsBigDecimal) {
value = durationAsBigDecimal.intValue();
if (taggedItem.getItem() instanceof NumberItem taggedNumberItem) {
taggedNumberItem.setState(new DecimalType(value));
}
}
}

@ -25,8 +25,6 @@ import java.util.function.Supplier;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.io.homekit.internal.HomekitCharacteristicType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.github.hapjava.characteristics.Characteristic;
import io.github.hapjava.characteristics.impl.airquality.AirQualityCharacteristic;
@ -70,10 +68,9 @@ import io.github.hapjava.characteristics.impl.thermostat.TargetHeatingCoolingSta
*/
@NonNullByDefault
public class HomekitMetadataCharacteristicFactory {
private static final Logger logger = LoggerFactory.getLogger(HomekitMetadataCharacteristicFactory.class);
// List of optional characteristics that can be set via metadata, and the corresponding method to create them.
private static final Map<HomekitCharacteristicType, Function<Object, Characteristic>> optional = new HashMap<>() {
private static final Map<HomekitCharacteristicType, Function<Object, Characteristic>> OPTIONAL = new HashMap<>() {
{
put(ACTIVE_IDENTIFIER, HomekitMetadataCharacteristicFactory::createActiveIdentifierCharacteristic);
put(ACTIVE_STATUS, HomekitMetadataCharacteristicFactory::createActiveStatusCharacteristic);
@ -103,16 +100,16 @@ public class HomekitMetadataCharacteristicFactory {
public static Optional<Characteristic> createCharacteristic(String characteristic, Object value) {
var type = HomekitCharacteristicType.valueOfTag(characteristic);
if (type.isEmpty() || !optional.containsKey(type.get())) {
if (type.isEmpty() || !OPTIONAL.containsKey(type.get())) {
return Optional.empty();
}
return Optional.of(optional.get(type.get()).apply(value));
return Optional.of(OPTIONAL.get(type.get()).apply(value));
}
private static Supplier<CompletableFuture<Integer>> getInteger(Object value) {
int intValue;
if (value instanceof BigDecimal) {
intValue = ((BigDecimal) value).intValue();
if (value instanceof BigDecimal valueAsBigDecimal) {
intValue = valueAsBigDecimal.intValue();
} else if (value instanceof Float) {
intValue = ((Float) value).intValue();
} else if (value instanceof Integer) {