Giter Site home page Giter Site logo

python_withings_api's Introduction

Python withings-api Build status Coverage Status PyPI

Python library for the Withings Health API

Withings Health API https://developer.withings.com/oauth2/

Uses OAuth 2.0 to authenticate. You need to obtain a client id and consumer secret from Withings by creating an application here: http://developer.withings.com/oauth2/

Installation

pip install withings-api

Usage

For a complete example, checkout the integration test in scripts/integration_test.py. It has a working example on how to use the API.

from withings_api import WithingsAuth, WithingsApi, AuthScope
from withings_api.common import get_measure_value, MeasureType

auth = WithingsAuth(
    client_id='your client id',
    consumer_secret='your consumer secret',
    callback_uri='your callback uri',
    mode='demo',  # Used for testing. Remove this when getting real user data.
    scope=(
        AuthScope.USER_ACTIVITY,
        AuthScope.USER_METRICS,
        AuthScope.USER_INFO,
        AuthScope.USER_SLEEP_EVENTS,
    )
)

authorize_url = auth.get_authorize_url()
# Have the user goto authorize_url and authorize the app. They will be redirected back to your redirect_uri.

credentials = auth.get_credentials('code from the url args of redirect_uri')

# Now you are ready to make calls for data.
api = WithingsApi(credentials)

meas_result = api.measure_get_meas()
weight_or_none = get_measure_value(meas_result, with_measure_type=MeasureType.WEIGHT)

Building

Building, testing and lintings of the project is all done with one script. You only need a few dependencies.

Dependencies:

  • python3 in your path.
  • The python3 venv module.

The build script will setup the venv, dependencies, test and lint and bundle the project.

./scripts/build.sh

Integration Testing

There exists a simple integration test that runs against Withings' demo data. It's best to run this after you have successful builds.

Note: after changing the source, you need to run build for the integration test to pickup the changes.

./scripts/build.sh
source ./venv/bin/activate
./scripts/integration_test.py --client-id <your client id> --consumer-secret <your consumer secret> --callback-uri <your clalback uri>

The integration test will cache the credentials in a <project root>/.credentials file between runs. If you get an error saying the access token expired, then remove that credentials file and try again.

python_withings_api's People

Contributors

ademasi avatar brad avatar chpego avatar crhuber avatar dependabot[bot] avatar dseifert avatar fabaff avatar grokcode avatar jlapenna avatar jmtatsch avatar jschram avatar keytoaster avatar magnific0 avatar maximebf avatar nbogojevic avatar requires avatar ronaldheft avatar vangorra avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python_withings_api's Issues

Unsupported value

I use home assistant integration for withings.

