Fitbit Aria WiFi Scales Weight Bash Script

All kinds of 'OS' scripts
Post Reply
ben53252642
Posts: 534
Joined: Saturday 02 July 2016 5:17
Target OS: Linux
Domoticz version: Beta
Contact:

Fitbit Aria WiFi Scales Weight Bash Script

Post by ben53252642 » Wednesday 31 January 2018 23:04

Hey Folks,

This is a bash script for getting weight data from the Fitbit Aria scales and loading it into Domoticz.

1) Register a new Fitbit app here: https://dev.fitbit.com/apps/new, the redirect domain also known as the "Callback URL" does not need to be real, the OAuth 2.0 Application Type is: personal, select read only access.

2) Copy your fitbit apps "OAuth 2.0 Client ID" and put it into the URL below along with your "Callback URL", then visit it using Google Chrome

Code: Select all

https://www.fitbit.com/oauth2/authorize?client_id=ENTERYOURCLIENTIDHERE&redirect_uri=ENTERYOURREDIRECTURLHERE&response_type=code&scope=weight+activity+heartrate+location+nutrition+profile+settings+sleep+social

EXAMPLE of how it should look with the added "OAuth" and "Callback URL":
https://www.fitbit.com/oauth2/authorize?client_id=abc123&redirect_uri=https://domoticz.com&response_type=code&scope=weight+activity+heartrate+location+nutrition+profile+settings+sleep+social
When you get to the Fitbit page asking if you want to authorize your app, right click the page and select "Inspect", go to the "Network" tab in Google Chrome then proceed with allowing Fitbit to authorize the app. Look for ?code= in the "Network" tab url's you should see a 40 character long code, put it in the "code" configuration section of the bash script below.

3) Go back to your app https://dev.fitbit.com/apps and copy the client id, client secret and callback URL into the script Fitbit configuration section.

4) Create a new Virtual Sensor in Domoticz type "Scale (Weight)" and get its IDX code from the Domoticz devices page.

5) Enter the IDX number in the bash script, fill out the Domoticz configuration section and set the weight units in the script

To make this as simple as possible, you do not need to edit anything outside of the two lines that look like this:
# ----------------------------------------------------------------------------------

6) Install system requirements at the Linux terminal: sudo apt-get install jq bc screen

7) Run the script ./aria.sh

aria.sh

Code: Select all

#!/bin/bash

# ----------------------------------------------------------------------------------
# Fitbit Configuration obtained from your app at: https://dev.fitbit.com/apps
clientid="ENTERHERE" #OAuth 2.0 Client ID
clientsecret="ENTERHERE" #Client Secret
callbackurl="ENTERHERE" #Callback URL, eg: https://domoticz.com

# Fitbit Configuration obtained from the browser redirect
code="ENTERHERE"

# Fitbit Configuration weight units
units="Metric" #Options are: Metric, en_US, en_GB

# Domoticz Configuration
domoticzserver="192.168.0.5"
domoticzport="443"
domoticzuser="USERNAME"
domoticzpass="PASSWORD"
domoticzweightsensoridx="ENTERHERE" # Virtual Sensor Type: Scale (Weight)

# Path to folder containing this script
cd /root/scripts/fitbit
# ----------------------------------------------------------------------------------

# Create fitbit basic auth token
basicauthtoken=$(echo -n "${clientid}:${clientsecret}" | openssl base64)

while true; do

# Get a Fitbit oauth2 token
refreshtoken=$(cat refreshtoken.txt 2> /dev/null)
# If we already have a stored token, get a new one.
if [ ! -f refreshtoken.txt ]; then
echo "Getting access token for the first time..."
oauth=$(curl --max-time 60 -s -X POST -H "Content-Type: application/x-www-form-urlencoded" -H "Authorization: Basic ${basicauthtoken}" "https://api.fitbit.com/oauth2/token?client_id=${clientid}&grant_type=authorization_code&redirect_uri=${callbackurl}&code=${code}")
else
echo "Detected existing refresh token, getting a new access token..."
oauth=$(curl --max-time 60 -s -X POST --header "Content-Type: application/x-www-form-urlencoded" --header "Authorization: Basic ${basicauthtoken}" "https://api.fitbit.com/oauth2/token?client_id=${clientid}&grant_type=refresh_token&refresh_token=${refreshtoken}")
fi

