This document provides a detailed technical overview of MirrorHR's architecture, designed to help developers understand the system structure, data flow, and key components.
- High-Level Architecture
- Core Components
- Data Flow
- State Management
- Threading Model
- Storage Architecture
- Watch Connectivity
- Real-time Monitoring Engine
- Key Algorithms
- External Integrations
- Performance Considerations
- Security Architecture
MirrorHR follows a modular architecture with clear separation of concerns:
┌─────────────────────────────────────────────────────────────┐
│ Application Layer │
│ ┌─────────────┐ ┌──────────────┐ ┌──────────────────────┐ │
│ │ iOS UI │ │ Watch UI │ │ Widget Extensions │ │
│ │ (SwiftUI) │ │ (SwiftUI) │ │ (SwiftUI) │ │
│ └─────────────┘ └──────────────┘ └──────────────────────┘ │
└────────────┬─────────────────┬──────────────────┬───────────┘
│ │ │
┌────────────▼─────────────────▼──────────────────▼───────────┐
│ Domain Layer │
│ ┌─────────────┐ ┌──────────────┐ ┌──────────────────────┐ │
│ │ MainClasses │ │ Profile Mgmt │ │ Session Coordinator │ │
│ └─────────────┘ └──────────────┘ └──────────────────────┘ │
│ ┌─────────────┐ ┌──────────────┐ ┌──────────────────────┐ │
│ │ Symptoms │ │ Therapy │ │ Analytics Engine │ │
│ │ Manager │ │ Manager │ │ │ │
│ └─────────────┘ └──────────────┘ └──────────────────────┘ │
└────────────┬─────────────────┬──────────────────┬───────────┘
│ │ │
┌────────────▼─────────────────▼──────────────────▼───────────┐
│ Data Layer │
│ ┌─────────────┐ ┌──────────────┐ ┌──────────────────────┐ │
│ │ Core Data │ │ HealthKit │ │ Cloud Sync │ │
│ │ Storage │ │ Integration │ │ │ │
│ └─────────────┘ └──────────────┘ └──────────────────────┘ │
│ ┌─────────────┐ ┌──────────────┐ ┌──────────────────────┐ │
│ │ Local Files │ │ Backup Mgr │ │ Telemetry │ │
│ └─────────────┘ └──────────────┘ └──────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
The architecture follows a modified MVVM pattern with Combine for reactive data flows.
The core framework that contains most of the domain logic and coordination.
-
MirrorHRMainClass: Central coordinator for the application.
- Manages sessions, state transitions, and component communication
- Initializes and configures subsystems
- Coordinates background/foreground transitions
-
KISSFlowManager: Real-time heart rate analysis engine.
- Processes incoming BPM data
- Applies pattern recognition algorithms
- Identifies potential seizure patterns
- Issues alerts based on configurable thresholds
-
SymptomsManager: Tracks and analyzes symptom records.
- Stores symptom history
- Integrates with video diary features
- Provides correlation with other health data
- Generates symptom reports and insights
-
TherapyManager: Medication and treatment tracking.
- Manages medication schedules
- Issues reminders
- Tracks adherence
- Correlates with symptoms
- SharedPkg: Common models, enums, and protocols.
- RoberdanToolbox: Utilities and debugging tools.
- PermissionsManager: Handles iOS permissions requests.
- Streaming: Real-time data streaming between devices.
- MirrorHRTelemetryPackage: Anonymized usage analytics.
MirrorHR uses a publisher/subscriber pattern for most data flows, implemented with Combine:
-
Heart Rate Monitoring Flow:
Apple Watch → WatchKit Extension → Watch Connectivity → iPhone App → KISSFlowManager → Analysis → Event Publishers → UI Updates + Alert System + Data Storage -
Symptom Recording Flow:
User Input → SymptomsManager → Data Validation → Storage → Analytics → UI Updates -
Video Diary Flow:
Video Recording → Speech Recognition → NLP Processing → Symptom Extraction → User Validation → Symptom Storage
The application uses a state machine approach for core components:
-
Session States:
idle: No active monitoringstarting: Initializing sensors and connectionsmonitoring: Active heart rate monitoringpaused: Temporarily paused monitoringending: Gracefully shutting down monitoringerror: Error state with recovery options
-
Data Source States:
appleWatch: Using Apple Watch as primary BPM sourcehealthKit: Using HealthKit historical datasimulatedData: Using test data (development only)remoteStreaming: Receiving data from another device
MirrorHR employs a disciplined threading model:
- Main Thread: UI updates and user interaction
- Background Queues:
analysisQueue: Heart rate pattern analysis (high priority)storageQueue: Data persistence operations (utility priority)processingQueue: Video and audio processing (background priority)
Critical sections use appropriate synchronization mechanisms:
os_unfair_lockfor lightweight locking- Dispatch semaphores for resource serialization
- Serial queues for ordered operations
The application uses a multi-context Core Data architecture:
- Main Context: UI-bound, read-only operations
- Background Context: Write operations
- Private Contexts: Temporary operations (import/export)
The schema includes these main entities:
SymptomLog: Records of symptoms and eventsHeartRateSession: Monitoring session metadataHeartRateSample: Individual heart rate measurementsMedication: Medication recordsMedicationDose: Individual medication doses
Certain data types use file-based storage:
- Video diary recordings
- Audio logs
- Export files
- Backup archives
Communication between the iPhone and Apple Watch uses a multi-channel approach:
- Application Context: Current session state
- User Info: Configuration updates
- File Transfers: Larger datasets (infrequent)
- Interactive Messages: Real-time data (heart rate updates)
- Complications: Watch face updates
The system handles connectivity transitions and reconnection automatically.
The heart rate monitoring system uses a multi-stage pipeline:
-
Data Acquisition:
- Watch workout session for real-time heart rate
- HealthKit historical data
- Background delivery capabilities
-
Preprocessing:
- Noise filtering
- Outlier detection
- Signal quality assessment
-
Pattern Analysis:
- Moving averages (short and long-term)
- Rate of change detection
- Pattern matching against known seizure signatures
- Adaptive thresholds based on user baseline
-
Alert Generation:
- Multi-level alerts (info, warning, critical)
- Caregiver notifications
- Local device alerts
The heart rate analysis uses several algorithms:
-
Baseline Establishment:
func calculateBaseline(samples: [HeartRateSample], period: TimeInterval) -> Double { // Filter samples within baseline period let baselineSamples = samples.filter { $0.timestamp > Date().addingTimeInterval(-period) } // Calculate the baseline let values = baselineSamples.map { $0.value } return values.reduce(0, +) / Double(values.count) }
-
Seizure Pattern Detection:
func detectPotentialSeizure(samples: [HeartRateSample], baseline: Double, thresholds: ThresholdConfiguration) -> SeizureDetectionResult { // Calculate rate of change over time let rateOfChangeValues = calculateRateOfChange(samples) // Check for rapid increase let hasRapidIncrease = rateOfChangeValues.contains { $0 > thresholds.rapidIncreaseThreshold } // Check for elevated heart rate let hasElevatedHeartRate = samples.suffix(3).allSatisfy { $0.value > baseline * thresholds.elevationMultiplier } // Check for sustained elevation let hasSustainedElevation = calculateSustainedElevation( samples: samples, baseline: baseline, threshold: thresholds.sustainedElevationThreshold, duration: thresholds.sustainedElevationDuration ) // Combine signals into a result return SeizureDetectionResult( hasRapidIncrease: hasRapidIncrease, hasElevatedHeartRate: hasElevatedHeartRate, hasSustainedElevation: hasSustainedElevation, confidenceScore: calculateConfidenceScore(...) ) }
The video diary analysis uses NLP techniques:
- Symptom Extraction:
func extractSymptoms(from transcript: String) -> [Symptom] { // Tokenize and normalize text let tokens = tokenize(transcript) // Match against symptom dictionary with context let matches = findSymptomMatches(in: tokens) // Resolve ambiguities and conflicts return resolveSymptoms(matches) }
MirrorHR integrates with HealthKit for:
- Reading heart rate data
- Accessing sleep analysis
- Exercise and activity information
- Height/weight for medication calculations
Used for secure remote notifications:
- Caregiver alerts
- Remote monitoring status updates
- Data synchronization triggers
Used for enhanced natural language processing:
- Symptom extraction from video diaries
- Context-aware analysis of user descriptions
- Sentiment analysis
-
Battery Optimization:
- Adaptive sampling rates based on context
- Background processing limitations
- Watch power management during monitoring
-
Memory Management:
- Streaming data processing to avoid memory pressure
- Cache management for historical data
- Video processing optimizations
-
Responsiveness:
- Critical paths optimized for minimal latency
- Alert generation prioritized over other operations
- Background tasks throttled during user interaction
-
Data Protection:
- Health data stored with
NSFileProtectionComplete - Sensitive fields use secure coding
- HTTPS for all network communications
- Health data stored with
-
Authentication:
- Biometric authentication for sensitive operations
- Secure caregiver pairing mechanism
- Revocation capabilities for shared access
-
Privacy Controls:
- Granular permission management
- Data minimization principles
- Anonymized analytics
-
Configuration Security:
- Environment variables for secrets
- Runtime credential verification
- Secure storage for API keys and tokens
For detailed implementation specifics, refer to the source code documentation and inline comments. This architecture may evolve over time as new features and optimizations are implemented.