Files
gh-asleep-ai-sleeptrack-ski…/skills/sleeptrack-foundation/SKILL.md
2025-11-29 17:58:23 +08:00

14 KiB
Raw Blame History

name, description
name description
sleeptrack-foundation This skill provides foundational knowledge about Asleep sleep tracking platform, covering core concepts, authentication, data structures, error handling, and platform-agnostic best practices. Use this skill when developers ask about Asleep fundamentals, API concepts, error codes, sleep data structures, or need to understand how the platform works before implementing platform-specific integration. This skill serves as prerequisite knowledge for sleeptrack-ios, sleeptrack-android, and sleeptrack-be skills.

Sleeptrack Foundation

Overview

This skill provides essential foundational knowledge for integrating the Asleep sleep tracking platform. It covers core concepts, authentication patterns, data structures, error handling, and platform-agnostic best practices that apply across all implementation approaches (iOS, Android, and backend API).

Use this skill when developers need to understand:

  • What Asleep is and how sleep tracking works
  • API authentication and key management
  • Sleep session concepts and lifecycle
  • Data structures (Sessions, Reports, Statistics)
  • Error codes and troubleshooting
  • Platform-agnostic integration patterns

Core Concepts

What is Asleep?

Asleep is a sleep tracking platform that analyzes sleep using audio-based monitoring through device microphones. The platform provides:

  • Real-time sleep stage analysis: Wake, Light, Deep, REM detection
  • Comprehensive sleep metrics: Efficiency, latency, total sleep time, wake after sleep onset
  • Snoring detection and analysis: Snoring stages and patterns
  • Multi-platform SDKs: Native iOS and Android SDKs plus REST API
  • Dashboard analytics: Web-based analytics and user management

User Management

Each application user must be registered with Asleep before tracking sleep.

Key Points:

  • User ID is managed by the host application (not generated by Asleep)
  • One user can have multiple sleep sessions
  • User data persists across sessions for trend analysis
  • Users can be created, retrieved, updated, and deleted via API

Example User ID Schemes:

- UUID: "550e8400-e29b-41d4-a716-446655440000"
- Email-based: "user@example.com"
- App-specific: "app_user_12345"

Sleep Sessions

A session represents one complete sleep tracking period from start to stop.

Session Lifecycle States:

  1. IDLE: No tracking in progress
  2. INITIALIZING: SDK preparing resources
  3. INITIALIZED: Ready to start tracking
  4. TRACKING_STARTED: Active tracking in progress
  5. TRACKING_STOPPING: Ending session and uploading data

Session Requirements:

  • Minimum tracking duration: 5 minutes for valid session
  • Microphone access required throughout tracking
  • Network connectivity needed for data upload
  • One active session per user at a time

Real-time Data Access:

  • Available after sequence 10
  • Check every 10 sequences thereafter
  • Provides preliminary sleep stage data during tracking

Sleep Reports

Reports contain comprehensive analysis of completed sleep sessions.

Report Structure:

Report
├── Session Metadata
│   ├── session_id
│   ├── user_id
│   ├── start_time
│   └── end_time
├── Sleep Stages Timeline
│   ├── Wake periods
│   ├── Light sleep periods
│   ├── Deep sleep periods
│   └── REM sleep periods
├── Sleep Statistics
│   ├── Total sleep time
│   ├── Time in bed
│   ├── Sleep efficiency (%)
│   ├── Sleep latency (time to fall asleep)
│   ├── Wake after sleep onset (WASO)
│   ├── Sleep stage durations
│   └── Sleep stage ratios
└── Snoring Analysis
    ├── Snoring detected (yes/no)
    ├── Snoring stages timeline
    └── Snoring statistics

Key Metrics Explained:

  • Sleep Efficiency: (Total sleep time / Time in bed) × 100%

    • Good: > 85%
    • Fair: 75-85%
    • Poor: < 75%
  • Sleep Latency: Time from lying down to falling asleep

    • Normal: 10-20 minutes
    • Fast: < 10 minutes (may indicate sleep deprivation)
    • Slow: > 20 minutes (may indicate insomnia)
  • WASO: Total wake time after initial sleep onset

    • Lower is better (indicates fewer disruptions)

Statistics

Aggregated metrics across multiple sessions for trend analysis.