# Put oauth2 token into easy to use variables and store the refresh token
accesstoken=$(echo "$oauth" | jq ".access_token" | sed 's/["]*//g')
newrefreshtoken=$(echo "$oauth" | jq ".refresh_token" | sed 's/["]*//g')
echo "$newrefreshtoken" > refreshtoken.txt

# Get weight data
date=$(date +"%Y-%m-%d")
getweight=$(curl --max-time 60 -s -X GET -H "Authorization: Bearer ${accesstoken}" -H "Accept-Language: ${units}" "https://api.fitbit.com/1/user/-/body/log/weight/date/${date}/1d.json")

# Extract data from the received json array
latestkey="-1"
for row in $(echo "${getweight}" | jq -c '.weight[]'); do
latestkey=$(echo $(("$latestkey" + 1))) # Since they are all in a single line, we simply count the number of results to work out the latest index key
done
weight=$(echo "$getweight" | jq ".weight[${latestkey}].weight")

# Display data in terminal
echo "Weight: $weight"

# Check to see if a new weight has been recorded since the previous check
logid=$(echo "$getweight" | jq ".weight[${latestkey}].logId")
storedlogid=$(cat storedlogid.txt 2> /dev/null)
if [ "$logid" == "$storedlogid" ]; then
echo "No new weight data"
else
echo "New weight detected"
echo "$logid" > storedlogid.txt

# Final integrity check, does weight equal more than 5?
if (( $(echo "$weight > 5" |bc -l) )); then

# Send data to Domoticz
echo "Sending data to Domoticz..."
# Domoticz Virtual Sensor Type: Scale (Weight)
curl --max-time 60 -k -s "https://{$domoticzuser}:{$domoticzpass}@{$domoticzserver}:{$domoticzport}/json.htm?type=command&param=udevice&idx={$domoticzweightsensoridx}&nvalue=0&svalue={$weight}"

else
echo "Problem occured during the final integrity check"
fi
fi

sleep 1800
done
The script is set to loop every 30 minutes to check for new data.

An alternate version is under development which is able to detect when the Fitbit Aria joins the WiFi network after standing on the scales and get the latest data within seconds. This is useful if for example you want an audio announcement in your home after a new weight is recorded: eg "Congratulations you have lost x kilograms". It is expected to be made available in the next few days.

weight.JPG
weight.JPG (33.66 KiB) Viewed 1951 times
I use this bash script to start aria.sh and run it in the background using screen at startup:

startup.sh

Code: Select all

#!/bin/bash
/usr/bin/screen -S ariamonitor -d -m nice -17 ionice -c2 -n6 /path/to/aria.sh
Notes:
1) If you delete refreshtoken.txt you must repeat step 2 and enter the new code into the bash script.
2) The send to Domoticz curl command is set to accept unsigned SSL certificates which may be a security risk.
3) You need to understand and edit as needed the above script to work in your own environment.
Last edited by ben53252642 on Thursday 01 February 2018 14:52, edited 11 times in total.

ben53252642
Posts: 534
Joined: Saturday 02 July 2016 5:17
Target OS: Linux
Domoticz version: Beta
Contact:

Re: Guide - Fitbit Aria WiFi Scales Weight Bash Script

Post by ben53252642 » Wednesday 31 January 2018 23:25

The alternate version is now available (only different steps from the above script are listed, follow the original script for setup).

This version sits constantly searching for the Fitbit Aria and updates when it is detected. You can experiment with the "sleep 10" value in the "# Check to see if Fitbit Aria is online" section of the script which is the amount of time the system waits after the Aria is detected online before checking for the new weight from the Fitbit API.

1) Set the Fitbit Aria LAN static ip address in the script (you will also need to have your router configured to give the Fitbit Aria a static IP based on it's mac address

2) System requirements: apt-get install jq bc screen fping

Code: Select all

#!/bin/bash

# ----------------------------------------------------------------------------------
# Fitbit Configuration obtained from your app at: https://dev.fitbit.com/apps
clientid="ENTERHERE" #OAuth 2.0 Client ID
clientsecret="ENTERHERE" #Client Secret
callbackurl="ENTERHERE" #Callback URL, eg: https://domoticz.com

# Fitbit Configuration obtained from the browser redirect
code="ENTERHERE"

# Fitbit Configuration weight units
units="Metric" #Options are: Metric, en_US, en_GB

