Skip to content

Commit

Permalink
Fetch only last hour of sensor data
Browse files Browse the repository at this point in the history
This heavily reduces request time (and server load).

Fixes #1
  • Loading branch information
nijel committed Apr 30, 2022
1 parent 9a7f8fe commit 2bb37ca
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
15 changes: 12 additions & 3 deletions custom_components/lacrosseview/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""LaCrosse View component for Home Assistant."""
from functools import partial
from typing import Optional
import time

from homeassistant.components.sensor import SensorEntity, SensorStateClass
from homeassistant.config_entries import ConfigEntry
Expand All @@ -26,15 +27,19 @@ def device_info_of(device: Device) -> DeviceInfo:


class LaCrosseViewSensor(SensorEntity):
def __init__(self, lacrosse_device: Device, field: Field):
def __init__(self, hass: HomeAssistant, lacrosse_device: Device, field: Field):
self._lacrosse_device = lacrosse_device
self._field = field
self._attr_state_class = SensorStateClass.MEASUREMENT
self._state = None
self._hass = hass

def update(self) -> None:
states = self._lacrosse_device.states()
self._state = states[self._field][-1].value
states = self._lacrosse_device.states(time_zone=self._hass.config.time_zone, start=time.time() - 3600)
try:
self._state = states[self._field][-1].value
except IndexError:
self._state = None

@property
def unique_id(self) -> str:
Expand All @@ -52,6 +57,10 @@ def name(self):
def state(self):
return self._state

@property
def available(self):
return self._state is not None

@property
def device_class(self) -> Optional[str]:
if self._field.unit == "degrees_celsius" or self._field.unit == "degrees_fahrenheit":
Expand Down
2 changes: 1 addition & 1 deletion custom_components/lacrosseview/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,5 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, asyn
for device in ws.devices:
states = await hass.loop.run_in_executor(None, partial(device.states))
for field in states.keys():
entities.append(LaCrosseViewSensor(device, field))
entities.append(LaCrosseViewSensor(hass, device, field))
async_add_entities(entities)

0 comments on commit 2bb37ca

Please sign in to comment.