Use _attr_* for Launch Library (#54388)

This commit is contained in:
Joakim Sørensen 2021-08-10 13:11:12 +02:00 committed by GitHub
parent 9c29d9f8eb
commit 39d7bb4f1a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -42,48 +42,32 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
class LaunchLibrarySensor(SensorEntity): class LaunchLibrarySensor(SensorEntity):
"""Representation of a launch_library Sensor.""" """Representation of a launch_library Sensor."""
def __init__(self, launches: PyLaunches, name: str) -> None: _attr_icon = "mdi:rocket"
def __init__(self, api: PyLaunches, name: str) -> None:
"""Initialize the sensor.""" """Initialize the sensor."""
self.launches = launches self.api = api
self.next_launch = None self._attr_name = name
self._name = name
async def async_update(self) -> None: async def async_update(self) -> None:
"""Get the latest data.""" """Get the latest data."""
try: try:
launches = await self.launches.upcoming_launches() launches = await self.api.upcoming_launches()
except PyLaunchesException as exception: except PyLaunchesException as exception:
_LOGGER.error("Error getting data, %s", exception) _LOGGER.error("Error getting data, %s", exception)
self._attr_available = False
else: else:
if launches: if launches and (
self.next_launch = launches[0] next_launch := next((launch for launch in launches), None)
):
@property self._attr_available = True
def name(self) -> str: self._attr_state = next_launch.name
"""Return the name of the sensor.""" self._attr_extra_state_attributes.update(
return self._name {
ATTR_LAUNCH_TIME: next_launch.net,
@property ATTR_AGENCY: next_launch.launch_service_provider.name,
def state(self) -> str | None: ATTR_AGENCY_COUNTRY_CODE: next_launch.pad.location.country_code,
"""Return the state of the sensor.""" ATTR_STREAM: next_launch.webcast_live,
if self.next_launch:
return self.next_launch.name
return None
@property
def icon(self) -> str:
"""Return the icon of the sensor."""
return "mdi:rocket"
@property
def extra_state_attributes(self) -> dict | None:
"""Return attributes for the sensor."""
if self.next_launch:
return {
ATTR_LAUNCH_TIME: self.next_launch.net,
ATTR_AGENCY: self.next_launch.launch_service_provider.name,
ATTR_AGENCY_COUNTRY_CODE: self.next_launch.pad.location.country_code,
ATTR_STREAM: self.next_launch.webcast_live,
ATTR_ATTRIBUTION: ATTRIBUTION, ATTR_ATTRIBUTION: ATTRIBUTION,
} }
return None )