ReviewOS

stacks/ts-watches

public
Clone

Push over the same URL. A password will not work: create a token under access tokens and use it in place of one.

A comprehensive TypeScript library for downloading, parsing, and analyzing data from smartwatches and fitness devices.

main
· 6 branches · 127 commits

Mirrored from stacksjs/ts-watches · synced 1 hour ago

1633011 chore: release v0.1.20 Chris Breuer 6 days ago History
README.md

Social Card of this repo

npm version GitHub Actions Commitizen friendly

ts-watches

A comprehensive TypeScript library for downloading, parsing, and analyzing data from smartwatches and fitness devices. Supports Garmin, Polar, Suunto, Coros, Wahoo, and Apple Watch with full FIT file parsing, cloud integrations, training analysis, and real-time data streaming.

Features

Device Support

  • Garmin - Full FIT file parsing for activities, monitoring, sleep, stress, HRV
  • Polar - HRM and JSON file format support
  • Suunto - SML (XML) format parsing
  • Coros - FIT file support with device detection
  • Wahoo - FIT file support for ELEMNT devices
  • Apple Watch - Health XML export parsing

Data Parsing

  • FIT Protocol - Complete binary parser for Garmin's FIT format
  • Activity Data - Runs, rides, swims, hikes with full GPS and metrics
  • Health Monitoring - Heart rate, sleep, stress, SpO2, HRV, respiration
  • Training Metrics - TSS, IF, NP, training load calculations

Data Export

  • GPX 1.1 - With Garmin TrackPoint extensions for heart rate, cadence, power
  • TCX - Training Center XML format for Strava and other platforms
  • CSV - Flexible export for activities and monitoring data
  • GeoJSON - For mapping applications with Douglas-Peucker simplification

Cloud Integrations

  • Garmin Activity API - Official OAuth 2.0 PKCE integration with webhook push notifications, backfill and deregistration
  • Garmin Connect - Download activities, daily summaries, sleep, stress, body battery (unofficial, password-based)
  • Strava - OAuth authentication, activity upload, stream data retrieval

Training Analysis

  • Training Load - TSS, ATL, CTL, TSB calculations with recommendations
  • Personal Records - Track PRs for various distances and metrics
  • Heart Rate Zones - Percentage, Karvonen (reserve), LTHR-based calculations
  • Power Zones - FTP-based zone calculations
  • Race Predictor - Riegel formula predictions, VO2max estimation, training paces
  • Running Dynamics - Form analysis, ground contact time, vertical oscillation

Workout Tools

  • Workout Builder - Fluent API for creating structured workouts
  • Course Builder - Create GPS courses with waypoints
  • Training Plans - Generate marathon and 5K training plans
  • iCal Export - Export training plans to calendar format

Real-time Data

  • ANT+ - Heart rate, power, speed/cadence sensor protocols
  • Bluetooth LE - BLE GATT services for fitness devices
  • Live Tracking - Real-time position and metrics sharing

Developer Experience

  • CLI Tool - Download, parse, and analyze from command line
  • TypeScript - Fully typed APIs with comprehensive type exports
  • Zero Dependencies - Core FIT parser has no external dependencies

Direct Garmin Bluetooth

ts-watches/garmin-bluetooth connects to a user-selected watch through Craft's native Bluetooth notification stream. Check garminBluetoothAvailable(bluetooth) first; an older native host cannot provide the lossless reads and writes it needs. The initial hardware target is Garmin Enduro 3. Hardware compatibility remains experimental and is not equivalent to all Garmin Connect health data.

import { connectGarminBluetooth, garminFileIdentity } from 'ts-watches/garmin-bluetooth'
import { decodeGarminHealthFile } from 'ts-watches/fit'

// bluetooth is the native Craft host; selectedId comes from explicit scanning/pairing.
const client = await connectGarminBluetooth(bluetooth, selectedId)
try {
  await client.sync({
    seen: entry => savedFiles.has(garminFileIdentity(entry)),
    async onFile(file) {
      // Persist the complete verified file before acknowledging this callback.
      await saveOriginal(file)
      const health = decodeGarminHealthFile(file.bytes, athleteTimeZone)
      await importHealth(health)
    },
  })
}
finally {
  await client.close()
}

