Skip to content

About

Script to fetch and sync health data from a fitbit air to intervals.icu

Resources

Stars

0 stars

Watchers

0 watching

Forks

 
 

Repository files navigation

Fitbit (Google Health API) to Intervals.icu Sync

Automatically synchronizes daily health metrics, sleep data, and fitness vitals from Google Health API (Fitbit devices) to Intervals.icu.


📊 Synced Metrics

Metric Google Health API Source Intervals.icu Field Unit / Format Notes
Resting Heart Rate daily-resting-heart-rate restingHR Beats per minute (bpm) Daily resting HR
Heart Rate Variability daily-heart-rate-variability hrv rMSSD (ms) Average HRV
Average Sleeping HR daily-heart-rate-variability avgSleepingHR Beats per minute (bpm) NREM Restoration HR
Sleep Duration sleep sleepSecs Seconds Mapped to wake-up date
Body Weight weight weight Kilograms (kg) Scale measurement
Body Fat body-fat bodyFat Percentage (%) Scale measurement
Oxygen Saturation daily-oxygen-saturation spO2 Percentage (%) Nightly average
Respiratory Rate daily-respiratory-rate respiration Breaths per minute Nightly average
VO2 Max daily-vo2-max / vo2-max vo2max mL/kg/min Aerobic capacity
Daily Steps steps (via dailyRollUp) steps Total count Daily aggregate

Note

Sleep Date Mapping: Sleep sessions are automatically assigned to the local wake-up date (endTime). This ensures overnight sleep aligns on the same day as your morning/daytime workout on Intervals.icu.

Sleep Score: Google Health API REST endpoints standardise raw metrics (duration, stages, sleeping HR) but exclude vendor-proprietary algorithm scores (such as Fitbit's 0–100 Sleep Score).


📋 Prerequisites

  1. Python 3.10+
  2. Intervals.icu API Key: Obtained from Intervals.icu Settings.
  3. Google Cloud OAuth Credentials: A credentials.json file for your Google Cloud Project with the Google Health API enabled. See Google Health API setup for setup instructions.
  4. (Optional but Recommended) Telegram Bot: A Telegram Bot Token & Chat ID to receive instant re-authentication prompts on your phone when Google OAuth refresh tokens expire.

🚀 Quick Setup Guide

1. Environment & Dependencies

Create a virtual environment and install dependencies:

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

2. Configure Credentials & Environment

Create a .env file in the project root:

INTERVALS_API_KEY="your_intervals_api_key_here"

# Telegram Re-Authentication Fallback (Optional)
TELEGRAM_BOT_TOKEN="your_telegram_bot_token_here"
TELEGRAM_CHAT_ID="your_telegram_chat_id_here"
TELEGRAM_AUTH_TIMEOUT_HOURS="12"

Ensure your Google OAuth credentials.json file is placed in the project root directory.

3. One-Time Google OAuth Authorization

Run the setup helper script to authorize access to your Google Health data:

.venv/bin/python auth_setup.py
  1. Click the link generated by the script to open the Google login page.
  2. Grant read permissions for your activity, health metrics, and sleep data.
  3. After approving, Google will redirect your browser to a URL starting with https://www.google.com/?code=....
  4. Copy the full redirected URL from your browser address bar and paste it into the script prompt.

This creates token.json with an authorized refresh token.


📱 Telegram Interactive Re-Authentication

When Google Cloud OAuth projects are in "Testing" publishing status, Google automatically invalidates refresh tokens after 7 days.

To eliminate manual SSH logins when tokens expire:

  1. When google_health_client detects an expired token or HTTP 401 error, it automatically sends a message to your Telegram app via your bot.
  2. The message contains a direct Google authorization link.
  3. The script enters low-resource HTTP long-polling (consuming 0% CPU) and waits up to 12 hours (configurable via TELEGRAM_AUTH_TIMEOUT_HOURS).
  4. Simply tap the link on your phone, approve access in your browser, and reply to the Telegram bot with the redirected URL.
  5. The script automatically updates token.json, sends a confirmation message to Telegram ("✅ Google OAuth Authorization successful!"), and completes the sync!

To test the Telegram flow manually at any time:

.venv/bin/python auth_setup.py --telegram

🔄 Running the Sync Script

By default, the script syncs past finalized days (yesterday and the day before) to guarantee 100% complete step counts, sleep totals, and resting metrics:

.venv/bin/python fitbit_intervals_sync.py --days 2
  • --days N: Specifies how many finalized days to sync (default: 2).
  • --include-today: Optional flag if you want to push partial intraday metrics for today.

🖥️ Server Deployment Options

Option A: Systemd Service & Timer (Recommended)

Systemd is the most robust way to run scheduled scripts on Ubuntu/Linux.

  1. Create a service file /etc/systemd/system/fitbit-sync.service:
[Unit]
Description=Fitbit to Intervals.icu Health Data Sync
After=network-online.target

[Service]
Type=oneshot
User=giacomo
WorkingDirectory=/home/giacomo/fitbit-intervals-sync
ExecStart=/home/giacomo/fitbit-intervals-sync/.venv/bin/python fitbit_intervals_sync.py --days 2
TimeoutStartSec=0
Restart=no
StandardOutput=append:/var/log/fitbit_sync.log
StandardError=append:/var/log/fitbit_sync.log

Tip

TimeoutStartSec=0 allows the script to wait overnight for your Telegram re-authentication reply without systemd killing the process.

  1. Create a timer file /etc/systemd/system/fitbit-sync.timer:
[Unit]
Description=Run Fitbit Sync twice daily

[Timer]
OnCalendar=*-*-* 07:00,19:00
Persistent=true

[Install]
WantedBy=timers.target
  1. Enable and start the timer:
sudo systemctl daemon-reload
sudo systemctl enable --now fitbit-sync.timer

Option B: Crontab (Lightweight Alternative)

crontab -e

Add a line to run the sync twice daily (e.g., 7:00 AM and 7:00 PM):

0 7,19 * * * cd /home/giacomo/fitbit-intervals-sync && .venv/bin/python fitbit_intervals_sync.py --days 2 >> /var/log/fitbit_intervals_sync.log 2>&1

📁 Repository Structure

.
├── auth_setup.py            # Initial Google OAuth authorization helper & --telegram CLI
├── telegram_auth.py         # Interactive Telegram bot OAuth re-authentication fallback module
├── google_health_client.py  # Wrapper client for Google Health REST API v4 (401 & token refresh handling)
├── intervals_client.py      # Wrapper client for Intervals.icu Wellness API
├── fitbit_intervals_sync.py # Main synchronization CLI script
├── requirements.txt         # Python package dependencies
├── README.md                # Project documentation
├── .env                     # Environment variables (git-ignored)
├── credentials.json         # Google OAuth Client Secrets (git-ignored)
└── token.json               # Authorized OAuth refresh tokens (git-ignored)

About

Script to fetch and sync health data from a fitbit air to intervals.icu

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages