Clean up surepetcare binary sensor (#52217)

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
This commit is contained in:
Daniel Hjelseth Høyer 2021-06-27 17:27:33 +02:00 committed by GitHub
parent a824313e9f
commit a788b6ebc1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 58 additions and 79 deletions

View File

@ -90,11 +90,9 @@ async def async_setup(hass: HomeAssistant, config: dict) -> bool:
async_track_time_interval(hass, spc.async_update, SCAN_INTERVAL) async_track_time_interval(hass, spc.async_update, SCAN_INTERVAL)
# load platforms # load platforms
for platform in PLATFORMS:
hass.async_create_task( hass.async_create_task(
hass.helpers.discovery.async_load_platform("binary_sensor", DOMAIN, {}, config) hass.helpers.discovery.async_load_platform(platform, DOMAIN, {}, config)
)
hass.async_create_task(
hass.helpers.discovery.async_load_platform("sensor", DOMAIN, {}, config)
) )
async def handle_set_lock_state(call): async def handle_set_lock_state(call):
@ -150,6 +148,7 @@ class SurePetcareAPI:
self.states = await self.surepy.get_entities() self.states = await self.surepy.get_entities()
except SurePetcareError as error: except SurePetcareError as error:
_LOGGER.error("Unable to fetch data: %s", error) _LOGGER.error("Unable to fetch data: %s", error)
return
async_dispatcher_send(self.hass, TOPIC_UPDATE) async_dispatcher_send(self.hass, TOPIC_UPDATE)

View File

@ -1,11 +1,11 @@
"""Support for Sure PetCare Flaps/Pets binary sensors.""" """Support for Sure PetCare Flaps/Pets binary sensors."""
from __future__ import annotations from __future__ import annotations
from abc import abstractmethod
import logging import logging
from typing import Any
from surepy.entities import SurepyEntity from surepy.entities import SurepyEntity
from surepy.enums import EntityType, Location, SureEnum from surepy.enums import EntityType, Location
from homeassistant.components.binary_sensor import ( from homeassistant.components.binary_sensor import (
DEVICE_CLASS_CONNECTIVITY, DEVICE_CLASS_CONNECTIVITY,
@ -67,31 +67,28 @@ class SurePetcareBinarySensor(BinarySensorEntity):
self._id = _id self._id = _id
self._spc: SurePetcareAPI = spc self._spc: SurePetcareAPI = spc
self._surepy_entity: SurepyEntity = self._spc.states[self._id] surepy_entity: SurepyEntity = self._spc.states[self._id]
self._state: SureEnum | dict[str, Any] = None
# cover special case where a device has no name set # cover special case where a device has no name set
if self._surepy_entity.name: if surepy_entity.name:
name = self._surepy_entity.name name = surepy_entity.name
else: else:
name = f"Unnamed {self._surepy_entity.type.name.capitalize()}" name = f"Unnamed {surepy_entity.type.name.capitalize()}"
self._name = f"{self._surepy_entity.type.name.capitalize()} {name.capitalize()}" self._name = f"{surepy_entity.type.name.capitalize()} {name.capitalize()}"
self._attr_device_class = device_class self._attr_device_class = device_class
self._attr_unique_id = f"{self._surepy_entity.household_id}-{self._id}" self._attr_unique_id = f"{surepy_entity.household_id}-{self._id}"
@property @property
def name(self) -> str: def name(self) -> str:
"""Return the name of the device if any.""" """Return the name of the device if any."""
return self._name return self._name
@abstractmethod
@callback @callback
def _async_update(self) -> None: def _async_update(self) -> None:
"""Get the latest data and update the state.""" """Get the latest data and update the state."""
self._surepy_entity = self._spc.states[self._id]
self._state = self._surepy_entity.raw_data()["status"]
_LOGGER.debug("%s -> self._state: %s", self._name, self._state)
async def async_added_to_hass(self) -> None: async def async_added_to_hass(self) -> None:
"""Register callbacks.""" """Register callbacks."""
@ -108,29 +105,23 @@ class Hub(SurePetcareBinarySensor):
"""Initialize a Sure Petcare Hub.""" """Initialize a Sure Petcare Hub."""
super().__init__(_id, spc, DEVICE_CLASS_CONNECTIVITY) super().__init__(_id, spc, DEVICE_CLASS_CONNECTIVITY)
@property @callback
def available(self) -> bool: def _async_update(self) -> None:
"""Return true if entity is available.""" """Get the latest data and update the state."""
return bool(self._state["online"]) surepy_entity = self._spc.states[self._id]
state = surepy_entity.raw_data()["status"]
@property self._attr_is_on = self._attr_available = bool(state["online"])
def is_on(self) -> bool: if surepy_entity.raw_data():
"""Return true if entity is online.""" self._attr_extra_state_attributes = {
return self.available "led_mode": int(surepy_entity.raw_data()["status"]["led_mode"]),
@property
def extra_state_attributes(self) -> dict[str, Any] | None:
"""Return the state attributes of the device."""
attributes = None
if self._surepy_entity.raw_data():
attributes = {
"led_mode": int(self._surepy_entity.raw_data()["status"]["led_mode"]),
"pairing_mode": bool( "pairing_mode": bool(
self._surepy_entity.raw_data()["status"]["pairing_mode"] surepy_entity.raw_data()["status"]["pairing_mode"]
), ),
} }
else:
return attributes self._attr_extra_state_attributes = None
_LOGGER.debug("%s -> state: %s", self._name, state)
self.async_write_ha_state()
class Pet(SurePetcareBinarySensor): class Pet(SurePetcareBinarySensor):
@ -140,29 +131,24 @@ class Pet(SurePetcareBinarySensor):
"""Initialize a Sure Petcare Pet.""" """Initialize a Sure Petcare Pet."""
super().__init__(_id, spc, DEVICE_CLASS_PRESENCE) super().__init__(_id, spc, DEVICE_CLASS_PRESENCE)
@property
def is_on(self) -> bool:
"""Return true if entity is at home."""
try:
return bool(Location(self._state.where) == Location.INSIDE)
except (KeyError, TypeError):
return False
@property
def extra_state_attributes(self) -> dict[str, Any] | None:
"""Return the state attributes of the device."""
attributes = None
if self._state:
attributes = {"since": self._state.since, "where": self._state.where}
return attributes
@callback @callback
def _async_update(self) -> None: def _async_update(self) -> None:
"""Get the latest data and update the state.""" """Get the latest data and update the state."""
self._surepy_entity = self._spc.states[self._id] surepy_entity = self._spc.states[self._id]
self._state = self._surepy_entity.location state = surepy_entity.location
_LOGGER.debug("%s -> self._state: %s", self._name, self._state) try:
self._attr_is_on = bool(Location(state.where) == Location.INSIDE)
except (KeyError, TypeError):
self._attr_is_on = False
if state:
self._attr_extra_state_attributes = {
"since": state.since,
"where": state.where,
}
else:
self._attr_extra_state_attributes = None
_LOGGER.debug("%s -> state: %s", self._name, state)
self.async_write_ha_state()
class DeviceConnectivity(SurePetcareBinarySensor): class DeviceConnectivity(SurePetcareBinarySensor):
@ -176,7 +162,7 @@ class DeviceConnectivity(SurePetcareBinarySensor):
"""Initialize a Sure Petcare Device.""" """Initialize a Sure Petcare Device."""
super().__init__(_id, spc, DEVICE_CLASS_CONNECTIVITY) super().__init__(_id, spc, DEVICE_CLASS_CONNECTIVITY)
self._attr_unique_id = ( self._attr_unique_id = (
f"{self._surepy_entity.household_id}-{self._id}-connectivity" f"{self._spc.states[self._id].household_id}-{self._id}-connectivity"
) )
@property @property
@ -184,24 +170,18 @@ class DeviceConnectivity(SurePetcareBinarySensor):
"""Return the name of the device if any.""" """Return the name of the device if any."""
return f"{self._name}_connectivity" return f"{self._name}_connectivity"
@property @callback
def available(self) -> bool: def _async_update(self) -> None:
"""Return true if entity is available.""" """Get the latest data and update the state."""
return bool(self._state) surepy_entity = self._spc.states[self._id]
state = surepy_entity.raw_data()["status"]
@property self._attr_is_on = self._attr_available = bool(self.state)
def is_on(self) -> bool: if state:
"""Return true if entity is online.""" self._attr_extra_state_attributes = {
return self.available "device_rssi": f'{state["signal"]["device_rssi"]:.2f}',
"hub_rssi": f'{state["signal"]["hub_rssi"]:.2f}',
@property
def extra_state_attributes(self) -> dict[str, Any] | None:
"""Return the state attributes of the device."""
attributes = None
if self._state:
attributes = {
"device_rssi": f'{self._state["signal"]["device_rssi"]:.2f}',
"hub_rssi": f'{self._state["signal"]["hub_rssi"]:.2f}',
} }
else:
return attributes self._attr_extra_state_attributes = None
_LOGGER.debug("%s -> state: %s", self._name, state)
self.async_write_ha_state()