Downloads are read-only and bounded. Unknown FIT fields remain available in the original bytes; live RR intervals are never represented as nightly HRV. Keep a separate Garmin Connect connection for reconciliation and unavailable data. The protocol implementation is first-party zig-garmin, which credits garmin-ble and Gadgetbridge in its provenance notice. It uses no Garmin SDK or third-party Bluetooth runtime dependency.

Install

bun install ts-watches

Quick Start

import { createGarminDriver } from 'ts-watches'

const driver = createGarminDriver()

// Detect connected devices
const devices = await driver.detectDevices()
console.log('Found devices:', devices)

// Download data from a device
if (devices.length > 0) {
  const result = await driver.downloadData(devices[0], {
    outputDir: './my-watch-data',
    includeActivities: true,
    includeMonitoring: true,
  })

  console.log(`Downloaded ${result.activities.length} activities`)
  console.log(`Downloaded ${result.monitoring.size} days of monitoring data`)
}

Usage Examples

Parse FIT Files

import { createGarminDriver } from 'ts-watches'

const driver = createGarminDriver()
const activity = await driver.parseActivityFile('/path/to/activity.fit')

console.log(`${activity.sport}: ${(activity.totalDistance / 1000).toFixed(2)}km`)
console.log(`Duration: ${Math.floor(activity.totalTime / 60)} minutes`)
console.log(`Avg HR: ${activity.avgHeartRate} bpm`)

Export to GPX

import { activityToGpx, activityToTcx, activityToCsv } from 'ts-watches'

// Export activity to GPX
const gpx = activityToGpx(activity)
await Bun.write('activity.gpx', gpx)

// Export to TCX for Strava upload
const tcx = activityToTcx(activity)
await Bun.write('activity.tcx', tcx)

// Export to CSV for analysis
const csv = activityToCsv(activity)
await Bun.write('activity.csv', csv)

Training Analysis

import { calculateTSS, ZoneCalculator, RacePredictor } from 'ts-watches'

// Calculate Training Stress Score
const tss = calculateTSS(activity, { ftp: 250 })

// Analyze zones
const zones = new ZoneCalculator({ maxHR: 185, restingHR: 50, ftp: 250 })
const zoneAnalysis = zones.analyzeActivity(activity)

// Predict race times
const predictor = new RacePredictor()
const predictions = predictor.predictFromPerformance(5000, 20 * 60) // 5K in 20min
console.log(`Predicted marathon: ${predictions.marathon}`)

Cloud Integration

import { GarminActivityApiClient, GarminConnectClient, StravaClient } from 'ts-watches'

// Garmin Activity API (official, OAuth 2.0 PKCE, push notifications).
// The athlete approves on Garmin's own site and can revoke at any time.
const garmin = new GarminActivityApiClient({
  clientId: process.env.GARMIN_CLIENT_ID!,
  clientSecret: process.env.GARMIN_CLIENT_SECRET!,
  redirectUri: 'https://example.com/garmin/callback',
})

const { verifier, challenge } = createPkcePair()
const url = garmin.buildAuthorizationUrl({ state, challenge }) // send the athlete here
const tokens = await garmin.exchangeCode(code, verifier) // on the callback
const userId = await garmin.getUserId(tokens.accessToken) // the key push notifications carry

// Garmin Connect (unofficial; needs the athlete's password, breaks under 2FA)
const legacy = new GarminConnectClient()
await legacy.login('email@example.com', 'password')
const activities = await legacy.getActivities(new Date('2024-01-01'))
const { bytes, filename } = await legacy.downloadOriginalActivity(activityId) // "Export Original" zip, in memory
// Structured workouts onto the watch: into the library, then onto a day
const { workoutId } = await legacy.createWorkout(workout) // Connect's workout JSON
const { workoutScheduleId } = await legacy.scheduleWorkout(workoutId, '2026-10-20')
await legacy.deleteWorkout(workoutId) // a 404 counts as done

