sensor.py (2438B)
1 """Sensors for Hunter BTT.""" 2 3 from datetime import datetime 4 from typing import override 5 6 from homeassistant.components.sensor import ( 7 SensorDeviceClass, 8 SensorEntity, 9 SensorStateClass, 10 ) 11 from homeassistant.const import PERCENTAGE 12 from homeassistant.core import HomeAssistant 13 from homeassistant.helpers.entity_platform import AddEntitiesCallback 14 15 from .coordinator import HunterBTTConfigEntry, HunterBTTCoordinator 16 from .entity import HunterBTTEntity 17 18 19 async def async_setup_entry( 20 _hass: HomeAssistant, 21 entry: HunterBTTConfigEntry, 22 async_add_entities: AddEntitiesCallback, 23 ) -> None: 24 """Set up Hunter BTT sensors.""" 25 coordinator = entry.runtime_data 26 channel_count = coordinator.data.state.channel_count or 1 27 async_add_entities( 28 [HunterBTTBatterySensor(coordinator)] 29 + [ 30 HunterBTTEndTimeSensor(coordinator, channel) 31 for channel in range(1, channel_count + 1) 32 ] 33 ) 34 35 36 class HunterBTTBatterySensor(HunterBTTEntity, SensorEntity): 37 """Report the controller's standard GATT battery percentage.""" 38 39 _attr_translation_key = "battery" 40 _attr_device_class = SensorDeviceClass.BATTERY 41 _attr_native_unit_of_measurement = PERCENTAGE 42 _attr_state_class = SensorStateClass.MEASUREMENT 43 44 def __init__(self, coordinator: HunterBTTCoordinator) -> None: 45 """Initialize the battery sensor.""" 46 super().__init__(coordinator, "battery") 47 48 @property 49 @override 50 def native_value(self) -> int | None: 51 """Return the latest battery percentage.""" 52 return ( 53 self.coordinator.data.state.battery_level if self.coordinator.data else None 54 ) 55 56 57 class HunterBTTEndTimeSensor(HunterBTTEntity, SensorEntity): 58 """Report the calculated end time of an active run.""" 59 60 _attr_translation_key = "end_time" 61 _attr_device_class = SensorDeviceClass.TIMESTAMP 62 63 def __init__(self, coordinator: HunterBTTCoordinator, channel: int) -> None: 64 """Initialize the end time sensor.""" 65 super().__init__(coordinator, f"zone_{channel}_end_time") 66 self._channel = channel 67 68 @property 69 @override 70 def native_value(self) -> datetime | None: 71 """Return the end time only while a known activity is active.""" 72 if self.coordinator.data is None: 73 return None 74 if self._channel == 1: 75 return self.coordinator.data.end_time 76 return None