|
| 1 | +"""Stromer Button component for Home Assistant.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +from homeassistant.components.button import ( |
| 5 | + ButtonDeviceClass, |
| 6 | + ButtonEntity, |
| 7 | + ButtonEntityDescription, |
| 8 | +) |
| 9 | +from homeassistant.config_entries import ConfigEntry |
| 10 | +from homeassistant.core import HomeAssistant |
| 11 | +from homeassistant.helpers.entity_platform import AddEntitiesCallback |
| 12 | + |
| 13 | +from .const import DOMAIN, LOGGER |
| 14 | +from .coordinator import StromerDataUpdateCoordinator |
| 15 | +from .entity import StromerEntity |
| 16 | + |
| 17 | +BUTTONS: tuple[ButtonEntityDescription, ...] = ( |
| 18 | + ButtonEntityDescription( |
| 19 | + key="trip_distance", # (ab)use trip_distance from the bike data to trigger adding button |
| 20 | + translation_key="reset_trip_data", |
| 21 | + icon="mdi:map-marker-distance", |
| 22 | + device_class=ButtonDeviceClass.RESTART, |
| 23 | + ), |
| 24 | +) |
| 25 | + |
| 26 | +async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback) -> None: |
| 27 | + """Set up the Stromer Buttons from a config entry.""" |
| 28 | + coordinator = hass.data[DOMAIN][config_entry.entry_id] |
| 29 | + |
| 30 | + entities = [] |
| 31 | + for idx, data in enumerate(coordinator.data.bikedata.items()): |
| 32 | + for description in BUTTONS: |
| 33 | + if data[0] == description.key: |
| 34 | + entities.append(StromerButton(coordinator, idx, data, description)) |
| 35 | + LOGGER.debug("Add %s %s button", data, description.translation_key) |
| 36 | + |
| 37 | + async_add_entities(entities, update_before_add=False) |
| 38 | + |
| 39 | + |
| 40 | +class StromerButton(StromerEntity, ButtonEntity): # type: ignore[misc] |
| 41 | + """Representation of a Button.""" |
| 42 | + |
| 43 | + _attr_has_entity_name = True |
| 44 | + |
| 45 | + entity_description: ButtonEntityDescription |
| 46 | + |
| 47 | + def __init__( |
| 48 | + self, |
| 49 | + coordinator: StromerDataUpdateCoordinator, |
| 50 | + idx: int, |
| 51 | + data: dict, |
| 52 | + description: ButtonEntityDescription, |
| 53 | + ): |
| 54 | + """Initialize the sensor.""" |
| 55 | + super().__init__(coordinator) |
| 56 | + self._ent = data[0] |
| 57 | + self._coordinator = coordinator |
| 58 | + |
| 59 | + device_id = coordinator.data.bike_id |
| 60 | + |
| 61 | + self.entity_description = description |
| 62 | + self._attr_unique_id = f"{device_id}-{description.key}-bu" |
| 63 | + |
| 64 | + async def async_press(self) -> None: |
| 65 | + """Handle the button press.""" |
| 66 | + if self.entity_description.key == "trip_distance": |
| 67 | + await self._coordinator.stromer.stromer_reset_trip_data() |
0 commit comments