// Strava
const strava = new StravaClient({
  clientId: 'your-client-id',
  clientSecret: 'your-client-secret',
})
const authUrl = strava.getAuthorizationUrl('http://localhost:3000/callback')

Build Workouts

import { WorkoutBuilder, workoutTemplates } from 'ts-watches'

// Use a template
const intervals = workoutTemplates.vo2maxIntervals({ ftp: 250 })

// Or build custom workout
const workout = new WorkoutBuilder('Custom Threshold')
  .warmup({ duration: 600, targetPower: { min: 100, max: 150 } })
  .interval({ duration: 1200, targetPower: { min: 240, max: 260 } })
  .recovery({ duration: 300, targetPower: { min: 100, max: 130 } })
  .repeat(4)
  .cooldown({ duration: 600, targetPower: { min: 100, max: 130 } })
  .build()

Real-time Data

import { createLiveTracking, createBleScanner } from 'ts-watches'

// Live tracking
const tracker = createLiveTracking({
  updateInterval: 5000,
  onUpdate: (session) => console.log(`Distance: ${session.totalDistance}m`),
})

tracker.start('Morning Run')
tracker.updatePosition({ lat: 37.7749, lng: -122.4194, altitude: 10 })

// BLE sensors
const ble = createBleScanner()
await ble.startScanning()
ble.on('data', (device, data) => {
  if (data.type === 'heart_rate') {
    console.log(`HR: ${data.data.heartRate} bpm`)
  }
})

CLI

# Detect connected watches
watch detect

# Download all data from connected watch
watch download

# Download to specific directory
watch download --output ./my-data

# Download only activities from the last week
watch download --activities --since 2024-01-01

# Parse a single FIT file
watch parse /path/to/activity.fit

# Parse and output as JSON
watch parse /path/to/activity.fit --format json

# Watch for device connection and auto-download
watch watch

Supported Data Types

Activities

  • Running (treadmill, trail, track)
  • Cycling (road, mountain, gravel, indoor)
  • Swimming (pool, open water)
  • Hiking, Walking
  • Strength training, Cardio, HIIT
  • Multisport (triathlon)
  • And 50+ more sport types

Health Metrics

MetricDescription
Heart RateContinuous monitoring, resting HR, zones
SleepDuration, stages (light, deep, REM), score
StressStress levels throughout the day
Body BatteryEnergy levels based on HRV
SpO2Blood oxygen saturation
RespirationBreathing rate
HRVHeart rate variability (RMSSD, SDRR)
StepsDaily count, goals, intensity minutes

Training Metrics

MetricDescription
TSSTraining Stress Score
IFIntensity Factor
NPNormalized Power
ATLAcute Training Load
CTLChronic Training Load (Fitness)
TSBTraining Stress Balance (Form)
TRIMPTraining Impulse

Device Setup

Garmin

  1. Connect your watch via USB
  2. On the watch: Settings > System > USB Mode > Mass Storage
  3. Close Garmin Express (it locks the device)
  4. The watch appears as /Volumes/GARMIN on macOS

Polar

  1. Export data from Polar Flow web interface
  2. Or use Polar's data export feature on the device

Apple Watch

  1. Open Health app on iPhone
  2. Tap profile > Export All Health Data
  3. Extract the ZIP file

API Reference

See the full API documentation for detailed type definitions and method signatures.

Testing

bun test

Changelog

Please see our releases page for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Community

For help, discussion about best practices, or any other conversation that would benefit from being searchable:

Discussions on GitHub

For casual chit-chat with others using this package:

Join the Stacks Discord Server

Postcardware

"Software that is free, but hopes for a postcard." We love receiving postcards from around the world showing where Stacks is being used! We showcase them on our website too.

Our address: Stacks.js, 12665 Village Ln #2306, Playa Vista, CA 90094, United States

Sponsors

We would like to extend our thanks to the following sponsors for funding Stacks development. If you are interested in becoming a sponsor, please reach out to us.

License

The MIT License (MIT). Please see LICENSE for more information.

Made with 💙

[codecov-href]: https://codecov.io/gh/stacksjs/ts-watches -->