Beispiel #1
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
Beispiel #2
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
Beispiel #3
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
Beispiel #4
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')
Beispiel #5
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)
Beispiel #6
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:
            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 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
Beispiel #9
0
        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
"""
try:
    client.login()
except (
        GarminConnectConnectionError,
        GarminConnectAuthenticationError,
        GarminConnectTooManyRequestsError,
) as err:
    print("Error occurred during Garmin Connect Client login: %s" % err)
    quit()
except Exception:  # pylint: disable=broad-except
    print("Unknown error occurred during Garmin Connect Client login")
    quit()
"""
Get full name from profile
"""
try:
    print(client.get_full_name())
Beispiel #10
0
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
Beispiel #11
0
            "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(":", "-")
                     + "_"
                     + activity_type)
        logger.info("Downloading activity with id: %s", activity_id)