Monday, May 21, 2012

Withings wifi scale python dashboard using matplotlib and pandas

The Withings wifi scale is a great bit of hardware, much more visually appealing than my handmade equivalent and wifi makes it standalone, also a big advantage over my bluetooth scale. I've been using the scale to log my weight and using fatsecret to track caloric intake for a while now and decided it would be nice to make a dashboard integrating data from both sources. The plots on Withings' website leave much to be desired. Thankfully, both Withings and fatsecret have APIs which make third party apps possible. Below I'll show some code that uses the rauth library to access both services. rauth provides OAuth 1.0/a, 2.0, and Ofly consumer support. You can install rauth using easy_install:
sudo easy_install rauth
Before using the Withings and fatsecret APIs, you'll need to register as a developer, you can do that by following the links below:
Withings developer registration:
https://oauth.withings.com/en/partner/add
If you just want to extend the code I provide further down you can fill an arbitrary value for the "Application Website" and "Organization" fields and leave the Callback URL blank. Otherwise, fill in those fields according to your needs. Once you've registered as a developer with both services you will have your Consumer Key and Shared Secret which you will need to send API requests. Now grab my python code from github:

git clone https://github.com/trtg/pywithings.git

The git repo has two files: withings.py(the actual library itself) and example.py (seen below). Open up example.py and fill in your consumer key, consumer secret, and the email address you used to register with Withings as indicated. Using the library is pretty straightforward: instantiate a withings object and then just call get_weights() to retrieve a list of weight measurements and an associated list of dates (in seconds since the epoch format) which you can then use however you'd like. Note that the very first time you run example.py you will be prompted to authorize the app to access your withings account by pasting a URL into your browser. Once you go to that URL and login, you will see a screen like this:
After you click "allow" you will see an oauth token string as shown below. Copy just the part after "oauth_verifier=" , in this case PZBDNyyuxDnGkeMxccY.
Paste the "PZ..." string into your terminal where prompted, hit enter, and you should get a graph like the one below.(Click on the graph to see a larger version) I used the python package pandas to treat the weight data as a time series and get nice date labels on the x-axis as well as to plot the smooth red rolling average of the data.
In an upcoming post, I'll discuss similar code that retrieves data from fatsecret to generate plots like the one below:

No comments:

Post a Comment