Example #1
0
def pull_withings_data():
    # UTC dates will get sampled into daily
    if withings_connected():
        client = WithingsApi(load_credentials(),
                             refresh_cb=save_withings_token)

        df = pd.DataFrame(
            columns=['date_utc', 'weight', 'fat_ratio', 'hydration'])
        meas_result = client.measure_get_meas()
        for x in meas_result.measuregrps:
            date = pd.to_datetime(str(x.date))
            weight = get_measure_value(x, with_measure_type=MeasureType.WEIGHT)
            fat_ratio = get_measure_value(
                x, with_measure_type=MeasureType.FAT_RATIO)
            hydration = get_measure_value(
                x, with_measure_type=MeasureType.HYDRATION)

            if weight and fat_ratio:
                df = df.append(
                    {
                        'date_utc': date,
                        'weight': weight,
                        'fat_ratio': fat_ratio,
                        'hydration': hydration
                    },
                    ignore_index=True)

        df = df.set_index(
            df['date_utc'].apply(lambda x: x.replace(tzinfo=None)))
        df = df[['weight', 'fat_ratio', 'hydration']]
        # Convert to lbs
        df['weight'] *= 2.20462

        # Filter to days later than what is already in db
        withings_max_date = app.session.query(func.max(
            withings.date_utc)).first()[0]
        withings_max_date = datetime.strptime(
            '1991-08-30 00:00:00', '%Y-%m-%d %H:%M:%S'
        ) if not withings_max_date else withings_max_date

        app.session.remove()

        df = df[(df.index > withings_max_date) & (~np.isnan(df['weight'])) &
                (~np.isnan(df['fat_ratio']))]
        if len(df) > 0:
            app.server.logger.info('New withings measurements found!')
            df.to_sql('withings', engine, if_exists='append', index=True)
Example #2
0
def test_get_measure_value() -> None:
    """Test function."""
    response: Final = MeasureGetMeasResponse(
        offset=0,
        more=False,
        timezone=TIMEZONE0,
        updatetime=arrow.get(100000),
        measuregrps=(MeasureGetMeasGroup(
            attrib=MeasureGetMeasGroupAttrib.
            MANUAL_USER_DURING_ACCOUNT_CREATION,
            category=MeasureGetMeasGroupCategory.USER_OBJECTIVES,
            created=arrow.utcnow(),
            date=arrow.utcnow(),
            deviceid="dev1",
            grpid=1,
            measures=(
                MeasureGetMeasMeasure(type=MeasureType.WEIGHT,
                                      unit=1,
                                      value=10),
                MeasureGetMeasMeasure(type=MeasureType.BONE_MASS,
                                      unit=-2,
                                      value=20),
            ),
        ), ),
    )

    assert get_measure_value(response, MeasureType.BODY_TEMPERATURE) is None

    assert get_measure_value(response.measuregrps,
                             MeasureType.BODY_TEMPERATURE) is None

    assert (get_measure_value(response.measuregrps[0],
                              MeasureType.BODY_TEMPERATURE) is None)

    assert get_measure_value(response, MeasureType.WEIGHT) == 100
    assert get_measure_value(response.measuregrps, MeasureType.WEIGHT) == 100
    assert get_measure_value(response.measuregrps[0],
                             MeasureType.WEIGHT) == 100

    assert get_measure_value(response, MeasureType.BONE_MASS) == 0.2
    assert get_measure_value(response.measuregrps,
                             MeasureType.BONE_MASS) == 0.2
    assert get_measure_value(response.measuregrps[0],
                             MeasureType.BONE_MASS) == 0.2
Example #3
0
    async def async_update_measure(self, data: MeasureGetMeasResponse) -> None:
        """Update the measures data."""
        measure_type = self._attribute.measure_type

        _LOGGER.debug(
            "Finding the unambiguous measure group with measure_type: %s", measure_type
        )

        value = get_measure_value(data, measure_type, MeasureGroupAttribs.UNAMBIGUOUS)

        if value is None:
            _LOGGER.debug("Could not find a value, setting state to %s", None)
            self._state = None
            return

        self._state = round(value, 2)