Available Statistics:

  • Average sleep duration over time range
  • Average sleep efficiency
  • Sleep stage distribution averages
  • Trends and patterns

Statistics API:

GET /users/{user_id}/statistics/average?from={date}&to={date}

Authentication

API Key Management

All Asleep integrations require an API key for authentication.

Obtaining an API Key:

  1. Sign up at https://dashboard.asleep.ai
  2. Navigate to API key generation section
  3. Create API key for the application
  4. Store securely (never commit to version control)

Using API Keys:

For SDK Integration (iOS/Android):

// Android
AsleepConfig.init(
    apiKey = "your_api_key_here",
    userId = "user_unique_id",
    ...
)
// iOS
AsleepConfig.init(
    apiKey: "your_api_key_here",
    userId: "user_unique_id",
    ...
)

For REST API Integration:

GET /sessions/{session_id}
X-API-Key: your_api_key_here

Security Best Practices:

  • Store API keys in environment variables or secure storage
  • Never hardcode keys in source code
  • Use different keys for development and production
  • Rotate keys periodically
  • Monitor usage in Dashboard to detect unauthorized access
  • Revoke compromised keys immediately

Error Handling

Understanding error codes is critical for robust integration.

Error Categories

Critical Errors (must stop tracking): These errors indicate conditions that prevent continued tracking and require user intervention or code fixes.

Warning Errors (can continue tracking): These are transient issues that the SDK handles automatically while tracking continues.

Error Code Reference

Critical Errors

ERR_MIC_PERMISSION

  • Cause: App lacks microphone access permission
  • Action: Request microphone permission from user
  • Platform Notes:
    • Android: Check RECORD_AUDIO permission
    • iOS: Check NSMicrophoneUsageDescription and authorization status

ERR_AUDIO

  • Cause: Microphone unavailable or in use by another app
  • Action:
    • Close conflicting apps using microphone
    • Check microphone hardware functionality
    • Verify no audio conflicts in device settings

ERR_INVALID_URL

  • Cause: Malformed API endpoint URL in configuration
  • Action: Verify AsleepConfig URL format
  • Example Fix: Ensure base URL is valid HTTPS endpoint

ERR_COMMON_EXPIRED

  • Cause: API rate limit exceeded or subscription plan expired
  • Action:
    • Check Dashboard for plan status
    • Review API usage patterns
    • Upgrade plan if needed
    • Implement rate limiting in application

ERR_UPLOAD_FORBIDDEN

  • Cause: Multiple simultaneous tracking attempts with same user_id
  • Action:
    • Ensure only one device tracks per user at a time
    • Check for orphaned sessions
    • Implement proper session cleanup

ERR_UPLOAD_NOT_FOUND / ERR_CLOSE_NOT_FOUND

  • Cause: Attempting to interact with non-existent or already-ended session
  • Action:
    • Verify session exists before operations
    • Handle session expiration properly
    • Implement session state management

Warning Errors

ERR_AUDIO_SILENCED

  • Cause: Audio temporarily unavailable but tracking continues
  • Impact: Minimal, SDK handles gracefully
  • Action: Log for monitoring, tracking continues

ERR_AUDIO_UNSILENCED

  • Cause: Audio restored after silence period
  • Impact: Tracking resumes normally
  • Action: Log for monitoring

ERR_UPLOAD_FAILED

  • Cause: Network connectivity issue during data upload
  • Impact: SDK will retry automatically
  • Action:
    • Verify network connectivity
    • Check for firewall/proxy issues
    • Monitor retry success

Error Handling Patterns

Distinguish Error Severity:

// Android example
when (errorCode) {
    in criticalErrors -> {
        // Stop tracking, notify user
        stopTracking()
        showErrorDialog(errorCode)
    }
    in warningErrors -> {
        // Log and continue
        logWarning(errorCode)
    }
}

Provide User-Friendly Messages:

fun getUserFriendlyMessage(errorCode: AsleepErrorCode): String {
    return when (errorCode) {
        ERR_MIC_PERMISSION -> "Please allow microphone access to track sleep"
        ERR_AUDIO -> "Another app is using the microphone. Please close it and try again"
        ERR_COMMON_EXPIRED -> "Your subscription has expired. Please renew to continue tracking"
        // ... more mappings
    }
}