# Fitbit Aria LAN Static IP address
ariaip="ENTERHERE"

# Domoticz Configuration
domoticzserver="192.168.0.5"
domoticzport="443"
domoticzuser="ENTERHERE"
domoticzpass="ENTERHERE"
domoticzweightsensoridx="ENTERHERE" # Virtual Sensor Type: Scale (Weight)

# Path to folder containing this script
cd /root/scripts/fitbit
# ----------------------------------------------------------------------------------

while true; do

# Check to see if Fitbit Aria is online
echo "Standing by to detect Fitbit Aria..."
until fping -b 12 -t 300 "$ariaip" &>/dev/null; do :; done
echo "Fitbit Aria Detected!"
sleep 10

# Create fitbit basic auth token
basicauthtoken=$(echo -n "${clientid}:${clientsecret}" | openssl base64)

# Get a Fitbit oauth2 token
refreshtoken=$(cat refreshtoken.txt 2> /dev/null)
# If we already have a stored token, get a new one.
if [ ! -f refreshtoken.txt ]; then
echo "Getting access token for the first time..."
oauth=$(curl --max-time 60 -s -X POST -H "Content-Type: application/x-www-form-urlencoded" -H "Authorization: Basic ${basicauthtoken}" "https://api.fitbit.com/oauth2/token?client_id=${clientid}&grant_type=authorization_code&redirect_uri=${callbackurl}&code=${code}")
else
echo "Detected existing refresh token, getting a new access token..."
oauth=$(curl --max-time 60 -s -X POST --header "Content-Type: application/x-www-form-urlencoded" --header "Authorization: Basic ${basicauthtoken}" "https://api.fitbit.com/oauth2/token?client_id=${clientid}&grant_type=refresh_token&refresh_token=${refreshtoken}")
fi

# Put oauth2 token into easy to use variables and store the refresh token
accesstoken=$(echo "$oauth" | jq ".access_token" | sed 's/["]*//g')
newrefreshtoken=$(echo "$oauth" | jq ".refresh_token" | sed 's/["]*//g')
echo "$newrefreshtoken" > refreshtoken.txt

# Get weight data
date=$(date +"%Y-%m-%d")
getweight=$(curl --max-time 60 -s -X GET -H "Authorization: Bearer ${accesstoken}" -H "Accept-Language: ${units}" "https://api.fitbit.com/1/user/-/body/log/weight/date/${date}/1d.json")

# Extract data from the received json array
latestkey="-1"
for row in $(echo "${getweight}" | jq -c '.weight[]'); do
latestkey=$(echo $(("$latestkey" + 1))) # Since they are all in a single line, we simply count the number of results to work out the latest index key
done
weight=$(echo "$getweight" | jq ".weight[${latestkey}].weight")

# Display data in terminal
echo "Weight: $weight"

# Check to see if a new weight has been recorded since the previous check
logid=$(echo "$getweight" | jq ".weight[${latestkey}].logId")
storedlogid=$(cat storedlogid.txt 2> /dev/null)
if [ "$logid" == "$storedlogid" ]; then
echo "No new weight data"
else
echo "New weight detected"
echo "$logid" > storedlogid.txt

# Final integrity check, does weight equal more than 5?
if (( $(echo "$weight > 5" |bc -l) )); then

# Send data to Domoticz
echo "Sending data to Domoticz..."
# Domoticz Virtual Sensor Type: Scale (Weight)
curl --max-time 60 -k -s "https://{$domoticzuser}:{$domoticzpass}@{$domoticzserver}:{$domoticzport}/json.htm?type=command&param=udevice&idx={$domoticzweightsensoridx}&nvalue=0&svalue={$weight}"

else
echo "Problem occured during the final integrity check"
fi
fi

done
The terminal should look something like this:
ariadetect.JPG
ariadetect.JPG (58.34 KiB) Viewed 1914 times

Notes:
1) It is not recommended to use this version if your Domoticz server is connected to your WiFi router / access point via wireless. The script relies on low latency to be able to detect the Fitbit Aria during the brief time that it is connected to the network.
2) Do not use this version if you know your Fitbit Aria has a poor WiFi signal. If an Aria can't connect when you step on the scales, it will store the result and try again later. In this case you may as well use the first version of the script.
3) My observation is that an Aria is usually detected within about 30 seconds however it can take up to around 10 minutes for an Aria to be detected if it fails to update on WiFi during the first attempt. That said I have yet to see the script fail to detect an Aria, be patient, best results are achieved with a good WiFi signal.