I first created the issue on that repo (home-assistant/core#68545) but I guess this is the right place.

I get this warning and has for a long time:

2022-03-23 11:19:47 WARNING (SyncWorker_8) [python_withings_api] Unsupported <enum 'MeasureGetMeasGroupAttrib'> value 10. Replacing with UNKNOWN value MeasureGetMeasGroupAttrib.UNKNOWN. Please report this warning to the developer to ensure proper support.

Please let me know what I can do to help.

sleep_get for rr & hr

I am trying to get the rr and hr values via sleep_get:

sleep_get(startdate=start_date, enddate=end_date, data_fields = [f for f in GetSleepField])

However I get an exception that $timestamp is not found. When I leave out data_fields it is working fine (except for not fetching hr and rr, of course). Same approach with converting the enum to a list works perfectly fine with sleep_get_summary.

Exception:

Warning: Failed to convert object. See exception for details. Traceback (most recent call last):
  File "path/.venv/lib/python3.8/site-packages/withings_api/common.py", line 682, in _flexible_tuple_of
    new_items.append(fun(item))
  File "path/.venv/lib/python3.8/site-packages/withings_api/common.py", line 572, in new_sleep_get_serie
    hr=new_sleep_timestamp(dict_or_none(data.get(GetSleepField.HR.value))),
  File "path/.venv/lib/python3.8/site-packages/withings_api/common.py", line 563, in new_sleep_timestamp
    return SleepGetTimestamp(arrow_or_raise(data.get("$timestamp")))
  File "path/.venv/lib/python3.8/site-packages/withings_api/common.py", line 480, in arrow_or_raise
    return enforce_type(arrow_or_none(value), Arrow)
  File "path/.venv/lib/python3.8/site-packages/withings_api/common.py", line 396, in enforce_type
    raise UnexpectedTypeException(value, expected)
withings_api.common.UnexpectedTypeException: Expected of "None" to be "<class 'arrow.arrow.Arrow'>" but was "<class 'NoneType'>."

That's for return SleepGetTimestamp(arrow_or_raise(data.get("$timestamp"))). Response from server is {'startdate': 1595288160, 'state': 3, 'enddate': 1595288520, 'model': 'Aura Sensor V2', 'hr': {'1595288160': 88, '1595288220': 87, '1595288280': 85, '1595288340': 83, '1595288400': 86, '1595288460': 87}, 'rr': {'1595288160': 15, '1595288220': 16, '1595288280': 15, '1595288340': 15, '1595288400': 19, '1595288460': 12}, 'model_id': 63}.

I see the code matches the API:

hr : Heart Rate. (Use 'data_fields' to request this data.)
--> $timestamp integer $timestamp represents the epoch value of the heart rate data, value of this key will be the heart rate data

however that might not to be taken literally.

P.S.: GetSleepField is missing data field "snoring".

Need help with README instructions

Hi there,

I tried to implement that README instructions to authenticate and retrieve data for my Withings account using python. However, when I follow the instructions on the README, I get stuck. I figured since this might be a problem when following the README instructions exactly, perhaps more people will have the same issue, therefore I'm posting it here. Hope that's ok.

My code (similar to README):

from withings_api import WithingsAuth, WithingsApi, AuthScope
from withings_api.common import get_measure_value, MeasureType

auth = WithingsAuth(
    client_id='dummy_id',
    consumer_secret='dummy_secret',
    callback_uri='https://www.withings.com/nl/en/',
    mode='demo',  # Used for testing. Remove this when getting real user data.
    scope=(
        AuthScope.USER_ACTIVITY,
        AuthScope.USER_METRICS,
        AuthScope.USER_INFO,
    )
)

authorize_url = auth.get_authorize_url()
code = 'xxx'     # code retrieved from the url code, formatted like: https://www.withings.com/nl/en/?code=xxx&state=xxx3

creds = auth.get_credentials('xxx')

I get the following error:


~/opt/anaconda3/envs/aeon/lib/python3.7/site-packages/oauthlib/oauth2/rfc6749/parameters.py in validate_token_parameters(params)
    439 
    440     if not 'access_token' in params:
--> 441         raise MissingTokenError(description="Missing access token parameter.")
    442 
    443     if not 'token_type' in params:

MissingTokenError: (missing_token) Missing access token parameter.

What am I doing wrong? It looked around but couldn't find an answer. Also, I looked at the source code but I couldn't figure out what was wrong. Thanks a lot in advance for the help.

Wrong URL in OAuth token endpoint

Hello,

Withings API documentation lists "https://wbsapi.withings.net/v2/oauth2" as the endpoint for refreshing the access_token.

However, in the python_withings_api package, in WithingsAuth class, the url is set to

URL: Final = "https://account.withings.com"
# And
PATH_TOKEN: Final = "oauth2/token"

Which is used to set the auto_refresh_url of the OAuth2Session

auto_refresh_url="%s/%s" % (WithingsAuth.URL, WithingsAuth.PATH_TOKEN),

That might be the reason refreshing the access_token fails when tried to be done using the refresh_token manual method.

According to the API documentation, the https://account.withings.com seems to be mostly used for user authorization.

Best regards,
Hannes Järvinen

userid not always str

repro:

rm .credentials
./scripts/build.sh
source ./venv/bin/activate
./scripts/integration_test.py --client-id='XXX' --consumer-secret='YYY' --callback-uri="http://localhost:8081/services/withings/redirect"
Attempting to get credentials...
Goto this URL in your browser and authorize: https://account.withings.com/oauth2_user/authorize2?response_type=code&client_id=XXX&redirect_uri=http%3A%2F%2Flocalhost%3A8081%2Fservices%2Fwithings%2Fredirect&scope=user.activity%2Cuser.metrics%2Cuser.info%2Cuser.sleepevents&state=ZZZ&mode=demo
Once you are redirected, copy and paste the whole url(including code) here.
Provide the entire redirect uri: http://localhost:8081/services/withings/redirect?code=CODECODECODE&state=ZZZ
Getting credentials with auth code CODECODECODE
Traceback (most recent call last):
File "./scripts/integration_test.py", line 119, in
main()
File "./scripts/integration_test.py", line 73, in main
credentials = auth.get_credentials(auth_code)
File "/home/jlapenna/code/python_withings_api/venv/lib/python3.6/site-packages/withings_api-2.1.2b1-py3.6.egg/withings_api/init.py", line 357, in get_credentials
File "/home/jlapenna/code/python_withings_api/venv/lib/python3.6/site-packages/withings_api-2.1.2b1-py3.6.egg/withings_api/common.py", line 451, in new_credentials
File "/home/jlapenna/code/python_withings_api/venv/lib/python3.6/site-packages/withings_api-2.1.2b1-py3.6.egg/withings_api/common.py", line 384, in str_or_raise
File "/home/jlapenna/code/python_withings_api/venv/lib/python3.6/site-packages/withings_api-2.1.2b1-py3.6.egg/withings_api/common.py", line 369, in enforce_type
withings_api.common.UnexpectedTypeException: Expected of "17633015" to be "<class 'str'>" but was "<class 'int'>."
(venv)

Code stopped working, Error 503 for sleep data

I have been using this code for a couple months and it was working perfectly the last time I checked it at the end of January 2021. Now when I run it I get an error trying to call sleep_get

This is the line that causes the error:
sleep = api.sleep_get(startdate=arrow.get('2021-01-20T21:23:58.970460+05:00'), enddate=arrow.utcnow(), data_fields=list(GetSleepField))
However using the line to use sleep_get_summary is working perfectly, with the same inputs (startdate and enddate).

Now when I try to get the sleep data, I get the following error:

InvalidParamsException Traceback (most recent call last)
in
----> 1 sleep = api.sleep_get(data_fields = [f for f in GetSleepField], startdate=arrow.get('2021-01-20T21:23:58.970460+07:00'), enddate=arrow.utcnow())

c:\users\rachel\appdata\local\programs\python\python38\lib\site-packages\withings_api_init_.py in sleep_get(self, data_fields, startdate, enddate)
178 update_params(params, "action", "get")
179
--> 180 return SleepGetResponse(**self.request(path=self.PATH_V2_SLEEP, params=params))
181
182 def sleep_get_summary(

c:\users\rachel\appdata\local\programs\python\python38\lib\site-packages\withings_api_init_.py in request(self, path, params, method)
76 ) -> Dict[str, Any]:
77 """Request a specific service."""
---> 78 return response_body_or_raise(
79 self._request(method=method, path=path, params=params)
80 )

c:\users\rachel\appdata\local\programs\python\python38\lib\site-packages\withings_api\common.py in response_body_or_raise(data)
823 raise AuthFailedException(status=status)
824 if status in STATUS_INVALID_PARAMS:
--> 825 raise InvalidParamsException(status=status)
826 if status in STATUS_UNAUTHORIZED:
827 raise UnauthorizedException(status=status)

InvalidParamsException: Error code 503

Thanks!

This library going forward

@vangorra I really appreciate that you created this awesome lib. I have been using it for a very long time and for me it has been priceless.

I really want this library to continue to work going forward. I'm happy to help maintaining and improving this. Please let me know if you want this help.

Token refresh

Hi,

My token keeps expiring. How do I refresh the token without having to delete the credentials file and allow the app again?

Thank you

Question: Distinguish weight by user

My partner and I are both set up on the same Body+ scales. How do I distinguish her measurements from mine?

I have looked at the docs and I cannot see how withings advises who logged the measurement. What am I missing here?

getting sleep data rr & hr

Hi,
I'm trying to get all sleep data with the method sleep_get(). I mainly want rr and hr data during the night. I'm using next call:

test_data = self.__api.sleep_get(startdate=arrow.utcnow().shift(days=-1), enddate=arrow.utcnow(), data_fields=GetSleepField )

But no data are retrieved.

If I remove data_fields parameter, I just get sleep levels but rr and hr have "None" values.

Is there any mistake in my call?

Thanks for your support! ;)