Example #4
0
def authorize():
    if request.method == "POST":
        data = request.form
        urlcode = data["url"]
        redirected_uri_params = dict(
            parse.parse_qsl(parse.urlsplit(urlcode).query))
        auth_code = redirected_uri_params["code"]
        text_file = open("credentials.txt", "w")
        n = text_file.write(auth_code)
        text_file.close()
        file = open("credentials.txt", "r")
        aa = file.readline()
        file.close()
        credentials = auth.get_credentials(auth_code)
        api = WithingsApi(credentials)
        meas_result = api.measure_get_meas()
        weight_or_none = get_measure_value(
            meas_result, with_measure_type=MeasureType.WEIGHT)
        fat = get_measure_value(meas_result,
                                with_measure_type=MeasureType.FAT_MASS_WEIGHT)
        musle_mass = get_measure_value(
            meas_result, with_measure_type=MeasureType.MUSCLE_MASS)
        bone_mass = get_measure_value(meas_result,
                                      with_measure_type=MeasureType.BONE_MASS)
        body_water = get_measure_value(meas_result,
                                       with_measure_type=MeasureType.HYDRATION)
        heart_rate = get_measure_value(
            meas_result, with_measure_type=MeasureType.HEART_RATE)
        pluse_vave_velicity = get_measure_value(
            meas_result, with_measure_type=MeasureType.PULSE_WAVE_VELOCITY)
        return render_template("showdata.html",
                               w=weight_or_none,
                               f=fat,
                               musle_mass=musle_mass,
                               bone_mass=bone_mass,
                               body_water=body_water,
                               heart_rate=heart_rate,
                               pvv=pluse_vave_velicity)
    return "credentials"
