-
-
Notifications
You must be signed in to change notification settings - Fork 37.7k
Add Garmin Connect integration #30792
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
Merged
Merged
Changes from 16 commits
Commits
Show all changes
45 commits
Select commit
Hold shift + click to select a range
1c8dda2
Added code files
cyberjunky 54a86b8
Correctly name init file
cyberjunky 88c8039
Update codeowners
cyberjunky f8d6f14
Update requirements
cyberjunky 0a6d74a
Added code files
cyberjunky 51b1d5a
Correctly name init file
cyberjunky d688f80
Update codeowners
cyberjunky 74059c9
Update requirements
cyberjunky 774fe24
Black changes, added to coveragerc
cyberjunky c2793f9
Merge branch 'garmin-connect' of https://github.com/cyberjunky/home-a…
cyberjunky 72350dc
Removed documentation location for now
cyberjunky 03a7b75
Added documentation url
cyberjunky 3c166ec
Fixed merge
cyberjunky 48783bf
Fixed flake8 syntax
cyberjunky 2a90f7c
Merge branch 'garmin-connect' of https://github.com/cyberjunky/home-a…
cyberjunky 30ada90
Fixed isort
cyberjunky 4aeaa0d
Removed false check and double throttle, applied time format change
cyberjunky 9043a5e
Renamed email to username, used dict, deleted unused type, changed at…
cyberjunky 2880a96
Async and ConfigFlow code
cyberjunky cd9b34f
Fixes
cyberjunky 42857f6
Added device_class and misc fixes
cyberjunky ebfa841
isort and pylint fixes
cyberjunky 3dea786
Removed from test requirements
cyberjunky cad6f49
Merge pull request #1 from cyberjunky/garmin-connect-configflow
cyberjunky 92b46eb
Fixed isort checkblack
cyberjunky b4357b4
Removed host field
cyberjunky f7735f4
Fixed coveragerc
cyberjunky db3f856
Start working test file
cyberjunky d021103
Added more config_flow tests
cyberjunky 60f5c11
Enable only most used sensors by default
cyberjunky a2f11ab
Added more default enabled sensors, fixed tests
cyberjunky cae9406
Fixed isort
cyberjunky 08d0a6d
Test config_flow improvements
cyberjunky 9a6ce6f
Remove unused import
cyberjunky 53b53e2
Removed redundant patch calls
cyberjunky 9a17cc1
Fixed mock return value
cyberjunky 39df719
Updated to garmin_connect 0.1.8 fixed exceptions
cyberjunky 37ee95a
Quick fix test patch to see if rest is error free
cyberjunky fb90fc0
Fixed mock routine
cyberjunky 282fa4c
Code improvements from PR feedback
cyberjunky 4325416
Fix entity indentifier
cyberjunky a4bf720
Reverted device identifier
cyberjunky d8c0839
Fixed abort message
cyberjunky d91f2de
Test fix
cyberjunky 14453e9
Fixed unique_id MockConfigEntry
cyberjunky File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| """The Garmin Connect integration.""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| { | ||
| "domain": "garmin_connect", | ||
| "name": "Garmin Connect", | ||
| "documentation": "https://www.home-assistant.io/integrations/garmin_connect", | ||
| "dependencies": [], | ||
| "requirements": ["garminconnect==0.1.4"], | ||
| "codeowners": ["@cyberjunky"] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,255 @@ | ||
| """Platform for Garmin Connect integration.""" | ||
| from datetime import date, timedelta | ||
| import logging | ||
|
|
||
| import garminconnect | ||
| import voluptuous as vol | ||
|
|
||
| from homeassistant.components.sensor import PLATFORM_SCHEMA | ||
| from homeassistant.const import ( | ||
| ATTR_ATTRIBUTION, | ||
| CONF_EMAIL, | ||
| CONF_MONITORED_CONDITIONS, | ||
| CONF_NAME, | ||
| CONF_PASSWORD, | ||
| ) | ||
| import homeassistant.helpers.config_validation as cv | ||
| from homeassistant.helpers.entity import Entity | ||
| from homeassistant.util import Throttle | ||
|
|
||
| GARMIN_CONDITIONS_LIST = { | ||
| "totalSteps": ["Total Steps", "steps", "mdi:walk"], | ||
| "dailyStepGoal": ["Daily Step Goal", "steps", "mdi:walk"], | ||
| "totalKilocalories": ["Total KiloCalories", "kcal", "mdi:food"], | ||
| "activeKilocalories": ["Active KiloCalories", "kcal", "mdi:food"], | ||
| "bmrKilocalories": ["BMR KiloCalories", "kcal", "mdi:food"], | ||
| "consumedKilocalories": ["Consumed KiloCalories", "kcal", "mdi:food"], | ||
| "burnedKilocalories": ["Burned KiloCalories", "kcal", "mdi:food"], | ||
| "remainingKilocalories": ["Remaining KiloCalories", "kcal", "mdi:food"], | ||
| "netRemainingKilocalories": ["Net Remaining KiloCalories", "kcal", "mdi:food"], | ||
| "netCalorieGoal": ["Net Calorie Goal", "cal", "mdi:food"], | ||
| "totalDistanceMeters": ["Total Distance Mtr", "mtr", "mdi:walk"], | ||
| "wellnessStartTimeLocal": ["Wellness Start Time", "", "mdi:clock"], | ||
| "wellnessEndTimeLocal": ["Wellness End Time", "", "mdi:clock"], | ||
| "wellnessDescription": ["Wellness Description", "", "mdi:clock"], | ||
| "wellnessDistanceMeters": ["Wellness Distance Mtr", "mtr", "mdi:walk"], | ||
| "wellnessActiveKilocalories": ["Wellness Active KiloCalories", "kcal", "mdi:food"], | ||
| "wellnessKilocalories": ["Wellness KiloCalories", "kcal", "mdi:food"], | ||
| "highlyActiveSeconds": ["Highly Active Time", "minutes", "mdi:fire"], | ||
| "activeSeconds": ["Active Time", "minutes", "mdi:fire"], | ||
| "sedentarySeconds": ["Sedentary Time", "minutes", "mdi:seat"], | ||
| "sleepingSeconds": ["Sleeping Time", "minutes", "mdi:sleep"], | ||
| "measurableAwakeDuration": ["Awake Duration", "minutes", "mdi:sleep"], | ||
| "measurableAsleepDuration": ["Sleep Duration", "minutes", "mdi:sleep"], | ||
| "floorsAscendedInMeters": ["Floors Ascended Mtr", "mtr", "mdi:stairs"], | ||
| "floorsDescendedInMeters": ["Floors Descended Mtr", "mtr", "mdi:stairs"], | ||
| "floorsAscended": ["Floors Ascended", "floors", "mdi:stairs"], | ||
| "floorsDescended": ["Floors Descended", "floors", "mdi:stairs"], | ||
| "userFloorsAscendedGoal": ["Floors Ascended Goal", "", "mdi:stairs"], | ||
| "minHeartRate": ["Min Heart Rate", "bpm", "mdi:heart-pulse"], | ||
| "maxHeartRate": ["Max Heart Rate", "bpm", "mdi:heart-pulse"], | ||
| "restingHeartRate": ["Resting Heart Rate", "bpm", "mdi:heart-pulse"], | ||
| "minAvgHeartRate": ["Min Avg Heart Rate", "bpm", "mdi:heart-pulse"], | ||
| "maxAvgHeartRate": ["Max Avg Heart Rate", "bpm", "mdi:heart-pulse"], | ||
| "abnormalHeartRateAlertsCount": ["Abnormal HR Counts", "", "mdi:heart-pulse"], | ||
| "lastSevenDaysAvgRestingHeartRate": [ | ||
| "Last 7 Days Avg Heart Rate", | ||
| "bpm", | ||
| "mdi:heart-pulse", | ||
| ], | ||
| "averageStressLevel": ["Avg Stress Level", "", "mdi:flash-alert"], | ||
| "maxStressLevel": ["Max Stress Level", "", "mdi:flash-alert"], | ||
| "stressQualifier": ["Stress Qualifier", "", "mdi:flash-alert"], | ||
| "stressDuration": ["Stress Duration", "minutes", "mdi:flash-alert"], | ||
| "restStressDuration": ["Rest Stress Duration", "minutes", "mdi:flash-alert"], | ||
| "activityStressDuration": [ | ||
| "Activity Stress Duration", | ||
| "minutes", | ||
| "mdi:flash-alert", | ||
| ], | ||
| "uncategorizedStressDuration": [ | ||
| "Uncat. Stress Duration", | ||
| "minutes", | ||
| "mdi:flash-alert", | ||
| ], | ||
| "totalStressDuration": ["Total Stress Duration", "minutes", "mdi:flash-alert"], | ||
| "lowStressDuration": ["Low Stress Duration", "minutes", "mdi:flash-alert"], | ||
| "mediumStressDuration": ["Medium Stress Duration", "minutes", "mdi:flash-alert"], | ||
| "highStressDuration": ["High Stress Duration", "minutes", "mdi:flash-alert"], | ||
| "stressPercentage": ["Stress Percentage", "%", "mdi:flash-alert"], | ||
| "restStressPercentage": ["Rest Stress Percentage", "%", "mdi:flash-alert"], | ||
| "activityStressPercentage": ["Activity Stress Percentage", "%", "mdi:flash-alert"], | ||
| "uncategorizedStressPercentage": [ | ||
| "Uncat. Stress Percentage", | ||
| "%", | ||
| "mdi:flash-alert", | ||
| ], | ||
| "lowStressPercentage": ["Low Stress Percentage", "%", "mdi:flash-alert"], | ||
| "mediumStressPercentage": ["Medium Stress Percentage", "%", "mdi:flash-alert"], | ||
| "highStressPercentage": ["High Stress Percentage", "%", "mdi:flash-alert"], | ||
| "moderateIntensityMinutes": ["Moderate Intensity", "minutes", "mdi:flash-alert"], | ||
| "vigorousIntensityMinutes": ["Vigorous Intensity", "minutes", "mdi:run-fast"], | ||
| "intensityMinutesGoal": ["Intensity Goal", "minutes", "mdi:run-fast"], | ||
| "bodyBatteryChargedValue": [ | ||
| "Body Battery Charged", | ||
| "%", | ||
| "mdi:battery-charging-100", | ||
| ], | ||
| "bodyBatteryDrainedValue": [ | ||
| "Body Battery Drained", | ||
| "%", | ||
| "mdi:battery-alert-variant-outline", | ||
| ], | ||
| "bodyBatteryHighestValue": ["Body Battery Highest", "%", "mdi:battery-heart"], | ||
| "bodyBatteryLowestValue": ["Body Battery Lowest", "%", "mdi:battery-heart-outline"], | ||
| "bodyBatteryMostRecentValue": [ | ||
| "Body Battery Most Recent", | ||
| "%", | ||
| "mdi:battery-positive", | ||
| ], | ||
| "averageSpo2": ["Average SPO2", "%", "mdi:diabetes"], | ||
| "lowestSpo2": ["Lowest SPO2", "%", "mdi:diabetes"], | ||
| "latestSpo2": ["Latest SPO2", "%", "mdi:diabetes"], | ||
| "latestSpo2ReadingTimeLocal": ["Latest SPO2 Time", "", "mdi:diabetes"], | ||
| "averageMonitoringEnvironmentAltitude": [ | ||
| "Average Altitude", | ||
| "%", | ||
| "mdi:image-filter-hdr", | ||
| ], | ||
| "durationInMilliseconds": ["Duration", "ms", "mdi:progress-clock"], | ||
|
MartinHjelmare marked this conversation as resolved.
Outdated
|
||
| "highestRespirationValue": ["Highest Respiration", "brpm", "mdi:progress-clock"], | ||
| "lowestRespirationValue": ["Lowest Respiration", "brpm", "mdi:progress-clock"], | ||
| "latestRespirationValue": ["Latest Respiration", "brpm", "mdi:progress-clock"], | ||
| "latestRespirationTimeGMT": ["Latest Respiration Update", "", "mdi:progress-clock"], | ||
| } | ||
|
|
||
| _LOGGER = logging.getLogger(__name__) | ||
|
|
||
| GARMIN_DEFAULT_CONDITIONS = ["totalSteps"] | ||
| ATTRIBUTION = "Data provided by garmin.com" | ||
| DEFAULT_NAME = "Garmin" | ||
| MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=10) | ||
|
|
||
| PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( | ||
| { | ||
| vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, | ||
| vol.Required(CONF_EMAIL): cv.string, | ||
|
cyberjunky marked this conversation as resolved.
Outdated
|
||
| vol.Required(CONF_PASSWORD): cv.string, | ||
| vol.Optional( | ||
| CONF_MONITORED_CONDITIONS, default=GARMIN_DEFAULT_CONDITIONS | ||
| ): vol.All(cv.ensure_list, [vol.In(GARMIN_CONDITIONS_LIST)]), | ||
| } | ||
| ) | ||
|
|
||
|
|
||
| def setup_platform(hass, config, add_entities, discovery_info=None): | ||
| """Set up the Garmin Connect component.""" | ||
|
|
||
| email = config.get(CONF_EMAIL) | ||
|
MartinHjelmare marked this conversation as resolved.
Outdated
|
||
| password = config.get(CONF_PASSWORD) | ||
|
MartinHjelmare marked this conversation as resolved.
Outdated
|
||
| prefix_name = config.get(CONF_NAME) | ||
|
MartinHjelmare marked this conversation as resolved.
Outdated
|
||
|
|
||
| try: | ||
| garmin_client = garminconnect.Garmin(email, password) | ||
|
cyberjunky marked this conversation as resolved.
Outdated
|
||
| except ValueError as err: | ||
| _LOGGER.error("Error occured during Garmin Connect Client init: %s", err) | ||
|
cyberjunky marked this conversation as resolved.
Outdated
|
||
| return | ||
|
|
||
| garmin_data = GarminConnectClient(garmin_client) | ||
|
|
||
| entities = [] | ||
| for resource in config[CONF_MONITORED_CONDITIONS]: | ||
| sensor_type = resource | ||
| name = prefix_name + " " + GARMIN_CONDITIONS_LIST[resource][0] | ||
|
MartinHjelmare marked this conversation as resolved.
Outdated
|
||
| unit = GARMIN_CONDITIONS_LIST[resource][1] | ||
| icon = GARMIN_CONDITIONS_LIST[resource][2] | ||
|
|
||
| _LOGGER.debug( | ||
| "Registered new sensor: %s, %s, %s, %s", sensor_type, name, unit, icon | ||
| ) | ||
| entities.append(GarminConnectSensor(garmin_data, sensor_type, name, unit, icon)) | ||
|
|
||
| add_entities(entities, True) | ||
|
|
||
|
|
||
| class GarminConnectClient: | ||
| """Set up the Garmin Connect client.""" | ||
|
|
||
| def __init__(self, client): | ||
| """Initialize the client.""" | ||
| self.client = client | ||
| self.data = None | ||
|
|
||
| @Throttle(MIN_TIME_BETWEEN_UPDATES) | ||
| def update(self): | ||
| """Fetch the latest data.""" | ||
| today = date.today() | ||
| try: | ||
| self.data = self.client.fetch_stats(today.strftime("%Y-%m-%d")) | ||
|
cyberjunky marked this conversation as resolved.
Outdated
|
||
| except ValueError as err: | ||
| _LOGGER.error("Error occured while fetching Garmin Connect data: %s", err) | ||
| return | ||
|
|
||
|
|
||
| class GarminConnectSensor(Entity): | ||
| """Representation of a Garmin Connect Sensor.""" | ||
|
|
||
| def __init__(self, data, sensor_type, name, unit, icon): | ||
|
cyberjunky marked this conversation as resolved.
Outdated
|
||
| """Initialize the sensor.""" | ||
| self._data = data | ||
| self._type = sensor_type | ||
| self._name = name | ||
| self._icon = icon | ||
| self._unit = unit | ||
| self._state = None | ||
|
|
||
| @property | ||
| def name(self): | ||
| """Return the name of the sensor.""" | ||
| return self._name | ||
|
|
||
| @property | ||
| def icon(self): | ||
| """Return the icon to use in the frontend.""" | ||
| return self._icon | ||
|
|
||
| @property | ||
| def state(self): | ||
| """Return the state of the sensor.""" | ||
| return self._state | ||
|
|
||
| @property | ||
| def unit_of_measurement(self): | ||
| """Return the unit of measurement.""" | ||
| return self._unit | ||
|
|
||
| @property | ||
| def device_state_attributes(self): | ||
| """Return attributes for sensor.""" | ||
|
|
||
| attributes = {} | ||
| if self._data.data: | ||
| attributes = { | ||
| "source": self._data.data["source"], | ||
| "last synced (GMT)": self._data.data["lastSyncTimestampGMT"], | ||
|
MartinHjelmare marked this conversation as resolved.
Outdated
|
||
| ATTR_ATTRIBUTION: ATTRIBUTION, | ||
| } | ||
| return attributes | ||
|
|
||
| @Throttle(MIN_TIME_BETWEEN_UPDATES) | ||
|
cyberjunky marked this conversation as resolved.
Outdated
|
||
| def update(self): | ||
| """Update data and set sensor states.""" | ||
| self._data.update() | ||
| data = self._data.data | ||
|
|
||
| if GARMIN_CONDITIONS_LIST[self._type] and self._type in data: | ||
|
cyberjunky marked this conversation as resolved.
Outdated
|
||
| if "Duration" in self._type: | ||
| self._state = data[self._type] // 60 | ||
| elif "Seconds" in self._type: | ||
| self._state = data[self._type] // 60 | ||
| else: | ||
| self._state = data[self._type] | ||
|
|
||
| _LOGGER.debug( | ||
| "Device %s set to state %s %s", self._type, self._state, self._unit | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.