Skip to content

Commit

Permalink
Added dynamic polling.
Browse files Browse the repository at this point in the history
- reduced poll interval from 2 minutes to 30 seconds to get more up to date info.
- block polling based on how far away the next bus is.  Within 3 minutes, allow all polls (every 30s), within 15 minutes, allow a poll every 2 minutes, within an hour allow a poll every 10 minutes, and more than an hour block further polls until an hour before the next departure.

Bump version.
  • Loading branch information
make-all committed May 15, 2021
1 parent b28195f commit 0e6b158
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
2 changes: 1 addition & 1 deletion custom_components/metlink/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"documentation": "https://github.com/make-all/metlink-nz/wiki",
"domain": "metlink",
"iot_class": "cloud_polling",
"version": "0.6.2",
"version": "0.7.0",
"name": "Metlink Wellington Transport",
"requirements": ["isodate==0.6.0"]
}
29 changes: 28 additions & 1 deletion custom_components/metlink/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@

_LOGGER = logging.getLogger(__name__)
VERBOSE = 1
SCAN_INTERVAL = timedelta(minutes=2)
# Set the scan interval to 30 seconds, to get up to date times as the time approaches. But polls are dynamically limited by update_time below.
SCAN_INTERVAL = timedelta(seconds=30)

STOP_SCHEMA = vol.Schema(
{
Expand Down Expand Up @@ -151,6 +152,7 @@ def __init__(self, metlink: Metlink, stop: Dict[str, str]):
self._state = None
self._available = True
self._icon = DEFAULT_ICON
self.update_time = dt_util.as_local(dt_util.utcnow())
_LOGGER.debug(f"Created Metlink sensor {self.uid}.")

@property
Expand Down Expand Up @@ -186,6 +188,11 @@ def device_state_attributes(self) -> Dict[str, Any]:
return self.attrs

async def async_update(self):
# Only poll the API if it is time to do so
now = dt_util.as_local(dt_util.utcnow())
if self.update_time > now:
return

num = 0
try:
data = await self.metlink.get_predictions(self.stop_id)
Expand Down Expand Up @@ -219,6 +226,26 @@ async def async_update(self):
self.attrs[ATTR_STOP_NAME] = departure[ATTR_NAME]
_LOGGER.info(f"{self._name}: {name} departs at {time}")
suffix = ""
# Dynamic polling of the API to get accurate predictions
# close to the time, without overloading the server when
# there is nothing pending:
when = (self._state - now).total_seconds()
# Within 3 minutes, poll next call as well
if when < 180:
self.update_time = now
# Within 15 minutes, poll every two minutes
elif when < 900:
self.update_time = now + timedelta(minutes=2)
# Within an hour, poll every 10 minutes
elif when < 3600:
self.update_time = now + timedelta(minutes=10)
# More than an hour away, don't poll until 1 hour before
else:
self.update_time = self._state - timedelta(hours=1)

_LOGGER.debug(
f"Next departure at {self._state}, blocking updates until {self.update_time}"
)
else:
suffix = f"_{num}"
_LOGGER.log(
Expand Down

0 comments on commit 0e6b158

Please sign in to comment.