Example #5
0
    def _update(self):
        """
        Updates information on diverse items
        """

        if 'access_token' not in self.get_items(
        ) or 'token_expiry' not in self.get_items(
        ) or 'token_type' not in self.get_items(
        ) or 'refresh_token' not in self.get_items():
            self.logger.error(
                "Mandatory Items for OAuth2 Data do not exist. Verify that you have items with withings_type: token_expiry, token_type, refresh_token and access_token in your item tree."
            )
            return

        if self._client is None:
            if self.get_item('access_token')(
            ) and self.get_item('token_expiry')() > 0 and self.get_item(
                    'token_type')() and self.get_item('refresh_token')():

                if (self.shtime.now() < datetime.datetime.fromtimestamp(
                        self.get_item('token_expiry')(),
                        tz=self.shtime.tzinfo())):
                    self.logger.debug(
                        "Token is valid, will expire on {}.".format(
                            datetime.datetime.fromtimestamp(
                                self.get_item('token_expiry')(),
                                tz=self.shtime.tzinfo()).strftime(
                                    '%d.%m.%Y %H:%M:%S')))
                    self.logger.debug(
                        "Initializing NokiaCredentials: access_token - {} token_expiry - {} token_type - {} refresh_token - {} user_id - {} client_id - {} consumer_secret - {}"
                        .format(
                            self.get_item('access_token')(),
                            self.get_item('token_expiry')(),
                            self.get_item('token_type')(),
                            self.get_item('refresh_token')(), self._user_id,
                            self._client_id, self._consumer_secret))
                    self._creds = Credentials(
                        access_token=self.get_item('access_token')(),
                        token_expiry=self.get_item('token_expiry')(),
                        token_type=self.get_item('token_type')(),
                        refresh_token=self.get_item('refresh_token')(),
                        userid=self._user_id,
                        client_id=self._client_id,
                        consumer_secret=self._consumer_secret)
                    self._client = WithingsApi(self._creds,
                                               refresh_cb=self._store_tokens)
                else:
                    self.logger.error(
                        "Token is expired, run OAuth2 again from Web Interface (Expiry Date: {})."
                        .format(
                            datetime.datetime.fromtimestamp(
                                self.get_item('token_expiry')(),
                                tz=self.shtime.tzinfo()).strftime(
                                    '%d.%m.%Y %H:%M:%S')))
                    return
            else:
                self.logger.error(
                    "Items for OAuth2 Data are not set with required values. Please run process via WebGUI of the plugin."
                )
                return
        try:
            measures = self._client.measure_get_meas(startdate=None,
                                                     enddate=None,
                                                     lastupdate=None)
        except Exception as e:
            self.logger.error(
                "An exception occured when running measure_get_meas(): {}. Aborting update."
                .format(str(e)))
            return

        if get_measure_value(measures,
                             with_measure_type=MeasureType.HEART_RATE
                             ) is not None and 'heart_rate' in self._items:
            self._items['heart_rate'](get_measure_value(
                measures, with_measure_type=MeasureType.HEART_RATE),
                                      self.get_shortname())
            self.logger.debug("heart_rate - {}".format(
                get_measure_value(measures,
                                  with_measure_type=MeasureType.HEART_RATE)))

        if get_measure_value(measures, with_measure_type=MeasureType.WEIGHT
                             ) is not None and 'weight' in self._items:
            self._items['weight'](get_measure_value(
                measures, with_measure_type=MeasureType.WEIGHT),
                                  self.get_shortname())
            self.logger.debug("weight - {}".format(
                get_measure_value(measures,
                                  with_measure_type=MeasureType.WEIGHT)))

        if get_measure_value(measures, with_measure_type=MeasureType.HEIGHT
                             ) is not None and 'height' in self._items:
            self._items['height'](get_measure_value(
                measures, with_measure_type=MeasureType.HEIGHT),
                                  self.get_shortname())
            self.logger.debug("height - {}".format(
                get_measure_value(measures,
                                  with_measure_type=MeasureType.HEIGHT)))

        if get_measure_value(measures,
                             with_measure_type=MeasureType.FAT_FREE_MASS
                             ) is not None and 'fat_free_mass' in self._items:
            self._items['fat_free_mass'](get_measure_value(
                measures, with_measure_type=MeasureType.FAT_FREE_MASS),
                                         self.get_shortname())
            self.logger.debug("fat_free_mass - {}".format(
                get_measure_value(
                    measures, with_measure_type=MeasureType.FAT_FREE_MASS)))

        if get_measure_value(measures, with_measure_type=MeasureType.FAT_RATIO
                             ) is not None and 'fat_ratio' in self._items:
            self._items['fat_ratio'](get_measure_value(
                measures, with_measure_type=MeasureType.FAT_RATIO),
                                     self.get_shortname())
            self.logger.debug("fat_ratio - {}".format(
                get_measure_value(measures,
                                  with_measure_type=MeasureType.FAT_RATIO)))

        if get_measure_value(
                measures, with_measure_type=MeasureType.FAT_MASS_WEIGHT
        ) is not None and 'fat_mass_weight' in self._items:
            self._items['fat_mass_weight'](get_measure_value(
                measures, with_measure_type=MeasureType.FAT_MASS_WEIGHT),
                                           self.get_shortname())
            self.logger.debug("fat_mass_weight - {}".format(
                get_measure_value(
                    measures, with_measure_type=MeasureType.FAT_MASS_WEIGHT)))

        if get_measure_value(
                measures,
                with_measure_type=MeasureType.DIASTOLIC_BLOOD_PRESSURE
        ) is not None and 'diastolic_blood_pressure' in self._items:
            self._items['diastolic_blood_pressure'](get_measure_value(
                measures,
                with_measure_type=MeasureType.DIASTOLIC_BLOOD_PRESSURE),
                                                    self.get_shortname())
            self.logger.debug("diastolic_blood_pressure - {}".format(
                get_measure_value(
                    measures,
                    with_measure_type=MeasureType.DIASTOLIC_BLOOD_PRESSURE)))

        if get_measure_value(
                measures, with_measure_type=MeasureType.SYSTOLIC_BLOOD_PRESSURE
        ) is not None and 'systolic_blood_pressure' in self._items:
            self._items['systolic_blood_pressure'](get_measure_value(
                measures,
                with_measure_type=MeasureType.SYSTOLIC_BLOOD_PRESSURE),
                                                   self.get_shortname())
            self.logger.debug("systolic_blood_pressure - {}".format(
                get_measure_value(
                    measures,
                    with_measure_type=MeasureType.SYSTOLIC_BLOOD_PRESSURE)))

        if get_measure_value(measures,
                             with_measure_type=MeasureType.TEMPERATURE
                             ) is not None and 'temperature' in self._items:
            self._items['temperature'](get_measure_value(
                measures, with_measure_type=MeasureType.TEMPERATURE),
                                       self.get_shortname())
            self.logger.debug("temperature - {}".format(
                get_measure_value(measures,
                                  with_measure_type=MeasureType.TEMPERATURE)))

        if get_measure_value(measures, with_measure_type=MeasureType.SP02
                             ) is not None and 'spo2' in self._items:
            self._items['spo2'](get_measure_value(
                measures, with_measure_type=MeasureType.SP02),
                                self.get_shortname())
            self.logger.debug("spo2 - {}".format(
                get_measure_value(measures,
                                  with_measure_type=MeasureType.SP02)))

        if get_measure_value(
                measures, with_measure_type=MeasureType.BODY_TEMPERATURE
        ) is not None and 'body_temperature' in self._items:
            self._items['body_temperature'](get_measure_value(
                measures, with_measure_type=MeasureType.BODY_TEMPERATURE),
                                            self.get_shortname())
            self.logger.debug("body_temperature - {}".format(
                get_measure_value(
                    measures, with_measure_type=MeasureType.BODY_TEMPERATURE)))

        if get_measure_value(
                measures, with_measure_type=MeasureType.SKIN_TEMPERATURE
        ) is not None and 'skin_temperature' in self._items:
            self._items['skin_temperature'](get_measure_value(
                measures, with_measure_type=MeasureType.SKIN_TEMPERATURE),
                                            self.get_shortname())
            self.logger.debug("skin_temperature - {}".format(
                get_measure_value(
                    measures, with_measure_type=MeasureType.SKIN_TEMPERATURE)))

        if get_measure_value(measures,
                             with_measure_type=MeasureType.MUSCLE_MASS
                             ) is not None and 'muscle_mass' in self._items:
            self._items['muscle_mass'](get_measure_value(
                measures, with_measure_type=MeasureType.MUSCLE_MASS),
                                       self.get_shortname())
            self.logger.debug("muscle_mass - {}".format(
                get_measure_value(measures,
                                  with_measure_type=MeasureType.MUSCLE_MASS)))

        if get_measure_value(measures, with_measure_type=MeasureType.HYDRATION
                             ) is not None and 'hydration' in self._items:
            self._items['hydration'](get_measure_value(
                measures, with_measure_type=MeasureType.HYDRATION),
                                     self.get_shortname())
            self.logger.debug("hydration - {}".format(
                get_measure_value(measures,
                                  with_measure_type=MeasureType.HYDRATION)))

        if get_measure_value(measures, with_measure_type=MeasureType.BONE_MASS
                             ) is not None and 'bone_mass' in self._items:
            self._items['bone_mass'](get_measure_value(
                measures, with_measure_type=MeasureType.BONE_MASS),
                                     self.get_shortname())
            self.logger.debug("bone_mass - {}".format(
                get_measure_value(measures,
                                  with_measure_type=MeasureType.BONE_MASS)))

        if get_measure_value(
                measures, with_measure_type=MeasureType.PULSE_WAVE_VELOCITY
        ) is not None and 'pulse_wave_velocity' in self._items:
            self._items['pulse_wave_velocity'](get_measure_value(
                measures, with_measure_type=MeasureType.PULSE_WAVE_VELOCITY),
                                               self.get_shortname())
            self.logger.debug("pulse_wave_velocity - {}".format(
                get_measure_value(
                    measures,
                    with_measure_type=MeasureType.PULSE_WAVE_VELOCITY)))

        if 'height' in self._items and (
                'bmi' in self._items
                or 'bmi_text' in self._items) and get_measure_value(
                    measures,
                    with_measure_type=MeasureType.WEIGHT) is not None:
            if self._items['height']() > 0:
                bmi = round(
                    get_measure_value(measures,
                                      with_measure_type=MeasureType.WEIGHT) /
                    ((self._items['height']()) * (self._items['height']())), 2)
                if 'bmi' in self._items:
                    self._items['bmi'](bmi, self.get_shortname())
                if 'bmi_text' in self._items:
                    if bmi < 16:
                        self._items['bmi_text'](
                            self.translate('starkes Untergewicht'),
                            self.get_shortname())
                    elif 16 <= bmi < 17:
                        self._items['bmi_text'](
                            self.translate('mäßiges Untergewicht'),
                            self.get_shortname())
                    elif 17 <= bmi < 18.5:
                        self._items['bmi_text'](
                            self.translate('leichtes Untergewicht'),
                            self.get_shortname())
                    elif 18.5 <= bmi < 25:
                        self._items['bmi_text'](
                            self.translate('Normalgewicht'),
                            self.get_shortname())
                    elif 25 <= bmi < 30:
                        self._items['bmi_text'](
                            self.translate('Präadipositas (Übergewicht)'),
                            self.get_shortname())
                    elif 30 <= bmi < 35:
                        self._items['bmi_text'](
                            self.translate('Adipositas Grad I'),
                            self.get_shortname())
                    elif 35 <= bmi < 40:
                        self._items['bmi_text'](
                            self.translate('Adipositas Grad II'),
                            self.get_shortname())
                    elif 40 <= bmi:
                        self._items['bmi_text'](
                            self.translate('Adipositas Grad III'),
                            self.get_shortname())
            else:
                self.logger.error(
                    "Cannot calculate BMI: height is 0, please set height (in m) for height item manually."
                )
        else:
            self.logger.error(
                "Cannot calculate BMI: height and / or bmi item missing.")