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],
            },
        )
Beispiel #2
0
    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())
except (
        GarminConnectConnectionError,
        GarminConnectAuthenticationError,
        GarminConnectTooManyRequestsError,
) as err:
    print("Error occurred during Garmin Connect Client get full name: %s" %
          err)
    quit()
except Exception:  # pylint: disable=broad-except
    print("Unknown error occurred during Garmin Connect Client get full name")
    quit()
"""
Get unit system from profile
"""
try:
Beispiel #3
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 #4
0
    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()


"""
Get full name from profile
"""
try:
    fullname = client.get_full_name()
    logging.info('Garmin user : '+ fullname)
except (
    GarminConnectConnectionError,
    GarminConnectAuthenticationError,
    GarminConnectTooManyRequestsError,
) as err:
    print("Error occured during Garmin Connect Client get full name: %s" % err)
    quit()
except Exception:  # pylint: disable=broad-except
    print("Unknown error occured during Garmin Connect Client get full name")
    quit()

"""
Get activities data
"""