def get_garmin_data(username, password): # input: username and passwrod # output: normalised pandas df containing garmain connect data of username # connect garmin client client = Garmin(username, password) client.login() activities = client.get_activities(0, 1000) # store as dataframe df = pd.DataFrame(activities) # make data useable wanted = [ 'activityId', 'activityName', 'startTimeLocal', 'distance', 'duration', 'elevationGain', 'elevationLoss', 'averageSpeed', 'maxSpeed', 'calories', 'averageHR', 'maxHR', 'averageRunningCadenceInStepsPerMinute', 'averageBikingCadenceInRevPerMinute', 'averageSwimCadenceInStrokesPerMinute', 'aerobicTrainingEffect', 'anaerobicTrainingEffect' ] df = df[df.columns.intersection(wanted)] df['duration'] = df['duration'].div(60).round(2) df['activityType'] = df['activityName'].str.split(' ').str[-1] df['startTimeLocal'] = pd.to_datetime(df['startTimeLocal'], errors='coerce') df['startTimeLocal'] = df['startTimeLocal'].dt.date return df
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up Garmin Connect from a config entry.""" username = entry.data[CONF_USERNAME] password = entry.data[CONF_PASSWORD] garmin_client = Garmin(username, password) try: garmin_client.login() except ( GarminConnectAuthenticationError, GarminConnectTooManyRequestsError, ) as err: _LOGGER.error("Error occurred during Garmin Connect login request: %s", err) return False except (GarminConnectConnectionError) as err: _LOGGER.error( "Connection error occurred during Garmin Connect login request: %s", err) raise ConfigEntryNotReady except Exception: # pylint: disable=broad-except _LOGGER.exception( "Unknown error occurred during Garmin Connect login request") return False garmin_data = GarminConnectData(hass, garmin_client) hass.data[DOMAIN][entry.entry_id] = garmin_data for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component)) return True
def get_client(self): ''' Initialize Garmin client with credentials and login to Garmin Connect portal The library will try to relogin when session expires ''' client = Garmin(self.user, self.password) client.login() return client
def _get_client(self): credentials = self.secret_api.get_credentials() if not credentials: raise SecretsError('Error fetching garmin login credentials') try: client = Garmin(credentials["EMAIL"], credentials["PASSWORD"]) client.login() return client except (GarminConnectConnectionError, GarminConnectAuthenticationError, GarminConnectTooManyRequestsError): raise GarminLoginError('Error logging into garmin')
def load_data(self, from_index=0, to_index=10): try: json_config = common.jsonConfig client = Garmin(json_config['Garmin']['Username'], json_config['Garmin']['Password']) activities = self.activities for start in range(from_index, to_index, 1): print(start) new_activities = self.load_data_batch(client, start) if new_activities is not None: activities = pandas.concat([activities, new_activities], ignore_index=True) activities = activities.drop_duplicates( subset=["activityId"]) activities.to_json("data.json") activities.to_excel("data.xlsx") self.activities = activities return activities except ( GarminConnectConnectionError, GarminConnectAuthenticationError, GarminConnectTooManyRequestsError, ) as err: print("Error occurred during Garmin Connect Client get stats: %s" % err)
def connect_to_garmin(username, password): """ initialize the connection to garmin servers The library will try to relogin when session expires :param username: garmin username :param password: garmin connect password :return: client object """ print("Garmin(email, password)") print("----------------------------------------------------------------------------------------") try: client = Garmin(username, password) except ( GarminConnectConnectionError, GarminConnectAuthenticationError, GarminConnectTooManyRequestsError, ) as err: print("Error occurred during Garmin Connect Client get initial client: %s" % err) quit() except Exception: print("Unknown error occurred during Garmin Connect Client get initial client") quit() print("client.login()") print("----------------------------------------------------------------------------------------") login_command = "client.login()" get_data_from_garmin("login", login_command, client=client) return client
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Garmin Connect from a config entry.""" username = entry.data[CONF_USERNAME] password = entry.data[CONF_PASSWORD] garmin_client = Garmin(username, password) try: await hass.async_add_executor_job(garmin_client.login) except ( GarminConnectAuthenticationError, GarminConnectTooManyRequestsError, ) as err: _LOGGER.error("Error occurred during Garmin Connect login request: %s", err) return False except (GarminConnectConnectionError) as err: _LOGGER.error( "Connection error occurred during Garmin Connect login request: %s", err) raise ConfigEntryNotReady from err except Exception: # pylint: disable=broad-except _LOGGER.exception( "Unknown error occurred during Garmin Connect login request") return False garmin_data = GarminConnectData(hass, garmin_client) hass.data.setdefault(DOMAIN, {}) hass.data[DOMAIN][entry.entry_id] = garmin_data hass.config_entries.async_setup_platforms(entry, PLATFORMS) return True
def login(self): try: self._api = Garmin(self._username, self._password, is_cn=self._is_cn) self._api.login() self.logger.info(self._api.get_full_name()) self.logger.info(self._api.get_unit_system()) except ( GarminConnectConnectionError, GarminConnectAuthenticationError, GarminConnectTooManyRequestsError, ) as err: self._api = Garmin(self._username, self._password, is_cn=self._is_cn) self._api.login() self.logger.error( "Error occurred during Garmin Connect communication: %s", err)
async def async_step_user(self, user_input=None): """Handle the initial step.""" if user_input is None: return await self._show_setup_form() garmin_client = Garmin(user_input[CONF_USERNAME], user_input[CONF_PASSWORD]) errors = {} try: await self.hass.async_add_executor_job(garmin_client.login) except GarminConnectConnectionError: errors["base"] = "cannot_connect" return await self._show_setup_form(errors) except GarminConnectAuthenticationError: errors["base"] = "invalid_auth" return await self._show_setup_form(errors) except GarminConnectTooManyRequestsError: errors["base"] = "too_many_requests" return await self._show_setup_form(errors) except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" return await self._show_setup_form(errors) unique_id = garmin_client.get_full_name() await self.async_set_unique_id(unique_id) self._abort_if_unique_id_configured() return self.async_create_entry( title=unique_id, data={ CONF_ID: unique_id, CONF_USERNAME: user_input[CONF_USERNAME], CONF_PASSWORD: user_input[CONF_PASSWORD], }, )
def set_user(email, password): try: client = Garmin(email, password) except ( GarminConnectConnectionError, GarminConnectAuthenticationError, GarminConnectTooManyRequestsError, ) as err: print("Error occurred during Garmin Connect Client init: %s" % err) return err except Exception: # pylint: disable=broad-except print("Unknown error occurred during Garmin Connect Client init") return return client
def get_garmin_client(): """ General access point for getting an authenticated Garmin Connect session. Returns ------- session : Garmin Connected Garmin Connect API object """ # 1. If an email / password is stored, attempt to login with the credentials while True: try: session = Garmin(*default_credentials()) session.login() return session except FileNotFoundError: # No credential file created break except (GarminConnectAuthenticationError, HTTPError): # Invalid authentication warn( f'Default credentials in {credential_file_path} are invalid.' f' Please update.', UserWarning) break # 2. Try entering credentials manually. while True: email, password = prompt_credentials() try: session = Garmin(email, password) session.login() save = confirm('Do you want to save these credentials?') if save: save_file_path = create_credential_file(email, password) echo(f'Email and password saved to {save_file_path}') return session except (GarminConnectConnectionError, GarminConnectAuthenticationError, GarminConnectTooManyRequestsError, HTTPError) as err: print("Error occured during Garmin Connect Client login: %s" % err)
def initiaConnection(): try: Garmin_User = os.environ.get("Garmin_User") Garmin_Passwort = os.environ.get("Garmin_Passwort") client = Garmin(Gamrin_User, Garmin_Passwort) except ( GarminConnectConnectionError, GarminConnectAuthenticationError, GarminConnectTooManyRequestsError, ) as err: print("Error occured during Garmin Connect Client init: %s" % err) quit() except Exception: # pylint: disable=broad-except print("Unknown error occured during Garmin Connect Client init") quit() """ Login to Garmin Connect portal Only needed at start of your program The libary will try to relogin when session expires """ try: client.login() except ( GarminConnectConnectionError, GarminConnectAuthenticationError, GarminConnectTooManyRequestsError, ) as err: print("Error occured during Garmin Connect Client login: %s" % err) quit() except Exception: # pylint: disable=broad-except print("Unknown error occured during Garmin Connect Client login") quit() return client
def doLogin(email, pswd): try: client = Garmin("*****@*****.**", "Pleasesnow24") except ( GarminConnectConnectionError, GarminConnectAuthenticationError, GarminConnectTooManyRequestsError, ) as err: print("Error occurred during Garmin Connect Client init: %s" % err) except Exception: # pylint: disable=broad-except print("Unknown error occurred during Garmin Connect Client init") try: client.login() except ( GarminConnectConnectionError, GarminConnectAuthenticationError, GarminConnectTooManyRequestsError, ) as err: print("Error occurred during Garmin Connect Client login: %s" % err) except Exception: # pylint: disable=broad-except print("Unknown error occurred during Garmin Connect Client login") return client
from datetime import date import datetime import pandas as pd """ Enable debug logging """ #import logging #logging.basicConfig(level=logging.DEBUG) today = date.today() """ Initialize Garmin client with credentials Only needed when your program is initialized """ try: client = Garmin(credentials['email'], credentials['password']) except ( GarminConnectConnectionError, GarminConnectAuthenticationError, GarminConnectTooManyRequestsError, ) as err: print("Error occurred during Garmin Connect Client init: %s" % err) quit() except Exception: # pylint: disable=broad-except print("Unknown error occurred during Garmin Connect Client init") quit() """ Login to Garmin Connect portal Only needed at start of your program The library will try to relogin when session expires """
class GarminConnect(SmartPlugin): """ Retrieves Garmin Connect Stats and Heart Rates. """ PLUGIN_VERSION = "1.2.0" def __init__(self, sh, *args, **kwargs): # Call init code of parent class (SmartPlugin or MqttPlugin) super().__init__() self._shtime = Shtime.get_instance() self._username = self.get_parameter_value("email") self._password = self.get_parameter_value("password") self._is_cn = self.get_parameter_value("is_cn") self._api = None self.init_webinterface() def run(self): self.alive = True def stop(self): """ Stop method for the plugin """ self.alive = False def parse_item(self, item): pass def parse_logic(self, logic): pass def update_item(self, item, caller=None, source=None, dest=None): pass def login(self): try: self._api = Garmin(self._username, self._password, is_cn=self._is_cn) self._api.login() self.logger.info(self._api.get_full_name()) self.logger.info(self._api.get_unit_system()) except ( GarminConnectConnectionError, GarminConnectAuthenticationError, GarminConnectTooManyRequestsError, ) as err: self._api = Garmin(self._username, self._password, is_cn=self._is_cn) self._api.login() self.logger.error( "Error occurred during Garmin Connect communication: %s", err) def get_stats(self, date_str=None): date = self._get_date(date_str) self.login() stats = self._api.get_stats(date.strftime('%Y-%m-%d')) return stats def get_heart_rates(self, date_str=None): date = self._get_date(date_str) self.login() heart_rates = self._api.get_heart_rates(date.strftime('%Y-%m-%d')) return heart_rates def _get_date(self, date_str): if date_str is not None: date = self._shtime.datetime_transform(date_str) else: date = self._shtime.now() return date def init_webinterface(self): """ Initialize the web interface for this plugin This method is only needed if the plugin is implementing a web interface """ try: self.mod_http = Modules.get_instance().get_module( 'http' ) # try/except to handle running in a core version that does not support modules except: self.mod_http = None if self.mod_http == None: self.logger.error( "Plugin '{}': Not initializing the web interface".format( self.get_shortname())) return False # set application configuration for cherrypy webif_dir = self.path_join(self.get_plugin_dir(), 'webif') config = { '/': { 'tools.staticdir.root': webif_dir, }, '/static': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'static' } } # Register the web interface as a cherrypy app self.mod_http.register_webif(WebInterface(webif_dir, self), self.get_shortname(), config, self.get_classname(), self.get_instance_name(), description='') return True
logger.warn("Skipping %s, as it already exists", output_file) else: logger.info( "Downloading %s format as .%s to %s", dl_fmt, ext, output_file) data = api.download_activity(activity_id, dl_fmt=dl_fmt) with open(output_file, "wb") as fb: fb.write(data) try: username = os.environ['GARMIN_CONNECT_USER'] password = os.environ['GARMIN_CONNECT_PASSWORD'] api = Garmin(username, password) logger.info("Logging in as '%s'", username) api.login() logger.info("Logged in!") activities = api.get_activities_by_date( startdate.isoformat(), enddate.isoformat(), None ) for activity in activities: activity_id = activity["activityId"] activity_start = activity["startTimeLocal"] activity_type = activity["activityType"]["typeKey"] file_name = (activity_start.replace(" ", "_").replace(":", "-")
def hr_for_date(api, date_to_fetch): return api.get_heart_rates(date_to_fetch.isoformat())['heartRateValues'] def stress_for_date(api, date_to_fetch): return api.get_stress_data(date_to_fetch.isoformat())['stressValuesArray'] date_to_fetch = date.today().isoformat() if len(sys.argv) > 1: date_to_fetch = sys.argv[1] date_to_fetch = date.fromisoformat(date_to_fetch) try: api = Garmin(email, password) api.login() hr_points = list( map(lambda p: hr2point(*p), hr_for_date(api, date_to_fetch - timedelta(days=1)))) stress_points = list( map(lambda p: stress2point(*p), stress_for_date(api, date_to_fetch - timedelta(days=1)))) hr_points += list( map(lambda p: hr2point(*p), hr_for_date(api, date_to_fetch))) stress_points += list( map(lambda p: stress2point(*p), stress_for_date(api, date_to_fetch))) with InfluxDBClient(url="https://stats.chvp.be:8086", token=token, org=org) as client: write_api = client.write_api(write_options=SYNCHRONOUS) write_api.write(bucket, org, hr_points)
#import logging #logging.basicConfig(level=logging.DEBUG) today = date.today() confpath = os.getcwd() conf = open(confpath + '\\config\\creds.conf') YOUR_EMAIL = conf.readline().rstrip() YOUR_PASSWORD = conf.readline().rstrip() """ Initialize Garmin client with credentials Only needed when your program is initialized """ try: client = Garmin(YOUR_EMAIL, YOUR_PASSWORD) except ( GarminConnectConnectionError, GarminConnectAuthenticationError, GarminConnectTooManyRequestsError, ) as err: print("Error occured during Garmin Connect Client init: %s" % err) quit() except Exception: # pylint: disable=broad-except print("Unknown error occured during Garmin Connect Client init") quit() """ Login to Garmin Connect portal Only needed at start of your program The libary will try to relogin when session expires """
import googleapiclient.discovery from garminconnect import ( Garmin, GarminConnectConnectionError, GarminConnectTooManyRequestsError, GarminConnectAuthenticationError, ) import config logging.basicConfig(level=logging.ERROR) today = date.today() try: client = Garmin(config.garmin["USERNAME"], config.garmin["PASSWORD"]) except ( GarminConnectConnectionError, GarminConnectAuthenticationError, GarminConnectTooManyRequestsError, ) as err: print("Error occurred during Garmin Connect Client init: %s" % err) quit() except Exception: # pylint: disable=broad-except print("Unknown error occurred during Garmin Connect Client init") quit() try: client.login() except ( GarminConnectConnectionError,
GarminConnectConnectionError, GarminConnectTooManyRequestsError, GarminConnectAuthenticationError, ) from datetime import date import pandas as pd import logging from garmin_credentials import garmin_password, garmin_username logging.basicConfig(level=logging.DEBUG) today = date.today() try: client = Garmin(garmin_username, garmin_password) except ( GarminConnectConnectionError, GarminConnectAuthenticationError, GarminConnectTooManyRequestsError, ) as err: print("Error occurred during Garmin Connect Client init: %s" % err) quit() except Exception: # pylint: disable=broad-except print("Unknown error occurred during Garmin Connect Client init") quit() try: client.login() except ( GarminConnectConnectionError,
""" config_object = ConfigParser() config_object.read("/python/config.ini") """ Get the password """ userinfo = config_object["USERINFO"] logging.info(userinfo["email"]) """ Initialize Garmin client with credentials """ try: client = Garmin(userinfo["email"],userinfo["password"]) except ( GarminConnectConnectionError, GarminConnectAuthenticationError, GarminConnectTooManyRequestsError, ) as err: print("Error occured during Garmin Connect Client init: %s" % err) quit() except Exception: # pylint: disable=broad-except print("Unknown error occured during Garmin Connect Client init") quit() """ Login to Garmin Connect portal """