Switch to using constants wherever possible in zwave_js (#56518)

This commit is contained in:
Raman Gupta 2021-09-29 20:21:53 -04:00 committed by GitHub
parent 2ff1fc83bc
commit e9d25974b8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 147 additions and 83 deletions

View File

@ -6,6 +6,10 @@ from typing import TypedDict
from zwave_js_server.client import Client as ZwaveClient from zwave_js_server.client import Client as ZwaveClient
from zwave_js_server.const import CommandClass from zwave_js_server.const import CommandClass
from zwave_js_server.const.command_class.lock import DOOR_STATUS_PROPERTY
from zwave_js_server.const.command_class.notification import (
CC_SPECIFIC_NOTIFICATION_TYPE,
)
from homeassistant.components.binary_sensor import ( from homeassistant.components.binary_sensor import (
DEVICE_CLASS_BATTERY, DEVICE_CLASS_BATTERY,
@ -196,9 +200,6 @@ NOTIFICATION_SENSOR_MAPPINGS: list[NotificationSensorMapping] = [
] ]
PROPERTY_DOOR_STATUS = "doorStatus"
class PropertySensorMapping(TypedDict, total=False): class PropertySensorMapping(TypedDict, total=False):
"""Represent a property sensor mapping dict type.""" """Represent a property sensor mapping dict type."""
@ -211,7 +212,7 @@ class PropertySensorMapping(TypedDict, total=False):
# Mappings for property sensors # Mappings for property sensors
PROPERTY_SENSOR_MAPPINGS: list[PropertySensorMapping] = [ PROPERTY_SENSOR_MAPPINGS: list[PropertySensorMapping] = [
{ {
"property_name": PROPERTY_DOOR_STATUS, "property_name": DOOR_STATUS_PROPERTY,
"on_states": ["open"], "on_states": ["open"],
"device_class": DEVICE_CLASS_DOOR, "device_class": DEVICE_CLASS_DOOR,
"enabled": True, "enabled": True,
@ -327,7 +328,9 @@ class ZWaveNotificationBinarySensor(ZWaveBaseEntity, BinarySensorEntity):
for mapping in NOTIFICATION_SENSOR_MAPPINGS: for mapping in NOTIFICATION_SENSOR_MAPPINGS:
if ( if (
mapping["type"] mapping["type"]
!= self.info.primary_value.metadata.cc_specific["notificationType"] != self.info.primary_value.metadata.cc_specific[
CC_SPECIFIC_NOTIFICATION_TYPE
]
): ):
continue continue
if not mapping.get("states") or self.state_key in mapping["states"]: if not mapping.get("states") or self.state_key in mapping["states"]:

View File

@ -7,6 +7,7 @@ from zwave_js_server.client import Client as ZwaveClient
from zwave_js_server.const import CommandClass from zwave_js_server.const import CommandClass
from zwave_js_server.const.command_class.thermostat import ( from zwave_js_server.const.command_class.thermostat import (
THERMOSTAT_CURRENT_TEMP_PROPERTY, THERMOSTAT_CURRENT_TEMP_PROPERTY,
THERMOSTAT_HUMIDITY_PROPERTY,
THERMOSTAT_MODE_PROPERTY, THERMOSTAT_MODE_PROPERTY,
THERMOSTAT_MODE_SETPOINT_MAP, THERMOSTAT_MODE_SETPOINT_MAP,
THERMOSTAT_MODES, THERMOSTAT_MODES,
@ -176,7 +177,7 @@ class ZWaveClimate(ZWaveBaseEntity, ClimateEntity):
if not self._unit_value: if not self._unit_value:
self._unit_value = self._current_temp self._unit_value = self._current_temp
self._current_humidity = self.get_zwave_value( self._current_humidity = self.get_zwave_value(
"Humidity", THERMOSTAT_HUMIDITY_PROPERTY,
command_class=CommandClass.SENSOR_MULTILEVEL, command_class=CommandClass.SENSOR_MULTILEVEL,
add_to_watched_value_ids=True, add_to_watched_value_ids=True,
check_all_endpoints=True, check_all_endpoints=True,

View File

@ -5,7 +5,16 @@ import logging
from typing import Any from typing import Any
from zwave_js_server.client import Client as ZwaveClient from zwave_js_server.client import Client as ZwaveClient
from zwave_js_server.const import TARGET_STATE_PROPERTY, TARGET_VALUE_PROPERTY
from zwave_js_server.const.command_class.barrier_operator import BarrierState from zwave_js_server.const.command_class.barrier_operator import BarrierState
from zwave_js_server.const.command_class.multilevel_switch import (
COVER_CLOSE_PROPERTY,
COVER_DOWN_PROPERTY,
COVER_OFF_PROPERTY,
COVER_ON_PROPERTY,
COVER_OPEN_PROPERTY,
COVER_UP_PROPERTY,
)
from zwave_js_server.model.value import Value as ZwaveValue from zwave_js_server.model.value import Value as ZwaveValue
from homeassistant.components.cover import ( from homeassistant.components.cover import (
@ -105,36 +114,36 @@ class ZWaveCover(ZWaveBaseEntity, CoverEntity):
async def async_set_cover_position(self, **kwargs: Any) -> None: async def async_set_cover_position(self, **kwargs: Any) -> None:
"""Move the cover to a specific position.""" """Move the cover to a specific position."""
target_value = self.get_zwave_value("targetValue") target_value = self.get_zwave_value(TARGET_VALUE_PROPERTY)
await self.info.node.async_set_value( await self.info.node.async_set_value(
target_value, percent_to_zwave_position(kwargs[ATTR_POSITION]) target_value, percent_to_zwave_position(kwargs[ATTR_POSITION])
) )
async def async_open_cover(self, **kwargs: Any) -> None: async def async_open_cover(self, **kwargs: Any) -> None:
"""Open the cover.""" """Open the cover."""
target_value = self.get_zwave_value("targetValue") target_value = self.get_zwave_value(TARGET_VALUE_PROPERTY)
await self.info.node.async_set_value(target_value, 99) await self.info.node.async_set_value(target_value, 99)
async def async_close_cover(self, **kwargs: Any) -> None: async def async_close_cover(self, **kwargs: Any) -> None:
"""Close cover.""" """Close cover."""
target_value = self.get_zwave_value("targetValue") target_value = self.get_zwave_value(TARGET_VALUE_PROPERTY)
await self.info.node.async_set_value(target_value, 0) await self.info.node.async_set_value(target_value, 0)
async def async_stop_cover(self, **kwargs: Any) -> None: async def async_stop_cover(self, **kwargs: Any) -> None:
"""Stop cover.""" """Stop cover."""
open_value = ( open_value = (
self.get_zwave_value("Open") self.get_zwave_value(COVER_OPEN_PROPERTY)
or self.get_zwave_value("Up") or self.get_zwave_value(COVER_UP_PROPERTY)
or self.get_zwave_value("On") or self.get_zwave_value(COVER_ON_PROPERTY)
) )
if open_value: if open_value:
# Stop the cover if it's opening # Stop the cover if it's opening
await self.info.node.async_set_value(open_value, False) await self.info.node.async_set_value(open_value, False)
close_value = ( close_value = (
self.get_zwave_value("Close") self.get_zwave_value(COVER_CLOSE_PROPERTY)
or self.get_zwave_value("Down") or self.get_zwave_value(COVER_DOWN_PROPERTY)
or self.get_zwave_value("Off") or self.get_zwave_value(COVER_OFF_PROPERTY)
) )
if close_value: if close_value:
# Stop the cover if it's closing # Stop the cover if it's closing
@ -156,7 +165,7 @@ class ZwaveMotorizedBarrier(ZWaveBaseEntity, CoverEntity):
"""Initialize a ZwaveMotorizedBarrier entity.""" """Initialize a ZwaveMotorizedBarrier entity."""
super().__init__(config_entry, client, info) super().__init__(config_entry, client, info)
self._target_state: ZwaveValue = self.get_zwave_value( self._target_state: ZwaveValue = self.get_zwave_value(
"targetState", add_to_watched_value_ids=False TARGET_STATE_PROPERTY, add_to_watched_value_ids=False
) )
@property @property

View File

@ -6,9 +6,32 @@ from dataclasses import asdict, dataclass, field
from typing import Any from typing import Any
from awesomeversion import AwesomeVersion from awesomeversion import AwesomeVersion
from zwave_js_server.const import CommandClass from zwave_js_server.const import (
CURRENT_STATE_PROPERTY,
CURRENT_VALUE_PROPERTY,
TARGET_STATE_PROPERTY,
TARGET_VALUE_PROPERTY,
CommandClass,
)
from zwave_js_server.const.command_class.barrier_operator import (
SIGNALING_STATE_PROPERTY,
)
from zwave_js_server.const.command_class.lock import (
CURRENT_MODE_PROPERTY,
DOOR_STATUS_PROPERTY,
LOCKED_PROPERTY,
)
from zwave_js_server.const.command_class.meter import VALUE_PROPERTY
from zwave_js_server.const.command_class.protection import LOCAL_PROPERTY, RF_PROPERTY
from zwave_js_server.const.command_class.sound_switch import (
DEFAULT_TONE_ID_PROPERTY,
DEFAULT_VOLUME_PROPERTY,
TONE_ID_PROPERTY,
)
from zwave_js_server.const.command_class.thermostat import ( from zwave_js_server.const.command_class.thermostat import (
THERMOSTAT_CURRENT_TEMP_PROPERTY, THERMOSTAT_CURRENT_TEMP_PROPERTY,
THERMOSTAT_MODE_PROPERTY,
THERMOSTAT_SETPOINT_PROPERTY,
) )
from zwave_js_server.exceptions import UnknownValueData from zwave_js_server.exceptions import UnknownValueData
from zwave_js_server.model.device_class import DeviceClassItem from zwave_js_server.model.device_class import DeviceClassItem
@ -179,16 +202,18 @@ def get_config_parameter_discovery_schema(
SWITCH_MULTILEVEL_CURRENT_VALUE_SCHEMA = ZWaveValueDiscoverySchema( SWITCH_MULTILEVEL_CURRENT_VALUE_SCHEMA = ZWaveValueDiscoverySchema(
command_class={CommandClass.SWITCH_MULTILEVEL}, command_class={CommandClass.SWITCH_MULTILEVEL},
property={"currentValue"}, property={CURRENT_VALUE_PROPERTY},
type={"number"}, type={"number"},
) )
SWITCH_BINARY_CURRENT_VALUE_SCHEMA = ZWaveValueDiscoverySchema( SWITCH_BINARY_CURRENT_VALUE_SCHEMA = ZWaveValueDiscoverySchema(
command_class={CommandClass.SWITCH_BINARY}, property={"currentValue"} command_class={CommandClass.SWITCH_BINARY}, property={CURRENT_VALUE_PROPERTY}
) )
SIREN_TONE_SCHEMA = ZWaveValueDiscoverySchema( SIREN_TONE_SCHEMA = ZWaveValueDiscoverySchema(
command_class={CommandClass.SOUND_SWITCH}, property={"toneId"}, type={"number"} command_class={CommandClass.SOUND_SWITCH},
property={TONE_ID_PROPERTY},
type={"number"},
) )
# For device class mapping see: # For device class mapping see:
@ -229,7 +254,7 @@ DISCOVERY_SCHEMAS = [
primary_value=ZWaveValueDiscoverySchema( primary_value=ZWaveValueDiscoverySchema(
command_class={CommandClass.SWITCH_MULTILEVEL}, command_class={CommandClass.SWITCH_MULTILEVEL},
endpoint={2}, endpoint={2},
property={"currentValue"}, property={CURRENT_VALUE_PROPERTY},
type={"number"}, type={"number"},
), ),
), ),
@ -287,7 +312,7 @@ DISCOVERY_SCHEMAS = [
product_type={0x0003}, product_type={0x0003},
primary_value=ZWaveValueDiscoverySchema( primary_value=ZWaveValueDiscoverySchema(
command_class={CommandClass.THERMOSTAT_MODE}, command_class={CommandClass.THERMOSTAT_MODE},
property={"mode"}, property={THERMOSTAT_MODE_PROPERTY},
type={"number"}, type={"number"},
), ),
data_template=DynamicCurrentTempClimateDataTemplate( data_template=DynamicCurrentTempClimateDataTemplate(
@ -334,7 +359,7 @@ DISCOVERY_SCHEMAS = [
firmware_version_range=FirmwareVersionRange(min="3.0"), firmware_version_range=FirmwareVersionRange(min="3.0"),
primary_value=ZWaveValueDiscoverySchema( primary_value=ZWaveValueDiscoverySchema(
command_class={CommandClass.THERMOSTAT_MODE}, command_class={CommandClass.THERMOSTAT_MODE},
property={"mode"}, property={THERMOSTAT_MODE_PROPERTY},
type={"number"}, type={"number"},
), ),
data_template=DynamicCurrentTempClimateDataTemplate( data_template=DynamicCurrentTempClimateDataTemplate(
@ -393,7 +418,7 @@ DISCOVERY_SCHEMAS = [
CommandClass.LOCK, CommandClass.LOCK,
CommandClass.DOOR_LOCK, CommandClass.DOOR_LOCK,
}, },
property={"currentMode", "locked"}, property={CURRENT_MODE_PROPERTY, LOCKED_PROPERTY},
type={"number", "boolean"}, type={"number", "boolean"},
), ),
), ),
@ -406,7 +431,7 @@ DISCOVERY_SCHEMAS = [
CommandClass.LOCK, CommandClass.LOCK,
CommandClass.DOOR_LOCK, CommandClass.DOOR_LOCK,
}, },
property={"doorStatus"}, property={DOOR_STATUS_PROPERTY},
type={"any"}, type={"any"},
), ),
), ),
@ -416,7 +441,7 @@ DISCOVERY_SCHEMAS = [
platform="climate", platform="climate",
primary_value=ZWaveValueDiscoverySchema( primary_value=ZWaveValueDiscoverySchema(
command_class={CommandClass.THERMOSTAT_MODE}, command_class={CommandClass.THERMOSTAT_MODE},
property={"mode"}, property={THERMOSTAT_MODE_PROPERTY},
type={"number"}, type={"number"},
), ),
), ),
@ -425,13 +450,13 @@ DISCOVERY_SCHEMAS = [
platform="climate", platform="climate",
primary_value=ZWaveValueDiscoverySchema( primary_value=ZWaveValueDiscoverySchema(
command_class={CommandClass.THERMOSTAT_SETPOINT}, command_class={CommandClass.THERMOSTAT_SETPOINT},
property={"setpoint"}, property={THERMOSTAT_SETPOINT_PROPERTY},
type={"number"}, type={"number"},
), ),
absent_values=[ # mode must not be present to prevent dupes absent_values=[ # mode must not be present to prevent dupes
ZWaveValueDiscoverySchema( ZWaveValueDiscoverySchema(
command_class={CommandClass.THERMOSTAT_MODE}, command_class={CommandClass.THERMOSTAT_MODE},
property={"mode"}, property={THERMOSTAT_MODE_PROPERTY},
type={"number"}, type={"number"},
), ),
], ],
@ -532,7 +557,7 @@ DISCOVERY_SCHEMAS = [
CommandClass.METER, CommandClass.METER,
}, },
type={"number"}, type={"number"},
property={"value"}, property={VALUE_PROPERTY},
), ),
data_template=NumericSensorDataTemplate(), data_template=NumericSensorDataTemplate(),
), ),
@ -558,7 +583,7 @@ DISCOVERY_SCHEMAS = [
CommandClass.BASIC, CommandClass.BASIC,
}, },
type={"number"}, type={"number"},
property={"currentValue"}, property={CURRENT_VALUE_PROPERTY},
), ),
required_values=[ required_values=[
ZWaveValueDiscoverySchema( ZWaveValueDiscoverySchema(
@ -566,7 +591,7 @@ DISCOVERY_SCHEMAS = [
CommandClass.BASIC, CommandClass.BASIC,
}, },
type={"number"}, type={"number"},
property={"targetValue"}, property={TARGET_VALUE_PROPERTY},
) )
], ],
data_template=NumericSensorDataTemplate(), data_template=NumericSensorDataTemplate(),
@ -584,7 +609,7 @@ DISCOVERY_SCHEMAS = [
hint="barrier_event_signaling_state", hint="barrier_event_signaling_state",
primary_value=ZWaveValueDiscoverySchema( primary_value=ZWaveValueDiscoverySchema(
command_class={CommandClass.BARRIER_OPERATOR}, command_class={CommandClass.BARRIER_OPERATOR},
property={"signalingState"}, property={SIGNALING_STATE_PROPERTY},
type={"number"}, type={"number"},
), ),
), ),
@ -609,13 +634,13 @@ DISCOVERY_SCHEMAS = [
hint="motorized_barrier", hint="motorized_barrier",
primary_value=ZWaveValueDiscoverySchema( primary_value=ZWaveValueDiscoverySchema(
command_class={CommandClass.BARRIER_OPERATOR}, command_class={CommandClass.BARRIER_OPERATOR},
property={"currentState"}, property={CURRENT_STATE_PROPERTY},
type={"number"}, type={"number"},
), ),
required_values=[ required_values=[
ZWaveValueDiscoverySchema( ZWaveValueDiscoverySchema(
command_class={CommandClass.BARRIER_OPERATOR}, command_class={CommandClass.BARRIER_OPERATOR},
property={"targetState"}, property={TARGET_STATE_PROPERTY},
type={"number"}, type={"number"},
), ),
], ],
@ -657,7 +682,7 @@ DISCOVERY_SCHEMAS = [
hint="Default tone", hint="Default tone",
primary_value=ZWaveValueDiscoverySchema( primary_value=ZWaveValueDiscoverySchema(
command_class={CommandClass.SOUND_SWITCH}, command_class={CommandClass.SOUND_SWITCH},
property={"defaultToneId"}, property={DEFAULT_TONE_ID_PROPERTY},
type={"number"}, type={"number"},
), ),
required_values=[SIREN_TONE_SCHEMA], required_values=[SIREN_TONE_SCHEMA],
@ -669,7 +694,7 @@ DISCOVERY_SCHEMAS = [
hint="volume", hint="volume",
primary_value=ZWaveValueDiscoverySchema( primary_value=ZWaveValueDiscoverySchema(
command_class={CommandClass.SOUND_SWITCH}, command_class={CommandClass.SOUND_SWITCH},
property={"defaultVolume"}, property={DEFAULT_VOLUME_PROPERTY},
type={"number"}, type={"number"},
), ),
required_values=[SIREN_TONE_SCHEMA], required_values=[SIREN_TONE_SCHEMA],
@ -680,7 +705,7 @@ DISCOVERY_SCHEMAS = [
platform="select", platform="select",
primary_value=ZWaveValueDiscoverySchema( primary_value=ZWaveValueDiscoverySchema(
command_class={CommandClass.PROTECTION}, command_class={CommandClass.PROTECTION},
property={"local", "rf"}, property={LOCAL_PROPERTY, RF_PROPERTY},
type={"number"}, type={"number"},
), ),
), ),

View File

@ -5,6 +5,7 @@ import math
from typing import Any from typing import Any
from zwave_js_server.client import Client as ZwaveClient from zwave_js_server.client import Client as ZwaveClient
from zwave_js_server.const import TARGET_VALUE_PROPERTY
from homeassistant.components.fan import ( from homeassistant.components.fan import (
DOMAIN as FAN_DOMAIN, DOMAIN as FAN_DOMAIN,
@ -59,7 +60,7 @@ class ZwaveFan(ZWaveBaseEntity, FanEntity):
async def async_set_percentage(self, percentage: int | None) -> None: async def async_set_percentage(self, percentage: int | None) -> None:
"""Set the speed percentage of the fan.""" """Set the speed percentage of the fan."""
target_value = self.get_zwave_value("targetValue") target_value = self.get_zwave_value(TARGET_VALUE_PROPERTY)
if percentage is None: if percentage is None:
# Value 255 tells device to return to previous value # Value 255 tells device to return to previous value
@ -83,7 +84,7 @@ class ZwaveFan(ZWaveBaseEntity, FanEntity):
async def async_turn_off(self, **kwargs: Any) -> None: async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the device off.""" """Turn the device off."""
target_value = self.get_zwave_value("targetValue") target_value = self.get_zwave_value(TARGET_VALUE_PROPERTY)
await self.info.node.async_set_value(target_value, 0) await self.info.node.async_set_value(target_value, 0)
@property @property

View File

@ -5,8 +5,24 @@ import logging
from typing import Any from typing import Any
from zwave_js_server.client import Client as ZwaveClient from zwave_js_server.client import Client as ZwaveClient
from zwave_js_server.const import CommandClass from zwave_js_server.const import (
from zwave_js_server.const.command_class.color_switch import ColorComponent TARGET_VALUE_PROPERTY,
TRANSITION_DURATION_OPTION,
CommandClass,
)
from zwave_js_server.const.command_class.color_switch import (
COLOR_SWITCH_COMBINED_AMBER,
COLOR_SWITCH_COMBINED_BLUE,
COLOR_SWITCH_COMBINED_COLD_WHITE,
COLOR_SWITCH_COMBINED_CYAN,
COLOR_SWITCH_COMBINED_GREEN,
COLOR_SWITCH_COMBINED_PURPLE,
COLOR_SWITCH_COMBINED_RED,
COLOR_SWITCH_COMBINED_WARM_WHITE,
CURRENT_COLOR_PROPERTY,
TARGET_COLOR_PROPERTY,
ColorComponent,
)
from homeassistant.components.light import ( from homeassistant.components.light import (
ATTR_BRIGHTNESS, ATTR_BRIGHTNESS,
@ -35,18 +51,16 @@ from .entity import ZWaveBaseEntity
LOGGER = logging.getLogger(__name__) LOGGER = logging.getLogger(__name__)
MULTI_COLOR_MAP = { MULTI_COLOR_MAP = {
ColorComponent.WARM_WHITE: "warmWhite", ColorComponent.WARM_WHITE: COLOR_SWITCH_COMBINED_WARM_WHITE,
ColorComponent.COLD_WHITE: "coldWhite", ColorComponent.COLD_WHITE: COLOR_SWITCH_COMBINED_COLD_WHITE,
ColorComponent.RED: "red", ColorComponent.RED: COLOR_SWITCH_COMBINED_RED,
ColorComponent.GREEN: "green", ColorComponent.GREEN: COLOR_SWITCH_COMBINED_GREEN,
ColorComponent.BLUE: "blue", ColorComponent.BLUE: COLOR_SWITCH_COMBINED_BLUE,
ColorComponent.AMBER: "amber", ColorComponent.AMBER: COLOR_SWITCH_COMBINED_AMBER,
ColorComponent.CYAN: "cyan", ColorComponent.CYAN: COLOR_SWITCH_COMBINED_CYAN,
ColorComponent.PURPLE: "purple", ColorComponent.PURPLE: COLOR_SWITCH_COMBINED_PURPLE,
} }
TRANSITION_DURATION = "transitionDuration"
async def async_setup_entry( async def async_setup_entry(
hass: HomeAssistant, hass: HomeAssistant,
@ -100,12 +114,12 @@ class ZwaveLight(ZWaveBaseEntity, LightEntity):
self._min_mireds = 153 # 6500K as a safe default self._min_mireds = 153 # 6500K as a safe default
self._max_mireds = 370 # 2700K as a safe default self._max_mireds = 370 # 2700K as a safe default
self._warm_white = self.get_zwave_value( self._warm_white = self.get_zwave_value(
"targetColor", TARGET_COLOR_PROPERTY,
CommandClass.SWITCH_COLOR, CommandClass.SWITCH_COLOR,
value_property_key=ColorComponent.WARM_WHITE, value_property_key=ColorComponent.WARM_WHITE,
) )
self._cold_white = self.get_zwave_value( self._cold_white = self.get_zwave_value(
"targetColor", TARGET_COLOR_PROPERTY,
CommandClass.SWITCH_COLOR, CommandClass.SWITCH_COLOR,
value_property_key=ColorComponent.COLD_WHITE, value_property_key=ColorComponent.COLD_WHITE,
) )
@ -113,10 +127,12 @@ class ZwaveLight(ZWaveBaseEntity, LightEntity):
# get additional (optional) values and set features # get additional (optional) values and set features
self._target_brightness = self.get_zwave_value( self._target_brightness = self.get_zwave_value(
"targetValue", add_to_watched_value_ids=False TARGET_VALUE_PROPERTY, add_to_watched_value_ids=False
) )
self._target_color = self.get_zwave_value( self._target_color = self.get_zwave_value(
"targetColor", CommandClass.SWITCH_COLOR, add_to_watched_value_ids=False TARGET_COLOR_PROPERTY,
CommandClass.SWITCH_COLOR,
add_to_watched_value_ids=False,
) )
self._calculate_color_values() self._calculate_color_values()
@ -133,12 +149,13 @@ class ZwaveLight(ZWaveBaseEntity, LightEntity):
self._attr_supported_features = 0 self._attr_supported_features = 0
self.supports_brightness_transition = bool( self.supports_brightness_transition = bool(
self._target_brightness is not None self._target_brightness is not None
and TRANSITION_DURATION and TRANSITION_DURATION_OPTION
in self._target_brightness.metadata.value_change_options in self._target_brightness.metadata.value_change_options
) )
self.supports_color_transition = bool( self.supports_color_transition = bool(
self._target_color is not None self._target_color is not None
and TRANSITION_DURATION in self._target_color.metadata.value_change_options and TRANSITION_DURATION_OPTION
in self._target_color.metadata.value_change_options
) )
if self.supports_brightness_transition or self.supports_color_transition: if self.supports_brightness_transition or self.supports_color_transition:
@ -284,9 +301,9 @@ class ZwaveLight(ZWaveBaseEntity, LightEntity):
if self.supports_color_transition: if self.supports_color_transition:
if transition is not None: if transition is not None:
zwave_transition = {TRANSITION_DURATION: f"{int(transition)}s"} zwave_transition = {TRANSITION_DURATION_OPTION: f"{int(transition)}s"}
else: else:
zwave_transition = {TRANSITION_DURATION: "default"} zwave_transition = {TRANSITION_DURATION_OPTION: "default"}
colors_dict = {} colors_dict = {}
for color, value in colors.items(): for color, value in colors.items():
@ -312,9 +329,9 @@ class ZwaveLight(ZWaveBaseEntity, LightEntity):
zwave_transition = None zwave_transition = None
if self.supports_brightness_transition: if self.supports_brightness_transition:
if transition is not None: if transition is not None:
zwave_transition = {TRANSITION_DURATION: f"{int(transition)}s"} zwave_transition = {TRANSITION_DURATION_OPTION: f"{int(transition)}s"}
else: else:
zwave_transition = {TRANSITION_DURATION: "default"} zwave_transition = {TRANSITION_DURATION_OPTION: "default"}
# setting a value requires setting targetValue # setting a value requires setting targetValue
await self.info.node.async_set_value( await self.info.node.async_set_value(
@ -328,34 +345,34 @@ class ZwaveLight(ZWaveBaseEntity, LightEntity):
# to find out what colors are supported # to find out what colors are supported
# as this is a simple lookup by key, this not heavy # as this is a simple lookup by key, this not heavy
red_val = self.get_zwave_value( red_val = self.get_zwave_value(
"currentColor", CURRENT_COLOR_PROPERTY,
CommandClass.SWITCH_COLOR, CommandClass.SWITCH_COLOR,
value_property_key=ColorComponent.RED.value, value_property_key=ColorComponent.RED.value,
) )
green_val = self.get_zwave_value( green_val = self.get_zwave_value(
"currentColor", CURRENT_COLOR_PROPERTY,
CommandClass.SWITCH_COLOR, CommandClass.SWITCH_COLOR,
value_property_key=ColorComponent.GREEN.value, value_property_key=ColorComponent.GREEN.value,
) )
blue_val = self.get_zwave_value( blue_val = self.get_zwave_value(
"currentColor", CURRENT_COLOR_PROPERTY,
CommandClass.SWITCH_COLOR, CommandClass.SWITCH_COLOR,
value_property_key=ColorComponent.BLUE.value, value_property_key=ColorComponent.BLUE.value,
) )
ww_val = self.get_zwave_value( ww_val = self.get_zwave_value(
"currentColor", CURRENT_COLOR_PROPERTY,
CommandClass.SWITCH_COLOR, CommandClass.SWITCH_COLOR,
value_property_key=ColorComponent.WARM_WHITE.value, value_property_key=ColorComponent.WARM_WHITE.value,
) )
cw_val = self.get_zwave_value( cw_val = self.get_zwave_value(
"currentColor", CURRENT_COLOR_PROPERTY,
CommandClass.SWITCH_COLOR, CommandClass.SWITCH_COLOR,
value_property_key=ColorComponent.COLD_WHITE.value, value_property_key=ColorComponent.COLD_WHITE.value,
) )
# prefer the (new) combined color property # prefer the (new) combined color property
# https://github.com/zwave-js/node-zwave-js/pull/1782 # https://github.com/zwave-js/node-zwave-js/pull/1782
combined_color_val = self.get_zwave_value( combined_color_val = self.get_zwave_value(
"currentColor", CURRENT_COLOR_PROPERTY,
CommandClass.SWITCH_COLOR, CommandClass.SWITCH_COLOR,
value_property_key=None, value_property_key=None,
) )
@ -370,9 +387,9 @@ class ZwaveLight(ZWaveBaseEntity, LightEntity):
# RGB support # RGB support
if red_val and green_val and blue_val: if red_val and green_val and blue_val:
# prefer values from the multicolor property # prefer values from the multicolor property
red = multi_color.get("red", red_val.value) red = multi_color.get(COLOR_SWITCH_COMBINED_RED, red_val.value)
green = multi_color.get("green", green_val.value) green = multi_color.get(COLOR_SWITCH_COMBINED_GREEN, green_val.value)
blue = multi_color.get("blue", blue_val.value) blue = multi_color.get(COLOR_SWITCH_COMBINED_BLUE, blue_val.value)
self._supports_color = True self._supports_color = True
if None not in (red, green, blue): if None not in (red, green, blue):
# convert to HS # convert to HS
@ -383,8 +400,8 @@ class ZwaveLight(ZWaveBaseEntity, LightEntity):
# color temperature support # color temperature support
if ww_val and cw_val: if ww_val and cw_val:
self._supports_color_temp = True self._supports_color_temp = True
warm_white = multi_color.get("warmWhite", ww_val.value) warm_white = multi_color.get(COLOR_SWITCH_COMBINED_WARM_WHITE, ww_val.value)
cold_white = multi_color.get("coldWhite", cw_val.value) cold_white = multi_color.get(COLOR_SWITCH_COMBINED_COLD_WHITE, cw_val.value)
# Calculate color temps based on whites # Calculate color temps based on whites
if cold_white or warm_white: if cold_white or warm_white:
self._color_temp = round( self._color_temp = round(
@ -398,14 +415,14 @@ class ZwaveLight(ZWaveBaseEntity, LightEntity):
# only one white channel (warm white) = rgbw support # only one white channel (warm white) = rgbw support
elif red_val and green_val and blue_val and ww_val: elif red_val and green_val and blue_val and ww_val:
self._supports_rgbw = True self._supports_rgbw = True
white = multi_color.get("warmWhite", ww_val.value) white = multi_color.get(COLOR_SWITCH_COMBINED_WARM_WHITE, ww_val.value)
self._rgbw_color = (red, green, blue, white) self._rgbw_color = (red, green, blue, white)
# Light supports rgbw, set color mode to rgbw # Light supports rgbw, set color mode to rgbw
self._color_mode = COLOR_MODE_RGBW self._color_mode = COLOR_MODE_RGBW
# only one white channel (cool white) = rgbw support # only one white channel (cool white) = rgbw support
elif cw_val: elif cw_val:
self._supports_rgbw = True self._supports_rgbw = True
white = multi_color.get("coldWhite", cw_val.value) white = multi_color.get(COLOR_SWITCH_COMBINED_COLD_WHITE, cw_val.value)
self._rgbw_color = (red, green, blue, white) self._rgbw_color = (red, green, blue, white)
# Light supports rgbw, set color mode to rgbw # Light supports rgbw, set color mode to rgbw
self._color_mode = COLOR_MODE_RGBW self._color_mode = COLOR_MODE_RGBW

View File

@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
from zwave_js_server.client import Client as ZwaveClient from zwave_js_server.client import Client as ZwaveClient
from zwave_js_server.const import TARGET_VALUE_PROPERTY
from homeassistant.components.number import DOMAIN as NUMBER_DOMAIN, NumberEntity from homeassistant.components.number import DOMAIN as NUMBER_DOMAIN, NumberEntity
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
@ -52,7 +53,7 @@ class ZwaveNumberEntity(ZWaveBaseEntity, NumberEntity):
if self.info.primary_value.metadata.writeable: if self.info.primary_value.metadata.writeable:
self._target_value = self.info.primary_value self._target_value = self.info.primary_value
else: else:
self._target_value = self.get_zwave_value("targetValue") self._target_value = self.get_zwave_value(TARGET_VALUE_PROPERTY)
# Entity class attributes # Entity class attributes
self._attr_name = self.generate_name( self._attr_name = self.generate_name(

View File

@ -4,7 +4,7 @@ from __future__ import annotations
from typing import Dict, cast from typing import Dict, cast
from zwave_js_server.client import Client as ZwaveClient from zwave_js_server.client import Client as ZwaveClient
from zwave_js_server.const import CommandClass from zwave_js_server.const import TARGET_VALUE_PROPERTY, CommandClass
from zwave_js_server.const.command_class.sound_switch import ToneID from zwave_js_server.const.command_class.sound_switch import ToneID
from homeassistant.components.select import DOMAIN as SELECT_DOMAIN, SelectEntity from homeassistant.components.select import DOMAIN as SELECT_DOMAIN, SelectEntity
@ -142,7 +142,7 @@ class ZwaveMultilevelSwitchSelectEntity(ZWaveBaseEntity, SelectEntity):
) -> None: ) -> None:
"""Initialize a ZwaveSelectEntity entity.""" """Initialize a ZwaveSelectEntity entity."""
super().__init__(config_entry, client, info) super().__init__(config_entry, client, info)
self._target_value = self.get_zwave_value("targetValue") self._target_value = self.get_zwave_value(TARGET_VALUE_PROPERTY)
assert self.info.platform_data_template assert self.info.platform_data_template
self._lookup_map = cast( self._lookup_map = cast(
Dict[int, str], self.info.platform_data_template.static_data Dict[int, str], self.info.platform_data_template.static_data

View File

@ -5,6 +5,7 @@ import logging
from typing import Any from typing import Any
from zwave_js_server.client import Client as ZwaveClient from zwave_js_server.client import Client as ZwaveClient
from zwave_js_server.const import TARGET_VALUE_PROPERTY
from zwave_js_server.const.command_class.barrier_operator import ( from zwave_js_server.const.command_class.barrier_operator import (
BarrierEventSignalingSubsystemState, BarrierEventSignalingSubsystemState,
) )
@ -55,6 +56,14 @@ async def async_setup_entry(
class ZWaveSwitch(ZWaveBaseEntity, SwitchEntity): class ZWaveSwitch(ZWaveBaseEntity, SwitchEntity):
"""Representation of a Z-Wave switch.""" """Representation of a Z-Wave switch."""
def __init__(
self, config_entry: ConfigEntry, client: ZwaveClient, info: ZwaveDiscoveryInfo
) -> None:
"""Initialize the switch."""
super().__init__(config_entry, client, info)
self._target_value = self.get_zwave_value(TARGET_VALUE_PROPERTY)
@property @property
def is_on(self) -> bool | None: # type: ignore def is_on(self) -> bool | None: # type: ignore
"""Return a boolean for the state of the switch.""" """Return a boolean for the state of the switch."""
@ -65,15 +74,13 @@ class ZWaveSwitch(ZWaveBaseEntity, SwitchEntity):
async def async_turn_on(self, **kwargs: Any) -> None: async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the switch on.""" """Turn the switch on."""
target_value = self.get_zwave_value("targetValue") if self._target_value is not None:
if target_value is not None: await self.info.node.async_set_value(self._target_value, True)
await self.info.node.async_set_value(target_value, True)
async def async_turn_off(self, **kwargs: Any) -> None: async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the switch off.""" """Turn the switch off."""
target_value = self.get_zwave_value("targetValue") if self._target_value is not None:
if target_value is not None: await self.info.node.async_set_value(self._target_value, False)
await self.info.node.async_set_value(target_value, False)
class ZWaveBarrierEventSignalingSwitch(ZWaveBaseEntity, SwitchEntity): class ZWaveBarrierEventSignalingSwitch(ZWaveBaseEntity, SwitchEntity):