Ejemplo n.º 1
0
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 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
Ejemplo n.º 3
0
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
Ejemplo n.º 4
0
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 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)
Ejemplo n.º 6
0
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)
Ejemplo n.º 7
0
 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
Ejemplo n.º 8
0
 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)
Ejemplo n.º 9
0
    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 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
Ejemplo n.º 11
0
    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 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
Ejemplo n.º 13
0
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
Ejemplo n.º 14
0
#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
"""
Ejemplo n.º 15
0
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
"""
Ejemplo n.º 16
0
        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(":", "-")
Ejemplo n.º 17
0
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)
Ejemplo n.º 18
0
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,
Ejemplo n.º 20
0
"""
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
"""