### Frontend Setup without Docker Source: https://github.com/the-momentum/open-wearables/blob/main/contributing/developing.md Instructions for setting up the frontend locally, including installing dependencies, configuring environment variables, and starting the development server. ```bash cd frontend pnpm install cp .env.example .env pnpm dev ``` -------------------------------- ### Install Frontend Dependencies and Start Server Source: https://github.com/the-momentum/open-wearables/blob/main/docs/quickstart.mdx Install frontend dependencies using npm and start the development server for local frontend development. ```bash cd frontend npm install ``` ```bash npm run dev ``` -------------------------------- ### Backend Setup without Docker Source: https://github.com/the-momentum/open-wearables/blob/main/contributing/developing.md Steps to set up the backend locally, including creating a virtual environment, installing dependencies, configuring environment variables, applying database migrations, and starting the development server. ```bash cd backend uv sync cp config/.env.example config/.env uv run alembic upgrade head uv run fastapi dev app/main.py --host 0.0.0.0 --port 8000 ``` -------------------------------- ### Local Open Wearables Setup Source: https://github.com/the-momentum/open-wearables/blob/main/docs/sdk/flutter/example-app.mdx Instructions to clone the repository, navigate to the directory, and start a local instance using Docker Compose. ```bash git clone https://github.com/the-momentum/open-wearables.git cd open-wearables docker compose up -d ``` -------------------------------- ### Install Example App Dependencies Source: https://github.com/the-momentum/open-wearables/blob/main/docs/sdk/react-native/example-app.mdx Install the Node.js dependencies specifically for the React Native example application. ```bash cd example npm install ``` -------------------------------- ### Run Flutter Example App Source: https://github.com/the-momentum/open-wearables/blob/main/docs/sdk/flutter/example-app.mdx Execute this command to run the Flutter example app on a connected device or emulator. Ensure platform-specific setup is completed beforehand. ```bash flutter run ``` -------------------------------- ### Install Flutter Dependencies Source: https://github.com/the-momentum/open-wearables/blob/main/docs/sdk/flutter/example-app.mdx After cloning the repository and navigating to the example app directory, install the necessary Flutter dependencies using the command below. ```bash flutter pub get ``` -------------------------------- ### Install SDK from npm Source: https://github.com/the-momentum/open-wearables/blob/main/docs/sdk/react-native/index.mdx Install the SDK using npm once it is published. This is the command to use for future installations. ```bash npm install open-wearables ``` -------------------------------- ### Python SDK Usage Example Source: https://github.com/the-momentum/open-wearables/blob/main/docs/dev-guides/integration-guide.mdx Demonstrates how to use the Python SDK to create a user, get an OAuth URL, and fetch data like workouts and health scores. ```python async def main(): client = OpenWearablesClient( base_url="http://localhost:8000", api_key="sk-your-api-key", ) # 1. Create or get user (pass your own user row; see get_or_create_user above) user = await client.get_or_create_user(local_user) user_id = user["id"] # 2. Get OAuth URL for Garmin auth_url = await client.get_auth_url( provider="garmin", user_id=user_id, redirect_uri="https://myapp.com/callback", ) print(f"Redirect user to: {auth_url}") # 3. After OAuth callback, confirm the connection is active. # Historical backfill is dispatched automatically - no explicit sync call needed. connections = await client.get_connections(user_id) garmin_connected = any( c["provider"] == "garmin" and c["status"] == "active" for c in connections ) if garmin_connected: # 4. Fetch whatever you need. workouts = await client.get_workouts(user_id, "2025-01-01", "2025-01-31") activity = await client.get_activity_summary(user_id, "2025-01-01", "2025-01-31") scores = await client.get_health_scores(user_id, category="sleep") print(f"{len(workouts)} workouts, {len(activity)} activity days, {len(scores)} sleep scores") ``` -------------------------------- ### Run Example App on Android Source: https://github.com/the-momentum/open-wearables/blob/main/docs/sdk/react-native/example-app.mdx Execute the example app on an Android device after setting up the Android SDK in Maven Local. ```bash npx expo run:android ``` -------------------------------- ### Start MCP Server Locally Source: https://github.com/the-momentum/open-wearables/blob/main/mcp/README.md Commands to start the backend and then the MCP server for local development. ```bash # Start the backend first (from project root) docker compose up -d # Then start the MCP server cd mcp uv run start ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/the-momentum/open-wearables/blob/main/backend/README.md Installs the pre-commit framework and its associated hooks for the project. ```bash uv run pre-commit install ``` -------------------------------- ### Start Development Server Source: https://github.com/the-momentum/open-wearables/blob/main/backend/README.md Starts the FastAPI development server with hot-reloading enabled for rapid development. ```bash uv run fastapi run app/main.py --reload ``` -------------------------------- ### Installing shadcn/ui Components Source: https://github.com/the-momentum/open-wearables/blob/main/frontend/AGENTS.md Commands to install specific shadcn/ui components like Button, Card, and Input using pnpm. Installed components are located in `src/components/ui/`. ```bash pnpm dlx shadcn@latest add button pnpm dlx shadcn@latest add card pnpm dlx shadcn@latest add input ``` -------------------------------- ### Sync Run Summary Examples Source: https://github.com/the-momentum/open-wearables/blob/main/docs/api-reference/guides/sync-status-stream.mdx Examples of sync run summary objects, showing both completed and in-progress syncs. ```json [ { "run_id": "pull_garmin_user42_1730000000", "user_id": "user42", "provider": "garmin", "source": "pull", "stage": "completed", "status": "success", "message": null, "progress": 1.0, "items_processed": 42, "items_total": 42, "error": null, "started_at": "2024-10-27T10:15:00Z", "ended_at": "2024-10-27T10:16:45Z", "last_update": "2024-10-27T10:16:45Z" }, { "run_id": "garmin_backfill_user42_trace-abc123", "user_id": "user42", "provider": "garmin", "source": "backfill", "stage": "fetching", "status": "in_progress", "message": "Fetching activities window 3 of 12", "progress": 0.25, "items_processed": null, "items_total": null, "error": null, "started_at": "2024-10-27T09:00:00Z", "ended_at": null, "last_update": "2024-10-27T09:45:00Z" } ] ``` -------------------------------- ### Install Project Dependencies with uv Source: https://github.com/the-momentum/open-wearables/blob/main/backend/README.md Installs all project dependencies, including development dependencies, and sets up the virtual environment. ```bash uv sync ``` -------------------------------- ### Install SDK Dependencies Source: https://github.com/the-momentum/open-wearables/blob/main/docs/sdk/react-native/example-app.mdx Install the necessary Node.js dependencies for the SDK from the repository root. ```bash npm install ``` -------------------------------- ### Start Development Server Source: https://github.com/the-momentum/open-wearables/blob/main/frontend/README.md Starts the local development server, typically on port 3000. Hot reloading is enabled. ```bash npm run dev ``` -------------------------------- ### Start Application with Docker Compose Source: https://github.com/the-momentum/open-wearables/blob/main/docs/quickstart.mdx Use Docker Compose to easily start all required services for the backend and frontend. Use the --watch flag for development with hot-reloading. ```bash docker compose up -d ``` ```bash docker compose watch ``` -------------------------------- ### Install SDK Locally Source: https://github.com/the-momentum/open-wearables/blob/main/docs/sdk/react-native/index.mdx Install the SDK locally from the project root. This command is used before the package is published to npm. ```bash npm install ``` -------------------------------- ### Install Backend Dependencies Locally Source: https://github.com/the-momentum/open-wearables/blob/main/docs/quickstart.mdx Install backend dependencies using uv (recommended) or pip before running the application locally without Docker. ```bash cd backend uv sync ``` -------------------------------- ### Environment Variable Example Source: https://github.com/the-momentum/open-wearables/blob/main/frontend/README.md Example of an environment variable for the backend API URL. This should be placed in the `.env` file. ```bash VITE_API_URL=http://localhost:8000 # Backend API URL ``` -------------------------------- ### Clone Open Wearables SDK Repository Source: https://github.com/the-momentum/open-wearables/blob/main/docs/sdk/flutter/example-app.mdx Clone the SDK repository to access the example app. Navigate into the cloned directory and then into the example app's directory. ```bash git clone https://github.com/the-momentum/open_wearables_health_sdk.git cd open_wearables_health_sdk/example ``` -------------------------------- ### Install and Run Pre-commit Hooks Source: https://github.com/the-momentum/open-wearables/blob/main/contributing/linting.md Install the necessary pre-commit hooks for the project and then run them manually to check code quality. This ensures consistency across the development environment. ```bash uv sync --group code-quality uv run pre-commit install ``` ```bash uv run pre-commit run --all-files ``` -------------------------------- ### Start the MCP Server Source: https://github.com/the-momentum/open-wearables/blob/main/docs/mcp-server/index.mdx Starts the Open Wearables MCP server. Successful startup is indicated by log messages showing initialization and worker status. ```bash uv run start ``` -------------------------------- ### Install Mintlify CLI Source: https://github.com/the-momentum/open-wearables/blob/main/docs/README.md Install the Mintlify CLI globally using npm. This is required for local development and previewing documentation changes. ```bash npm i -g mint ``` -------------------------------- ### Install Dependencies Source: https://github.com/the-momentum/open-wearables/blob/main/docs/mcp-server/index.mdx Installs project dependencies using the `uv` package manager. Ensure you are in the `mcp` directory. ```bash cd mcp uv sync --group code-quality ``` -------------------------------- ### Start Docker Services Source: https://github.com/the-momentum/open-wearables/blob/main/AGENTS.md Starts all project services using Docker Compose. Includes commands for seeding data, viewing logs, and stopping services. ```bash docker compose up -d # Admin account and series type definitions are auto-created on startup (admin@admin.com / your-secure-password) # Seed sample test data (optional) make seed # View logs docker compose logs -f app # Stop make stop ``` -------------------------------- ### Clone Repository and Start Services with Docker Compose Source: https://github.com/the-momentum/open-wearables/blob/main/contributing/developing.md Use these commands to clone the repository and start all services with hot-reloading enabled for development. An admin account is automatically created upon startup. ```bash git clone https://github.com/the-momentum/open-wearables.git cd open-wearables make watch make seed ``` -------------------------------- ### CRUD Repository Example with Custom Method Source: https://github.com/the-momentum/open-wearables/blob/main/backend/AGENTS.md Example of a UserRepository inheriting from CrudRepository, demonstrating a custom method to retrieve a user by email. ```python from app.repositories.repositories import CrudRepository class UserRepository(CrudRepository[User, UserCreate, UserUpdate]): def __init__(self, model: type[User]): super().__init__(model) def get_by_email(self, db_session: DbSession, email: str) -> User | None: return db_session.query(self.model).filter(self.model.email == email).one_or_none() ``` -------------------------------- ### Start Docker Compose for Local Development Source: https://github.com/the-momentum/open-wearables/blob/main/docs/mcp-server/claude-desktop.mdx Execute this command from the project root to start the backend services using Docker Compose, which is often necessary for local development and troubleshooting connection issues. ```bash # From project root docker compose up -d ``` -------------------------------- ### Service Layer Business Logic Example Source: https://github.com/the-momentum/open-wearables/blob/main/backend/AGENTS.md Example of a UserService class, inheriting from AppService, which contains business logic and interacts with a UserRepository. ```python from app.services.services import AppService from app.utils.exceptions import handle_exceptions class UserService(AppService[UserRepository, User, UserCreate, UserUpdate]): def __init__(self, crud_model: type[UserRepository], model: type[User], log: Logger, **kwargs): super().__init__(crud_model, model, log, **kwargs) ``` -------------------------------- ### Offset Pagination Example Source: https://github.com/the-momentum/open-wearables/blob/main/docs/api-reference/introduction.mdx This example demonstrates how to use offset pagination to retrieve a list of users. The `page` parameter specifies the desired page number, and the `limit` parameter controls the number of items per page. ```APIDOC ## GET /api/v1/users ### Description Retrieves a list of users with offset pagination. ### Method GET ### Endpoint /api/v1/users ### Parameters #### Query Parameters - **page** (integer) - Optional - Page number, defaults to 1. - **limit** (integer) - Optional - Items per page, defaults to 20, max: 100. ``` -------------------------------- ### Navigate to Backend Directory Source: https://github.com/the-momentum/open-wearables/blob/main/backend/README.md Change the current directory to the backend folder to begin setup. ```bash cd backend ``` -------------------------------- ### Start Local Development Server Source: https://github.com/the-momentum/open-wearables/blob/main/docs/README.md Run the Mintlify development server from the root of your documentation directory. Ensure your `docs.json` file is present. The default port is 3333. ```bash mint dev --port 3333 ``` -------------------------------- ### Dry Run Output Example Source: https://github.com/the-momentum/open-wearables/blob/main/docs/data-migrations/backfill-garmin-sleep-end-datetime.mdx This is an example of the output you will see when running the script with the --dry-run flag. It details the records that would be updated, including their IDs, start and end times, and the calculated difference. ```text ID Start Current End New End Diff (min) ------------------------------------------------------------------------------------------------------------------ 3f2a1b... 2024-11-10 22:14:00 2024-11-11 06:02:00 2024-11-11 06:31:00 +29 Total: 1 record(s) to update. Dry run - no changes made. ``` -------------------------------- ### API Testing with Curl Source: https://github.com/the-momentum/open-wearables/blob/main/backend/AGENTS.md Examples of how to test API endpoints using curl for GET and POST requests. Assumes the application is running on localhost:8000. ```bash # Test endpoints with curl (app runs on localhost:8000) curl -X GET http://localhost:8000/api/v1/endpoint curl -X POST http://localhost:8000/api/v1/endpoint -H "Content-Type: application/json" -d '{"key": "value"}' ``` -------------------------------- ### Timeseries Endpoint Query Parameters Source: https://github.com/the-momentum/open-wearables/blob/main/docs/dev-guides/integration-guide.mdx Example of required query parameters for timeseries data endpoints, including start time, end time, and data types. ```bash ?start_time=2025-01-15T00:00:00Z&end_time=2025-01-15T23:59:59Z&types=heart_rate&types=steps ``` -------------------------------- ### Garmin Backfill Status Response Source: https://github.com/the-momentum/open-wearables/blob/main/docs/providers/garmin-data-pipeline.mdx Example JSON response for the GET /api/v1/providers/garmin/users/{user_id}/backfill/status endpoint, showing the overall backfill status and details for each window. ```json { "overall_status": "in_progress", "current_window": 0, "total_windows": 1, "windows": { "0": {"sleeps": "done", "dailies": "done", "activities": "timed_out", "activityDetails": "done", "hrv": "pending"} }, "summary": { "sleeps": {"done": 1, "timed_out": 0, "failed": 0}, "dailies": {"done": 1, "timed_out": 0, "failed": 0}, "activities": {"done": 0, "timed_out": 1, "failed": 0}, "activityDetails": {"done": 1, "timed_out": 0, "failed": 0}, "hrv": {"done": 0, "timed_out": 0, "failed": 0} }, "in_progress": true, "retry_phase": false, "retry_type": null, "retry_window": null, "attempt_count": 0, "max_attempts": 3, "permanently_failed": false } ``` -------------------------------- ### Configure Backend Environment Variables Source: https://github.com/the-momentum/open-wearables/blob/main/README.md Copy the example environment file to create a new .env file for backend configuration. This file should contain specific settings for the backend application. ```bash cp ./backend/config/.env.example ./backend/config/.env ``` -------------------------------- ### Configure SDK and Host Source: https://github.com/the-momentum/open-wearables/blob/main/docs/sdk/android/troubleshooting.mdx Call `configure()` with the appropriate host URL during application startup after initializing the SDK. ```kotlin // In Application.onCreate() val sdk = OpenWearablesHealthSDK.initialize(this) sdk.configure(host = "https://api.openwearables.io") ``` -------------------------------- ### Complete Health Sync Service Example Source: https://github.com/the-momentum/open-wearables/blob/main/docs/sdk/flutter/integration.mdx This Dart class demonstrates a full integration of the Open Wearables Health SDK, including initialization, user sign-in via a backend, starting background sync, and handling disconnections. ```dart import 'dart:convert'; import 'dart:io'; import 'package:open_wearables_health_sdk/open_wearables_health_sdk.dart'; import 'package:open_wearables_health_sdk/open_wearables_health_sdk_method_channel.dart'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; class HealthSyncService { final String _backendUrl; final String _authToken; HealthSyncService({ required String backendUrl, required String authToken, }) : _backendUrl = backendUrl, _authToken = authToken; /// Initialize the health sync service Future initialize() async { // Set up event listeners MethodChannelOpenWearablesHealthSdk.logStream.listen((message) { print('[HealthSync] $message'); }); MethodChannelOpenWearablesHealthSdk.authErrorStream.listen((error) { print('[HealthSync] Auth error: ${error['statusCode']}'); }); await OpenWearablesHealthSdk.configure( host: 'https://api.openwearables.io', ); // Enable logs in all builds for debugging (default is debug-only) await OpenWearablesHealthSdk.setLogLevel(OWLogLevel.always); } /// Get current status OpenWearablesHealthSdkStatus get status => OpenWearablesHealthSdk.status; bool get isConnected => OpenWearablesHealthSdk.isSignedIn; bool get isSyncing => OpenWearablesHealthSdk.isSyncActive; /// Connect health data for the current user Future connect() async { switch (OpenWearablesHealthSdk.status) { case OpenWearablesHealthSdkStatus.signedIn: if (!OpenWearablesHealthSdk.isSyncActive) { await _startSync(); } return; case OpenWearablesHealthSdkStatus.configured: await _signIn(); await _startSync(); return; case OpenWearablesHealthSdkStatus.notConfigured: throw Exception('SDK not configured. Call initialize() first.'); } } Future _signIn() async { // Call YOUR backend — not the Open Wearables API directly final response = await http.post( Uri.parse('$_backendUrl/api/health/connect'), headers: { 'Authorization': 'Bearer $_authToken', 'Content-Type': 'application/json', }, ); if (response.statusCode != 200) { throw Exception('Failed to get health credentials'); } final data = json.decode(response.body); await OpenWearablesHealthSdk.signIn( userId: data['userId'], accessToken: data['accessToken'], refreshToken: data['refreshToken'], ); } Future _startSync() async { if (Platform.isAndroid) { final providers = await OpenWearablesHealthSdk.getAvailableProviders(); final prefs = await SharedPreferences.getInstance(); final savedName = prefs.getString('health_provider'); // Restore saved provider or pick the best available one AndroidHealthProvider? chosen; if (savedName != null) { chosen = providers.cast().firstWhere( (p) => p?.name == savedName, orElse: () => null, ); } chosen ??= providers.contains(AndroidHealthProvider.healthConnect) ? AndroidHealthProvider.healthConnect : providers.contains(AndroidHealthProvider.samsungHealth) ? AndroidHealthProvider.samsungHealth : null; if (chosen == null) { throw Exception( 'No supported health provider available on this device. ' 'Please install Health Connect or Samsung Health.', ); } await prefs.setString('health_provider', chosen.name); await OpenWearablesHealthSdk.setProvider(chosen); } final authorized = await OpenWearablesHealthSdk.requestAuthorization( types: [ HealthDataType.steps, HealthDataType.heartRate, HealthDataType.sleep, HealthDataType.workout, HealthDataType.activeEnergy, ], ); if (!authorized) { throw Exception('Health permissions not granted'); } await OpenWearablesHealthSdk.startBackgroundSync(syncDaysBack: 90); } /// Disconnect health data Future disconnect() async { await OpenWearablesHealthSdk.stopBackgroundSync(); await OpenWearablesHealthSdk.signOut(); } /// Check for interrupted sync sessions Future checkAndResumeSync() async { final status = await OpenWearablesHealthSdk.getSyncStatus(); if (status['hasResumableSession'] == true) { print('Resuming interrupted sync...'); print('Already sent: ${status['sentCount']} records'); await OpenWearablesHealthSdk.resumeSync(); } } /// Force a full re-sync of all data Future resyncAllData() async { await OpenWearablesHealthSdk.resetAnchors(); await OpenWearablesHealthSdk.syncNow(); } } ``` -------------------------------- ### Configure Frontend Environment Variables Source: https://github.com/the-momentum/open-wearables/blob/main/README.md Copy the example environment file to create a new .env file for frontend configuration. This file should contain specific settings for the frontend application. ```bash cp ./frontend/.env.example ./frontend/.env ``` -------------------------------- ### Install iOS CocoaPods Manually Source: https://github.com/the-momentum/open-wearables/blob/main/docs/sdk/react-native/index.mdx Manually install iOS native dependencies by navigating to the ios directory and running pod install. ```bash cd ios && pod install ``` -------------------------------- ### Install Production Dependencies Source: https://github.com/the-momentum/open-wearables/blob/main/backend/README.md Installs only the production dependencies, excluding development tools. ```bash uv sync --no-dev ``` -------------------------------- ### Run Backend Tests with Make Source: https://github.com/the-momentum/open-wearables/blob/main/contributing/testing.md Use the Make command for a streamlined backend testing experience. Ensure you are in the project root directory. ```bash make test ``` -------------------------------- ### Example Error Response Source: https://github.com/the-momentum/open-wearables/blob/main/docs/api-reference/introduction.mdx An example of a JSON error response structure from the API. ```json { "detail": "Error message describing what went wrong" } ``` -------------------------------- ### Install ngrok via Homebrew Source: https://github.com/the-momentum/open-wearables/blob/main/docs/dev-guides/ngrok-setup.mdx Install ngrok on macOS using the Homebrew package manager. ```bash brew install ngrok ``` -------------------------------- ### Normalized Data Example Source: https://github.com/the-momentum/open-wearables/blob/main/docs/providers/coverage.mdx An example of a data point normalized to consistent units and UTC format. ```json { "timestamp": "2025-01-07T14:30:00Z", "type": "heart_rate", "value": 72, "unit": "bpm" } ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/the-momentum/open-wearables/blob/main/docs/mcp-server/index.mdx Copies the example environment file and prompts to edit it with your specific settings, including the API URL and API key. ```bash cp config/.env.example config/.env ``` ```bash OPEN_WEARABLES_API_URL=http://localhost:8000 OPEN_WEARABLES_API_KEY=ow_your_api_key_here ``` -------------------------------- ### Configure SDK on Launch Source: https://github.com/the-momentum/open-wearables/blob/main/docs/sdk/ios/troubleshooting.mdx Call `configure()` with your API host when your application launches. This ensures the SDK initializes correctly and can automatically restore sync state. ```swift // In AppDelegate or app init sdk.configure(host: "https://api.openwearables.io") ``` -------------------------------- ### Install Code Quality Dependencies Source: https://github.com/the-momentum/open-wearables/blob/main/backend/README.md Installs dependencies specifically for code quality tools like linters and formatters. ```bash uv sync --group code-quality ``` -------------------------------- ### Configure and Sign In SDK Source: https://github.com/the-momentum/open-wearables/blob/main/docs/sdk/react-native/index.mdx Configure the SDK with your backend host and sign in using either a token-based or API key method. ```typescript import OpenWearablesHealthSDK from "open-wearables"; // Configure the SDK with your backend host OpenWearablesHealthSDK.configure("https://your-api-host.com"); // Sign in (token-based) OpenWearablesHealthSDK.signIn(userId, accessToken, refreshToken, null); // Or sign in (API key) OpenWearablesHealthSDK.signIn(userId, null, null, apiKey); ``` -------------------------------- ### Start Services with Docker Compose Source: https://github.com/the-momentum/open-wearables/blob/main/backend/README.md Starts all backend services defined in the Docker Compose file in detached mode. ```bash docker compose up -d ``` -------------------------------- ### Install iOS CocoaPods Dependencies Source: https://github.com/the-momentum/open-wearables/blob/main/docs/sdk/react-native/index.mdx Install iOS native dependencies for bare React Native projects using pod-install. ```bash npx pod-install ``` -------------------------------- ### Garmin Provider Strategy Example Source: https://github.com/the-momentum/open-wearables/blob/main/backend/AGENTS.md Example implementation of a provider strategy for Garmin, defining its name and API base URL. ```python class GarminStrategy(BaseProviderStrategy): @property def name(self) -> str: return "garmin" @property def api_base_url(self) -> str: return "https://apis.garmin.com" ``` -------------------------------- ### Project Structure Overview Source: https://github.com/the-momentum/open-wearables/blob/main/frontend/README.md Illustrates the directory structure of the frontend application, including components, routes, libraries, and hooks. ```bash src/ ├── components/ │ ├── ui/ # shadcn/ui components │ ├── layout/ # Layout components (Sidebar, etc.) │ └── features/ # Feature-specific components ├── routes/ │ ├── __root.tsx # Root layout with providers │ ├── index.tsx # Home (redirects to /login) │ ├── login.tsx # Login page │ └── _authenticated/ # Protected routes │ ├── dashboard.tsx │ └── users.tsx ├── lib/ │ └── utils.ts # Utility functions ├── hooks/ # Custom React hooks └── styles.css # Global styles and design tokens ``` -------------------------------- ### Request Health Authorization and Start Sync Source: https://github.com/the-momentum/open-wearables/blob/main/docs/sdk/react-native/index.mdx Request authorization for specific health data types and start background synchronization. ```typescript // Request HealthKit authorization await OpenWearablesHealthSDK.requestAuthorization(["steps", "heartRate", "sleep"]); // Start background sync await OpenWearablesHealthSDK.startBackgroundSync(); // Sync immediately await OpenWearablesHealthSDK.syncNow(); ``` -------------------------------- ### Seed Sample Data Source: https://github.com/the-momentum/open-wearables/blob/main/README.md Run the 'seed' make command to populate the database with test users and sample activity data. This is an optional step for testing purposes. ```bash make seed ``` -------------------------------- ### Sync Status Event Schema Example Source: https://github.com/the-momentum/open-wearables/blob/main/docs/api-reference/guides/sync-status-stream.mdx An example of a single sync status event object, detailing the outcome of a synchronization process. ```json [ { "event_id": "evt_01HZ...", "run_id": "pull_garmin_user42_1730000000", "user_id": "user42", "provider": "garmin", "source": "pull", "stage": "completed", "status": "success", "message": null, "progress": 1.0, "items_processed": 42, "items_total": 42, "error": null, "metadata": {}, "started_at": "2024-10-27T10:15:00Z", "ended_at": "2024-10-27T10:16:45Z", "timestamp": "2024-10-27T10:16:45Z" } ] ``` -------------------------------- ### Initialize SDK Source: https://github.com/the-momentum/open-wearables/blob/main/docs/sdk/flutter/example-app.mdx Configure the Open Wearables SDK with the host URL. This is the first step before using any other SDK functionalities. ```dart await OpenWearablesHealthSdk.configure( host: hostUrl, ); ``` -------------------------------- ### Copy Environment Variables Source: https://github.com/the-momentum/open-wearables/blob/main/frontend/README.md Copies the example environment file to `.env`. This file should contain backend API URL and other sensitive configurations. ```bash cp .env.example .env ``` -------------------------------- ### Configure Open Wearables SDK (TypeScript) Source: https://github.com/the-momentum/open-wearables/blob/main/docs/sdk/react-native/integration.mdx Configure the Open Wearables SDK once at app startup using this TypeScript example. Provide the required API host URL during configuration. ```typescript import OpenWearablesHealthSDK from "open-wearables"; export default function App() { useEffect(() => { OpenWearablesHealthSDK.configure("https://your-api-host.com"); ... }, []); } ``` -------------------------------- ### SQLAlchemy Model Structure Example Source: https://github.com/the-momentum/open-wearables/blob/main/backend/AGENTS.md Example of defining a User and Workout model using SQLAlchemy, including custom types for constraints and relationships. ```python from sqlalchemy.orm import Mapped from app.database import BaseDbModel from app.mappings import PrimaryKey, Unique, datetime_tz, email, OneToMany, ManyToOne, FKUser class User(BaseDbModel): id: Mapped[PrimaryKey[UUID]] email: Mapped[Unique[email]] created_at: Mapped[datetime_tz] workouts: Mapped[OneToMany["Workout"]] class Workout(BaseDbModel): user_id: Mapped[FKUser] user: Mapped[ManyToOne["User"]] ``` -------------------------------- ### Offset Pagination Example Source: https://github.com/the-momentum/open-wearables/blob/main/docs/api-reference/introduction.mdx Demonstrates how to use offset pagination for requests, specifying page number and items per page. ```http GET /api/v1/users?page=2&limit=50 ``` -------------------------------- ### Start Background Sync Source: https://github.com/the-momentum/open-wearables/blob/main/docs/sdk/ios/integration.mdx Enable background synchronization to continuously receive health data. The completion handler indicates if the sync was successfully started. ```swift OpenWearablesHealthSDK.shared.startBackgroundSync { started in print("Background sync started: \(started)") } ``` -------------------------------- ### Initialize and Configure SDK Source: https://github.com/the-momentum/open-wearables/blob/main/docs/sdk/android/integration.mdx Initialize the Open Wearables SDK once in your Application class and configure it with your backend host. Optional listeners for logging and auth errors can also be set. ```kotlin import com.openwearables.health.sdk.OpenWearablesHealthSDK class MyApplication : Application() { override fun onCreate() { super.onCreate() // Initialize SDK (once per app lifecycle) val sdk = OpenWearablesHealthSDK.initialize(this) // Optional: Set up logging sdk.logListener = { message -> Log.d("HealthSDK", message) } // Optional: Set log level (default is OWLogLevel.DEBUG — logs only in debuggable builds) sdk.logLevel = OWLogLevel.ALWAYS // Optional: Handle auth errors (e.g. token expired) sdk.authErrorListener = { error -> Log.e("HealthSDK", "Auth error: $error") } // Configure with your backend host sdk.configure(host = "https://api.openwearables.io") } } ``` -------------------------------- ### Common Development Commands Source: https://github.com/the-momentum/open-wearables/blob/main/frontend/AGENTS.md Lists essential pnpm commands for development, including starting the dev server, building for production, linting, formatting, and running tests. It's recommended to run lint and format commands after making changes. ```bash pnpm run dev # Start dev server (port 3000) pnpm run build # Production build pnpm run lint # Run oxlint pnpm run lint:fix # Fix linting issues pnpm run format # Format with Prettier pnpm run format:check # Check formatting pnpm run test # Run tests ``` -------------------------------- ### Conventional Commits PR Title Examples Source: https://github.com/the-momentum/open-wearables/blob/main/contributing/pull-requests.md Provides examples of pull request titles adhering to the Conventional Commits format, which is automatically validated by the CI workflow. ```text feat: add user profile endpoint ``` ```text fix(auth): resolve token refresh issue ``` ```text docs: update API documentation ``` ```text ci: add PR title validation to workflow ``` ```text refactor(backend): simplify authentication logic ```