def get_activity_data(access_token): client = Client(access_token) athlete = client.get_athlete() activity_stats = client.get_athlete_stats() run_count = activity_stats.all_run_totals.count bike_count = activity_stats.all_ride_totals.count swim_count = activity_stats.all_swim_totals.count total_count = run_count + bike_count + swim_count all_activities = client.get_activities() run_activities = [] swim_activities = [] bike_activities = [] calorie_count = 0.0 for activity in all_activities: if (activity.type == "Run"): run_activities.append(activity) calorie_count += (float(activity.distance) / 1000) * float(athlete.weight) * 1.036 if (activity.type == "Swim"): swim_activities.append(activity) if (activity.type == "Ride"): bike_activities.append(activity) return ({"Runs": run_activities, "Swims" : swim_activities, "Rides": bike_activities, "Calorie_Count" : calorie_count})
class StravaData: """Implementation of the Strava data retriever.""" def __init__(self, hass, accesstoken, devices): self.hass = hass from stravalib import Client from stravalib.util import limiter self._strava_client = Client(access_token=accesstoken, rate_limiter=limiter.DefaultRateLimiter()) self._athlete = self._strava_client.get_athlete() self._accesstoken = accesstoken self._devices = devices self._athlete_stats = None @asyncio.coroutine def fetch_data(self, *_): """Get the athlete stats.""" stats_fetched_ok = False from requests.exceptions import ConnectionError try: athlete_stats = self._strava_client.get_athlete_stats( athlete_id=self._athlete.id) stats_fetched_ok = True except: _LOGGER.warn("Failed to get athlete stats, re-initiating client") from stravalib import Client from stravalib.util import limiter self._strava_client = Client( access_token=self._accesstoken, rate_limiter=limiter.DefaultRateLimiter()) if stats_fetched_ok: self._athlete_stats = athlete_stats.to_dict() yield from self.update_devices() async_call_later(self.hass, 2 * 60, self.fetch_data) @asyncio.coroutine def update_devices(self, *_): if not self._athlete_stats: return tasks = [] for sensor_type in self._athlete_stats: for device in self._devices: if device.type == sensor_type: device.set_state(self._athlete_stats[sensor_type]) tasks.append(device.async_update_ha_state()) if tasks: yield from asyncio.wait(tasks, loop=self.hass.loop)