1
mirror of https://github.com/home-assistant/core synced 2024-09-06 10:29:55 +02:00

Do data extraction in sensors (#22444)

* Do data extraction in sensors

* Hopefully fix lint
This commit is contained in:
Anders Melchiorsen 2019-03-28 00:24:02 +01:00 committed by Charles Garwood
parent f795d03503
commit 90c4f6f6e5
2 changed files with 20 additions and 16 deletions

View File

@ -62,19 +62,14 @@ class ModemData:
host = attr.ib()
modem = attr.ib()
serial_number = attr.ib(init=False, default=None)
unread_count = attr.ib(init=False, default=None)
usage = attr.ib(init=False, default=None)
data = attr.ib(init=False, default=None)
connected = attr.ib(init=False, default=True)
async def async_update(self):
"""Call the API to update the data."""
import eternalegypt
try:
information = await self.modem.information()
self.serial_number = information.serial_number
self.unread_count = sum(1 for x in information.sms if x.unread)
self.usage = information.usage
self.data = await self.modem.information()
if not self.connected:
_LOGGER.warning("Connected to %s", self.host)
self.connected = True
@ -82,8 +77,7 @@ class ModemData:
if self.connected:
_LOGGER.warning("Lost connection to %s", self.host)
self.connected = False
self.unread_count = None
self.usage = None
self.data = None
async_dispatcher_send(self.hass, DISPATCHER_NETGEAR_LTE)

View File

@ -24,7 +24,7 @@ async def async_setup_platform(
modem_data = hass.data[DATA_KEY].get_modem_data(discovery_info)
if not modem_data:
if not modem_data or not modem_data.data:
raise PlatformNotReady
sensor_conf = discovery_info[DOMAIN]
@ -47,6 +47,14 @@ class LTESensor(Entity):
modem_data = attr.ib()
sensor_type = attr.ib()
_unique_id = attr.ib(init=False)
@_unique_id.default
def _init_unique_id(self):
"""Register unique_id while we know data is valid."""
return "{}_{}".format(
self.sensor_type, self.modem_data.data.serial_number)
async def async_added_to_hass(self):
"""Register callback."""
async_dispatcher_connect(
@ -61,10 +69,15 @@ class LTESensor(Entity):
"""Return that the sensor should not be polled."""
return False
@property
def available(self):
"""Return the availability of the sensor."""
return self.modem_data.data is not None
@property
def unique_id(self):
"""Return a unique ID like 'usage_5TG365AB0078V'."""
return "{}_{}".format(self.sensor_type, self.modem_data.serial_number)
return self._unique_id
class SMSSensor(LTESensor):
@ -78,7 +91,7 @@ class SMSSensor(LTESensor):
@property
def state(self):
"""Return the state of the sensor."""
return self.modem_data.unread_count
return sum(1 for x in self.modem_data.data.sms if x.unread)
class UsageSensor(LTESensor):
@ -97,7 +110,4 @@ class UsageSensor(LTESensor):
@property
def state(self):
"""Return the state of the sensor."""
if self.modem_data.usage is None:
return None
return round(self.modem_data.usage / 1024**2, 1)
return round(self.modem_data.data.usage / 1024**2, 1)