diff --git a/homeassistant/components/mazda/__init__.py b/homeassistant/components/mazda/__init__.py index 38054bc653e..1fd0c3bd618 100644 --- a/homeassistant/components/mazda/__init__.py +++ b/homeassistant/components/mazda/__init__.py @@ -37,7 +37,13 @@ from .const import DATA_CLIENT, DATA_COORDINATOR, DATA_VEHICLES, DOMAIN, SERVICE _LOGGER = logging.getLogger(__name__) -PLATFORMS = [Platform.BUTTON, Platform.DEVICE_TRACKER, Platform.LOCK, Platform.SENSOR] +PLATFORMS = [ + Platform.BINARY_SENSOR, + Platform.BUTTON, + Platform.DEVICE_TRACKER, + Platform.LOCK, + Platform.SENSOR, +] async def with_timeout(task, timeout_seconds=10): diff --git a/homeassistant/components/mazda/binary_sensor.py b/homeassistant/components/mazda/binary_sensor.py new file mode 100644 index 00000000000..cc60d6318c7 --- /dev/null +++ b/homeassistant/components/mazda/binary_sensor.py @@ -0,0 +1,135 @@ +"""Platform for Mazda binary sensor integration.""" +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass +from typing import Any + +from homeassistant.components.binary_sensor import ( + BinarySensorDeviceClass, + BinarySensorEntity, + BinarySensorEntityDescription, +) +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_platform import AddEntitiesCallback + +from . import MazdaEntity +from .const import DATA_CLIENT, DATA_COORDINATOR, DOMAIN + + +@dataclass +class MazdaBinarySensorRequiredKeysMixin: + """Mixin for required keys.""" + + # Suffix to be appended to the vehicle name to obtain the binary sensor name + name_suffix: str + + # Function to determine the value for this binary sensor, given the coordinator data + value_fn: Callable[[dict[str, Any]], bool] + + +@dataclass +class MazdaBinarySensorEntityDescription( + BinarySensorEntityDescription, MazdaBinarySensorRequiredKeysMixin +): + """Describes a Mazda binary sensor entity.""" + + # Function to determine whether the vehicle supports this binary sensor, given the coordinator data + is_supported: Callable[[dict[str, Any]], bool] = lambda data: True + + +def _plugged_in_supported(data): + """Determine if 'plugged in' binary sensor is supported.""" + return ( + data["isElectric"] and data["evStatus"]["chargeInfo"]["pluggedIn"] is not None + ) + + +BINARY_SENSOR_ENTITIES = [ + MazdaBinarySensorEntityDescription( + key="driver_door", + name_suffix="Driver Door", + icon="mdi:car-door", + device_class=BinarySensorDeviceClass.DOOR, + value_fn=lambda data: data["status"]["doors"]["driverDoorOpen"], + ), + MazdaBinarySensorEntityDescription( + key="passenger_door", + name_suffix="Passenger Door", + icon="mdi:car-door", + device_class=BinarySensorDeviceClass.DOOR, + value_fn=lambda data: data["status"]["doors"]["passengerDoorOpen"], + ), + MazdaBinarySensorEntityDescription( + key="rear_left_door", + name_suffix="Rear Left Door", + icon="mdi:car-door", + device_class=BinarySensorDeviceClass.DOOR, + value_fn=lambda data: data["status"]["doors"]["rearLeftDoorOpen"], + ), + MazdaBinarySensorEntityDescription( + key="rear_right_door", + name_suffix="Rear Right Door", + icon="mdi:car-door", + device_class=BinarySensorDeviceClass.DOOR, + value_fn=lambda data: data["status"]["doors"]["rearRightDoorOpen"], + ), + MazdaBinarySensorEntityDescription( + key="trunk", + name_suffix="Trunk", + icon="mdi:car-back", + device_class=BinarySensorDeviceClass.DOOR, + value_fn=lambda data: data["status"]["doors"]["trunkOpen"], + ), + MazdaBinarySensorEntityDescription( + key="hood", + name_suffix="Hood", + icon="mdi:car", + device_class=BinarySensorDeviceClass.DOOR, + value_fn=lambda data: data["status"]["doors"]["hoodOpen"], + ), + MazdaBinarySensorEntityDescription( + key="ev_plugged_in", + name_suffix="Plugged In", + device_class=BinarySensorDeviceClass.PLUG, + is_supported=_plugged_in_supported, + value_fn=lambda data: data["evStatus"]["chargeInfo"]["pluggedIn"], + ), +] + + +async def async_setup_entry( + hass: HomeAssistant, + config_entry: ConfigEntry, + async_add_entities: AddEntitiesCallback, +) -> None: + """Set up the sensor platform.""" + client = hass.data[DOMAIN][config_entry.entry_id][DATA_CLIENT] + coordinator = hass.data[DOMAIN][config_entry.entry_id][DATA_COORDINATOR] + + async_add_entities( + MazdaBinarySensorEntity(client, coordinator, index, description) + for index, data in enumerate(coordinator.data) + for description in BINARY_SENSOR_ENTITIES + if description.is_supported(data) + ) + + +class MazdaBinarySensorEntity(MazdaEntity, BinarySensorEntity): + """Representation of a Mazda vehicle binary sensor.""" + + entity_description: MazdaBinarySensorEntityDescription + + def __init__(self, client, coordinator, index, description): + """Initialize Mazda binary sensor.""" + super().__init__(client, coordinator, index) + self.entity_description = description + + self._attr_name = f"{self.vehicle_name} {description.name_suffix}" + self._attr_unique_id = f"{self.vin}_{description.key}" + + @property + def is_on(self): + """Return the state of the binary sensor.""" + return self.entity_description.value_fn(self.data) diff --git a/homeassistant/components/mazda/sensor.py b/homeassistant/components/mazda/sensor.py index d94a4798630..99f8c74d64d 100644 --- a/homeassistant/components/mazda/sensor.py +++ b/homeassistant/components/mazda/sensor.py @@ -3,6 +3,7 @@ from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass +from typing import Any from homeassistant.components.sensor import ( SensorDeviceClass, @@ -35,7 +36,7 @@ class MazdaSensorRequiredKeysMixin: name_suffix: str # Function to determine the value for this sensor, given the coordinator data and the configured unit system - value: Callable[[dict, UnitSystem], StateType] + value: Callable[[dict[str, Any], UnitSystem], StateType] @dataclass @@ -45,7 +46,7 @@ class MazdaSensorEntityDescription( """Describes a Mazda sensor entity.""" # Function to determine whether the vehicle supports this sensor, given the coordinator data - is_supported: Callable[[dict], bool] = lambda data: True + is_supported: Callable[[dict[str, Any]], bool] = lambda data: True # Function to determine the unit of measurement for this sensor, given the configured unit system # Falls back to description.native_unit_of_measurement if it is not provided diff --git a/tests/components/mazda/fixtures/diagnostics_config_entry.json b/tests/components/mazda/fixtures/diagnostics_config_entry.json index 445ae141cb2..e6319b3c43c 100644 --- a/tests/components/mazda/fixtures/diagnostics_config_entry.json +++ b/tests/components/mazda/fixtures/diagnostics_config_entry.json @@ -30,11 +30,11 @@ "odometerKm": 2795.8, "doors": { "driverDoorOpen": false, - "passengerDoorOpen": false, + "passengerDoorOpen": true, "rearLeftDoorOpen": false, "rearRightDoorOpen": false, "trunkOpen": false, - "hoodOpen": false, + "hoodOpen": true, "fuelLidOpen": false }, "doorLocks": { diff --git a/tests/components/mazda/fixtures/diagnostics_device.json b/tests/components/mazda/fixtures/diagnostics_device.json index 0b2fa8550ac..cbfa1ec8397 100644 --- a/tests/components/mazda/fixtures/diagnostics_device.json +++ b/tests/components/mazda/fixtures/diagnostics_device.json @@ -29,11 +29,11 @@ "odometerKm": 2795.8, "doors": { "driverDoorOpen": false, - "passengerDoorOpen": false, + "passengerDoorOpen": true, "rearLeftDoorOpen": false, "rearRightDoorOpen": false, "trunkOpen": false, - "hoodOpen": false, + "hoodOpen": true, "fuelLidOpen": false }, "doorLocks": { diff --git a/tests/components/mazda/fixtures/get_vehicle_status.json b/tests/components/mazda/fixtures/get_vehicle_status.json index 1e74d7202ca..70a8a4bf7cc 100644 --- a/tests/components/mazda/fixtures/get_vehicle_status.json +++ b/tests/components/mazda/fixtures/get_vehicle_status.json @@ -8,11 +8,11 @@ "odometerKm": 2795.8, "doors": { "driverDoorOpen": false, - "passengerDoorOpen": false, + "passengerDoorOpen": true, "rearLeftDoorOpen": false, "rearRightDoorOpen": false, "trunkOpen": false, - "hoodOpen": false, + "hoodOpen": true, "fuelLidOpen": false }, "doorLocks": { diff --git a/tests/components/mazda/test_binary_sensor.py b/tests/components/mazda/test_binary_sensor.py new file mode 100644 index 00000000000..f2b272109c9 --- /dev/null +++ b/tests/components/mazda/test_binary_sensor.py @@ -0,0 +1,98 @@ +"""The binary sensor tests for the Mazda Connected Services integration.""" + +from homeassistant.components.binary_sensor import BinarySensorDeviceClass +from homeassistant.const import ATTR_DEVICE_CLASS, ATTR_FRIENDLY_NAME, ATTR_ICON +from homeassistant.helpers import entity_registry as er + +from . import init_integration + + +async def test_binary_sensors(hass): + """Test creation of the binary sensors.""" + await init_integration(hass) + + entity_registry = er.async_get(hass) + + # Driver Door + state = hass.states.get("binary_sensor.my_mazda3_driver_door") + assert state + assert state.attributes.get(ATTR_FRIENDLY_NAME) == "My Mazda3 Driver Door" + assert state.attributes.get(ATTR_ICON) == "mdi:car-door" + assert state.attributes.get(ATTR_DEVICE_CLASS) == BinarySensorDeviceClass.DOOR + assert state.state == "off" + entry = entity_registry.async_get("binary_sensor.my_mazda3_driver_door") + assert entry + assert entry.unique_id == "JM000000000000000_driver_door" + + # Passenger Door + state = hass.states.get("binary_sensor.my_mazda3_passenger_door") + assert state + assert state.attributes.get(ATTR_FRIENDLY_NAME) == "My Mazda3 Passenger Door" + assert state.attributes.get(ATTR_ICON) == "mdi:car-door" + assert state.attributes.get(ATTR_DEVICE_CLASS) == BinarySensorDeviceClass.DOOR + assert state.state == "on" + entry = entity_registry.async_get("binary_sensor.my_mazda3_passenger_door") + assert entry + assert entry.unique_id == "JM000000000000000_passenger_door" + + # Rear Left Door + state = hass.states.get("binary_sensor.my_mazda3_rear_left_door") + assert state + assert state.attributes.get(ATTR_FRIENDLY_NAME) == "My Mazda3 Rear Left Door" + assert state.attributes.get(ATTR_ICON) == "mdi:car-door" + assert state.attributes.get(ATTR_DEVICE_CLASS) == BinarySensorDeviceClass.DOOR + assert state.state == "off" + entry = entity_registry.async_get("binary_sensor.my_mazda3_rear_left_door") + assert entry + assert entry.unique_id == "JM000000000000000_rear_left_door" + + # Rear Right Door + state = hass.states.get("binary_sensor.my_mazda3_rear_right_door") + assert state + assert state.attributes.get(ATTR_FRIENDLY_NAME) == "My Mazda3 Rear Right Door" + assert state.attributes.get(ATTR_ICON) == "mdi:car-door" + assert state.attributes.get(ATTR_DEVICE_CLASS) == BinarySensorDeviceClass.DOOR + assert state.state == "off" + entry = entity_registry.async_get("binary_sensor.my_mazda3_rear_right_door") + assert entry + assert entry.unique_id == "JM000000000000000_rear_right_door" + + # Trunk + state = hass.states.get("binary_sensor.my_mazda3_trunk") + assert state + assert state.attributes.get(ATTR_FRIENDLY_NAME) == "My Mazda3 Trunk" + assert state.attributes.get(ATTR_ICON) == "mdi:car-back" + assert state.attributes.get(ATTR_DEVICE_CLASS) == BinarySensorDeviceClass.DOOR + assert state.state == "off" + entry = entity_registry.async_get("binary_sensor.my_mazda3_trunk") + assert entry + assert entry.unique_id == "JM000000000000000_trunk" + + # Hood + state = hass.states.get("binary_sensor.my_mazda3_hood") + assert state + assert state.attributes.get(ATTR_FRIENDLY_NAME) == "My Mazda3 Hood" + assert state.attributes.get(ATTR_ICON) == "mdi:car" + assert state.attributes.get(ATTR_DEVICE_CLASS) == BinarySensorDeviceClass.DOOR + assert state.state == "on" + entry = entity_registry.async_get("binary_sensor.my_mazda3_hood") + assert entry + assert entry.unique_id == "JM000000000000000_hood" + + +async def test_electric_vehicle_binary_sensors(hass): + """Test sensors which are specific to electric vehicles.""" + + await init_integration(hass, electric_vehicle=True) + + entity_registry = er.async_get(hass) + + # Plugged In + state = hass.states.get("binary_sensor.my_mazda3_plugged_in") + assert state + assert state.attributes.get(ATTR_FRIENDLY_NAME) == "My Mazda3 Plugged In" + assert state.attributes.get(ATTR_DEVICE_CLASS) == BinarySensorDeviceClass.PLUG + assert state.state == "on" + entry = entity_registry.async_get("binary_sensor.my_mazda3_plugged_in") + assert entry + assert entry.unique_id == "JM000000000000000_ev_plugged_in" diff --git a/tests/components/mazda/test_button.py b/tests/components/mazda/test_button.py index cb9fdb40737..71b16434ee3 100644 --- a/tests/components/mazda/test_button.py +++ b/tests/components/mazda/test_button.py @@ -8,7 +8,7 @@ from homeassistant.const import ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME, ATTR_ICON from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry as er -from tests.components.mazda import init_integration +from . import init_integration async def test_button_setup_non_electric_vehicle(hass) -> None: diff --git a/tests/components/mazda/test_device_tracker.py b/tests/components/mazda/test_device_tracker.py index 5e09c23ecd8..4af367c1c04 100644 --- a/tests/components/mazda/test_device_tracker.py +++ b/tests/components/mazda/test_device_tracker.py @@ -9,7 +9,7 @@ from homeassistant.const import ( ) from homeassistant.helpers import entity_registry as er -from tests.components.mazda import init_integration +from . import init_integration async def test_device_tracker(hass): diff --git a/tests/components/mazda/test_init.py b/tests/components/mazda/test_init.py index e2d4661d36f..9d221bbfe88 100644 --- a/tests/components/mazda/test_init.py +++ b/tests/components/mazda/test_init.py @@ -20,8 +20,9 @@ from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import device_registry as dr from homeassistant.util import dt as dt_util +from . import init_integration + from tests.common import MockConfigEntry, async_fire_time_changed, load_fixture -from tests.components.mazda import init_integration FIXTURE_USER_INPUT = { CONF_EMAIL: "example@example.com", diff --git a/tests/components/mazda/test_lock.py b/tests/components/mazda/test_lock.py index 1230e624cdd..9f0959dc88b 100644 --- a/tests/components/mazda/test_lock.py +++ b/tests/components/mazda/test_lock.py @@ -9,7 +9,7 @@ from homeassistant.components.lock import ( from homeassistant.const import ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME from homeassistant.helpers import entity_registry as er -from tests.components.mazda import init_integration +from . import init_integration async def test_lock_setup(hass): diff --git a/tests/components/mazda/test_sensor.py b/tests/components/mazda/test_sensor.py index 8d4085930dd..f7fb379da51 100644 --- a/tests/components/mazda/test_sensor.py +++ b/tests/components/mazda/test_sensor.py @@ -18,7 +18,7 @@ from homeassistant.const import ( from homeassistant.helpers import entity_registry as er from homeassistant.util.unit_system import IMPERIAL_SYSTEM -from tests.components.mazda import init_integration +from . import init_integration async def test_sensors(hass):