Add binary sensor platform to openevse (#172924)

This commit is contained in:
Chris
2026-06-03 19:37:55 +02:00
committed by GitHub
parent 8124544125
commit 8db064c929
6 changed files with 570 additions and 2 deletions
@@ -11,7 +11,7 @@ from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import DOMAIN
from .coordinator import OpenEVSEConfigEntry, OpenEVSEDataUpdateCoordinator
PLATFORMS = [Platform.NUMBER, Platform.SENSOR]
PLATFORMS = [Platform.BINARY_SENSOR, Platform.NUMBER, Platform.SENSOR]
async def async_setup_entry(hass: HomeAssistant, entry: OpenEVSEConfigEntry) -> bool:
@@ -0,0 +1,120 @@
"""Support for monitoring OpenEVSE Charger binary sensors."""
from collections.abc import Callable
from dataclasses import dataclass
from openevsehttp.__main__ import OpenEVSE
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
BinarySensorEntityDescription,
)
from homeassistant.const import ATTR_CONNECTIONS, ATTR_SERIAL_NUMBER, EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, DeviceInfo
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import OpenEVSEConfigEntry, OpenEVSEDataUpdateCoordinator
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class OpenEVSEBinarySensorDescription(BinarySensorEntityDescription):
"""Describes an OpenEVSE binary sensor entity."""
value_fn: Callable[[OpenEVSE], bool | None]
BINARY_SENSOR_TYPES: tuple[OpenEVSEBinarySensorDescription, ...] = (
OpenEVSEBinarySensorDescription(
key="vehicle",
translation_key="vehicle",
device_class=BinarySensorDeviceClass.PLUG,
value_fn=lambda ev: ev.vehicle,
),
OpenEVSEBinarySensorDescription(
key="divert_active",
translation_key="divert_active",
value_fn=lambda ev: ev.divert_active,
),
OpenEVSEBinarySensorDescription(
key="using_ethernet",
translation_key="using_ethernet",
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
value_fn=lambda ev: ev.using_ethernet,
),
OpenEVSEBinarySensorDescription(
key="shaper_active",
translation_key="shaper_active",
value_fn=lambda ev: ev.shaper_active,
),
OpenEVSEBinarySensorDescription(
key="has_limit",
translation_key="has_limit",
entity_registry_enabled_default=False,
value_fn=lambda ev: ev.has_limit,
),
OpenEVSEBinarySensorDescription(
key="mqtt_connected",
translation_key="mqtt_connected",
device_class=BinarySensorDeviceClass.CONNECTIVITY,
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
value_fn=lambda ev: ev.mqtt_connected,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: OpenEVSEConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up OpenEVSE binary sensors based on config entry."""
coordinator = entry.runtime_data
identifier = entry.unique_id or entry.entry_id
async_add_entities(
OpenEVSEBinarySensor(coordinator, description, identifier, entry.unique_id)
for description in BINARY_SENSOR_TYPES
)
class OpenEVSEBinarySensor(
CoordinatorEntity[OpenEVSEDataUpdateCoordinator], BinarySensorEntity
):
"""Implementation of an OpenEVSE binary sensor."""
_attr_has_entity_name = True
entity_description: OpenEVSEBinarySensorDescription
def __init__(
self,
coordinator: OpenEVSEDataUpdateCoordinator,
description: OpenEVSEBinarySensorDescription,
identifier: str,
unique_id: str | None,
) -> None:
"""Initialize the binary sensor."""
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f"{identifier}-{description.key}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, identifier)},
manufacturer="OpenEVSE",
)
if unique_id:
self._attr_device_info[ATTR_CONNECTIONS] = {
(CONNECTION_NETWORK_MAC, unique_id)
}
self._attr_device_info[ATTR_SERIAL_NUMBER] = unique_id
@property
def is_on(self) -> bool | None:
"""Return True if the binary sensor is on."""
return self.entity_description.value_fn(self.coordinator.charger)
@@ -42,6 +42,26 @@
}
},
"entity": {
"binary_sensor": {
"divert_active": {
"name": "Divert active"
},
"has_limit": {
"name": "Limit active"
},
"mqtt_connected": {
"name": "MQTT connected"
},
"shaper_active": {
"name": "Shaper active"
},
"using_ethernet": {
"name": "Ethernet connected"
},
"vehicle": {
"name": "Vehicle connected"
}
},
"number": {
"charge_rate": {
"name": "Charge rate"
+7 -1
View File
@@ -38,7 +38,6 @@ def mock_charger() -> Generator[MagicMock]:
charger.callback = None
# Status sensors
charger.status = "Charging"
charger.vehicle = True
charger.mode = "STA"
charger.charge_mode = "fast"
charger.divertmode = "normal"
@@ -90,6 +89,13 @@ def mock_charger() -> Generator[MagicMock]:
# System diagnostic sensors
charger.uptime = 86400 # 1 day in seconds
charger.freeram = 50000
# Binary sensors
charger.vehicle = True
charger.divert_active = False
charger.using_ethernet = False
charger.shaper_active = False
charger.has_limit = False
charger.mqtt_connected = False
yield charger
@@ -0,0 +1,303 @@
# serializer version: 1
# name: test_entities[binary_sensor.openevse_mock_config_divert_active-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'binary_sensor',
'entity_category': None,
'entity_id': 'binary_sensor.openevse_mock_config_divert_active',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'Divert active',
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'Divert active',
'platform': 'openevse',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': 'divert_active',
'unique_id': 'deadbeeffeed-divert_active',
'unit_of_measurement': None,
})
# ---
# name: test_entities[binary_sensor.openevse_mock_config_divert_active-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'openevse_mock_config Divert active',
}),
'context': <ANY>,
'entity_id': 'binary_sensor.openevse_mock_config_divert_active',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'off',
})
# ---
# name: test_entities[binary_sensor.openevse_mock_config_ethernet_connected-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'binary_sensor',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'binary_sensor.openevse_mock_config_ethernet_connected',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'Ethernet connected',
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'Ethernet connected',
'platform': 'openevse',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': 'using_ethernet',
'unique_id': 'deadbeeffeed-using_ethernet',
'unit_of_measurement': None,
})
# ---
# name: test_entities[binary_sensor.openevse_mock_config_ethernet_connected-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'openevse_mock_config Ethernet connected',
}),
'context': <ANY>,
'entity_id': 'binary_sensor.openevse_mock_config_ethernet_connected',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'off',
})
# ---
# name: test_entities[binary_sensor.openevse_mock_config_limit_active-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'binary_sensor',
'entity_category': None,
'entity_id': 'binary_sensor.openevse_mock_config_limit_active',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'Limit active',
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'Limit active',
'platform': 'openevse',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': 'has_limit',
'unique_id': 'deadbeeffeed-has_limit',
'unit_of_measurement': None,
})
# ---
# name: test_entities[binary_sensor.openevse_mock_config_limit_active-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'openevse_mock_config Limit active',
}),
'context': <ANY>,
'entity_id': 'binary_sensor.openevse_mock_config_limit_active',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'off',
})
# ---
# name: test_entities[binary_sensor.openevse_mock_config_mqtt_connected-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'binary_sensor',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'binary_sensor.openevse_mock_config_mqtt_connected',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'MQTT connected',
'options': dict({
}),
'original_device_class': <BinarySensorDeviceClass.CONNECTIVITY: 'connectivity'>,
'original_icon': None,
'original_name': 'MQTT connected',
'platform': 'openevse',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': 'mqtt_connected',
'unique_id': 'deadbeeffeed-mqtt_connected',
'unit_of_measurement': None,
})
# ---
# name: test_entities[binary_sensor.openevse_mock_config_mqtt_connected-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'connectivity',
'friendly_name': 'openevse_mock_config MQTT connected',
}),
'context': <ANY>,
'entity_id': 'binary_sensor.openevse_mock_config_mqtt_connected',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'off',
})
# ---
# name: test_entities[binary_sensor.openevse_mock_config_shaper_active-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'binary_sensor',
'entity_category': None,
'entity_id': 'binary_sensor.openevse_mock_config_shaper_active',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'Shaper active',
'options': dict({
}),
'original_device_class': None,
'original_icon': None,
'original_name': 'Shaper active',
'platform': 'openevse',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': 'shaper_active',
'unique_id': 'deadbeeffeed-shaper_active',
'unit_of_measurement': None,
})
# ---
# name: test_entities[binary_sensor.openevse_mock_config_shaper_active-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'openevse_mock_config Shaper active',
}),
'context': <ANY>,
'entity_id': 'binary_sensor.openevse_mock_config_shaper_active',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'off',
})
# ---
# name: test_entities[binary_sensor.openevse_mock_config_vehicle_connected-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': None,
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'binary_sensor',
'entity_category': None,
'entity_id': 'binary_sensor.openevse_mock_config_vehicle_connected',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'Vehicle connected',
'options': dict({
}),
'original_device_class': <BinarySensorDeviceClass.PLUG: 'plug'>,
'original_icon': None,
'original_name': 'Vehicle connected',
'platform': 'openevse',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': 'vehicle',
'unique_id': 'deadbeeffeed-vehicle',
'unit_of_measurement': None,
})
# ---
# name: test_entities[binary_sensor.openevse_mock_config_vehicle_connected-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'plug',
'friendly_name': 'openevse_mock_config Vehicle connected',
}),
'context': <ANY>,
'entity_id': 'binary_sensor.openevse_mock_config_vehicle_connected',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---
@@ -0,0 +1,119 @@
"""Tests for the OpenEVSE binary sensor platform."""
from datetime import timedelta
from unittest.mock import MagicMock, patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_entities(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
mock_charger: MagicMock,
) -> None:
"""Test the binary sensor entities."""
with patch("homeassistant.components.openevse.PLATFORMS", [Platform.BINARY_SENSOR]):
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_disabled_by_default_entities(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
mock_charger: MagicMock,
) -> None:
"""Test the disabled by default binary sensor entities."""
with patch("homeassistant.components.openevse.PLATFORMS", [Platform.BINARY_SENSOR]):
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
state = hass.states.get("binary_sensor.openevse_mock_config_ethernet_connected")
assert state is None
entry = entity_registry.async_get(
"binary_sensor.openevse_mock_config_ethernet_connected"
)
assert entry
assert entry.disabled
assert entry.disabled_by is er.RegistryEntryDisabler.INTEGRATION
state = hass.states.get("binary_sensor.openevse_mock_config_limit_active")
assert state is None
entry = entity_registry.async_get("binary_sensor.openevse_mock_config_limit_active")
assert entry
assert entry.disabled
assert entry.disabled_by is er.RegistryEntryDisabler.INTEGRATION
state = hass.states.get("binary_sensor.openevse_mock_config_mqtt_connected")
assert state is None
entry = entity_registry.async_get(
"binary_sensor.openevse_mock_config_mqtt_connected"
)
assert entry
assert entry.disabled
assert entry.disabled_by is er.RegistryEntryDisabler.INTEGRATION
async def test_missing_sensor_graceful_handling(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_charger: MagicMock,
) -> None:
"""Test that missing binary sensor attributes are handled gracefully."""
mock_charger.shaper_active = None
with patch("homeassistant.components.openevse.PLATFORMS", [Platform.BINARY_SENSOR]):
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
# The binary sensor with missing attribute should be unknown
state = hass.states.get("binary_sensor.openevse_mock_config_shaper_active")
assert state is not None
assert state.state == STATE_UNKNOWN
# Other binary sensors should still work
state = hass.states.get("binary_sensor.openevse_mock_config_vehicle_connected")
assert state is not None
assert state.state == "on"
async def test_binary_sensor_unavailable_on_coordinator_timeout(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_config_entry: MockConfigEntry,
mock_charger: MagicMock,
) -> None:
"""Test binary sensors become unavailable when coordinator times out."""
with patch("homeassistant.components.openevse.PLATFORMS", [Platform.BINARY_SENSOR]):
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("binary_sensor.openevse_mock_config_vehicle_connected")
assert state
assert state.state != STATE_UNAVAILABLE
mock_charger.update.side_effect = TimeoutError("Connection timed out")
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get("binary_sensor.openevse_mock_config_vehicle_connected")
assert state
assert state.state == STATE_UNAVAILABLE