User avatar
Derik
Posts: 2186
Joined: Friday 18 October 2013 23:33
Target OS: Raspberry Pi
Domoticz version: BETA
Location: Arnhem/Nijmegen Nederland
Contact:

Re: Fitbit Aria WiFi Scales Weight Bash Script

Post by Derik » Thursday 01 February 2018 22:06

mmm Perhaps this also working with this scale??

https://health.nokia.com/nl/en/body-plus
Xu4: Beta Extreme antenna RFXcomE,WU Fi Ping ip P1 Gen5 PVOutput Harmony HUE SolarmanPv OTG Winddelen Alive ESP Buienradar MySensors WOL Winddelen counting RPi: Beta SMAspot RFlinkTest Domoticz ...Different backups

ben53252642
Posts: 534
Joined: Saturday 02 July 2016 5:17
Target OS: Linux
Domoticz version: Beta
Contact:

Re: Fitbit Aria WiFi Scales Weight Bash Script

Post by ben53252642 » Thursday 01 February 2018 22:09

Derik wrote:
Thursday 01 February 2018 22:06
mmm Perhaps this also working with this scale??

https://health.nokia.com/nl/en/body-plus
Different system unfortunately, if I had one of their scales I could try to create a Domoticz interface but for now I'm happy with the Fitbit Aria, it's very good quality. If your looking for a scale I suggest getting the Aria.

franzelare
Posts: 148
Joined: Thursday 19 February 2015 22:48
Target OS: Raspberry Pi
Domoticz version:
Contact:

Re: Fitbit Aria WiFi Scales Weight Bash Script

Post by franzelare » Sunday 29 April 2018 14:24

did you ever try to post data to the fitbit api?
i have a different brand scale that is already connected to domoticz but like to send that data to my fitbit profile

ben53252642
Posts: 534
Joined: Saturday 02 July 2016 5:17
Target OS: Linux
Domoticz version: Beta
Contact:

Re: Fitbit Aria WiFi Scales Weight Bash Script

Post by ben53252642 » Tuesday 01 May 2018 9:44

franzelare wrote:
Sunday 29 April 2018 14:24
did you ever try to post data to the fitbit api?
i have a different brand scale that is already connected to domoticz but like to send that data to my fitbit profile
Not sure.