Implement Retry Logic:

// For network-related errors
suspend fun uploadWithRetry(maxRetries: Int = 3) {
    repeat(maxRetries) { attempt ->
        try {
            upload()
            return
        } catch (e: NetworkException) {
            if (attempt == maxRetries - 1) throw e
            delay(2.0.pow(attempt) * 1000) // Exponential backoff
        }
    }
}

Data Plan Considerations

Asleep operates on different data plans that affect API usage.

Plan Limits:

  • Request rate limits
  • Total sessions per month
  • Data retention periods
  • Feature availability

Monitoring Usage:

  • Check Dashboard regularly
  • Implement usage tracking in application
  • Set up alerts for approaching limits
  • Plan capacity for user growth

Integration Workflows

Typical Integration Flow

  1. Setup Phase:

    • Obtain API key from Dashboard
    • Install SDK (iOS/Android) or configure REST API client
    • Configure authentication
  2. User Registration:

    • Create user in Asleep system
    • Store user_id mapping in application
  3. Sleep Tracking Session:

    • Request necessary permissions
    • Initialize SDK with user credentials
    • Start tracking session
    • Monitor session state
    • Handle real-time data (optional)
    • Stop tracking session
  4. Report Generation:

    • Wait for report processing (automatic)
    • Fetch completed report
    • Display sleep analysis to user
  5. Statistics & Trends:

    • Query historical sessions
    • Calculate aggregated statistics
    • Display trends over time

Common Integration Scenarios

Scenario 1: First-Time User Setup

User downloads app
  → Request microphone permission
  → Create Asleep user (POST /users)
  → Initialize SDK with API key + user_id
  → Guide user through first tracking session

Scenario 2: Returning User

User opens app
  → Load user_id from local storage
  → Initialize SDK with credentials
  → Check for existing running session (reconnect if found)
  → Display previous sleep reports

Scenario 3: Background Tracking

User starts tracking before sleep
  → Start foreground service (Android) / background mode (iOS)
  → Maintain microphone access
  → Handle app lifecycle events
  → Continue tracking through sleep
  → Stop tracking in morning
  → Process and display report

Platform Selection Guide

Choose the appropriate integration approach based on application type:

Use iOS SDK (sleeptrack-ios):

  • Native iOS application
  • Need deep iOS integration (Siri, HealthKit, etc.)
  • Require iOS-specific UI patterns
  • Swift/SwiftUI development

Use Android SDK (sleeptrack-android):

  • Native Android application
  • Need Android-specific features (foreground service, etc.)
  • Require Android UI patterns
  • Kotlin/Jetpack Compose development

Use REST API (sleeptrack-be):

  • Backend/server-side integration
  • Multi-platform web application
  • Data aggregation and analytics
  • Webhook-based event processing
  • Cross-platform mobile framework (React Native, Flutter) with custom bridge

Resources

Official Documentation

Key Documentation Pages

Platform-Specific Documentation

Android:

iOS:

Reference Files

This skill includes detailed API reference documentation:

  • references/asleep_api_reference.md: Comprehensive API endpoint reference, data structures, and integration patterns

To load this reference for detailed API information:

Read references/asleep_api_reference.md

Best Practices Summary

Security

  • Never expose API keys in client code
  • Implement secure storage for credentials
  • Use HTTPS for all API communications
  • Validate user permissions before operations

Performance

  • Cache reports when appropriate
  • Batch API requests to respect rate limits
  • Implement efficient session state management
  • Monitor real-time data access patterns

User Experience

  • Provide clear permission rationales
  • Show friendly error messages
  • Display progress during tracking
  • Handle app lifecycle gracefully

Reliability

  • Implement comprehensive error handling
  • Add retry logic for transient failures
  • Log errors for debugging
  • Test edge cases (interruptions, low battery, etc.)

Data Management

  • Clean up old sessions appropriately
  • Respect user privacy and data retention
  • Implement proper user deletion flows
  • Backup critical session data

Next Steps

After understanding these foundational concepts, proceed to platform-specific skills:

  • iOS Development: Use sleeptrack-ios skill
  • Android Development: Use sleeptrack-android skill
  • Backend API Integration: Use sleeptrack-be skill

Each platform-specific skill builds on this foundation with implementation details, code examples, and platform-specific patterns.