Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 17 additions & 5 deletions custom_components/doorman/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
- The door sensor is event-driven: the 2N device emits ``DoorStateChanged``
log events when a door contact is configured (Hardware → Digital Inputs →
Door State). There is no HTTP endpoint to poll for it, so the sensor
listens on the ``doorman_access`` bus and stays ``unknown`` until the
first event arrives.
listens on the ``doorman_access`` bus. It restores its last known
open/closed state across restarts (the 2N only reports transitions), and
is ``unknown`` only until the first event on a fresh install.
- One sensor per hardware input port from ``/api/io/caps`` (e.g. a REX
button or an external contact), state polled via ``/api/io/status`` and
updated instantly by ``InputChanged`` events through the coordinator.
Expand All @@ -20,9 +21,10 @@
BinarySensorEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EntityCategory
from homeassistant.const import STATE_OFF, STATE_ON, EntityCategory
from homeassistant.core import Event, HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from .const import DOMAIN
Expand Down Expand Up @@ -51,8 +53,12 @@ async def async_setup_entry(
async_add_entities(entities)


class DoormanDoorSensor(BinarySensorEntity):
"""Physical door open/closed, driven by DoorStateChanged events."""
class DoormanDoorSensor(BinarySensorEntity, RestoreEntity):
"""Physical door open/closed, driven by DoorStateChanged events.

The 2N only emits transitions, so without restoring, every HA restart
would leave the sensor ``unknown`` until the door next moves.
"""

_attr_name = "Doorman Door"
_attr_device_class = BinarySensorDeviceClass.DOOR
Expand All @@ -72,6 +78,12 @@ def __init__(
self._attr_is_on = None # unknown until the first DoorStateChanged

async def async_added_to_hass(self) -> None:
await super().async_added_to_hass()
if (last := await self.async_get_last_state()) is not None and last.state in (
STATE_ON,
STATE_OFF,
):
self._attr_is_on = last.state == STATE_ON
self.async_on_remove(
self.hass.bus.async_listen(f"{DOMAIN}_access", self._handle_bus_event)
)
Expand Down
2 changes: 1 addition & 1 deletion custom_components/doorman/frontend/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
// browser tab still running frontend code from before a HACS update. Keep it
// in step with custom_components/doorman/manifest.json — a unit test asserts
// the two match.
export const PANEL_VERSION = "0.10.0";
export const PANEL_VERSION = "0.11.0";

// ─── Helpers ────────────────────────────────────────────────────────────────

Expand Down
2 changes: 1 addition & 1 deletion custom_components/doorman/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@
"iot_class": "local_push",
"issue_tracker": "https://github.com/dougrathbone/2n-doorman/issues",
"requirements": [],
"version": "0.10.0"
"version": "0.11.0"
}
58 changes: 56 additions & 2 deletions tests/test_binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@
from __future__ import annotations

import pytest
from homeassistant.core import HomeAssistant
from pytest_homeassistant_custom_component.common import MockConfigEntry
from homeassistant.core import HomeAssistant, State
from pytest_homeassistant_custom_component.common import (
MockConfigEntry,
mock_restore_cache,
)

from custom_components.doorman.const import DOMAIN

Expand Down Expand Up @@ -31,6 +34,57 @@ async def test_door_sensor_starts_unknown(
assert state.state == "unknown"


@pytest.mark.asyncio
@pytest.mark.parametrize("restored", ["on", "off"])
async def test_door_sensor_restores_last_state(
hass: HomeAssistant,
doorman_config_entry: MockConfigEntry,
mock_2n_client,
restored: str,
) -> None:
"""The last open/closed state survives an HA restart (2N only reports transitions)."""
mock_restore_cache(hass, [State("binary_sensor.doorman_1012345678_door", restored)])
doorman_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(doorman_config_entry.entry_id)
await hass.async_block_till_done()

assert hass.states.get("binary_sensor.doorman_1012345678_door").state == restored


@pytest.mark.asyncio
@pytest.mark.parametrize("restored", ["unknown", "unavailable"])
async def test_door_sensor_ignores_non_binary_restored_state(
hass: HomeAssistant,
doorman_config_entry: MockConfigEntry,
mock_2n_client,
restored: str,
) -> None:
"""A restored unknown/unavailable is not mistaken for open or closed."""
mock_restore_cache(hass, [State("binary_sensor.doorman_1012345678_door", restored)])
doorman_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(doorman_config_entry.entry_id)
await hass.async_block_till_done()

assert hass.states.get("binary_sensor.doorman_1012345678_door").state == "unknown"


@pytest.mark.asyncio
async def test_door_sensor_event_overrides_restored_state(
hass: HomeAssistant,
doorman_config_entry: MockConfigEntry,
mock_2n_client,
) -> None:
"""A live DoorStateChanged after restart wins over the restored value."""
mock_restore_cache(hass, [State("binary_sensor.doorman_1012345678_door", "on")])
doorman_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(doorman_config_entry.entry_id)
await hass.async_block_till_done()

_fire(hass, doorman_config_entry.entry_id, "DoorStateChanged", {"state": "closed"})
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.doorman_1012345678_door").state == "off"


@pytest.mark.asyncio
async def test_door_sensor_follows_door_state_events(
hass: HomeAssistant,
Expand Down
Loading