Pandas df?

Hello!

I'm trying to upgrade from the nokia library to start using this one. I have the auth and everything working so far, just wanted to ask the best way to get data from this library into a pandas df... I've started down this route, but feel like there is probably a better way?

    client = WithingsApi(withings_creds(current_token_dict()), 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

Thanks!

TypeError: unsupported operand type(s) for -: 'int' and 'method'

Hello,

Recently the code has started to raise errors on the issue mentioned on the title:

File "/env/local/lib/python3.7/site-packages/withings_api/__init__.py", line 416,
    in __init__ self._credentials = maybe_upgrade_credentials(credentials)
File "/env/local/lib/python3.7/site-packages/withings_api/common.py", line 627,
    in maybe_upgrade_credentials expires_in=creds.token_expiry - arrow.utcnow().timestamp,

TypeError: unsupported operand type(s) for -: 'int' and 'method' 

Release: 2.3, but was also present in 2.1.9, just in different place in the code.

Completely clone to adapt to another API

Hi,

I wanted to let you know that i clone your repo to adapt it to another API.
It's Xee api v4 that also use Oauth2 like withings.

I'm going to make it working as much as i can.

The goal will be to have a pure python api and made it available in Homeassistant in the future.

Thank's for all your work.

notify_list response type issues

File "/env/lib/python3.7/site-packages/withings_api/__init__.py", line 251, in notify_list self.request(path=self.PATH_NOTIFY, params=params) 
File "/env/lib/python3.7/site-packages/withings_api/common.py", line 531, in new_notify_list_response new_notify_list_profile(profile) for profile in data.get("profiles", ()) 
File "/env/lib/python3.7/site-packages/withings_api/common.py", line 531, in <genexpr> new_notify_list_profile(profile) for profile in data.get("profiles", ()) 
File "/env/lib/python3.7/site-packages/withings_api/common.py", line 522, in new_notify_list_profile expires=arrow_or_raise(data.get("expires")), 
File "/env/lib/python3.7/site-packages/withings_api/common.py", line 464, in arrow_or_raise return enforce_type(arrow_or_none(value), Arrow) 
File "/env/lib/python3.7/site-packages/withings_api/common.py", line 380, in enforce_type raise UnexpectedTypeException(value, expected) withings_api.common.UnexpectedTypeException: Expected of "None" to be "<class 'arrow.arrow.Arrow'>" but was "<class 'NoneType'>."

some measures are floats

Getting devices...
Getting measures...
Getting activity...
Traceback (most recent call last):
File "./scripts/integration_test.py", line 119, in
main()
File "./scripts/integration_test.py", line 93, in main
startdateymd=arrow.utcnow().shift(days=-21), enddateymd=arrow.utcnow()
File "/home/jlapenna/code/python_withings_api/venv/lib/python3.6/site-packages/withings_api-2.1.2b1-py3.6.egg/withings_api/init.py", line 131, in measure_get_activity
File "/home/jlapenna/code/python_withings_api/venv/lib/python3.6/site-packages/withings_api-2.1.2b1-py3.6.egg/withings_api/common.py", line 652, in new_measure_get_activity_response
File "/home/jlapenna/code/python_withings_api/venv/lib/python3.6/site-packages/withings_api-2.1.2b1-py3.6.egg/withings_api/common.py", line 652, in
File "/home/jlapenna/code/python_withings_api/venv/lib/python3.6/site-packages/withings_api-2.1.2b1-py3.6.egg/withings_api/common.py", line 636, in new_measure_get_activity_activity
File "/home/jlapenna/code/python_withings_api/venv/lib/python3.6/site-packages/withings_api-2.1.2b1-py3.6.egg/withings_api/common.py", line 404, in int_or_raise
File "/home/jlapenna/code/python_withings_api/venv/lib/python3.6/site-packages/withings_api-2.1.2b1-py3.6.egg/withings_api/common.py", line 369, in enforce_type
withings_api.common.UnexpectedTypeException: Expected of "296.34" to be "<class 'int'>" but was "<class 'float'>."

I didn't have a chance to check out which measure it was; will do in a follow-up comment.

refresh_cb returning Error code 401

Code has been working now for over a year, stopped working all of the sudden...wondering if something has changed

Code is pretty straightforward, user clicks 'Allow', I parse query params for the code and then pass to the .get_credentials() function.

The code is being parsed correctly so it seems something with the function is off...

query_params = urlparse.urlparse(search)
creds = withings_auth_client.get_credentials(parse_qs(query_params.query)['code'][0])

Here is the error I'm getting

Traceback (most recent call last):
  File "/Users/ethan/PycharmProjects/fitly/src/fitly/pages/settings.py", line 1234, in update_tokens
    creds = withings_auth_client.get_credentials(parse_qs(query_params.query)['code'][0])
  File "/Users/ethan/PycharmProjects/fitly/venv/lib/python3.7/site-packages/withings_api/__init__.py", line 376, in get_credentials
    include_client_id=True,
  File "/Users/ethan/PycharmProjects/fitly/venv/lib/python3.7/site-packages/requests_oauthlib/oauth2_session.py", line 360, in fetch_token
    self._client.parse_request_body_response(r.text, scope=self.scope)
  File "/Users/ethan/PycharmProjects/fitly/venv/lib/python3.7/site-packages/oauthlib/oauth2/rfc6749/clients/base.py", line 421, in parse_request_body_response
    self.token = parse_token_response(body, scope=scope)
  File "/Users/ethan/PycharmProjects/fitly/venv/lib/python3.7/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 431, in parse_token_response
    validate_token_parameters(params)
  File "/Users/ethan/PycharmProjects/fitly/venv/lib/python3.7/site-packages/oauthlib/oauth2/rfc6749/parameters.py", line 441, in validate_token_parameters
    raise MissingTokenError(description="Missing access token parameter.")
oauthlib.oauth2.rfc6749.errors.MissingTokenError: (missing_token) Missing access token parameter.

Also, when trying to print(creds) I get invalid syntax (<unknown>, line 1)

device info

Would be nice if home assistant could also list my withings device info.
More specifically, I'm interested in the battery status of my body+ scale

What Is The Official Withings Python Module To Use That Is Supported?

What Is The Official Withings Python Module To Use That Is Supported?

I was hoping somebody could help me understand this better. I am looking to interface with the Withings API, for the Withings bathroom scales. I have been using the Python module called “Nokia”, but it has not been updated in some time. Is there an “official” Withings Python module that should be used instead?

Here are 3 Withings modules I have found. Is there an “official” or preferred one to code with?

Thanks for any help!
Jean-Marie Vaneskahian
[email protected]
(January 31st, 2021)

Unexpected error fetching poll_data_update_coordinator data: 'dict' object has no attribute 'context'

Logger: homeassistant.components.withings
Source: components/withings/common.py:747
Integration: Withings (documentation, issues)
First occurred: 3:12:23 AM (1 occurrences)
Last logged: 3:12:23 AM

Unexpected error fetching poll_data_update_coordinator data: 'dict' object has no attribute 'context'
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/withings/common.py", line 730, in async_get_all_data
    return await self._do_retry(self._async_get_all_data)
  File "/usr/src/homeassistant/homeassistant/components/withings/common.py", line 654, in _do_retry
    raise exception
  File "/usr/src/homeassistant/homeassistant/components/withings/common.py", line 647, in _do_retry
    return await func()
  File "/usr/src/homeassistant/homeassistant/components/withings/common.py", line 766, in _async_get_all_data
    **await self.async_get_measures(),
  File "/usr/src/homeassistant/homeassistant/components/withings/common.py", line 776, in async_get_measures
    response = await self._hass.async_add_executor_job(
  File "/usr/local/lib/python3.9/concurrent/futures/thread.py", line 52, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/local/lib/python3.9/site-packages/withings_api/__init__.py", line 161, in measure_get_meas
    **self.request(path=self.PATH_MEASURE, params=params)
  File "/usr/local/lib/python3.9/site-packages/withings_api/__init__.py", line 81, in request
    return response_body_or_raise(
  File "/usr/local/lib/python3.9/site-packages/withings_api/common.py", line 823, in response_body_or_raise
    raise AuthFailedException(status=status)
withings_api.common.AuthFailedException: Error code 401

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 187, in _async_refresh
    self.data = await self._async_update_data()
  File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 147, in _async_update_data
    return await self.update_method()
  File "/usr/src/homeassistant/homeassistant/components/withings/common.py", line 743, in async_get_all_data
    flow = next(
  File "/usr/src/homeassistant/homeassistant/components/withings/common.py", line 747, in <genexpr>
    if flow.context == context
AttributeError: 'dict' object has no attribute 'context'

sleep summary data incomplete?

I tried the example on the homepage, but changed the last two lines to receive the sleep summary data:

print(api.sleep_get_summary(startdateymd='2020-12-01', enddateymd='2020-12-05'))

The response I received is fine apart from some data that is missing, a snippet of the response:

GetSleepSummarySerie(timezone=tzfile('Europe/Amsterdam'), model=<SleepModel.SLEEP_MONITOR: 32>, startdate=<Arrow [2020-12-03T23:41:00+01:00]>, enddate=<Arrow [2020-12-04T10:12:00+01:00]>, date=<Arrow [2020-12-04T01:00:00+01:00]>, modified=<Arrow [2020-12-04T12:15:06+01:00]>, data=GetSleepSummaryData(breathing_disturbances_intensity=None, deepsleepduration=5640, durationtosleep=2640, durationtowakeup=1620, hr_average=None, hr_max=None, hr_min=None, lightsleepduration=18420, remsleepduration=7380, rr_average=None, rr_max=None, rr_min=None, sleep_score=None, snoring=None, snoringepisodecount=None, wakeupcount=4, wakeupduration=6420), id=1738096164)

I'm especially interested in retrieving the heart rate data (hr_max / hr_min / hr_average), but that part is missing. Snoring and sleepscore are missing as well. In my iOS app all of these metrics are shown for the past days, so the data should be available.

Am I doing something wrong in the retrieval of the data?

ValueError: 123 is not a valid MeasureType

Hy I'm trying to get the API working. I got results from integration_test.py but as soon as I ty to get my data and not the mode='demo' I get: ValueError: 123 is not a valid MeasureType

the cose is

`from urllib import parse

from withings_api import WithingsAuth, WithingsApi, AuthScope
from withings_api.common import get_measure_value, MeasureType

auth = WithingsAuth(
client_id='myID',
consumer_secret='myCons',
callback_uri='https://google.com/',
scope=(
AuthScope.USER_ACTIVITY,
AuthScope.USER_METRICS,
AuthScope.USER_INFO,
AuthScope.USER_SLEEP_EVENTS,
)
)

authorize_url = auth.get_authorize_url()
print("Goto this URL in your browser and authorize:")
print(authorize_url)
redirected_uri = input("Provide the entire redirect uri: ")
redirected_uri_params = dict(
parse.parse_qsl(parse.urlsplit(redirected_uri).query)
)
auth_code = redirected_uri_params["code"]
print("Getting credentials with auth code", auth_code)
credentials = auth.get_credentials(auth_code)
print(credentials)

api = WithingsApi(credentials)

meas_result = api.measure_get_meas() <--------------here get the error
weight_or_none = get_measure_value(meas_result, with_measure_type=MeasureType.WEIGHT)
print(meas_result);`

Anyone can help me?
Thanks

notify_list() incorrect return type

File "/srv/services/withings/withings.py", line 86, in _revoke_unknown_subscriptions notify_response = self.client.notify_list() 
File "/env/lib/python3.7/site-packages/withings_api/__init__.py", line 251, in notify_list self.request(path=self.PATH_NOTIFY, params=params) 
File "/env/lib/python3.7/site-packages/withings_api/common.py", line 515, in new_notify_list_response new_notify_list_profile(profile) for profile in data.get("profiles", ()) 
File "/env/lib/python3.7/site-packages/withings_api/common.py", line 515, in <genexpr> new_notify_list_profile(profile) for profile in data.get("profiles", ()) 
File "/env/lib/python3.7/site-packages/withings_api/common.py", line 506, in new_notify_list_profile expires=arrow_or_raise(data.get("expires")), 
File "/env/lib/python3.7/site-packages/withings_api/common.py", line 448, in arrow_or_raise return enforce_type(value is not None and arrow.get(value), Arrow) 
File "/env/lib/python3.7/site-packages/withings_api/common.py", line 380, in enforce_type raise UnexpectedTypeException(value, expected) withings_api.common.UnexpectedTypeException: Expected of "False" to be "<class 'arrow.arrow.Arrow'>" but was "<class 'bool'>."

New Measure Type

Hi,
I just loaded Data from Withings and got the Message:
Unsupported <enum 'MeasureType'> value 123. Replacing with UNKNOWN value MeasureType.UNKNOWN. Please report this warning to the developer to ensure proper support.

If I look for the Withings Documentation I found:
123 VO2 max is a numerical measurement of your body’s ability to consume oxygen (ml/min/kg)

Can you please adde the Code.

Cheers
Jochen

<MeasureType.UNKNOWN: -999999> - python3.9/site-packages/withings_api/common.py:38

Hi Robbert, can you pls take a look at:

Withings Integration Issues #52089 for HA. The setup never finish to create the Webhook

Error: Retrying setup: <MeasureType.UNKNOWN: -999999>
Logger: python_withings_api
Source: /usr/local/lib/python3.9/site-packages/withings_api/common.py:38
Unsupported <enum 'MeasureType'> value 135. Replacing with UNKNOWN value MeasureType.UNKNOWN. Please report this warning to the developer to ensure proper support.

measure_get_meas() does not return all data

it looks like commit 02a3164 has changed the defaults for startdate, enddate and lastupdate from None to utcnow(). So, if I you don't provide these optional arguments then you will only get data from today. The only way around this is to set each of these arguments to None in the function call, which does not make much sense. Also startdate and enddate should be mutually exclusive from lastupdate if I read the official doc correctly. with this commit all three are set in the params of the rest call with the default value of utcnow(). When I change these Optional arguments defaults back to None within the code, then things started working again as expected.

consider change to pydantic

I saw a lot of attempts to do validation.
I saw your love in arrow lib. really good taste
pydantic might be a good fit to this project.
I can help you migrate.

def new_measure_get_meas_group(data: dict, timezone: tzinfo) -> MeasureGetMeasGroup:
"""Create GetMeasGroup from json."""
return MeasureGetMeasGroup(
grpid=int_or_raise(data.get("grpid")),
attrib=new_measure_group_attrib(data.get("attrib")),
date=arrow_or_raise(data.get("date")).to(timezone),
created=arrow_or_raise(data.get("created")).to(timezone),
category=new_measure_category(data.get("category")),
deviceid=data.get("deviceid"),
measures=_flexible_tuple_of(
data.get("measures", ()), new_measure_get_meas_measure
),
)

Withings integration in HA broke

Hi Robert
Are you still developing this Integration.
Since 2021.3.0 we (approximately 300 users) have had issues. We now get sleep data in nicely thanks to @ronaldheft . But no data from scale, blood pressure and others.

Unexpected error fetching subscription_update_coordinator data: Error code 293

Trying to get the sleep monitor to work getting an invalid params exception error 293. I'm trying to track down the cause but I'm a bit lost.

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 187, in _async_refresh
    self.data = await self._async_update_data()
  File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 147, in _async_update_data
    return await self.update_method()
  File "/usr/src/homeassistant/homeassistant/components/withings/common.py", line 658, in async_subscribe_webhook
    return await self._do_retry(self._async_subscribe_webhook)
  File "/usr/src/homeassistant/homeassistant/components/withings/common.py", line 654, in _do_retry
    raise exception
  File "/usr/src/homeassistant/homeassistant/components/withings/common.py", line 647, in _do_retry
    return await func()
  File "/usr/src/homeassistant/homeassistant/components/withings/common.py", line 700, in _async_subscribe_webhook
    await self._hass.async_add_executor_job(
  File "/usr/local/lib/python3.9/concurrent/futures/thread.py", line 52, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/local/lib/python3.9/site-packages/withings_api/__init__.py", line 311, in notify_subscribe
    self.request(path=self.PATH_NOTIFY, params=params)
  File "/usr/local/lib/python3.9/site-packages/withings_api/__init__.py", line 78, in request
    return response_body_or_raise(
  File "/usr/local/lib/python3.9/site-packages/withings_api/common.py", line 825, in response_body_or_raise
    raise InvalidParamsException(status=status)
withings_api.common.InvalidParamsException: Error code 293

Question about token refreshing

Hello,

We are using the API in this repository, seems awesome.

However, we are experiencing issues on token refreshing, and the token fails to be refreshed. Currently we are using the api in 30 minute intervals, by pulling data from Withings. The token causes issues and we receive the following error: Failed to get measurements from Withings, aborting. Exception: (missing_token) Missing access token parameter. (The part before the "Exception" is our own debugging information.

When this occurs, we also try to manually refresh the token, using the api.refresh_token() method, but the same error comes up: Failed to manually refresh the token. Exception: (missing_token) Missing access token parameter..

We however do have the access token parameter, because for a while the pull works without issues. It is only after some days, that the flow breaks for some reason.

When trying to figure out what is wrong, I noticed that in the __init__.py is the following:

        self._client: Final = OAuth2Session(
            credentials.client_id,
            token=token,
            client=WebApplicationClient(  # nosec
                credentials.client_id, token=token, default_token_placement="query"
            ),
            auto_refresh_url="%s/%s" % (WithingsAuth.URL, WithingsAuth.PATH_TOKEN),
            auto_refresh_kwargs={
                "client_id": credentials.client_id,https://guides.github.com/features/mastering-markdown/
                "client_secret": credentials.consumer_secret,
            },
            token_updater=self._update_token,

In which the keyword arguments client_id and client_secret are set, and some parameters are handled by the OAuth library. But in the Withings API, they also mention: action which should take the constant value of requesttoken. This seems new, since I don't remember seeing this before in the Withings API documentation.

Could it be that because of that, the token refresh fails sometimes?

If not, do you have some suggestions on how we should proceed on solving this inconsistent operation.

Best regards,
Hannes Järvinen

Invalid State when following redirect URI

Hi,

When I run integration_test.py and paste the URL into my browser the web page shows "Invalid State"

Any ideas how I can fix this to get the credentials file?

Thanks,
Jack

Error Refreshing Token

Hi,

I'm trying to Manually Refresh the token. The Integration_test..py works until the token expires. Then I am unable to refresh the token. Is there anything I am missing for this to work?

Thank you!

Below is my error...

Traceback (most recent call last):
File "./scripts/integration_test.py", line 132, in
main()
File "./scripts/integration_test.py", line 86, in main
api.refresh_token()
File "/usr/local/lib/python3.7/dist-packages/withings_api/init.py", line 415, in refresh_token
token_dict = self._client.refresh_token(token_url=self._client.auto_refresh_url)
File "/usr/local/lib/python3.7/dist-packages/requests_oauthlib/oauth2_session.py", line 309, in refresh_token
self.token = self._client.parse_request_body_response(r.text, scope=self.scope)
File "/usr/local/lib/python3.7/dist-packages/oauthlib/oauth2/rfc6749/clients/base.py", line 411, in parse_request_body_response
self.token = parse_token_response(body, scope=scope)
File "/usr/local/lib/python3.7/dist-packages/oauthlib/oauth2/rfc6749/parameters.py", line 379, in parse_token_response
validate_token_parameters(params)
File "/usr/local/lib/python3.7/dist-packages/oauthlib/oauth2/rfc6749/parameters.py", line 389, in validate_token_parameters
raise MissingTokenError(description="Missing access token parameter.")
oauthlib.oauth2.rfc6749.errors.MissingTokenError: (missing_token) Missing access token parameter.

[Feature][Help] Add support for air quality and room temperature

Hey @vangorra, thanks for creating/supporting this lib and integrate with homeassistant.

I saw your PR in homeassistant GitHub and I'm testing until your branch until your PR gets merged.

I don't know if it's possible to add living room temperature and air quality (CO2) to the python lib and consequently in homeassistant component.

Based on the https://healthmate.withings.com (I can see a chart with this information):

Screenshot 2019-10-19 at 22 13 33

If my scale, can provide me with that information, I can use the other temperature sensor in other rom.

Thanks, best regards
Diogo

How to use from a script?

Thanks for the great module.
How would one use this in a script to get my own measurements? Once I have the credentials, can I continue to use them in a long lived process?
For example, once Ive gone through the oauth steps can I continue to use those creds to get measurements at a later date?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.