That said the Fitbit scales we're not expensive, I'm very happy with mine. Considering the amount of time it would take to create an interface (assuming it's even possible), I suggest thinking about switching to the Fitbit scale since there is an existing solution now for getting data into Domoticz.

DAVIZINHO
Posts: 205
Joined: Sunday 27 August 2017 18:00
Target OS: Raspberry Pi
Domoticz version: Beta
Location: Spain
Contact:

Re: Fitbit Aria WiFi Scales Weight Bash Script

Post by DAVIZINHO » Tuesday 01 May 2018 12:49

this is a great script and works perfect!!!
Its posible to obtain the body fat values???

hello again, edit my last post.

i see that the script receive all the data of the aria, like:
{"bmi":19.74,"date":"2018-05-01","fat":14.260000228881836,"logId":1525180250000,"source":"Aria","time":"13:10:50","weight":57.7}

now the script obtain the weight but its posible to obtain also the:
- bmi
- fat

this is great!!!, i will try to save this 2 values in a variables to push in 2 new custom idx in domoticz
im very noob in linux, but if i make it posible i post here

franzelare
Posts: 148
Joined: Thursday 19 February 2015 22:48
Target OS: Raspberry Pi
Domoticz version:
Contact:

Re: Fitbit Aria WiFi Scales Weight Bash Script

Post by franzelare » Tuesday 01 May 2018 21:18

ben53252642 wrote:
Tuesday 01 May 2018 9:44
franzelare wrote:
Sunday 29 April 2018 14:24
did you ever try to post data to the fitbit api?
i have a different brand scale that is already connected to domoticz but like to send that data to my fitbit profile
Not sure.

That said the Fitbit scales we're not expensive, I'm very happy with mine. Considering the amount of time it would take to create an interface (assuming it's even possible), I suggest thinking about switching to the Fitbit scale since there is an existing solution now for getting data into Domoticz.
I use a medisana scale and blood pressure sensor, both connected through BT-LE with a raspi zero, works fine! so i already have the data in domoticz
so will try to push data to fitbit api.. when i read the api documentation, it must not be so hard when i use this script as start

DAVIZINHO
Posts: 205
Joined: Sunday 27 August 2017 18:00
Target OS: Raspberry Pi
Domoticz version: Beta
Location: Spain
Contact:

Re: Fitbit Aria WiFi Scales Weight Bash Script

Post by DAVIZINHO » Wednesday 02 May 2018 13:41

Hello again,
I modify the script with this 2 easy things:

Firs in config parameters i put the idx of the new 2 devices: fat and bmi

Code: Select all

domoticzbmisensoridx="185" # Virtual Sensor Type: Scale (bmi)
domoticzfatsensoridx="184" # Virtual Sensor Type: Scale (fat)
After this in the # Extract data from the received json array y add this

Code: Select all

bmi=$(echo "$getweight" | jq ".weight[${latestkey}].bmi")
fat=$(echo "$getweight" | jq ".weight[${latestkey}].fat" | cut -c 1-5)
To obtain the bmi and fat

Then the last thing is update domotic with this 2 lines:

Code: Select all

# Domoticz Virtual Sensor Type: Scale (BMI)
curl -s -i -H "Accept: application/json" "http://{$domoticzuser}:{$domoticzpass}@{$domoticzserver}:$domoticzport/json.htm?type=command&param=udevice&idx=$domoticzbmisensoridx&nvalue=0&svalue=$bmi"

# Domoticz Virtual Sensor Type: Scale (Fat)
curl -s -i -H "Accept: application/json" "http://{$domoticzuser}:{$domoticzpass}@{$domoticzserver}:$domoticzport/json.htm?type=command&param=udevice&idx=$domoticzfatsensoridx&nvalue=0&svalue=$fat"
easy changes and very usefull for me.
Thanks for your work and inspiration!!!

ben53252642
Posts: 534
Joined: Saturday 02 July 2016 5:17
Target OS: Linux
Domoticz version: Beta
Contact:

Re: Fitbit Aria WiFi Scales Weight Bash Script

Post by ben53252642 » Wednesday 02 May 2018 13:55

DAVIZINHO, very good!

I will add these into my Domoticz as well.

DAVIZINHO
Posts: 205
Joined: Sunday 27 August 2017 18:00
Target OS: Raspberry Pi
Domoticz version: Beta
Location: Spain
Contact:

Re: Fitbit Aria WiFi Scales Weight Bash Script

Post by DAVIZINHO » Monday 28 May 2018 22:23

hello.
Recently I need to reinstall domoticz :-(
And now the aria script stop working :-(

The first error was:

Code: Select all

Fitbit Aria Detected!
Getting access token for the first time...
./aria.sh: línea 56: refreshtoken.txt: Permiso denegado
jq: error (at <stdin>:1): Cannot iterate over null (null)
i solved it by sudo chmod 777 refreshtoken.txt

after this, i run again and this error:

Code: Select all

Standing by to detect Fitbit Aria...
Fitbit Aria Detected!
Detected existing refresh token, getting a new access token...
jq: error (at <stdin>:1): Cannot iterate over null (null)
Weight: null
bmi: null
fat: null
No new weight data
Standing by to detect Fitbit Aria...
any idea???
this works like a charm and now broken. im sure is my problem :-(

ben53252642
Posts: 534
Joined: Saturday 02 July 2016 5:17
Target OS: Linux
Domoticz version: Beta
Contact:

Re: Fitbit Aria WiFi Scales Weight Bash Script

Post by ben53252642 » Tuesday 29 May 2018 3:20

Try getting another token (follow steps in the first post using Google Chrome), you will need to delete refreshtoken.txt it will get re-created automatically.

Does that fix it?

DAVIZINHO
Posts: 205
Joined: Sunday 27 August 2017 18:00
Target OS: Raspberry Pi
Domoticz version: Beta
Location: Spain
Contact:

Re: Fitbit Aria WiFi Scales Weight Bash Script

Post by DAVIZINHO » Tuesday 29 May 2018 13:06

WOW, im stupid!!!
i thought this steps are only necesary for the first time, jejeje.
I make it again and works like a charm!
thanks!!!

Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest