Fitbit - Steps, Floors, Calories, Weight Bash Script

All kinds of 'OS' scripts

Moderator: leecollings

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

Fitbit - Steps, Floors, Calories, Weight Bash Script

Post by ben53252642 »

This is an extension of the work done here:

viewtopic.php?f=63&t=21979

Follow steps in the above thread to do general setup of the script.

Goal of this script to get useful data from the Fitbit API and make it easily available to send to Domoticz sensors:

Data includes:
* Weight
* Steps
* Floors Climbed
* Calories Out
* Sedentary Minutes

All data displayed is for today's date as reported by the system making the request.

Sample terminal output:

snap3.JPG
snap3.JPG (41.01 KiB) Viewed 2961 times

Code:

Code: Select all

#!/bin/bash
while true; do

# ----------------------------------------------------------------------------------
# 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 set your units
units="Metric" #Options are: Metric, en_US, en_GB

# Domoticz Configuration
domoticzserver="192.168.0.5"
domoticzport="443"
domoticzuser="ENTERHERE"
domoticzpass="ENTERHERE"

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

# 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 data from Fitbit
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")
getactivities=$(curl --max-time 60 -s -X GET -H "Authorization: Bearer ${accesstoken}" -H "Accept-Language: ${units}" "https://api.fitbit.com/1/user/-/activities/date/${date}.json")

# Extract weight 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

# Easy bash variables to access Fitbit data
weight=$(echo "$getweight" | jq ".weight[${latestkey}].weight")
steps=$(echo "$getactivities" | jq ".summary.steps")
floorsclimbed=$(echo "$getactivities" | jq ".summary.floors")
caloriesout=$(echo "$getactivities" | jq ".summary.caloriesOut")
sedentaryMinutes=$(echo "$getactivities" | jq ".summary.sedentaryMinutes")

# Display data in terminal
echo "Weight: $weight"
echo "Steps: $steps"
echo "Floors Climbed: $floorsclimbed"
echo "Calories Out: $caloriesout"
echo "Sedentary Minutes: $sedentaryMinutes"

# Example send data to Domoticz virtual sensor
#curl --max-time 60 -k -s "https://{$domoticzuser}:{$domoticzpass}@{$domoticzserver}:{$domoticzport}/json.htm?type=command&param=udevice&idx=335&nvalue=0&svalue={$steps}"

echo "Waiting 30 minutes before next update..."
sleep 1800
done
Notes:
1) If you delete refreshtoken.txt you must repeat step 2 in the weight thread 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.
Unless otherwise stated, all my code is released under GPL 3 license: https://www.gnu.org/licenses/gpl-3.0.en.html
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest