Add lock platform to zwave_js (#45175)

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
This commit is contained in:
Raman Gupta 2021-01-16 10:43:25 -06:00 committed by GitHub
parent b6148bbbe7
commit 562d30319b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 2297 additions and 2 deletions

View file

@ -3,7 +3,7 @@
DOMAIN = "zwave_js"
NAME = "Z-Wave JS"
PLATFORMS = ["binary_sensor", "light", "sensor", "switch"]
PLATFORMS = ["binary_sensor", "light", "lock", "sensor", "switch"]
DATA_CLIENT = "client"
DATA_UNSUBSCRIBE = "unsubs"

View file

@ -57,7 +57,24 @@ class ZWaveDiscoverySchema:
DISCOVERY_SCHEMAS = [
# light
# locks
ZWaveDiscoverySchema(
platform="lock",
device_class_generic={"Entry Control"},
device_class_specific={
"Door Lock",
"Advanced Door Lock",
"Secure Keypad Door Lock",
"Secure Lockbox",
},
command_class={
CommandClass.LOCK,
CommandClass.DOOR_LOCK,
},
property={"currentMode", "locked"},
type={"number", "boolean"},
),
# lights
# primary value is the currentValue (brightness)
ZWaveDiscoverySchema(
platform="light",

View file

@ -0,0 +1,88 @@
"""Representation of Z-Wave locks."""
import logging
from typing import Any, Callable, Dict, List, Optional, Union
from zwave_js_server.client import Client as ZwaveClient
from zwave_js_server.const import (
LOCK_CMD_CLASS_TO_LOCKED_STATE_MAP,
LOCK_CMD_CLASS_TO_PROPERTY_MAP,
CommandClass,
DoorLockMode,
)
from zwave_js_server.model.value import Value as ZwaveValue
from homeassistant.components.lock import DOMAIN as LOCK_DOMAIN, LockEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import STATE_LOCKED, STATE_UNLOCKED
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .const import DATA_CLIENT, DATA_UNSUBSCRIBE, DOMAIN
from .discovery import ZwaveDiscoveryInfo
from .entity import ZWaveBaseEntity
LOGGER = logging.getLogger(__name__)
STATE_TO_ZWAVE_MAP: Dict[int, Dict[str, Union[int, bool]]] = {
CommandClass.DOOR_LOCK: {
STATE_UNLOCKED: DoorLockMode.UNSECURED,
STATE_LOCKED: DoorLockMode.SECURED,
},
CommandClass.LOCK: {
STATE_UNLOCKED: False,
STATE_LOCKED: True,
},
}
async def async_setup_entry(
hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: Callable
) -> None:
"""Set up Z-Wave lock from config entry."""
client: ZwaveClient = hass.data[DOMAIN][config_entry.entry_id][DATA_CLIENT]
@callback
def async_add_lock(info: ZwaveDiscoveryInfo) -> None:
"""Add Z-Wave Lock."""
entities: List[ZWaveBaseEntity] = []
entities.append(ZWaveLock(client, info))
async_add_entities(entities)
hass.data[DOMAIN][config_entry.entry_id][DATA_UNSUBSCRIBE].append(
async_dispatcher_connect(hass, f"{DOMAIN}_add_{LOCK_DOMAIN}", async_add_lock)
)
class ZWaveLock(ZWaveBaseEntity, LockEntity):
"""Representation of a Z-Wave lock."""
@property
def is_locked(self) -> Optional[bool]:
"""Return true if the lock is locked."""
return int(
LOCK_CMD_CLASS_TO_LOCKED_STATE_MAP[
CommandClass(self.info.primary_value.command_class)
]
) == int(self.info.primary_value.value)
async def _set_lock_state(
self, target_state: str, **kwargs: Dict[str, Any]
) -> None:
"""Set the lock state."""
target_value: ZwaveValue = self.get_zwave_value(
LOCK_CMD_CLASS_TO_PROPERTY_MAP[self.info.primary_value.command_class]
)
if target_value is not None:
await self.info.node.async_set_value(
target_value,
STATE_TO_ZWAVE_MAP[self.info.primary_value.command_class][target_state],
)
async def async_lock(self, **kwargs: Dict[str, Any]) -> None:
"""Lock the lock."""
await self._set_lock_state(STATE_LOCKED)
async def async_unlock(self, **kwargs: Dict[str, Any]) -> None:
"""Unlock the lock."""
await self._set_lock_state(STATE_UNLOCKED)

View file

@ -61,6 +61,12 @@ def bulb_6_multi_color_state_fixture():
return json.loads(load_fixture("zwave_js/bulb_6_multi_color_state.json"))
@pytest.fixture(name="lock_schlage_be469_state", scope="session")
def lock_schlage_be469_state_fixture():
"""Load the schlage lock node state fixture data."""
return json.loads(load_fixture("zwave_js/lock_schlage_be469_state.json"))
@pytest.fixture(name="client")
def mock_client_fixture(controller_state, version_state):
"""Mock a client."""
@ -108,6 +114,14 @@ def bulb_6_multi_color_fixture(client, bulb_6_multi_color_state):
return node
@pytest.fixture(name="lock_schlage_be469")
def lock_schlage_be469_fixture(client, lock_schlage_be469_state):
"""Mock a schlage lock node."""
node = Node(client, lock_schlage_be469_state)
client.driver.controller.nodes[node.node_id] = node
return node
@pytest.fixture(name="integration")
async def integration_fixture(hass, client):
"""Set up the zwave_js integration."""

View file

@ -0,0 +1,124 @@
"""Test the Z-Wave JS lock platform."""
from zwave_js_server.event import Event
from homeassistant.components.lock import (
DOMAIN as LOCK_DOMAIN,
SERVICE_LOCK,
SERVICE_UNLOCK,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_LOCKED, STATE_UNLOCKED
SCHLAGE_BE469_LOCK_ENTITY = "lock.touchscreen_deadbolt_current_lock_mode"
async def test_door_lock(hass, client, lock_schlage_be469, integration):
"""Test a lock entity with door lock command class."""
node = lock_schlage_be469
state = hass.states.get(SCHLAGE_BE469_LOCK_ENTITY)
assert state
assert state.state == STATE_UNLOCKED
# Test locking
await hass.services.async_call(
LOCK_DOMAIN,
SERVICE_LOCK,
{ATTR_ENTITY_ID: SCHLAGE_BE469_LOCK_ENTITY},
blocking=True,
)
assert len(client.async_send_command.call_args_list) == 1
args = client.async_send_command.call_args[0][0]
assert args["command"] == "node.set_value"
assert args["nodeId"] == 20
assert args["valueId"] == {
"commandClassName": "Door Lock",
"commandClass": 98,
"endpoint": 0,
"property": "targetMode",
"propertyName": "targetMode",
"metadata": {
"type": "number",
"readable": True,
"writeable": True,
"min": 0,
"max": 255,
"label": "Target lock mode",
"states": {
"0": "Unsecured",
"1": "UnsecuredWithTimeout",
"16": "InsideUnsecured",
"17": "InsideUnsecuredWithTimeout",
"32": "OutsideUnsecured",
"33": "OutsideUnsecuredWithTimeout",
"254": "Unknown",
"255": "Secured",
},
},
}
assert args["value"] == 255
client.async_send_command.reset_mock()
# Test locked update from value updated event
event = Event(
type="value updated",
data={
"source": "node",
"event": "value updated",
"nodeId": 20,
"args": {
"commandClassName": "Door Lock",
"commandClass": 98,
"endpoint": 0,
"property": "currentMode",
"newValue": 255,
"prevValue": 0,
"propertyName": "currentMode",
},
},
)
node.receive_event(event)
assert hass.states.get(SCHLAGE_BE469_LOCK_ENTITY).state == STATE_LOCKED
client.async_send_command.reset_mock()
# Test unlocking
await hass.services.async_call(
LOCK_DOMAIN,
SERVICE_UNLOCK,
{ATTR_ENTITY_ID: SCHLAGE_BE469_LOCK_ENTITY},
blocking=True,
)
assert len(client.async_send_command.call_args_list) == 1
args = client.async_send_command.call_args[0][0]
assert args["command"] == "node.set_value"
assert args["nodeId"] == 20
assert args["valueId"] == {
"commandClassName": "Door Lock",
"commandClass": 98,
"endpoint": 0,
"property": "targetMode",
"propertyName": "targetMode",
"metadata": {
"type": "number",
"readable": True,
"writeable": True,
"min": 0,
"max": 255,
"label": "Target lock mode",
"states": {
"0": "Unsecured",
"1": "UnsecuredWithTimeout",
"16": "InsideUnsecured",
"17": "InsideUnsecuredWithTimeout",
"32": "OutsideUnsecured",
"33": "OutsideUnsecuredWithTimeout",
"254": "Unknown",
"255": "Secured",
},
},
}
assert args["value"] == 0

File diff suppressed because it is too large Load diff