Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reverse out change #14234 BOM Weather throttle fix #17468

Merged
merged 6 commits into from Oct 30, 2018
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
42 changes: 38 additions & 4 deletions homeassistant/components/sensor/bom.py
Expand Up @@ -17,13 +17,13 @@
import requests
import voluptuous as vol

import homeassistant.helpers.config_validation as cv
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IntellJ import ordering? 🤷‍♂️

from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_MONITORED_CONDITIONS, TEMP_CELSIUS, CONF_NAME, ATTR_ATTRIBUTION,
CONF_LATITUDE, CONF_LONGITUDE)
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
import homeassistant.helpers.config_validation as cv

_RESOURCE = 'http://www.bom.gov.au/fwo/{}/{}.{}.json'
_LOGGER = logging.getLogger(__name__)
Expand All @@ -39,7 +39,7 @@
CONF_ZONE_ID = 'zone_id'
CONF_WMO_ID = 'wmo_id'

MIN_TIME_BETWEEN_UPDATES = datetime.timedelta(minutes=35)
MIN_TIME_BETWEEN_UPDATES = datetime.timedelta(seconds=60)

SENSOR_TYPES = {
'wmo': ['wmo', None],
Expand Down Expand Up @@ -188,6 +188,7 @@ def __init__(self, hass, station_id):
self._hass = hass
self._zone_id, self._wmo_id = station_id.split('.')
self._data = None
self._last_updated = None

def _build_url(self):
"""Build the URL for the requests."""
Expand All @@ -211,17 +212,50 @@ def get_reading(self, condition):
for the latest value that is not `-`.

Iterators are used in this method to avoid iterating needlessly
iterating through the entire BOM provided dataset.
through the entire BOM provided dataset.
"""
condition_readings = (entry[condition] for entry in self._data)
return next((x for x in condition_readings if x != '-'), None)

def should_update(self):
if self._last_updated is None:
# Never updated before, therefore an update should occur.
return True

now = datetime.datetime.now()
update_due_at = self._last_updated + datetime.timedelta(minutes=35)
return now > update_due_at


@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Get the latest data from BOM."""
"""Get the latest data from BOM.

BOM provides updated data every 30 minutes. We manually define
refreshing logic here rather than a throttle to keep updates
in lock-step with BOM.

If 35 minutes has passed since the last BOM data update, then
an update should be done.
"""
if not self.should_update():
_LOGGER.debug(
"BOM was updated %s minutes ago, skipping update as"
" < 35 minutes, Now: %s, LastUpdate: %s",
(datetime.datetime.now() - self._last_updated),
datetime.datetime.now(), self._last_updated)
return

try:
result = requests.get(self._build_url(), timeout=10).json()
self._data = result['observations']['data']

# set lastupdate using self._data[0] as the first element in the
# array is the latest date in the json
self._last_updated = datetime.datetime.strptime(
str(self._data[0]['local_date_time_full']), '%Y%m%d%H%M%S')
return

except ValueError as err:
_LOGGER.error("Check BOM %s", err.args)
self._data = None
Expand Down