Skip to content

Architecture

github-actions[bot] edited this page Nov 29, 2026 · 66 revisions

Purpose

OpenWatch is a phone app that owns the devices, a watch app, and the link between the two. This document is the map of the phone app and the rules that hold across it. The device layer came from OpenVitals unchanged where it could; the sections below are its sections, with the OpenWatch seams noted.

Current Snapshot

  • App namespace: tech.mmarca.openwatch
  • Build logic: build-logic/, an included build with the convention plugins every module applies (openwatch.android.application, openwatch.android.library, openwatch.jvm.library, and openwatch.robolectric for a library whose tests run on Robolectric): SDK levels, Java 17, signing from the environment, the debug, release and nightly build types, lint and dependency locking. A module's own file holds only what is its own (version codes, the ci type, the diagnostics flag). A change there must leave the release APKs byte-identical; compare their hashes before and after.
  • Project shape: twenty-eight Gradle modules. The phone app is :app, the shell (Phone modules): the application, the activities, the navigation and the Hilt root. The screens are the :feature:* modules; :core:model and :core:fit hold the pure code the app depends on (below); :core:devices-api the device contracts (devices/core); :core:health-api how the devices talk to Health Connect (rule 3); :core:health Health Connect as the app reaches it, which implements those contracts (the gateway, the record sink, the activity writes, the sync gate, the data catalog; rule 3); :core:ui what every screen shares (the theme, the shared components, core/presentation's formatters and ScreenError, core/permissions); :core:data what the phone keeps (the Room database, the registry, the per-device state, the preferences; below); :devices:core the platform half every device family shares (below); :devices:garmin, :devices:wearos, :devices:xiaomi and :devices:ble-standard are the families' platform halves, device modules that bind themselves (devices/garmin, devices/wearos, devices/xiaomi, devices/blestandard); :devices:garmin:protocol, :devices:xiaomi:protocol and :devices:ble-standard:protocol are the Garmin protocol, the S400 codec and the standard profiles' bytes, pure Kotlin (devices/garmin, devices/xiaomi, devices/blestandard); :link-host is the OpenLink host (below); :wear is the Wear OS watch app with its own CI gate; :wearlink is the pure-Kotlin link both apps depend on. Package names are the same across :app and the modules under core/, devices/ and feature/. The health calculations, shared with OpenVitals, come from the health-calculations/ submodule, a composite build (below).
  • The watch app's pure core is :wear:recording-core, plain Kotlin in wear/recording-core/ with the watch app's package names; only :wear depends on it (below).
  • Dependency wiring: Hilt in :app, rooted at OpenWatchApp; modules are di/AppModule.kt, di/RepositoryModule.kt, di/DevicesModule.kt and di/LinkModule.kt, each device module's own (GarminModule, WearOsModule, XiaomiScaleModule, BleStandardModule), and the screen modules' (a family's screens bind their contributions, GarminFeatureModule, WearOsFeatureModule, XiaomiScaleFeatureModule; :feature:device declares the maps), which the graph installs from the modules' classes (Hilt wiring).
  • UI stack: Jetpack Compose + Material 3 + Navigation Compose + ViewModel + coroutines.
  • Health data backend: the Health Connect AndroidX client, behind HealthConnectGateway.
  • Room is at version 2, with five tables: devices (the registry) and device_state (what an integration keeps per device, gone with its device), and garmin_wellness_samples, garmin_sleep_minutes, scale_weigh_ins, each keyed by the device's id salt as well (OpenWatchMigrations.MIGRATION_1_2; a family's first device has the empty salt, so the rows from before belong to it).

Top-Level Package Map

Package Role
devices/ Nothing in the app: the device layer is the modules under devices/ (below). The app's tests keep the checks that need two families at once (DeviceIntegrationParityTest, NotificationCategoryParityTest, the classifiers').
features/home The device list and the way to the other screens.
features/device, features/watches, features/scales The device screens, as in OpenVitals, and Home's "Other devices" section (features/device/DevicesSection): the devices of every family that pairs through the app's own flow (DevicePairing), and that flow, which scans for the services the families name, offers each device one of them claims and no watch family does, and pairs it through its family; it names no family. Every paired device opens on one route, DeviceDetail(deviceId); features/device picks its screen once from the registry: its family's own screen when the family brings one (the scale), the device screen otherwise. A device's screen is the part every device has (WatchDeviceScreen: the header, the schedule, removal) and its family's panel, features/watches/garmin or features/watches/wearos, each with its own ViewModel, or the generic panel for a family with none. The generic screens name no family: a family's screens plug in through the contributions of features/device/DeviceContributions.kt, bound under the family's persisted name by the family's own Hilt module in the screens (GarminFeatureModule, WearOsFeatureModule, XiaomiScaleFeatureModule): a DeviceScreenContribution draws a whole destination, a DevicePanelContribution a panel, and a WatchOnboarding is a watch family's pairing in Home's add-a-watch flow, with the checklist it shows. A family's panel opens its own screens through DeviceScreenHost.navigate, with routes it declares.
features/healthconnect, features/settings Health Connect setup, the sync switch, the body profile, the units, notification access.
features/connectedapps The apps that use OpenWatch over OpenLink: allow, block, per-capability switches, forget; a warning for a first-party name under an unknown signer; overlays hidden while it shows.
link/ The OpenLink host, the module :link-host: the exported service, the device list and profile as OpenLink shows them (each device with its last sync's result and time, DeviceSyncUiState.attempts, which DeviceSyncController keeps for every run), what was written to Health Connect (onDataWritten: the record types and the time they cover, never a value, from HealthConnectWrites, which the gateway tells of each write that went through; once per burst, after five quiet seconds), the shared settings (the daily goals, in LinkSettingsStore, the newer value per key winning; it is also devices/core's SharedGoals, which a Wear OS watch's sync sends to the watch and its card sets, and a Garmin watch's hydration widget shows, so no device family sees an OpenLink type), recording sessions and live readings for another app (a session in RECORD mode, a workout the device records itself, is answered FAILED, unsupported, to its owner until a watch can record one; LinkDevices offers no recordingFeatures meanwhile).
healthconnect/ HealthConnectGateway, ActivityRecordWriter, the sync gate, intents and availability, and the data catalog; in :core:health, with data/repository/ImportedRecordRepository and ActivityWriteRepository.
activityimport/ FIT activity files into ActivityWriteRequests; in :devices:core.
data/local, data/repository Room, the repositories and the SharedPreferences stores, in :core:data; the app keeps what joins a family's own contract to them (the Garmin and scale tables over their DAOs, the Garmin and Wear OS preferences over OpenWatchPreferences). BleDeviceRepository is the device registry: the devices table read once into memory, every read answered from there (the first waits for the load) and every change written behind it in order on the registry's own thread; the JSON in ble_sensor_devices it replaced is imported once and left in place. It gives a family's first device the empty id salt and each later one its own. A row of a family this version does not bind (RegisteredFamilies), from a newer build, stays in the table unread, never taken for another family's device; a kind is any name a family gave.
comaps/ The CoMaps guidance feed a Garmin watch relays; in :devices:core (below).
sensors/ble/ In :devices:core: the BLE discovery scan the add-a-device flows use, for the services they name, with every advertised service of a device kept for the families that pair by a standard profile.
core/ ScreenError, UnitFormatter, the OS permissions service, RuntimePermissions (which grant a Bluetooth scan or connection takes on each Android release), all four in :core:ui; the dispatcher provider (:core:model's) and the foreground gate (:devices:core's), which the app and the device modules share; core/security, the Keystore key the app seals its secrets under.
navigation/, ui/ (ui/ in :core:ui) The routes, @Serializable types in navigation/Routes.kt whose properties are the arguments, read back in each ViewModel with toRoute; from 840 dp of width (a tablet, an unfolded phone, a large phone on its side) AppNavigation keeps Home's list beside what it opens, one device or page at a time; the app bar state, the theme and the shared components every screen uses instead of its own copy: SwitchRow / SwitchCard (the whole row is one toggle, so TalkBack reads the title with the state), SectionHeader (a heading), DeviceListRow, RenameDialog, ConfirmRemoveDialog, ScreenErrorContent, and rememberRuntimePermissionRequester, the one way a screen asks for runtime grants (Health Connect's go through rememberHealthConnectPermissionLauncher), and ObscuredTouchGuard, the activity's filter of touches made through another app's window, which Connected apps turns on. What two feature screens share, and only that, sits in :core:ui in the package it came from: the notification-access disclosure and WatchNotificationsGateway (features/watches), a Health Connect permission's label (features/healthconnect), the relative time (features/connectedapps). A screen never names the app: what only the app knows comes in through the navigation's callbacks (the health data activity) or Hilt (@AppVersionName).

The OpenWatch Seams

Where the copied code met an OpenVitals class that did not come along, it meets this instead:

OpenVitals OpenWatch
HealthConnectManager, HealthRepository HealthConnectGateway: the granted set (cached thirty seconds, dropped on a return to the foreground), readsOtherAppsDataNow, inserts and deletes by client id, this app's own ids and versions over a span (readOwnClientRecordVersions, origin-filtered, so it needs no read grant), a page reader, the exercise session ranges, the latest weight and height. Reads throw on failure.
AppleHealthImportRepository ImportedRecordRepository, the same three methods, behind the HealthRecordStore interface the write helpers and their tests' fake use.
BodyRepository.resolveBodyProfile BodyProfileProvider: the declared profile with Health Connect's weight and height on top.
PreferencesRepository OpenWatchPreferences: the sync switch, the body profile, the fallback exercise type, setup done, OpenWatch's own units (which give way to a connected app's through core/model's SharedUnits).
ActivityRepository (reads and writes) ActivityWriteRepository over ActivityRecordWriter: the write half, verbatim.
ActivityRecordingController Gone: OpenWatch records no activity, so a sync is never refused for one.
Body Energy, home widgets Gone: OpenVitals derives those from the records OpenWatch writes.
RouteElevationCorrector with DEM tiles A no-op: the watch's altitudes stand.

Device Layer

devices/ is a layer, not a feature. It owns everything that talks to a physical device over Bluetooth and exposes ports that features consume. It has no Compose code and no navigation. The user-facing screens are the screen modules: the generic ones in :feature:device, a family's own in :feature:watches-garmin, :feature:watches-wearos and :feature:scales-xiaomi (Phone modules).

devices/core

Vendor-neutral ports plus the two things every integration shares.

The contracts are their own module, :core:devices-api (core/devices-api, pure Kotlin, same packages, linted as in the app): DeviceClassification, DeviceScanClassifier, DeviceFamily (with DeviceFamilies, DeviceFeature and the live readings), RecordIds, ble/BleUuids, pairing/WatchPairingPort, pairing/CompanionPresenceObserver, and in sync/ the port and its types (DeviceSyncPort, SyncFailure), CompositeDeviceSyncPort, AutoSyncInterval and the SyncWakeLock seam; and the registry as a device sees it, data/repository/contract/DeviceRegistry (the devices and their flow, add, update, remove, the battery reading and the sync stamp), which the app's BleDeviceRepository implements and di/RepositoryModule binds. What holds Android is the module :devices:core (below): the radio lease (RadioLease, RadioLeaseUse), DeviceLog, ble/BlePermissions, the GATT link and the BLE scanner, the pairing and companion implementations, and in sync/ DeviceSyncController, SyncBudget, AndroidSyncWakeLock, the schedule and its worker, and EstimatedSleepRecord. In measure/, the push path's contracts: PushedMeasurement (a key that names the measurement for good, and the family's own payload), MeasurementSink and MeasurementOutcome. DevicePairing is how a family with no add flow of its own is paired by the app's (below). Families and kinds are open sets (DeviceIntegration and BleDeviceKind in :core:model, persisted names with the built-in ones as constants): a family names itself and its kinds in its own module. DeviceFamilies keeps its @Inject constructor (javax.inject); Dagger in :app generates its factory. The module's test fixtures are the fakes the tests share: sync/FakeDeviceSyncPort, pairing/FakeWatchPairing, FakeDeviceFamily and data/repository/contract/FakeDeviceRegistry (the registry's rules in memory: one row per address, a family's first device the empty salt).

  • RadioLease.kt — RadioLeaseRegistry, one injected singleton for the process, a lease keyed per Bluetooth address. Two holders on different peripherals is allowed by design; two holders on the same peripheral is not.
  • RadioLeaseUse.kt — registry.withRadioLease(address, owner) { ... }, RadioLeaseBusyException, and object RadioLeaseOwner with the six owner tags: SYNC, FIND, SETTINGS, NOTIFICATIONS, PROBE, and LIVE for a live stream held while someone collects it. They are strings rather than an enum because they appear in logcat.
  • ble/GattLink.kt — one GATT connection as coroutines, the only connectGatt a device family makes: peripheral(), dial (up to three attempts, redialling after a stack error such as status 133 with a two-second settle pause, never after silence; 20 s each), requestMtu, discoverServices, subscribe (the CCCD, for notifications or, as the standard health profiles send their measurements, indications), read and write (one at a time, a write with the characteristic's own write type), onDisconnected and close. It takes no lease and decides nothing about the peripheral: its owner holds the lease for the link's whole life and decides the bond, the MTU and the characteristics between the steps. Every failure is raised as the owner's exception type (failure), so the Garmin stack still sees only GarminGattClientException. The timeouts default to the Garmin link's.
  • ble/BleScanner.kt — the phone's one BLE scanner, both ways the device layer listens: a foreground discovery scan with a callback (sensors/ble/BleSensorCoordinator, the add-a-device list) and a background scan the system runs for a PendingIntent on service-data filters (ServiceDataFilter) matched in the chip (the scale). A scan opens no link and takes no lease.
  • DeviceClassification.kt / DeviceScanClassifier.kt — DeviceClassifier and DeviceScanClassifier function interfaces; the first non-null classification wins, otherwise the device is a plain sensor.
  • core/pairing/ — WatchPairingPort (bond, unbond, associate, disassociate), its BleWatchPairing implementation, CompanionDevicePairing around CompanionDeviceManager, OpenWatchCompanionDeviceService, and CompanionPresenceObserver. The service is declared in :devices:core's manifest, merged into the app's, and is the app's only companion service, so it is the primary one, the only one Android tells that an associated device appeared; it passes that to every observer bound @IntoSet in di/DevicesModule.kt. A second companion service, declared anywhere, would have to come after it.
  • core/DeviceFamily.kt — one DeviceFamily per integration (GarminFamily, WearOsFamily, XiaomiScaleFamily), bound by its persisted name into the map DeviceFamilies reads: which registered devices are its own, what they can do (DeviceFeature: sync, find, live heart rate), and how one is let go. Removing a device takes its registry row and schedule, then forget takes its state, keys and the system's bond or association; the last Garmin device's family offers to delete its history.
  • core/sync/DeviceSyncPort.kt — canSync(device) plus a progress-reporting sync(device, trigger), so the watch UI never names a vendor. The trigger says who asked: REQUESTED (a screen, OpenLink) or BACKGROUND (the schedule, a file a Garmin watch announced); a Garmin watch holds a requested link 20 s for its own errands, and a background failure ends without a banner. A success counts what it wrote by kind (SyncTally) and lists what it left out as SkippedSeries (series, reason, the grants that would unblock it); a failure is a SyncFailure type, never a sentence, with what it wrote first as partial. The screens word both, in features/watches/SyncOutcomeSummary.kt and SyncFailureText.kt, the same way for every device. The worker retries only a transient failure. core/sync/DeviceSyncController runs a sync through the port, one per device at a time and devices side by side (each radio held by its own lease), for the screens, the schedule and OpenLink alike; WatchAutoSyncScheduler and WatchAutoSyncWorker are the per-device periodic sync (unique work device-auto-sync-<id>; the name before the move, watch-auto-sync-<id>, is cancelled at start). The interval comes through AutoSyncIntervalStore. A scheduled sync runs in its worker's coroutine under an eight-minute SyncBudget: an integration that reaches it at a safe point (Wear OS, between series) returns moreRemains, and the worker queues up to three one-time continuations (device-auto-sync-more-<id>). A Garmin pull has no such point inside its session; the job's stop cancels it, and the files it saved import as pending on the next run. A sync no job holds awake runs under SyncWakeLock (30-minute timeout). Each integration binds its own port @IntoSet; CompositeDeviceSyncPort is the one the sync controller sees and hands a device to the port that claims it.
  • core/sync/EstimatedSleepRecord.kt — sleepNightWindow (18:00 the evening before to 14:00) and estimatedSleepSessionRecord, the Health Connect shape of a night health-calculations' insights/SleepStageEstimator produced from per-minute movement and heart rate. Garmin and Wear OS both write their estimates through it, each under its own id prefix and wording.

devices/garmin

The GFDI protocol stack, bottom to top. Everything above the GATT client is transport-free and unit-testable, and most of it is its own module (below the table):

Layer Files
Byte primitives GarminByteReader/Writer, GarminCrc, GarminCobs, GarminProtobuf, GarminTime, GarminLog
BLE transport GarminUuids, GarminGattClient (the GFDI channel over devices/core/ble/GattLink), GarminGattProbe, GarminTransport, GarminTransportProbe, GarminFrameTransport, GarminV1Transport, GarminMlTransport, GarminMlServiceChannel, GarminMlrChannel
Framing GarminGfdiFrame
Message vocabulary GarminMessages, GarminCapabilities
Session GarminSession, GarminSessionResponders, GarminStageTimers, GarminHeldSyncOwner, GarminProtobufTransport, GarminFitCapabilities
HTTP proxy GarminHttp (the proxy: the firmware's raw requests, and a Connect IQ app's web requests, whose headers and body are Monkey C values GarminMonkeyCData reads and writes, handed to the interceptors as JSON), GarminWeatherInterceptor, GarminOauthInterceptor, GarminAgpsInterceptor, GarminHydrationInterceptor (the hydration widget's drinks, day totals and containers, Gadgetbridge's paths); on the phone GarminHydrationStore (each watch's days in its device_state, which answer the widget with the water goal of SharedGoals; each drink to the MeasurementSink, a subtraction taking back the day's newest drinks first) and GarminHydrationRecords (the family's MeasurementRecords: one manual HydrationRecord per drink, garmin_hydration_<millis> salted by the watch, its version raised by each subtraction that changes it)
File sync GarminWatchSyncService, GarminDirectory (legacy listing), GarminFileSyncProtocol and GarminFileSyncTransfer (protobuf listing and download), GarminSyncProtocol, GarminFileTypes, GarminFileStore, GarminDeviceStateStore, GarminCounterWatermarkStore, GarminActivityImporter
Wellness import wellness/GarminFitWellness (decode), wellness/FitWellnessExtras (Pulse Ox, HRV values, thresholds, scores, restless moments), wellness/FitWellnessImport and wellness/FitWellnessExtrasImport (mapping; every record auto-recorded by a Garmin watch, importMetadata), wellness/FitWellnessImporter (orchestration)
Notifications GarminNotificationBridge (also the watch's CompanionPresenceObserver), GarminNotificationForwarder, GarminNotificationLink, GarminGncsHandler, GarminNotificationMessages, GarminNotificationActions
Settings link GarminSettingsLink, GarminSettingsService, GarminSettingsModel
Device screen GarminWatchOptions: the watch's switches as one flow that reads GarminDeviceStateStore again after each change (changes), and setters that go to the bridge, the relays or the store
Onboarding OnboardGarminWatchUseCase, GarminDeviceClassifier, GarminDeviceNames, GarminPhoneIdentity

The protocol module, :devices:garmin:protocol (devices/garmin/protocol), is plain Kotlin with explicitApi(), in the same packages, and Android lint checks it as it did in the app (com.android.lint; the one baseline entry it took along is GarminAgpsFile's). It holds every file of the table that touches neither Android nor the rest of the app: the byte primitives, GarminLog (without its logcat sink), framing, the messages and capabilities, the transports above the GATT client (GarminTransport, GarminV1Transport, GarminMlTransport, GarminMlServiceChannel, GarminMlrChannel, GarminUuids), the session, its responders, stage timers and held-sync owner, the protobuf transport and services (HTTP proxy, weather, OAuth, hydration, calendar, core location, A-GPS), file sync (GarminDirectory, GarminFileSyncProtocol, GarminFileSyncTransfer, GarminFileTypes, GarminFileDates, GarminFileStore), the uploads (GarminFileUploader, alarms, locations), the settings model and service, the notification messages and actions and GNCS, music messages, the realtime and navigation notices, the device names, and the FIT wellness decoders wellness/GarminFitWellness and wellness/FitWellnessExtras. The module :devices:garmin keeps what holds a radio, a Context or Health Connect: GarminGattClient, GarminGattProbe, the radio link, the notification link, forwarder and bridge, the settings link, the music and navigation relays, the stores on SharedPreferences (GarminDeviceStateStore, GarminCounterWatermarkStore, GarminAgpsStore), the injected in-memory GarminRealtimeStore and the hydration widget's GarminHydrationStore and GarminHydrationRecords, the platform sources (GarminCalendarSource, GarminPhoneLocationSource, GarminFindPhoneRinger), the importers and the Health Connect mapping (GarminActivityImporter, GarminDownloadImport, GarminLocalData, wellness/FitWellnessImport, FitWellnessExtrasImport, FitWellnessImporter, GarminSleepEstimation), the family, the onboarding, the watch options and GarminDeviceClassifier.

:devices:garmin (devices/garmin, an Android library, namespace tech.mmarca.openwatch.devices.garmin) depends on :devices:core and its protocol (api), :core:fit and Hilt, and on no other family. It binds itself (GarminModule): its family as GARMIN, GarminWatchSyncService into the sync port set, GarminGattRadio to GarminRadio, GarminNotificationBridge as a presence observer and into the notification listener's NotificationSink set, the GATT probe, GarminDeviceStateStore, the one GarminFileStore, GarminCounterWatermarkStore, and its four startup actors (garmin notifications, navigation, music, pruning). The app's DevicesModule keeps two rules across families: its classifiers' rank before Wear OS's, and every watch's auto-sync interval kept in GarminDeviceStateStore under its old key. Its manifest declares GarminFindPhoneStopReceiver; the find-phone notification's strings are its own, with their translations. It owns its tables' contracts (data/repository/contract/GarminWellnessRepository, GarminSleepMinuteRepository, implemented by the app's Room repositories) and the one preference it reads, GarminActivityPreferences (the exercise type an imported activity falls back to, which OpenWatchPreferences implements); it takes the registry, the per-device state, the body profile and ActivityRepository (:core:devices-api) as contracts. The activity files go through :devices:core's activityimport, whose parser, request type and conversion became public for it. Its public API is what the watch screens, OpenLink and the graph use: the family, the sync port, the radio and links (GarminSettingsLink, the notification bridge and its live hold), the stores and the watch options, the A-GPS import and the uploads, the onboarding use case and its outcome, the classifiers, and the protocol's types they hand over (settings, alarms, waypoints, capabilities); the GATT client stays public because the screens catch its exception. Its tests (236, over the shared fakes and the protocol's FIT test bytes) run on the JVM in the phone gate (:devices:garmin:testCiUnitTest).

Three edges were cut for the move to the protocol module, none of them a behaviour: GarminLog.installLogcatSink is an extension in the app (GarminLogcatSink.kt); GarminPhoneLocationSource left GarminCoreLocation.kt for a file of its own; garminFileStore(context), which puts the store under the app's files dir, is the app's (GarminFileStoreDirectory.kt). The values the protocol takes from the platform sources, WeatherSnapshot (its JSON form stays in the app, WeatherSnapshotJson.kt) and NotificationMsg, and runSuspendCatching are :core:model's. The weather, OAuth and hydration answers of the HTTP proxy, and the Monkey C values of a Connect IQ request, are org.json: the module compiles against the reference build (compileOnly) and runs on the copy Android ships, so it uses only the calls that copy has. The module's test fixtures hold wellness/FitTestBytes, which the app's wellness import tests share.

Notes worth carrying:

  • GarminWatchSyncService is a @Singleton class, not an Android Service, despite the name. It implements DeviceSyncPort.
  • The GATT client prefers V2 multi-link and falls back to the direct V1 pair. V2 startup waits for CLOSE_ALL_RESP before registering GFDI; do not collapse the two writes into one batch.
  • A logical GFDI frame is one transport write, however many BLE chunks it takes. Both transports hold their send mutex across the whole COBS frame, or concurrent traffic interleaves into corrupt frames.
  • Complete protobuf messages get the extended request-id ACK; a watch that NAKs it with LENGTH_ERROR gets the generic ACK for the rest of the connection. Chunks always get the extended ACK. The history behind that is on GarminProtobufTransport.extendedAcks.
  • A protobuf message over 375 bytes goes in chunks both ways. Going out, the next chunk waits for the watch to accept the last at its offset. A vívoactive 5 NAKs a reply sent whole (for message 65535, the frame being unreadable to it) and asks again a minute later: the fake OAuth tokens, 547 bytes, never arrived until outgoing messages were chunked (verified on a vívoactive 5 on 2026-11-22).
  • A file pull sends FILTER, waits for its answer (a NAK or silence lists anyway), then requests the legacy directory. FILTER is sent again in reply to an announcement. An empty legacy listing on a V2 watch not yet proven legacy probes the protobuf FileSyncService, which streams files over a temporary reliable-ML channel. The proven protocol is remembered per device; a timeout leaves it UNKNOWN, never "unsupported".
  • Once a session finishes or aborts its result is sealed: a kept-open link still answers the watch but ignores directory, download and announcement messages, so nothing is archived outside the result.
  • Newer firmware announces recordings over FileSyncService, not the legacy SYNCHRONIZATION message. Both run the same held-link handoff; a watch whose legacy directory lists nothing is handed to the owner for a full sync instead.
  • A held companion link never ends its session over a transfer. A stall cancels only the transfer (GarminSession.cancelTransfer), imports what was persisted, and keeps listening. The forwarder holds the radio for a transfer for at most maxSyncHold before yielding to a user-started sync.
  • Stage timeouts are named on GarminSession's constructor with their reasons; the radio's thirty-minute limit is only a whole-sync safety net, wide enough for a first sync of a watch holding months of activities. A partial pull is imported but reported as interrupted, so a dropped link is not mistaken for an empty sync.
  • Link policy: the dial and the writes are GattLink's, with its defaults: writes with the characteristic's own write type (with a response when the watch offers one), up to three connection attempts, redialling after a stack error such as status 133 with a settle pause between dials but never after silence. GarminGattClient checks the bond first, and asks for a 515-byte MTU unless the watch's GarminDeviceStateStore.highMtu is off, the per-address switch under "Large Bluetooth packets" on the watch screen for a watch that misbehaves with big packets.
  • A watch that never sends CONFIGURATION still completes the handshake: GarminFitCapabilities reads connectivity_supported from the FIT capabilities record some watches push as FIT_DEFINITION and FIT_DATA messages, and GarminSession.completeInitialisation runs the same start-up sequence from it. Those two messages are answered with the companion's status, ACK plus the APPLIED code.
  • Monitoring FIT records often carry only timestamp_16; resolve it to the nearest rollover in either direction (resolveMonitoringTimestamp16), or samples shift by 65,536 seconds.
  • Logs identify protobuf traffic by type, request id, status and byte count. Never log raw protobuf, settings or unknown-message payloads: they can carry notification text, locations or credentials.
  • Archiving is irreversible, and the import runs only after the whole pull, so nothing downloaded may be dropped on the way. A session that fails after a download still returns the files it has, as an abort does. GarminFileStore.save leaves a .pending note beside each file; markImported removes it once an import is done with the file, and the next sync imports what pending() still holds before it lists the watch. That covers a crash or an exception between the download and the import.
  • A downloaded file's key is recorded only once the file is dealt with. The watch archives a file as it downloads, so the key is the only thing that brings it back. A workout that did not reach Health Connect (no write access, or a failed write) keeps no key, the sync reports it as a failure, and the next sync fetches it again. A file that does not convert is done with.
  • A watch sync writes Health Connect records through ImportedRecordRepository.insertImportedRecords, the same deterministic-clientRecordId path the Apple Health importer uses, so a re-import upserts instead of duplicating. data/repository/ImportedRecordWrites.kt holds what every device writes with. The platform's Health Connect (Android 14 and newer) refuses no stored id: an equal version replaces, a lower one is kept out (ClientRecordVersionTest). Where a batch is refused anyway (the Health Connect APK on older Android), the refusal is diagnosed by reading this app's own ids and versions, never by its text: what is stored at its version or newer is present and the rest is written again, in one read and at most two more writes. replaceImportedRecord deletes and rewrites where a provider refuses a newer version. A missing grant, the pause switch and a spent quota (isHealthConnectRateLimit, by the platform exception's code) are thrown as they come. Only the watch-only series go to GarminWellnessRepository.
  • Activity files take their own path, shared with the bulk folder import: RouteFileImport.toImportWriteRequest builds the request straight from the parsed file, and ActivityRepository.writeActivityEntries writes it. The client ids are a function of a hash of the file's bytes, so a second import of the same file updates its records instead of adding a second workout, and a watch's file is stored as recorded by a watch. A headless import must not go through the entry form's text fields: that lost the seconds, rounded the duration up, and gave every record a random id.
  • The OS bond is the security boundary. GFDI's own auth challenge is answered with zeroes, so OnboardGarminWatchUseCase treats bonding as mandatory and the companion association as optional.

devices/wearos

A Wear OS watch is a registered device plus a Bluetooth Classic link to the OpenWatch watch app (:wear). There is no vendor protocol to speak: the watch runs our own app, and the phone talks to it over an RFCOMM socket on AOSP APIs only.

The phone side is the module :devices:wearos (devices/wearos, an Android library, namespace tech.mmarca.openwatch.devices.wearos), every file below, in the app's package devices/wearos. It depends on :devices:core and :wearlink (api: the link's types are in its signatures; the watch app compiles the same module), Hilt, and no other family. It binds itself (WearOsModule): its family as WEAROS, WearOsWatchSyncService into the sync port set, BluetoothWearOsNodePort to WearOsNodePort, WearOsNotificationRelay into the notification sinks, as the per-watch switch (WearOsNotificationSwitch) and as what it sent each watch (WearOsRelayedNotifications), and its startup actors (phone activity, and wrist actions, which keeps the phone's listener for the wrist's actions open while it can be used); its classifier is ranked in the app's DevicesModule with Garmin's. It declares no manifest component. It takes the registry, the per-device state (DeviceStateRepository, which the app's DeviceStateStore implements on device_state) and the body profile as contracts, and owns the preferences it reads, data/repository/contract/WearOsSyncPreferences (whether to write the breathing rate, on by default, and whether to write the watch's night and naps beside a session another app wrote, also on by default, Health Connect's data source priority then deciding which apps show), which OpenWatchPreferences implements (write_respiratory_rate, write_sleep_beside_others). The link states' sentences (WearOsAppStatus.messageRes) are its strings, moved with their translations; "Bluetooth is off", which every family's sync failure says too, is :devices:core's. The classes the sync runs on (WearOsSessionCache, the series readers and syncs, the progress) are internal to the module; what the watch screen, onboarding, OpenLink and the app's graph use is public: the family, the sync port, the node port and its status types, WearOsCompanionManager, WearOsLinkStore and its snapshot, WearOsSyncCursorStore, the notification relay, its switch and WearOsVendorCompanions, the wrist's listener, its requests, its actor and its state, the onboarding use case and outcome, the classifier, isWearOs. Its tests (247, over FakeDeviceStateRepository, mocks of the contracts and health-calculations' wear sleep fixtures) run on the JVM in the phone gate (:devices:wearos:testCiUnitTest).

  • WearOsDeviceClassifier / WearOsDeviceNames — claims a scanned device as (WEAROS, WATCH) when its name is a known smartwatch family or its SDP record lists the OpenWatch app UUID. A wrist-watch Bluetooth class alone is not enough.
  • OnboardWearOsWatchUseCase — a single optional ASSOCIATING step, no bond and no probe; the device is registered with no capabilities, off the Garmin sync path. The bond itself comes from Android's Bluetooth settings, or from the vendor's onboarding.
  • WearOsNodePort — the port: pairing and reachability of the watch app. WearOsAppStatus is NOT_PAIRED, NO_ANSWER or APP_RUNNING; a bond alone is never shown as connected.
  • BluetoothWearOsNodePort — the implementation. WearOsBondMatcher finds the bonded Classic entry for the registered watch (exact address, then name with a trailing LE stripped: the scan address is a BLE private address), then one PING/PONG exchange with a ten-second watchdog, once the check has the watch's link. RFCOMM is Classic, so no radio lease is taken. Its hello announces tm and bc, and nb while the wrist's listener is open (WearOsWristState).
  • WearOsCompanionManager — the thin facade the watch screen calls.
  • WearOsNotificationRelay — the phone's notifications on the Wear OS watches whose own switch is on, a NotificationSink. The switch is per watch, off by default, kept in device_state (WearOsNotificationSwitchStore, key show_phone_notifications) and held in memory, so hasTarget() (an enabled Wear OS watch switched on) costs no read; the global switch and the apps chosen apply on top of it, in the listener. Each watch has its own PendingNotifications; a burst waits for 1.5 s of quiet, at most 4 s after its first, and goes in one turn (WearOsNodePort.pushNotifications, behind nt): the latest of each id posted, the removals of what that watch shows. One coroutine carries a burst and whatever comes within 1.5 s of its last turn, so they share the watch's session. A watch out of reach keeps its queue and is tried again after 15 s, doubling to 5 minutes; its first turn after a failure, and the first since the process started, opens with the reconcile (NT_KEEP) of what the phone still shows there, so a removal that never arrived is made up for. A watch keeps at most 50 of the phone's notifications, the oldest taken down. Turning a watch's switch off, or the global switch, sends it a reconcile with none (a watch out of reach is told five times at most); an app switched off has its own taken down (the relay keeps each id's package in memory for that). A link failure and a missing Bluetooth grant (SecurityException, which the app scope would not catch) are caught and logged as counts. It runs on the app scope, one coroutine at a time, with an injected clock, so its tests run on virtual time. Each notification goes with the actions the wrist may take on it (wearOsActionsFor, Garmin's rules: only an action the phone can fire from the background; a call's answer and decline first, one of each, without a title, since the phone has only fixed English words for them; the first reply; then at most five buttons, a second reply among them), with two differences for a call. CallStyle lists the answer and decline among the app's actions as well as under its own extras, so the listener marks the copy among the actions (NotificationActionMsg.repeats: the same PendingIntent, whose equals compares the system's token across apps, or CallStyle's own key_action_priority mark on an action it built, or SEMANTIC_ACTION_CALL on a ringing call), and the Wear OS rules leave it out, keeping the role's copy; Garmin's rules read no such mark. And a call's answer that opens an activity (Signal's does) goes to a watch the phone has a companion device association with (WatchPairingPort.isCompanionAssociated, asked at each turn, outside the relay's lock): Android lets an app with an association start an activity from the background in answer to what the user does on that device, and NotificationActions lends that right to the answer's intent. Every other activity action stays off the wrist. The relay keeps, per watch, the actions each notification it shows there went with (WearOsRelayedNotifications.offered): that is all the wrist's requests can reach. The ids of the watches switched on are a StateFlow too (switchedOn()), which the wrist's listener follows.
  • WearOsWristListener, WearOsWristRequests, WearOsWristListenerActor — the way back from the wrist (WearLinkWrist, below). The listener is an RFCOMM server on the phone (listenUsingRfcommWithServiceRecord, secure, on WearLinkProtocol.PHONE_SERVICE_UUID), its accept loop on a thread of its own and each watch served on another by WearLinkWristServer (two at once, a hello within 5 s, 15 s idle, 120 s at most); a socket that fails is opened again after 5 s, three times in a row at most. WearOsWristListenerActor, the startup actor wrist actions, keeps it open exactly while a registered, enabled Wear OS watch has its notifications switch on and Bluetooth is on (WearOsBluetoothState, from ACTION_STATE_CHANGED), and closes it otherwise. No foreground service is added: the notification listener being bound keeps the process alive while notifications are relayed. While it is open WearOsWristState.listening is true, and the port's hello announces nb. WearOsWristRequests is the gate and the dispatch. A connection is a watch only from a bonded device that WearOsBondMatcher finds for a registered, enabled Wear OS watch with its switch on (the Classic address its hello last came from first), and its hello's token must be the one the phone presents to that watch (WearOsLinkStore.knownTokenFor, which never makes one), compared by the server in constant time; anything else is answered UNAUTHORIZED and closed. A request reaches a notification only when the relay shows it on that watch, and an action only by an index it was sent there with: an id it did not relay to that watch is gone, an action it did not offer (or a reply's index tapped as a button) a bad request. What is left runs through the shared NotificationActions, whose refusal is gone. A call's answer the relay sent is offered, so the wrist's NT_ACT on it is too, an activity's included. Its log lines are counts and outcomes, never an address, an id, a title or a reply.
  • WearOsVendorCompanions — whether Galaxy Wearable or the Pixel Watch app (either package) is on the phone, through the app manifest's <queries> entry for exactly those three: then the panel notes that the watch may show each notification twice.
  • The line protocol itself lives in :wearlink (WearLinkProtocol), compiled into both apps, at version 5 on both sides: a peer of version 4 (the 0.4.x apps) is answered VERSION 5 5, or answers VERSION 4 4, and the phone reads either as "update the app" on the side that is behind. The hello offers the phone's highest version; the watch speaks it when it is in its own range, else refuses with that range, and the phone says hello once more, on a new connection, at the highest version both speak (WearLinkClient.hello), so a later bump need not cut the link. WearLinkVersionGoldenTest holds the hello of every pairing with 0.4.0 and 0.4.1 line for line. PING/PONG; SINCE <key> <cursor> <limit> (WearLinkSince) for every series the watch keeps one line per value, asked only for a key its hello announces: hr (HR <epochMillis> <bpm>), sm (SM lines, one per clock minute, nineteen integer fields defined in sleep-minute-features.md), st (ST <minuteStartMillis> <steps>), as (AS <minuteStartMillis> <decimetres>, the height climbed; builds that sent whole floors announced fl and are not asked), hv, rr, o2, sk and lg (the entries made on the watch, WearLinkEntries). The watch answers from its store by sequence number, the lines as stored, in the order it wrote them, so a row rewritten in place or written late comes again after the rows sent before it, and ends with END <count> <more> <cursor>. The cursor is <store>.<seq>, the watch's store id and the last row's number, which the phone keeps as it came; a cursor of another store starts from the first row. A time position, t<epochMillis>, starts at the first row in sequence order newer than that time: that is how a time cursor of an earlier build hands over (every row newer than it comes, and every row written after the first of those), and how the phone reads a window an estimate needs (filtering to the window). Version 5 replaced the eight per-series requests of version 4 (HR_SINCE and the rest). A phone that announces tm in its hello gets the watch's clock in OK, as OK <version> <caps,tm> <epochMillis> <name...>, and logs a skew over two minutes as a direction (WearOsClock); a phone that does not, a 0.4.x one included, gets the line it always did. A phone that listens for the wrist's actions announces nb; the watch's handler is given the phone's capabilities after its OK (phoneCapabilities), and the watch keeps, per phone, whether its last hello said so. HR_LIVE <seconds> (at most 10, below the watch's 15-second idle timeout) is answered with an HR line per reading as the sensor takes it, asked only of a watch that announces hl, and answered at once with none while the watch is off the wrist; workouts keep WO_SINCE, a header with its pauses and route under three keys. PUT_DAY (WearLinkDaily, asked only of a watch that announces dy, added without a version bump) hands the watch the phone's figures for one day and is answered DAY_OK. The phone's notifications go to a watch that announces nt (WearLinkNotifications, added without a version bump), each line one request answered END 0 0: NT_PUT <id> <seq> <last> <field> <chunk> carries one notification line by line (its id the phone's 31-bit one; the app's name, the title and the text as base64url of UTF-8 without padding, 400 characters a line, clipped first to 48, 100 and 1000 characters; the notification's actions as text the same way, before the time: one line <index> <kind> <title> per action, the kind p, r, a or d, at most eight, a title clipped to 40 characters and left out for a call's; the time in decimal milliseconds), and the watch posts it on its last line; a field the watch does not know is taken and dropped, so a watch from before the actions drops them. NT_DEL <id> takes one down. NT_KEEP <seq> <last> <ids|-> is the reconcile, forty ids a line: on its last line the watch takes down every notification of that phone it does not name. A line the watch refuses is ERROR bad_request, and the phone leaves that notification out and sends the rest. The way back is a connection of the watch's own, to the phone's PHONE_SERVICE_UUID (WearLinkWrist): the link's hello with the token the phone presents to that watch, answered OK <version> or UNAUTHORIZED, then one of NT_DISMISS <id>, NT_ACT <id> <index> and NT_REPLY <id> <index> <seq> <last> <chunk> (a reply of at most 500 characters in base64url, 400 characters a line, fired on its last), each line answered END 0 0, ERROR gone or ERROR bad_request, and the watch closes. Each reply ends with END <count> <more>, and the phone refuses a page whose count differs from the lines that arrived. The watch answers one request after another on a connection, and RFCOMM takes one connection at a time between a phone and a watch on the watch's one channel: while one is open the phone's stack drops a second. So WearOsSessionCache is the one owner of each bonded watch's link: every connect, request and close happens in a turn, one at a time, and a call that finds the link busy waits for its turn, up to its own timeout, then runs under a watchdog of that timeout; it never opens a second connection. Turns go first come, first served, except a live heart rate window: it lets every other waiting call go first, and also waits while another caller whose coroutine still runs asked within the last 10 seconds, so a sync's requests follow one another with no window between them. The calls share the watch's one session: one connect and one hello, whose capabilities decide which series are asked for at all. A session is reused while it is under 540 seconds old and its last request went out under 10 seconds ago (the watch closes at 600 and 15), is closed by the phone when the coroutine that opened it ends, when it idles past that, or when a request on it fails, and is replaced once by a new connection when it turns out closed.
  • WearOsWatchSyncService — the DeviceSyncPort for Wear OS. Each series is a WearSeries in WearOsSeries (its key, how a line reads, a value's time, and for the series written one record per value the record and its grant), pulled with WearOsNodePort.pullSeries page by page (WearOsSeriesReader). Heart rate first: pulls pages from the watch's cursor (WearOsSyncCursorStore.seriesCursor, kept per device and series as series_cursor_<key> in device_state), writes each page through ImportedRecordRepository.insertImportedRecords before asking for the next, and advances the cursor after each write, so a sync that dies mid-way resumes where it stopped. The first pull of a series hands its time cursor (the newest sample time, kept as before) over to the sequence, so no sample already written is sent again: the hour records are keyed on their first sample, so a sample sent twice in another page would be written twice. A sample the watch wrote late, behind the cursor, now comes with the next page. Then steps, the same way: the watch rewrites its newest minute as late steps arrive, and the rewrite comes again by the cursor, so no pull takes the cursor's minute again; the first pull after an earlier build hands over one millisecond before the time cursor, taking that minute once more. Then ascent, the same way, written as floors and filtered by the step minutes around each minute (WearOsStepContext): this sync's, and for a minute it did not pull, a window of the watch's steps from the earliest one missing, written to nothing. A minute seen before (not after the ascent time cursor) is written apart from the rest, so an unchanged one does not make the batch fall back to one record at a time. Without the Health Connect grant to write steps, steps and floors stay on the watch and the sync goes on. Then sleep, which keeps its time cursor: the estimate needs the whole night and the phone keeps no minutes, so each sync reads the window again whatever the sequence says. It pulls the minutes from the start of the night the sleep cursor sits in (WearOsSleepImport.pullStart), estimates every night those minutes touch and writes one SleepSessionRecord per night, skipping a night whose window already holds a session from anywhere else (the vendor's app, the user's own entry), then moves the sleep cursor. Refuses while an activity recording holds the foreground slot. The result counts the heart rate samples, the minutes of steps and the nights (WearOsSyncProgress).
  • WearOsEntrySync — the entries made on the watch (SINCE lg, WearOsSeries.ENTRIES), pulled after the night series and before the workouts, which stay the last pull since the watch counts a phone's pull by them. Page by page from the watch's cursor (series_cursor_lg; the first pull asks from t0, everything the watch keeps): each page mapped by WearOsEntryImport, split by partitionByWriteGrant, and the granted types written with insertNewer, so an entry written before is not written again. An entry whose grant is missing is held back: from then on the cursor stays, so it comes again with the next sync, while the other types of every later page are still written, and its grant goes to the result's skipped as RECORDS, which the watch's card asks for. An entry Health Connect cannot keep at all (a breathing session where it stores no mindfulness, HealthConnectReads.isMindfulnessAvailable) or a value it refuses is dropped and the cursor moves past it.
  • WearOsEntryImport — pure mapping of an entry (WearLinkEntry) to its record: water HydrationRecord, weight WeightRecord, blood pressure BloodPressureRecord, a breathing session MindfulnessSessionRecord (stamped at its end, its start that many minutes before), a spot heart rate HeartRateRecord (one sample), a spot HRV HeartRateVariabilityRmssdRecord, body fat BodyFatRecord, blood oxygen OxygenSaturationRecord, breathing rate RespiratoryRateRecord, body temperature BodyTemperatureRecord (Celsius), blood glucose BloodGlucoseRecord (mmol/L), height HeightRecord (whole centimetres on the watch, metres there); keyed wearos_entry_<type>_<millis> with the watch's id salt, from a watch, a manual entry for h and actively recorded for m.
  • WearOsDaySync — after the zones, the last seven days' figures to the watch (PUT_DAY), from any app: per local day the longest night that ended on it with its stages, the latest resting heart rate (READ_SLEEP, READ_RESTING_HEART_RATE), and the active calories and distance as Health Connect aggregates them (HealthConnectReads.readDayTotals, READ_ACTIVE_CALORIES_BURNED, READ_DISTANCE); WearOsDaySummaries is the pure part. A figure whose read is not granted is left out, and a sync that cannot read other apps' data now (readsOtherAppsDataNow) sends none, so a background sync never sends figures that leave out every other app. Like the zones it never fails the sync.
  • WearOsZoneSync — after the workouts, what the watch's zones and figures rest on, as watch settings over SET_PREF: the zones' maximum and resting heart rate (HeartRateZoneBasis on the declared profile, the year's highest heart rate and the latest night's resting rate) and the body profile a workout's figures need (body_hg, body_cm, birth_year, sex; the weight Health Connect's latest, else the profile's). A failed read skips only what it was for, and neither ever fails the sync.
  • WearOsWorkoutFigures and WearOsWorkoutMetrics — a workout's figures, the ones the watch's summary shows (WorkoutMetrics in :wearlink): WearOsWorkoutFigures reads, through HealthConnectReads, the watch's own heart rate over the session (watchBeats: its hour records under its salt, which the same sync wrote before the workouts, the read widened by an hour both ways since Health Connect finds a record by its bounds), the highest heart rate of the year and the latest night's resting rate for the zones' basis (HeartRateZoneBasis on the declared profile, as WearOsZoneSync hands it to the watch); WearOsWorkoutMetrics (pure) turns them into the session's laps (a kilometre each), a line of its notes (the mean and highest heart rate, the minutes per zone, the TRIMP, and the heart rate recovery's falls where the two minutes after the stop hold a reading a second, WorkoutMetrics.MIN_RECOVERY_READINGS, with the reading's verdict where it is not clean: "effort not near-maximal", "approximate") and a Vo2MaxRecord at the session's end (keyed wearos_workout_vo2_<start> with the watch's salt, written only with WRITE_VO2_MAX). WearOsWorkoutSync writes them with the session; a workout whose figures cannot be read is written without them. The session's active calories (WearOsWorkoutEnergy, once it is written) are WorkoutMetrics.energy over the same watchBeats, the session's own span, with the resolved body profile (the one WearOsZoneSync sends the watch) and the age on the workout's day, the number the watch's summary shows; WearOsWorkoutImport.activeCalories only makes it a record (wearos_workout_energy_<start>, salted).
  • WearOsHeartRateImport — pure mapping: one HeartRateRecord per clock hour, keyed wearos_hr_<first sample millis>, so a re-pull upserts. The watch keeps a week of samples and prunes on its own; nothing is deleted on the phone's behalf.
  • WearOsStepsImport — pure mapping: one StepsRecord per minute, keyed wearos_steps_<minute millis>, with the count as clientRecordVersion, so a re-pulled minute that grew replaces its record and one that did not is skipped: the write reads this app's stored step minutes first (insertNewer), since the platform's Health Connect takes an unchanged minute again without a word and only the read tells what changed. The same minutes become a StepsCadenceRecord each (wearos_cadence_) and, when a body weight is known (Health Connect's latest, else the body profile's), an ActiveCaloriesBurnedRecord each (wearos_walk_kcal_, versioned on the step count like the others, so the estimate is frozen at first write and a later weight or session does not revise it) from health-calculations' insights/WalkingEnergy: Moore et al. 2021's cadence equation, net of one resting MET. A minute inside any exercise session in Health Connect gets none, so a recorded walk's own active calories are not counted twice. The weight is read once per sync, and only when a minute costs more than rest; without one the walking energy is skipped, as a NO_BODY_WEIGHT entry in the result's skipped, so the sync card says so. The write grants for steps (Health Connect files cadence under it) and active calories, and the exercise read grant the walking energy filters with, are checked before the pull: a withheld one skips its series, never failing the sync, and the result's skipped entry names the series and the grants its button asks for. A minute is estimated when its steps are written (new or grown); one synced without the grant, the weight or visible sessions (in the background without the background-read grant, HealthConnectGateway.readsOtherAppsDataNow, or when the session read fails) keeps no estimate. Cadence and walking energy follow the steps insert: a minute Health Connect already held is skipped, except past the step cursor, where only a sync that failed after its steps leaves minutes, so they are tried again. The energy grants and the weight hint are reported only when a pulled minute outside a recorded workout would have had walking energy; without READ_WEIGHT the NO_BODY_WEIGHT entry carries that grant. The weight and the sessions (HealthConnectGateway.readExerciseSessions) are read under withStrictHealthConnectReads, so a failed read skips the estimate rather than passing for "none". Cadence and walking-energy writes are optional: a failure is logged and skipped, never failing the sync. Every minute record carries the zone offset in force at its minute. It also stays put when the exercise sessions cannot be seen: in the background without the background-read grant (HealthConnectGateway.readsOtherAppsDataNow), where other apps' sessions and weights are invisible, or when the session read fails.
  • WearOsFloorsImport — pure mapping: one FloorsClimbedRecord per minute, keyed wearos_floors_<minute millis>, the credited metres over 3 m with the fraction kept, and one ElevationGainedRecord of the same credited metres, keyed wearos_elevation_<minute millis>; both versioned by the credited decimetres. Height counts only with 10 steps per floor's height in its minute and the one before, so elevator rides and weather drift are dropped; the threshold is an app heuristic. The rule is AscentCredit in health-calculations, so the watch app counts floors the same way.
  • WearOsSleepMinuteMapping — the wire row (WearLinkProtocol.SleepMinute, integers) into domain/model/WearSleepMinute (physical units, WearMinuteFlags).
  • WearOsSleepImport — pure: the nights a pull touched, each night's rows inside its window, the night through health-calculations' insights/WearSleepEstimator, and the record through estimatedSleepSessionRecord, keyed wearos_sleep_est_<night> with the sync time as version so the later estimate replaces the earlier. The phone stores no minutes: the watch is the store and a whole night window is re-pulled to re-estimate it.
  • WearOsRestingHeartRateImport — pure: one RestingHeartRateRecord per estimated night, keyed wearos_rhr_est_<night> with the sync time as version, stamped at the night's end, from health-calculations' insights/NocturnalRestingHeartRate (the lowest 30-minute mean of the per-minute heart rate between onset and end, at least 20 minutes with a reading; the rule Dial et al. 2025 report for Garmin). No value while the night is in progress. The sync writes it only when the calendar day of the night's end holds no resting heart rate from elsewhere (the day the app averages), removes its own when one turns up later, replaces a stale version like the session, and fails closed when the read fails, the grants are missing (a RESTING_HEART_RATE entry in skipped) or other apps' data is unreadable in the background.

The Wear OS night itself is estimated by pure objects in health-calculations' insights package, in the order the actigraphy literature settled on: WearMinuteGrid (the rows on a one-minute grid, missing minutes absent), WearStateDetector (worn or not per minute: charging, off-body, a pulseless run while heart rate is recorded, then van Hees' still-hour rule vetoed by any pulse in the hour; a not-worn minute is a gap to everything after it), SptWindowDetector (the night's window: HDCZA on the z-angle change, tightened at its end by the heart rate quantile window), SleepWakeScorer (one linear score of Cole-Kripke movement, heart rate volatility after Walch, the z-angle range and the median small z-angle drift, then WebsterRescoring), and SleepStageEstimator.estimateWindow for the stages, with Lids as a prior behind lidsWeight. WearSleepEstimator strings them together and returns the night with its window and worn counts. The per-minute features are specified in sleep-minute-features.md.

On the watch, OpenWatchWearApplication owns WearGraph, the app's hand-written object graph (the watch has no DI framework): the store, the link's state (WearLinkState), the workout's (WorkoutState), the trust store and its Keystore key (WearSecretKey), the phone requests' notifications (WearPhoneRequests), the phone's own notifications (PhoneNotifications), the debug protocol, the Samsung feed, the recorders and the link server, each built once per process and on first use. WearAppService hosts them: at each change of an input it decides what runs with RecorderPlan (pure, tested: the settings, the grants, the sensors present, the wrist, bedtime mode, the sleep hold, a workout and its recovery in; one plan out) and hands the plan to every Recorder in WearGraph.recorders, the heart rate first since the step counter's variant follows it; the recorders and the link tell the running service through WearGraph.Host, on the main thread, when the sleep hold, the heart rate's source, the wrist, a workout or a phone setting changes. The service hosts the RFCOMM listener and the recorders, and all write to one MetricStore: a single plain-SQLite table keyed by metric and time whose rows are the values' :wearlink protocol lines, so the format is defined and tested in one place and the store holds exactly what the phone receives. The store is one instance per process, owned by OpenWatchWearApplication and shared by the service, the activity, the dashboard and the tiles, in write-ahead logging so readers never wait on a recorder. Every write goes through one guarded path: one writer at a time, each write one transaction, and a failure (a full disk, a corrupt file) counted for the debug snapshots and answered with false instead of thrown on a recorder's thread; a workout whose header cannot be written keeps its checkpoint, the step recorder keeps its unsaved minutes for the next flush, and the legacy import keeps its file. A link page's "more" comes from the stored rows, not from what decoded, so a row this build cannot read never ends the paging early. Every row also carries a sequence number (store version 3), taken from one counter on every insert and every replace, so a row rewritten in place or written late comes again after the rows already read (MetricStore.changes); the counter's high-water mark is kept beside the rows, so pruning never hands a number out twice, and a random store id names the numbering, so a cleared watch starts it over. The migration from version 2 numbers the existing rows in time order (MetricStoreSequenceTest). Each series is a WearMetric in WearMetrics, which names its key (the capability the link announces), its line codec, whether a second value at the same time is kept or replaces the first, and its retention (a week; a month for the workouts and the entries). The entries made on the watch are one such series (WearMetrics.ENTRIES, key lg, line LG, WearLinkEntries): what the wearer logs by hand in the quick log (water, weight, blood pressure, a breathing session) and what a spot measurement takes, each flagged h or m, its values in thousandths of its type's unit. EntryLog, built once in WearGraph, is their one writer: the store keeps the first value at a time and drops a second silently, so it moves an entry to the first free millisecond under a lock, refuses one its own line would not parse back to, and prunes the month at each write; no screen opens the store to write, and the quick log tile logs its glass of water through it too. Each entry it writes is told to the graph, which asks the quick log tile to show the new water total (TileService.getUpdater). A screen follows a metric's writes instead of waiting for its next poll: MetricStore.updates(metric) is a count per metric, held by the store instance, that moves after each committed write of that metric (a value stored, a range deleted, rows pruned). The phone's figures for a day (PUT_DAY) are no store rows: PhoneDays (WearGraph.phoneDays, preferences file wear_day_summaries, keys day_<epochDay>, each the line as it came, the fourteen newest kept) holds them as a StateFlow, and WearReadings puts them on the sleep, resting heart rate, active calories and distance tiles, today's value as the value now, as for the night's vitals, and the night that ended today gives the sleep detail its stages (WearUiState.sleepStages). Rows are pruned by age whether a phone pulled them or not, so PhonePulls records when a phone last pulled (the WO_SINCE request, the last series of a phone sync; preferences file wear_phone_pulls, key last_pulled_millis) and SyncRetention (pure) warns from the fifth day after it, two days before the pruning reaches unpulled rows: the status screen shows the last pull and the days left, and SyncReminder posts a notification once per pull and level (soon, then pruning), checked at the service's start and on an hourly non-waking alarm, and cancelled by the next pull. A workout's route is stored whole (the five-second gap between kept points bounds a day to WorkoutTracker.MAX_STORED_POINTS) and thinned to the link's 9000 points when it is read, every second point as often as it takes, so a long workout keeps its end. The link's request handler pages any metric with one generic function. The link's request handler serves every one-line series from the store by sequence number (MetricStore.changes, and seqBeforeNewerThan for a time position). Adding a metric, one pull request per metric, is: its line in :wearlink, a WearMetric in WearMetrics.SERIES (the link serves it to SINCE by its key from then on), a recorder that calls MetricStore.put, and on the phone a WearSeries and what writes it; the store, its pruning, the link and their tests (MetricStoreTest, on Robolectric in the watch gate and on a watch) do not change. LegacyStoreImport moves the per-metric databases of earlier builds into the store once, at service start. HeartRateRecorder keeps one sample per ten seconds from a HeartRateSource, the batched TYPE_HEART_RATE listener (SensorHeartRateSource) or the Samsung platform (SamsungHeartRateSource), and hands each stored sample and each no-contact reading to the minute recorder. While a workout runs the plan asks for the heart rate live (RecorderPlan.Plan.heartRateLive, the sensor whatever the source setting): the sensor registers unbatched, empties the other sensors' buffers as often as a batch would come, and the recorder keeps every reading, one a second. A day's heart rate is therefore read with a limit of a 25-hour day at one a second (TileDay.MAX_HEART_RATE_SAMPLES_PER_DAY, which WearReadingsSource reads every series with), and a mean of samples (the tiles' quarter hours, a day's average) counts them on the ten-second grid (TileDay.onDayGrid), so a workout's minutes do not outweigh the rest of the day; the low, the high and the time in zones take every sample. The phone pulls the seconds as it pulls the rest (SINCE hr, 2000 a page, one record per clock hour of each page). The recorders reach the Samsung platform only through source interfaces built in WearGraph: HeartRateSource, HrvWindowSource (the night windows) and SpotSource (SpO2 and skin temperature; the Samsung source turns the platform's status codes into plain readings), so a recorder never names the platform's client, nor the platform: HeartRateRecorder takes the sensor and the alternatives a vendor offers by the MeasurementSource the wearer chooses each as, and falls back to the sensor when the chosen one refuses, fails or stays silent; NightHrvRecorder takes NightHrvSources, a list of HrvChoices (the id, its word in the debug protocol, the source, and whether a grant of its own is in), and a window reads the wearer's choice where the watch has it, else the default under RAW_SENSOR, which also stands in after a chosen source's window failed, until a setting changes. StepRecorder is the non-waking TYPE_STEP_COUNTER at the heart rate's report latency, or its waking variant, where the watch has one, while the heart rate is not running and nothing of ours would wake the processor; StepMinuteCounter (pure) turns its running total into one row per clock minute, never writing before the newest minute. A difference between two readings at most two minutes apart (a batched counter's, and the live ones) is spread over the minutes between them in proportion to time at once. A longer one, as a counter without a buffer gives (the OnePlus Watch 2R's reports only when the processor wakes for something else, at times hours apart), waits until the sleep minutes of its span are stored (SleepMinuteRecorder tells StepRecorder.noteMovementStored; ten minutes at most) and goes to the minutes that moved, in proportion to the square of their movement, at most 200 steps a minute and none to a minute off the wrist or on the charger; what that cannot place, and a long difference while the sleep minutes are not recorded, is spread by time over at most the hour before the newer reading (of a longer gap only that hour's share, at the gap's pace). A batch is written once, a second after its last event, together with the last reading and the difference still waiting in one transaction (MetricStore's state table, StepMinuteCounter.Stored), so a restart neither loses nor double-counts steps. While the watch app is on screen (MainActivity.onResume and onPause set WearGraph.setInteractive, an input of RecorderPlan) the plan asks for the steps live (RecorderPlan.Plan.stepsLive; not in a workout, which counts its own): the counter registers again without batching, so the dashboard, which reads again on the steps' writes, counts each step within seconds. On a new boot the counter starts again at 0, so its first total is credited from the boot time. AscentRecorder reads the barometer (TYPE_PRESSURE, no grant) once a second at the same latency; AscentMinuteCounter (pure) averages 10 seconds, converts to altitude and counts a rise once it reaches 3 m above the last low point, then with all of its metres, in decimetres, one row per clock minute. The 3 m dead band keeps the barometer's wobble of about a metre from adding up. Each recorder starts only when the watch has its sensor and the grant is in (ACTIVITY_RECOGNITION for steps). SleepMinuteRecorder keeps one row per clock minute: MinuteAggregator (pure) and AccelerationMinuteFeatures compute the specification's fields from the batched accelerometer in g, the heart rate samples, the off-body sensor, the charger broadcasts and screen wake-ups. WornMonitor is the one owner of the off-body sensor: it hands each reading to the minute recorder and stops HeartRateRecorder after 60 seconds off the wrist, starting it again at once when the watch is back on (WornGate, pure). Because the off-body sensor may depend on the heart rate sensor on some watches, a screen wake-up or a pulled charger runs the heart rate for another 60 seconds, enough for an "on" to arrive. The accelerometer keeps running: it is cheap, and its events close the minutes. A watch without an off-body sensor keeps its heart rate on. While the heart rate rests, StepRecorder switches to the waking step counter; off the wrist it reports nothing, so it wakes nothing. LiveHeartRate (one instance in WearGraph) serves HR_LIVE: each window registers its own unbatched heart rate listener and drops it at the end, only while HeartRateRecorder runs, and stores nothing; the window is built on listen, a registration that stays until it is closed, which a spot measurement holds too, and so does the heart rate's detail screen while it is shown (LiveHeartRate.bpm), whose value is then the heart rate now. On the phone, WearOsCompanionManager.liveHeartRate asks for 5-second HR_LIVE windows one after another on the watch's one link: 5 seconds, so the session stays inside its 10-second reuse window and a status check, a setting or a sync that comes meanwhile waits at most one window. It pauses after two windows in a row without a reading, or while a sync holds the link, and asks again 15 seconds later. WearOsWatchPanelViewModel starts it after the screen's first status check and settings read and shares it WhileSubscribed, so it runs only while the watch's device screen is open. The accelerometer needs no permission and shares the heart rate's report latency, so the two batches arrive in one wake-up. That is not enough on the Galaxy Watch8: its accelerometer cannot wake the processor and buffers 48 seconds, and the hub lets a still arm sleep for minutes, so most of a night's movement was lost. While bedtime mode is on (BedtimeMonitor: the vendor's own switch where the watch has one, a BedtimeSignal of sources, which is Samsung's setting_bedtime_mode_running_state in vendor/samsung/SamsungBedtimeSetting, falling back to Do Not Disturb, which counts only from 21:00 to 09:00 local, BedtimeWindow, so a Do Not Disturb or theater mode left on by day is no night), or SleepHold (pure, from OpenVitals) sees sleep starting from the closed minutes (ten still, worn minutes with a falling pulse), and the watch is worn and off the charger, the recorder holds sleep (a phone unlock, PHONE_ACTIVE, ends an automatic hold). By default the hold is synced wherever the heart rate sensor is a wake-up sensor: no lasting lock, SensorWakeSync flushes the accelerometer, barometer and step counter at each heart rate batch. Where the sensor cannot wake the watch, or the wearer or the phone chose it (WearSettings.syncedSleepHold; a choice is kept apart from the default, and the phone writing another setting is not one), the hold is a partial wake lock renewed once a minute with a ten-minute timeout (BedtimeHold); a synced hold also falls back to the lock while the heart rate is not dense from the sensor. SleepHoldBudget counts the minutes held per day, lock and synced apart, for the debug protocol: today's figures in every snapshot, a SleepHold day line per finished day and an over_budget line when the lock passes two hours. The rest of the day it holds nothing. NightHrvRecorder measures heart rate variability at night: while bedtime mode holds the processor and the last ten minute rows show a still arm, it listens for five minutes, at most every 30 minutes, to an HrvWindowSource: Samsung's raw PPG (PpgWindowSource, com.samsung.sensor.hr_raw under the heart rate grant, unbatched), whose beats PpgBeats finds, or, chosen on the status screen of a watch that has the Samsung Health Platform, the platform's own intervals (SamsungIbiSource) or its green PPG (SamsungPpgSource, tracker PPG_CONTINUOUS, analysed by the same NightHrv as the raw PPG; see samsung-health-and-privacy.md); HrvRmssd (pure) turns either into an RMSSD, and the window is stored as one HV row only once the minute rows that cover it show the arm stayed still (NightHrvSchedule). A watch without the sensor does not announce hv. The phone writes each window as a HeartRateVariabilityRmssdRecord (WearOsSeriesSync, by the watch's cursor, the time cursor handing over on the first pull, as for the breathing rate and SpO2), keyed on its start; without the write grant the windows stay on the watch and the sync card asks for it. HeartRateRecorder runs at the plan WearAppService gives it (HeartRateSchedule, pure, from OpenVitals): the full rate in bedtime mode, otherwise the day setting on the status screen (WearSettings): every 10 seconds, batched, or power save, a window about every 10 minutes on AlarmManager.setAndAllowWhileIdle (HeartRateAlarmReceiver) that closes at the first usable reading. Only the full rate from the sensor counts as dense for the sleep minutes and keeps the step counter non-waking. On a watch with the Samsung Health Platform the heart rate can come from it instead (SamsungHeartRateFeed, see samsung-health-and-privacy.md). Debuggable builds keep a measurement protocol (DebugProtocol, DebugSnapshots): a JSON line at each battery percent and each screen, Doze, charger or plan change, with per-sensor delivery counts, plus events from the heart rate, the Samsung feed and the HRV windows. At each service start it writes a device line (SensorReport): every sensor's type, name, vendor, FIFO sizes (reserved and maximum) and wake-up flag, the batching profile the recorders use (hub-40s: one 40-second report latency, tuned on the Galaxy Watch7 and Watch8 hub; BatchingProfile in :wear:recording-core holds it, decided once from the watch's sensor list, WatchHardware, a list of SensorFacts with each sensor's place, type, waking flag, buffer sizes and reporting mode: the latency the heart rate, the accelerometer, the barometer and the step counter share, and the variant each takes, so no recorder holds a latency or asks the platform for a default sensor; they register through SensorPort, AndroidSensorPort over the platform, which reads the list once and registers by a fact's place in it; a test drives a recorder through a port of its own, FakeSensorPort, on the recorder's own thread: StepRecorderTest, SensorWakeSyncTest, BatchedRecordersTest), and whether the Samsung sources are there (the Health Platform and its version, the raw PPG sensor, the bedtime-mode setting, the diagnostics consent); each recorder's registration is a registered line with the variant it took, its sampling period and its report latency (DebugProtocol.registered). The same facts leave a release build too, as structure: SensorReport.report builds a WearLinkHardware.Report (:wearlink: the watch and the app, each sensor in the watch's order, the registrations SensorPort holds now, the vendors' facts; no reading, time, setting or grant, and nothing that names the wearer or this one watch), the watch shows it under Settings, This watch (features/settings/HardwareScreen, route hardware, read off the main thread when the screen opens), and the link serves it as GET_HW to a phone, a watch announcing hw; its HW lines are also how a watch is kept as a test fixture. On the phone WearOsNodePort.pullHardwareReport asks a watch that announces hw, WearOsHardwareReportText (pure) makes the text of it, the readable lines and then the report as the watch sent it, and the watch's panel shows it on a tap (WearOsHardwareReportCard): whole, before anything leaves, with Copy and Share, and dropped when the dialog closes. The panel shows the skin temperature and SpO2 switches by the series the watch announced in the hello its settings were read in (sk, o2; WearOsNodePort.announcedCapabilities, kept per watch in memory), not by whether it reports the Samsung platform: a watch announces a series where it has a source of it, whoever built the watch. scripts/wear-debug-report.py pulls it and prints the drain per state, the source answers, and per recorder whether a batch fits the sensor's FIFO. A batching profile tested on a watch without the Samsung hub is still to come. PpgRawLogger is a research spike for debuggable builds only: a long press on the status screen dumps Samsung's raw PPG sensor to a CSV; nothing depends on it, and the host-side inspection script was dropped in 2026-10. The service's foreground type is connectedDevice, plus health once the heart rate or step grant is in. Android 16 gates the sensor behind android.permission.health.READ_HEART_RATE, not BODY_SENSORS; WearPermissions picks the right one per release.

The phone's notifications (NT_PUT, NT_DEL, NT_KEEP, behind nt, which every watch announces) are PhoneNotifications (WearGraph.phoneNotifications), which the link's handler hands each line with the address of the phone that sent it. Its WearLinkNotifications.Assembler puts them together in memory, by phone and id; on the last line it posts the notification on the phone_alerts channel (importance high, with vibration on: a channel made without it only plays the sound, and its vibration cannot change once it exists), tagged phone under the phone's id, so an update replaces it: the title, the text (also as big text), the app's name as sub text, the phone's time with setWhen, local only, the monochrome launcher icon, no tap action. The same content again, as a batch the phone sent twice after a failed link, is not posted twice. The notifications of one app are one group, phone:<app name>, under a summary of their own (tagged phone_group, silent: GROUP_ALERT_CHILDREN) once it holds two, kept until the group is empty: the system takes a summary's notifications down with it, so one left alone keeps it. Each carries the delivering phone's address in its extras, and the class keeps it beside each id: NT_DEL and the reconcile take down only that phone's, and the reconcile reads the system's own list of what it shows, so it also clears what an earlier run of the app posted. For a phone whose last hello announced nb, kept in memory per phone address, each notification also carries its actions and a delete intent (PhoneNotificationActions): a button per plain action, titled as on the phone; a reply with a RemoteInput (setAllowGeneratedReplies, so the system offers voice, the keyboard and smart replies), labelled with the phone's title or else the watch's "Reply"; a call's answer and decline in the watch's own words; and the delete intent, which the system sends only on the wearer's dismissal: an app's own cancel passes sendDelete = false in NotificationManagerService, so NT_DEL, the reconcile and an update send none. Every intent goes to PhoneNotificationActionReceiver, which is not exported, with the phone's address, the id and the action's index in its extras. It holds the broadcast (goAsync) while PhoneWristSender, on a thread of its own, reads the token the watch holds for that phone (WearTrustStore) and dials it once (BluetoothPhoneDialer: createRfcommSocketToServiceRecord(PHONE_SERVICE_UUID), the hello, the request and the close within 8 s under a watchdog). A dismissal takes the notification off the class's list at once; after a button or a reply, the update the app posts within 30 s replaces it without a buzz; after a reply the notification is posted again without a buzz, the text sent shown under it (setRemoteInputHistory), so the system's reply does not wait on it; one the phone answers gone for is taken down. A ringing call from such a phone (a notification sent with an answer or a decline) rings as a call (PhoneCalls): on its own channel, phone_calls (importance high, a ring's vibration pattern, fixed once the channel exists), FLAG_INSISTENT so the vibration repeats while it rings, category call, ongoing, in no app group, no delete intent, setTimeoutAfter 90 s so a lost NT_DEL cannot ring on. It is posted with Notification.CallStyle.forIncomingCall (the title, else the app's name, as the person; the phone's decline and answer as CallStyle's own buttons, which CallStyle puts into the action list itself, so they are not added again) from Android 12 with both and a name, and otherwise, or when notify throws, as any phone notification on the same channel with its buttons, so a call is never lost; the debug protocol counts which (notifications.call.<call_style|plain|not_posted>). NotificationManagerService refuses a CallStyle that is not a foreground service's or a user-initiated job's and has no full-screen intent (checkDisqualifyingFeatures throws IllegalArgumentException back through notify), so every call has one, to PhoneCallActivity (also its content intent), and the watch declares USE_FULL_SCREEN_INTENT. Where full-screen intents are not granted (Android 14 and later, canUseFullScreenIntent, counted as notifications.call.full_screen_denied), fixNotification takes the intent off itself, marks the notification FLAG_FSI_REQUESTED_BUT_DENIED, which the CallStyle check accepts, and shows it as a heads-up that stays. PhoneCallActivity (not exported, singleTask in a task of its own, shown when locked) draws the caller, the app and the answer and decline the phone sent, on Wear's Material theme with Android's call colours; it follows the call (PhoneNotifications.watchCall) and closes when the call stops ringing on the watch, or when the ring's time is up. Its buttons send the notification's own intents. The wearer's answer or decline (acted) takes the call off the watch at once, so the ring stops before the dial; the call screen sent away (the system's swipe, or back) silences it on the watch only (silence), never declines it, and a call cannot be swiped in the list (Android keeps an ongoing CallStyle non-dismissible). A call stopped on the watch is kept on the class's list, so the same one sent again stays off; NT_DEL and the reconcile take it down and close its screen. A failed send is counted in the debug protocol (notifications.wrist.<outcome>) and dropped, never queued. Another phone's notifications have no actions, and a swipe clears them on the watch only. No notification text is written to disk; the system holds the posted ones in memory until they go, and a reply's text lives in memory until the phone has it. Robolectric's notification manager holds its tests (PhoneNotificationsTest, PhoneNotificationActionsTest and PhoneCallsTest, the last two through the receiver to a fake dialer, the last with the call screen and a notify that refuses CallStyle as Android does), and the watch's unit tests read its merged resources for the channel's name.

The watch's screens are one SwipeDismissableNavHost (OpenWatchWearApp): the dashboard and its tile editor (features/dashboard, tile_editor), a metric's detail (features/metric, the route metric/{metric}, which a dashboard tile opens), the quick log (features/quicklog: quick_log, with log_weight, log_blood_pressure and log_value/{type} for a value of one number (body fat, blood oxygen, breathing rate, body temperature, blood glucose, height: LogValueSpecs, each in the metric unit or an imperial one), picked with the stepper or the crown, and breathe, a guided minute that holds the screen on while it runs and is logged as a mindful session when it ends), the spot measurements (features/measure: the list, measure, and one measurement, measure/{measurement} by its SpotKind, which the list and the heart rate and HRV details open), the settings (features/settings: the hub, settings, which the dashboard opens, the phone, phone, the sensor access, sensors, and the recording settings, recording_settings, the watch's own WearSettings with a line each on what it does, through RecordingSettingsViewModel and RecordingSettingsPort, which the status screen held before), the status screen (features/status, status, the recording details the sensor access screen opens) and the workout (features/recording/WorkoutScreen), each a ScreenScaffold over a TransformingLazyColumn, so rotary input, the position indicator and the round screen's insets come with the list. Each feature package declares its own destinations, a NavGraphBuilder extension in its …Navigation.kt (dashboardDestinations, metricDestination, measureDestinations, quickLogDestinations, settingsDestinations, statusDestination, workoutDestination) that OpenWatchWearApp calls with the nav controller and the state, and what only the activity can do (ask for the grants, open the Bluetooth settings) as one ActivityActions from MainActivity, not a screen slot each; the routes stay in WearRoutes, in the root package, so one feature opens another's. The dashboard shows the tiles the wearer chose, in their order, those of them the watch offers now (WearUiState.shownTiles), so a chosen tile that is not on offer, a night's vital before its first reading, stays chosen and appears once it is. The tile editor lists only what the watch offers, the chosen tiles first with arrows that move one a place up or down, then the others to switch on, and a reset to the defaults; it is ChoiceEditor (ui/components), a generic editor of an ordered choice, and the edits are Choices in :wear:recording-core (a move trades places with the shown neighbour, so a hidden tile keeps its place). The quick log's editor (quick_log_editor, which the quick log's last button opens) is the same ChoiceEditor over every QuickLogItem; the choice is WearQuickLogPreferences (WearGraph.quickLog, preferences file wear_quicklog_prefs, key active_items: the QuickLogItem names joined by commas, WATER, WEIGHT, BLOOD_PRESSURE, BODY_FAT, BLOOD_OXYGEN, RESPIRATORY_RATE, BODY_TEMPERATURE, BLOOD_GLUCOSE, HEIGHT, BREATHE, never renamed; nothing stored is every entry in that order, an empty string none). The choice is WearTilePreferences (WearGraph.tiles, a StateFlow; preferences file wear_tile_prefs, key active_tiles: the MetricTile names joined by commas, so no MetricTile is ever renamed; nothing stored is the default tiles, an empty string none), changed through WearAppViewModel off the main thread, one change at a time under a lock. A tile opens the app at a screen by naming its route in MainActivity.EXTRA_ROUTE: MainActivity (launchMode="singleTask", so the running one gets it in onNewIntent) hands it to OpenWatchWearApp, which opens it over the dashboard once, and only a logging or measuring screen (WearRoutes.isDeepLinkable, pure and tested); a running workout still takes the screen and the request is dropped. What the screens offer follows what the watch has to measure with: WearGraph.sensors (WatchSensors, plain facts in :wear:recording-core: the heart rate sensor, the heart-beat sensor, the step counter, the barometer, the GPS receiver) is read once, off the main thread, from the facts the recorders and the link already go by (LiveHeartRate.hasSensor, StepRecorder.hasStepCounter, AscentRecorder.hasBarometer) and the GPS feature. The dashboard offers every metric from the phone or logged by hand, a day's metric the watch records itself where its sensor is there or a reading of it is, and a night's vital once a reading is (MetricOffer, pure); a workout shows the fields its sensors give and whether it records a route (workoutFieldsOf), and a sport with a route asks for location only on a watch with a GPS receiver. A spot measurement runs in SpotMeasurements (root package, WearGraph.spot), never in a screen: MeasureViewModel collects spot.run(kind), a flow of live values and waits that ends in one reading or one reason (SpotEvent, SpotFailure), and each source is handed in as a SpotSensor, asked for when a measurement starts and only where WearGraph.sensors has its sensor: the heart rate through LiveHeartRate.listen, the heart rate sensor's second listener, unbatched and without the recorder's gate, since the wearer asked; for an HRV a window of three minutes from an HrvWindowSource of its own, chosen when it starts (WearGraph.spotHrvWindow): the Samsung platform's intervals through a second SamsungIbiSource over the same feed, waiting at most 20 seconds for its last batch where a night's waits twelve minutes, where the wearer chose them as the HRV source and the watch has the platform; else the single beats of the heart-beat sensor (HeartBeatWindowSource over HeartBeatSensor) where the watch reports them, else Samsung's raw PPG through a second PpgWindowSource (the night's holds one window's samples, so the two never share an instance), with LiveHeartRate.listen held for the window, since the raw signal likely gets light only while the heart rate sensor runs, and as the live pulse, and the accelerometer beside it (MotionSensor); an HRV is kept only when the arm stayed still (Stillness, else SpotFailure.MOVED), and while the night's HRV window holds the sensor (SensorClaim, shared with NightHrvRecorder, which in turn starts no window while a spot runs) a spot HRV refuses with SpotFailure.BUSY; the barometer once a second (PressureSensor), its own listener beside the ascent recorder's batched one; the blood oxygen, on a watch with the Samsung Health Platform only, from the platform's SpO2 tracker through a second SamsungSpotSource.spo2 over the same feed, under the oxygen saturation grant: the first completed reading since the start, within 45 seconds, SpotFailure.MOVED when the arm moved and none came; the platform starts its tracker for the first reader only, so the night's Spo2Recorder and a spot take turns through a SensorClaim of their own, and a spot refuses with SpotFailure.BUSY while the night's measurement runs. The rules are SpotRules in :wear:recording-core: the pulse settled once eight readings are a heart's, the median of the newest five, within 30 seconds; the HRV the RMSSD of the window's beats as health-calculations takes a night window's (HrvRmssd, on at least 60 clean beats where a night's five minutes need 100); the air pressure the mean of five readings and its altitude (AscentMinuteCounter.altitudeMetres). A running measurement's time fills an arc along the screen's edge (EdgeProgress), and its end buzzes the wrist (MeasureViewModel's onEnd, endCue: one pulse for a reading, two for a failure, none for one found before it ran). A metric's detail lists the five newest entries of its type made on the watch (features/metric/EntryHistory: the HRV, the weight, the water, a blood oxygen and a breathing rate logged by hand). A measurement holds a partial wake lock of its own (OpenWatch:spot) for as long as it may run, so it ends with its reading when the screen goes off, and a heart rate, an HRV or a blood oxygen is kept as an entry flagged m; the air pressure is shown, not kept. On a watch whose Samsung platform lists the trackers (vendor/samsung/SamsungTrackerTypes, asked when the wearer opens the measure list, not at the service's start, and kept, so the next reading of WatchSensors has it without waiting; WearGraph.withListedSpots adds it; the graph speaks of the platform's listed spots, PlatformSpots.listed, and SamsungPlatformSpots is the Samsung platform's), an ECG and a body composition run the same way under Samsung's additional health data grant: the ECG through SamsungSpotSource.ecg, thirty unbroken seconds (EcgRecording, pure), its trace sent as it grows (SpotEvent.Trace) and its heart rate and rhythm description (EcgHeartRate) shown, never kept; the body composition through SamsungSpotSource.bodyComposition, built for the body profile the phone sent (SpotFailure.NO_PROFILE without all four of height, weight, year of birth and sex), its progress and what the contact lacks sent as SpotEvent.Progress, a tracker without its calibration started again (BodyCompositionRun, pure), and its body fat, lean mass and body water kept as three entries flagged m. A heart rate or HRV first asks for the heart rate grant where it is missing, a blood oxygen for the oxygen saturation grant (Measurement.grant); the blood oxygen's detail offers its measurement as the heart rate's and the HRV's do. Each has one ViewModel built from the graph: WearAppViewModel the dashboard's, the metric detail's and the quick log's (one WearUiState: what WearReadingsSource reads from the store on the IO dispatcher every 30 seconds while a screen collects, and again soon after the steps' writes (MetricStore.updates), at most every 2 seconds, a day that is over only once; a day's night vitals (HRV, blood oxygen, skin temperature, breathing rate) are those of the night that ended on it, read from noon to noon (WearReadings.nightWindow), one value a night, and only last night's is shown as the value now; the week runs from the first day with data, a later day without any is no data, not a zero, and the daily average leaves out today's part of a day; a sampled metric's chart is a line over time in runs (WearReadings.line), broken where the watch has no reading, the heart rate's on the tile's quarter-hour buckets (TileDay.meanPerBucket), and the week's bars of a level start from a floor near their range (barShares); the heart rate's low, average and high are those of the day's samples, as on its tile, and its time in the zones is health-calculations' HeartRateZones.timeInZones over them, counted with the read on the basis the settings give (WatchPreferences.zoneBasis, null until the phone sends a maximum, and then no screen draws or counts zones), which the source follows, so a maximum or resting rate the phone sends is read on at once; a route whose name is no metric (WearRoutes.metricOf) goes back to the dashboard; the entries made on the watch join the state as they are logged, read again at the store's count for them: the water drunk is the water tile's daily total by the hour against a goal of two litres, the newest weight the weight tile's value however old, each day's last its bar, and a heart rate or HRV measured on the spot today the value now only where the watch's own recording has none (WearReadings, over EntryDays); the quick log shows the entries the wearer chose, in their order (WearUiState.quickLogItems), lists the newest six made by hand (a spot measurement's, flagged m, is not one) and logs through the view model, off the main thread), StatusViewModel (through StatusPort: the store's counts, the grants and the trust store, read on the IO dispatcher every three seconds while the screen is shown and again when it resumes), SettingsViewModel for the settings, the phone and the sensor access screens (through SettingsPort: the grants, read on the IO dispatcher when a screen starts and again when it resumes, the link's state, the unit system, and a phone allowed or blocked as on the status screen; the phone screen lists the phones with the status screen's phoneItems; a phone counts as connected while one is allowed, still paired and the link listens) and WorkoutViewModel (the WorkoutState the recorder publishes, its actions through WearAppService, the zones' basis from the same settings flow, and a saved workout's figures, WorkoutFigures in workout/: WorkoutMetrics over the workout and the heart rate the store keeps, the zones and the body profile the phone sent, read by the workout's start off the main thread). The screens collect with collectAsStateWithLifecycle. The settings are WearGraph.settings, a StateFlow that WearSettingsState keeps in step with the preferences file, so a setting the phone changes over SET_PREF shows at once. The unit system is one of them (WatchPreferences.unitSystem, key unit_system, a UnitSystem name, written only once the wearer chooses on the settings hub; not a link token): every screen shows its readings in it (WearUiState.preferences), and so does the quick log tile. A running workout, or a saved one whose summary is open, brings the workout destination forward when the app opens or the watch face pill is tapped. Stop asks "End workout?" and then whether to measure the heart rate recovery: with a yes WorkoutRecorder keeps isRecovering for two minutes after the stop (an input of RecorderPlan, so the heart rate stays live from the sensor, and a partial wake lock, OpenWatch:recovery, holds the processor), puts the heart rate now into WorkoutUiState.recovery (RecoveryState) while RecoveryScreen counts down, then works the falls after one and two minutes out from the stored readings (WorkoutMetrics.recovery) and the summary shows them; the pill says "Recovery" meanwhile (WorkoutPillKey.recovering). Whether to ask is RecoveryPlan (:wear:recording-core, pure): only with zones from the phone and a heart rate in the light zone or above (RecoveryAtStop.LIVE); after a minute of rest before the stop, from a peak in those zones, the recovery is read from the moment the arm came to rest without asking (RecoveryAtStop.FROM_REST: RestDetector over the workout's own accelerometer listener, which WorkoutTracker.restRecovery turns into a RestRecovery, and which WorkoutRecorder works out at the stop from the stored readings with the same WorkoutMetrics.recovery, so it needs no live phase); otherwise nothing is asked. The rest still counts for 15 seconds after it ended, the reach for the watch to stop it. The accelerometer runs at the sleep minutes' own five readings a second, so the shared sensor runs no faster, unbatched while the workout runs, which makes the sleep minutes' batches come unbatched too; the workout's wake lock holds the processor anyway. A run or a ride with a route pauses and goes on by itself (AutoPause, pure, from the GPS fixes' speed, which arrive in a pause too; the pause starts at the last movement; WorkoutTracker.autoPauseStep at each tick, with a buzz; a pause the wearer made is never undone), unless the auto_pause setting is off. ActivityDetectionMonitor (workout/, WearGraph.detection, started and stopped by the service) looks at the last three hours of step minutes at each write of steps, and, once the phone has sent a maximum heart rate, at each write of heart rate (MetricStore.updates, at most once a minute, on the IO dispatcher: no timer, no wake-up; a ride writes no steps) and, where ActivityDetector (pure) sees ten minutes or more of a brisk walk or a run that no workout covers, or of a ride (a raised heart rate with few steps; read from the last offer or workout on) and auto_detect is on, offers it once in a notification (channel detected_activity, id 5; 1 is the link's, 2 the phone requests', 3 the workout pill's, 4 the sync reminder's; the phone's notifications are tagged phone and their app groups' summaries phone_group, so their ids, the phone's own, never meet these; a ringing call is one of them on the phone_calls channel, beside phone_alerts) whose Record action (ActivityDetectionReceiver) starts the workout at the walk's start, at most three hours back: WorkoutRecorder.start credits the step minutes and the heart rate the store kept since (WorkoutTracker.credit), and the workout's start, its rows' key, is that start. The settings auto_pause and auto_detect (WatchPreferences.autoPause, autoDetect, both on by default) are the watch's own, not link tokens. The workout itself is saved at the stop, so a recovery lost with the service loses no workout, and the checkpoint carries nothing of it (a credited start is its start and its steps are in its steps; an automatic pause is a pause); while a workout runs its screen observes the ambient state (WorkoutAmbient over ui/ambient/AmbientAware, Wear Compose's AmbientModeManager, only where the Wear SDK's ambient service is present, and only while it is composed) and draws a dim layout without seconds or live values, in the wearer's unit system; a running spot measurement does the same through AmbientAware, its name, a dash for the value and what to do. The interactive layout leaves composition meanwhile, so the page the wearer is on and an open "End workout?" are remembered above it (rememberRecordingScreenState) and are there again when the watch wakes. That layout is a HorizontalPager of pages (the controls, the overview, the heart rate zones, the pace), each a centred column that scrolls, by touch and with the crown, only when its rows do not fit the screen. The app targets API 36, so on Wear OS 6 every other screen stays visible, dimmed, in ambient mode too; the ongoing activity keeps the system from returning to the watch face during a workout.

The watch's tiles share one base, OpenWatchTileService (MetricTileService.kt): it reads the process's one MetricStore (WearGraph.store, never a store of its own) on the IO dispatcher, shows a tile that says so when the store cannot be read rather than the system's error tile, lays the tile out in protolayout-material3's materialScope, serves its own resources, and keeps a tile current for five minutes. The metric tiles (Heart rate, Steps, Floors) are MetricTileService subclasses in MetricTiles.kt, its chart part. The Today tile (MainVitalsTileService) shows the steps and the heart rate side by side, read through the same functions as those two tiles, with an edge button that opens the app. The quick log tile (QuickLogTileService) draws today's water (readWaterToday, every glass from midnight) as a ring toward the day's goal, with a button that logs a glass on the tile, a shortcut to a heart rate measurement where the watch has the sensor (WearGraph.sensors) and one to the quick log; the shortcuts open the app at their screen. The glass goes through EntryLog, and the button's click id carries a count (preferences file quick_log_tile, key add_water_clicks) that moves on before the glass is logged, so a request that repeats the id of a tap already logged, a refresh, logs nothing. No tile starts a sensor, and only the quick log tile writes. A tile's preview in the picker is a 1:1 PNG in drawable-nodpi and drawable-round-nodpi (lint's SquareAndRoundTilePreviews; the three metric tiles' round copies are still baselined). TileDay (pure) cuts today from local midnight to the next into quarter hours on an elapsed-time axis, so a 23- or 25-hour day keeps its hour marks where those hours fell and the line ends at now; the floors go through AscentCredit.creditedPerMinute in health-calculations, the rule the phone's WearOsFloorsImport uses, so both count alike. TileChart draws the day's curve into a PNG, styled like the phone's BodyEnergyPlot. A tile names the PNG's hash and size as its resources version and keeps the PNG under that name in the cache directory (the four newest per tile), so onTileResourcesRequest serves exactly that image; when it is gone, the service asks Wear OS for the tile again instead of drawing a different one under the old version. Two choices are deliberate, both from a Wear OS 4 watch, and hold for every tile: a plain TileService with its own resources request rather than Material3TileService, whose images inside the tile never reached that renderer, and the value in a plain font rather than the Material 3 display and numeral styles, whose variable font made the renderer drop the text. The chart is a PNG of unspecified format, not raw ARGB pixels, because the latter need a newer renderer than Wear OS 3. The heart rate, steps and floors complications (MetricComplications.kt, SuspendingComplicationDataSourceService from androidx.wear.watchface:watchface-complications-data-source-ktx, with its unused androidx.preference left out) read through the same functions as those three tiles (MetricReads.kt: readHeartRateNow, readStepsToday, readFloorsToday), on the IO dispatcher, and answer a short text, the steps also a ranged value against 8,000 steps (health-calculations' default goal, MetricDailyGoalKey.STEPS; the watch has no goal setting); the manifest asks for an update every 300 seconds. Their class names are on users' watch faces: never renamed.

The UUID and the protocol words come from :wearlink on both sides. Verified on 2026-10-07 with a Galaxy Watch8 and a phone that never ran Galaxy Wearable: the watch accepted a plain second-phone bond, and the ping answered.

devices/xiaomi

The Xiaomi Body Composition Scale S400. The scale takes no connection: it broadcasts each weigh-in as MiBeacon v5 frames in the service data of 0xFE95, sealed with AES-CCM under a bind key the Xiaomi account issued when the scale was paired. The user pastes that key once; the app never sees the account.

Its platform half is the module :devices:xiaomi (devices/xiaomi, an Android library, namespace tech.mmarca.openwatch.devices.xiaomi), every file of the table below but the codec, in the app's package devices/xiaomi. It depends on :devices:core and its own codec (api), :wearlink for SecretSeal, WorkManager and Hilt, and on no other family. It binds itself (XiaomiScaleModule): its family as XIAOMI in the DeviceFamily map, XiaomiScaleListener as a CompanionPresenceObserver, SystemScaleScanRadio and ScaleListeningForeground to their ports, the one XiaomiScaleStore, and its startup actor (scale listener). Its manifest declares ScaleScanReceiver and ScaleListeningService, merged into the app's under the same names; WorkManager's ScaleListenerWorker keeps its name. It owns the weigh-in table's contract, data/repository/contract/ScaleWeighInRepository (test fixture FakeScaleWeighInRepository), which the app's Room implementation keeps implementing (ScaleWeighInRepositoryImpl, bound in di/RepositoryModule), and takes the registry and the body profile as contracts (DeviceRegistry, BodyProfileRepository). The notification's two strings are its own, with their translations; the notification icon is :devices:core's. What the Scales screens use stays public: the listener (status, find, set up, rename, release), the store and its config, the writer and ScaleWriteFailure, ScaleWritePermissions, ScaleListenerStatus. Its tests run on the JVM in the phone gate (:devices:xiaomi:testCiUnitTest), over the shared fakes.

Layer Files
Decoding, transport-free AesCcm (RFC 3610 on the AES block cipher: Android ships no CCM), S400Beacon (header rules, nonce, the weigh-in object, the scan-filter bytes), XiaomiDevices (isXiaomiScale): the module :devices:xiaomi:protocol (devices/xiaomi/protocol), plain Kotlin with explicitApi(), linted as in the app. The scan filter type, devices/core/ServiceDataFilter, is :core:model's, since the companion pairing builds its dialog's filters from it too
Health Connect mapping S400WeighInImport (record kinds, ids, record time)
Listening ScaleScanRadio (the S400's filters and PendingIntent on devices/core/ble/BleScanner's background scan; devices/core/pairing/CompanionDevicePairing builds the dialog's filters), ScaleScanReceiver, XiaomiScaleListener (also the CompanionPresenceObserver), ScaleListeningService and its ScaleForeground port, ScaleListenerWorker, ScaleLog
Pipeline ScaleWeighInIngest (decode, fold into Room, write), ScaleWeighInWriter (Room to Health Connect, retries, delete)
Family XiaomiScaleFamily: the scale is a registry row of kind SCALE and integration XIAOMI, kept by XiaomiScaleListener beside the store (made at set-up, adopted once at start for a scale set up before, renamed and removed with it). It syncs and streams nothing; its link is up while the scan runs. One scale: setting up another replaces it
State XiaomiScaleStore (key, sealed by SecretSeal; address, user slot, last failure)

Notes worth carrying:

  • The scan is the system's, started with a PendingIntent. It outlives the process, and the system starts ScaleScanReceiver for each broadcast that passes the filter. The filter is matched in the Bluetooth chip: 0xFE95 service data, the product id, the "encrypted object" control bits, and the scale's address once known. The scale's idle beacons and a neighbour's scale wake nobody.
  • Measured on an S400: the scale advertises idle beacons from the moment someone steps on, and sends the result only once it has finished measuring, as two frames repeated for about a second each, some twenty seconds in. Its timestamp is true UTC. A scale that does not recognise the person shows "----" and broadcasts no result at all. The S400 Pro (MJTZC03YM) sends the same two frames, but marks the second one's missing weight with every weight bit set rather than none; S400Beacon reads both as no weight.
  • Two seconds on the air is too short for a background scan, which the system runs a tenth of the time, and a twentieth with the screen off on Android 13 and later. So adding a scale goes through Android's companion dialog (XiaomiScaleListener.findScale, CompanionDevicePairing.discover): it lists the S400s it hears, and the one picked is associated and watched for presence, which is also how the app learns the scale's address and advertised name. allowSystemWake asks again for a user who revoked that in Android's settings. When Android reports the scale awake, the listener opens a window of WEIGH_IN_WINDOW_MILLIS: it starts ScaleListeningService, a foreground service that runs no logic, restarts the scan so it runs at foreground speed from its first moment, and closes both when both frames are in or the window runs out. Verified on a dozing Pixel with the process dead: wake at 0 s, both frames at 23 s. Android tells only the app's primary companion service, OpenWatchCompanionDeviceService, which is why that one passes the event to the observers.
  • Each frame is still folded into its row as it arrives and the weigh-in is written again if it grows, so a frame missed on a phone that was not woken, or on Android 10 and 11, still saves what was heard.
  • Room comes before Health Connect. The scale says each weigh-in once, and a background write cannot ask for a permission. A weigh-in Health Connect has not taken stays pending and is retried on the next frame, at app start, by the worker and when the Scales screen opens.
  • A weigh-in is (scale timestamp, user slot). Record ids are built from those two and from no address, since ids travel to other phones. clientRecordVersion is the row's updated_millis, so a fuller rewrite replaces the earlier records.
  • Only what the key authenticates counts. An unsealed object is ignored, and the first sealed frame the key opens says which of the scale's user slots is this person's. A frame from another slot is someone else's body: it is dropped, and only the slot number is kept so the screen can offer to switch. A new key (the scale was paired again in Xiaomi Home) keeps the scale: its address is its identity.
  • A reboot, or Bluetooth going off, drops the scan, and no broadcast tells a closed app that Bluetooth is back. XiaomiScaleListener arms it again at every process start, and ScaleListenerWorker every half hour.
  • Android 12 and later listen with the app closed. Android 10 and 11 would need background location for that, which the app does not ask for, so there weigh-ins arrive while the app is open.
  • Body composition is an estimate from Sun et al. (2003) in health-calculations' insights/BioimpedanceComposition, not what the scale displays. No basal metabolic rate is written: a second source would evict BmrEstimateService's daily estimate on weigh-in days.
  • Never log the key, a decrypted payload, a measurement or the address.

devices/blestandard

The devices that speak a Bluetooth SIG standard health profile, as one family, BLE_STANDARD: a heart rate strap (the Heart Rate Service, 0x180D), a blood pressure monitor (0x1810), a weight scale (0x181D) and a glucose meter (0x1808), each by the service it advertises, the measuring ones before a heart rate. It is the first family built on the foundation of Phase 5, and the strap needed nothing outside its module, its Hilt binding and its permission rows: the app's add flow, Home's "Other devices" list, the generic device panel, OpenLink and the measurement sink take it from its contracts. The other three are pushed devices on the same path; they added two record types (their catalog rows and permissions, their spans in ImportedRecordWrites.timeSpan) and made OpenLink's supportsRecording follow a family's live features rather than the kind.

Trust: the cuff, the scale and the meter are bonded (their profiles require it) and associated, so their readings come over an encrypted link from the device the user paired; the strap is unbonded, as its profile allows, and only read while someone collects it. A reading is parsed whole against its specification's layout or dropped, and logs hold counts and class names only.

Its bytes are the module :devices:ble-standard:protocol (devices/ble-standard/protocol, plain Kotlin with explicitApi(), in the package devices/blestandard): HeartRateMeasurement (the measurement, 0x2A37, read whole as the specification lays it out: flags, a uint8 or uint16 value, the sensor contact, the energy expended and the RR intervals in 1/1024 s); BloodPressureMeasurement (0x2A35: three SFLOAT pressures in mmHg or kPa, the time stamp, pulse, user and status), WeightMeasurement (0x2A9D: SI or imperial resolution, the unsuccessful value, time stamp, user, BMI and height) and GlucoseMeasurement with GlucoseContext (0x2A18 and 0x2A34: sequence number, base time and offset, the concentration in kg/L or mol/L read as mmol/L, the sample type and location, the meal and carbohydrate), over the IEEE 11073 SFLOAT and the Date Time layout (HealthValueFields); RecordAccessControlPoint (0x2A52: report all stored records, or those from a sequence number on, and the response code); ReceivedValue, how a pushed reading is kept, the bytes as sent with the phone's time and offset when they came (raw1;<millis>;<offset>;<hex>;<context hex>), so it is read again by the same parser; and HeartRateSamples (a clock minute's samples as the family keeps them until Health Connect has them, hr1;<offset>;<millis>:<bpm>,..., under the key hr_<first millis>, and HeartRateMinutes, which cuts a stream into those minutes). Its platform half is the module :devices:ble-standard (devices/ble-standard, an Android library, namespace tech.mmarca.openwatch.devices.blestandard), which depends on :devices:core and its protocol and on no other family, and declares no manifest component:

File What it holds
StandardProfiles The family's persisted names (BLE_STANDARD, the record id prefix ble_standard_) and the profiles' UUIDs, the Heart Rate and Battery ones taken from the app's BleUuids
ProfileRadio The port the family opens a link through (withLink(address, owner) { link -> }: has, enable a notification or indication, read, write, the values as a flow that fails when the link drops), and GattProfileRadio, its implementation over GattLink under the radio lease
HeartRateStream A strap's stream: one link per strap however many collect it (the device screen, OpenLink), held as LIVE while collected and five seconds after, dialled again ten seconds after a drop while collected. Each usable measurement (on the skin, above zero) is a LiveReading; each clock minute goes to the MeasurementSink as one run, and the minute under way when the stream stops. The battery level is read once per link
StandardMeasurementRecords The family's MeasurementRecords: a run is one HeartRateRecord, auto-recorded by a chest strap; a cuff's reading a BloodPressureRecord and its pulse a HeartRateRecord; a weigh-in a WeightRecord by a scale; a glucose record a BloodGlucoseRecord (its specimen source, its relation to a meal and the meal from its context), none for a control solution check. Every id is ble_standard_<key> salted by the device. A reading's time is the device's own wall clock read in the phone's offset when it came, or the time it came when the device sent none, one its clock does not know, or one more than ten minutes ahead
PushProfile The three pushed profiles by the kind their devices are registered as (BLOOD_PRESSURE_MONITOR, SCALE, GLUCOSE_METER): the service, the measurement, and the key a reading goes under, its user and its own time stamp (bp_<user>_<yyyyMMddHHmmss>, weight_...), or for a glucose record its sequence number and base time (glucose_<sequence>_<stamp>)
MeasurementCollector The CompanionPresenceObserver the family binds: when an associated cuff, scale or meter comes into range, it dials it under the SYNC lease, switches its measurement on (indications) and takes what it sends until it falls quiet for ten seconds, hangs up, or ninety seconds pass; a meter is asked through the control point for its records from the one after the last it gave (glucose.last_sequence in device_state), all of them the first time, until it answers. Every reading goes to the sink, kept before it is written; what came before a drop is kept too. A device that names a user is one person's: the first id it names is kept (user_id), a reading of another is left out, and the unknown user (0xFF) is anyone's
StandardDeviceFamily The family and its DevicePairing: a device that advertises the Heart Rate Service is offered as a SENSOR; pairing asks for no bond and no association (the profile needs neither, and the strap is read only while collected) and registers it with the HEART_RATE capability, as the registry has always kept a sensor. Its feature is LIVE_HEART_RATE. A cuff, a scale or a meter is bonded and associated (a refused association pairs nothing, and drops the bond the pairing made), registered, and read at once while it is awake; it has no feature. Forgetting one drops its stream, what it kept, and for a pushed device its association and bond
BleStandardModule Binds the family and its mapping by BLE_STANDARD, the collector as a presence observer, and the radio

The RR intervals a measurement carries are read and tested, and written nowhere: Health Connect has no beat-to-beat record, and a variability figure from them would be a health calculation, which belongs in health-calculations. Health Connect refuses a systolic pressure over 200 mmHg and a diastolic one over 180, and a glucose level over 50 mmol/L: such a reading gives no record and is dropped. A meter whose memory was cleared starts its sequence numbers again, and is asked from the last one it gave, so its new records come only once it passes that number. Android tells an app a companion device appeared from Android 12 on; before it, a pushed device is read only at pairing. The family's tests run each profile end to end over a fake radio (FakeProfileRadio) into the real DeviceMeasurementSink and FakeHealthRecordStore; nothing of it has run against a strap, a cuff, a scale or a meter.

devices/notifications

In :devices:core, with devices/media (PhoneMediaSource and the media sessions it reads through the listener's component), devices/weather (the generic-weather broadcast, its receiver and WeatherStore) and comaps: the phone's sources a watch relays, vendor-neutral, so a second family relays them without reaching into Garmin. The listener and the weather receiver are declared in that module's manifest under their names, and Diagnostics reads its build config's OPENWATCH_DIAGNOSTICS, set as the app's is. That the filter's category numbers follow Garmin's enum is the app's NotificationCategoryParityTest, the one place both are visible.

OpenWatchNotificationListenerService is the platform NotificationListenerService. It reads posted notifications, filters them through the pure NotificationFilter against the one setting of what to forward (WatchNotificationPrefsStore, which the screen, the listener and every family's sink read; the listener's old copy is adopted once and dropped), keeps each one a wrist action may still reach in the memory-only NotificationStore (64, as many as the Garmin watch's handler keeps answerable), and hands it to every NotificationSink that has a watch to send to (NotificationHandOff). The sinks are a set each family binds @IntoSet in its own module, GarminNotificationBridge and WearOsNotificationRelay; with no sink holding a watch, nothing is captured. Every sink gets every message and queues it in its own PendingNotifications (20, the oldest dropped), so no family drains or clears another's, and a sink that throws keeps none of the others from it. The listener touches no Bluetooth; each family owns its forwarding. What a wearer chooses on the wrist (a dismissal, an action, a reply through RemoteInput) is carried out on the phone by NotificationActions, which every family shares: Garmin's over its notification link, a Wear OS watch's over the phone's wrist listener (WearOsWristRequests). An action that opens an activity, which only a Wear OS watch's call answer reaches, is sent with ActivityOptions that lend the phone's own right to start an activity from the background (setPendingIntentBackgroundActivityStartMode: MODE_BACKGROUND_ACTIVITY_START_ALLOW_ALWAYS from Android 16, which deprecated MODE_BACKGROUND_ACTIVITY_START_ALLOWED, the mode on 14 and 15; nothing below 14, where a sender's right went with its intent unasked). A sender's right counts only when it opts in from Android 14, and ALLOW_ALWAYS is the mode that also lends a companion app's right while the app is not visible; the right itself is the companion association's. Every other intent is sent as before. The listener enumerates the actions in one place (wristActionMessages, over wristActions), the call's repeats marked there (above). The settings screen is every watch's (WatchNotificationAppsScreen in :feature:device, route WatchNotifications, which a family's panel opens); its gateway tells every sink of a change (NotificationSink.onConfigChanged). Nothing is written to a file or a database.

Hilt wiring

A device family that is a Gradle module of its own binds itself (the owner's decision 4, 2026-11, which reversed the rule that only di/DevicesModule.kt bound the layer): its Hilt module, @InstallIn(SingletonComponent::class) and in the family's package, binds its family into the DeviceFamily map under its persisted name (@StringKey, which DeviceFamilies checks against the family's id), its sync port and presence observer @IntoSet, its ports and stores, and its startup actors. Hilt and KSP run in the module, so the app's graph installs the module from its classes; the app names the module in its build file and nowhere else. :devices:garmin's is GarminModule, :devices:wearos's WearOsModule, :devices:xiaomi's XiaomiScaleModule, :devices:ble-standard's BleStandardModule.

di/DevicesModule.kt binds what every family shares and the families still in the app: BleWatchPairing to WatchPairingPort, DeviceMeasurementSink to MeasurementSink with the families' MeasurementRecords map (@Multibinds, so none is needed) and its startup actor, RegisteredFamilies (the families' persisted names, from the map's keys through providers, which the registry reads its rows against), AndroidSyncWakeLock, the composite DeviceSyncPort over the set, the classifiers in their order, the schedule's startup actor, and the auto-sync interval store (every watch's interval is kept in the Garmin store, under its old key). The app's RepositoryModule binds the contracts the device modules take to the app's implementations: DeviceRegistry, DeviceStateRepository, BodyProfileRepository, ActivityRepository, GarminWellnessRepository, GarminSleepMinuteRepository, GarminActivityPreferences, ScaleWeighInRepository, WearOsSyncPreferences. Everything else is constructor injection. Only :app and the device modules declare Hilt modules: not the app's devices/ packages, not :devices:core, a contract or a protocol module. A device module depends on no other device module, no feature and not on the app. DevicesLayeringTest holds the three (and that each device module binds its family), and HiltGraphTest that every family, sync port, presence observer and classifier is in the built graph.

The BLE discovery scan the add-a-device flows use lives in sensors/ble (:devices:core), trimmed to discovery: a family that streams a sensor live (a heart rate strap) opens its own link through GattLink and hands its readings out as DeviceFamily.liveReadings, which the device screen and OpenLink collect.

Two ways in: pairing and pushed measurements

A family whose devices need no flow of their own (no bind key, no watch app) declares a DevicePairing on its DeviceFamily: the services its devices advertise, which scanned device it claims and as what kind, and how one is paired (a bond, a companion association, then its registry row). The app then lists its devices in Home's "Other devices" section and pairs them through one generic dialog, and opens them on the device screen with the generic panel (features/watches/generic/GenericDevicePanel): the live heart rate while the screen is open, when the family streams one, and what the device pushed that waits for Health Connect, with the grant that would let it. The section shows nothing while no family declares a pairing.

Data reaches Health Connect two ways. A watch is pulled: DeviceSyncPort. A device that pushes (a cuff that indicates a reading, a meter or scale that hands over what it stored, a strap that streams, a Garmin watch's hydration widget) gives each measurement to the MeasurementSink: DeviceMeasurementSink (:devices:core, devices/core/measure) keeps it in the device's own device_state first (key measurement.<its key>, value the family's payload; it goes with the device), then reads every kept one back through the family's MeasurementRecords (bound @IntoMap @StringKey by family id; the app declares the map with @Multibinds), writes in one batch through the record sink what the grants allow, forgets what was written and stamps the device's last sync. One whose first record's grant is missing stays kept, the grant named in backlog; one that gives no record is dropped; a failed write keeps them all. The next measurement, the device screen (on a grant) and every start (pending measurements) try again. The family builds each record's clientRecordId from the measurement's key, salted by the device (saltedRecordId), so a measurement handed over twice is one record. It is the S400 pipeline's rule, Room before Health Connect, for any family; the S400 keeps its own table.

Phone modules

Who depends on whom (api where a module's signatures carry the other's types):

:app (the shell)
  -> every :feature:*, every :devices:<family>, :link-host, :core:*
:feature:home, :feature:healthconnect, :feature:settings, :feature:connectedapps
  -> :core:ui, :core:data; :feature:settings and :feature:connectedapps also :link-host
:feature:device            the screens every family shares, and the contributions they take
  -> :core:ui, :core:data, :devices:core (api)
:feature:watches-garmin    -> :feature:device, :devices:garmin, :core:ui, :core:data
:feature:watches-wearos    -> :feature:device, :devices:wearos, :core:ui, :core:data
:feature:scales-xiaomi     -> :feature:device, :devices:xiaomi, :core:ui, :core:data
:link-host                 -> openlink:host (api), :core:data (api), :devices:core, :core:ui
:core:data                 -> :core:health (api), :core:devices-api (api), :core:model (api)
:core:ui                   -> :core:health, :core:model (api), Compose (api)
:core:health               -> :core:health-api (api), :core:devices-api (api), :core:model (api), :devices:core
:devices:<family>          -> :devices:core (api), its :protocol; never a screen, never another family
:devices:core              -> :core:devices-api (api), :core:health-api (api), :core:fit

A screen module never depends on a device family, except a family's own screens, which depend on that family and are named for it (feature/<screens>-<family>); DevicesLayeringTest holds both rules, and no screen module depends on the app. A generic screen reaches a family's through the contributions in features/device/DeviceContributions.kt (Device Layer). A device module holds no screen. A route a screen reads back with toRoute is declared in that screen's module, in the package navigation, so its serial name is the one it always had (DeviceDetail and WatchNotifications in :feature:device, the Garmin screens' four in :feature:watches-garmin); the app's navigation/ declares the rest, the titles and the graph, and the R8 keep check reads every screen module's sources beside the app's.

What :app still holds, and why: OpenWatchApp, MainActivity and the two Health Connect activities (the manifest's entries), the navigation (the graph, the list-detail layout, the roots' routes), features/home/HomeRoute.kt (it fills Home's slots with each family's section, which only the app sees), the Hilt modules of di/, core/security/KeystoreSecretKey (the key the Hilt root seals with), and in data/repository what joins a family's own contract to :core:data (the Garmin and scale tables over their DAOs, the Garmin and Wear OS preferences over OpenWatchPreferences): :core:data depends on no family and a family on no core module but its contracts, so the app is where the two meet. Its tests are the architecture tests, the Hilt graph, the routes, the add-a-watch flow over both watch families' pairings, and the instrumented tests, which run against the app's own APK.

A screen module's strings live in its own res, every translation with its key; a string two screen modules share is :core:ui's, or :feature:device's when only a family's screens and the device screen share it.

Modules :core:model and :core:fit

The app-local code that nothing in the rest of the phone app sits below, in two pure-Kotlin modules (openwatch.jvm.library, JDK only, no Android):

  • core/model (:core:model): the packages domain/model (the device, sleep-minute, scale and activity models), domain/preferences (the unit and theme choices, and the SystemUnitSystemProvider interface) and core/geo (coordinate parsing); the plain values the device protocols take from the platform sources, devices/weather/WeatherSnapshot and devices/notifications/NotificationMessages, and the scan filter devices/core/ServiceDataFilter; and in core/performance RunSuspendCatching, the injected DispatcherProvider and the @ApplicationScope qualifier, which the device modules inject as the app does (it takes coroutines as api and javax.inject for the qualifier). The calculations it once held (the sleep and walking estimators, body composition, workout energy) are health-calculations', which it takes as an api dependency, since the activity models carry its route and lap types.
  • core/fit (:core:fit): the FIT container codec, package core/fit: the decoder, the encoder, the CRC, the 16-bit float. What a record means stays with the code that reads it.

Package names are unchanged, so an import does not say which module a class is in. :app depends on both. The one piece of domain/preferences that reads the platform, the locale's measurement system, is the app's core/presentation/LocaleUnitSystemProvider, bound to the interface in di/AppModule. Nothing in either module is injected: they hold no Hilt module, and their classes are constructed by the app's repositories and the app's di/ modules.

The wear sleep fixtures the app's Wear OS sync tests use are health-calculations' test fixtures (testFixtures("tech.mmarca.healthcalculations:health-calculations")); these modules have none of their own.

The modules exist for the build and for the boundary: a change elsewhere leaves their compile and test results in the build cache, and the compiler, not a test, keeps Android and the rest of the app out of them. Their tests are plain JUnit (:core:model:test, :core:fit:test, in verifyCiUnitTest, as are :core:devices-api:test, :devices:garmin:protocol:test and :devices:xiaomi:protocol:test; :core:health-api, an Android library, runs testCiUnitTest and lintCi), and Android lint still checks them, the contracts and the protocol modules (com.android.lint with the app's rules, each module's lint in verifyCiLint), without its API-level check (see development.md). What does not belong here: anything with an inbound dependency from data/, healthconnect/ or features/, resources, and Hilt wiring. The architecture ratchets walk them through LibraryModuleRoots in the app's architecture tests, and LibraryModuleRootsTest fails on a module under core/ or devices/ that is not listed there.

Shared module :wearlink

The phone-to-watch link, in wearlink/, pure Kotlin on the JDK with no Android dependency, compiled into both :app and :wear. It exists because both apps need exactly the same protocol and the copied file it replaced was held in sync only by a test. Package tech.mmarca.openwatch.wearlink:

  • WearLinkProtocol — the line grammar over the RFCOMM socket: words, limits, the SM row type and every format and parse function. The SM fields are specified in sleep-minute-features.md.
  • WearLinkPreferences — the watch settings the phone reads with GET_PREF and changes with SET_PREF: their keys and values, opaque tokens on the wire, and the read-only keys that say what the watch can offer.
  • WorkoutMetrics — what a workout comes to, the watch's summary and what the phone writes being one number: the time-weighted mean and the highest heart rate, the time in zones, the TRIMP, the energy, the kilometre splits, the VO2max and the heart rate recovery after the stop with its verdict (HeartRateRecoveryQuality: clean, approximate, not comparable, invalid, no data), each health-calculations' (timeWeightedMeanHeartRate, HeartRateZones.timeInZones, workoutTrimp, estimateWorkoutEnergy, buildActivitySplits, estimateRouteVo2Max, calculateHeartRateRecovery) over the workout's active time, its session less its pauses; only the pace, the distance over that time, is worked out here. The mean, the zones, the TRIMP and the energy's mean heart rate all count each pair of readings for the time between them, a gap of more than five minutes for nothing (health-calculations' one gap), so readings at uneven intervals do not skew them.
  • WearLinkDaily — the PUT_DAY line (DaySummary): a day number, the night's minutes asleep, awake, REM, light and deep, the resting heart rate, the active kilocalories and the metres, each a whole number within what a day holds or -, and the capability dy.
  • WearLinkNotifications — the phone's notifications on the watch (RelayedNotification): the NT_PUT, NT_DEL and NT_KEEP lines, the encoding and chunking of a notification's text and its actions (RelayedAction: an index, a kind, a title), and the watch's Assembler, which puts a notification back together by phone and id in the order its lines are numbered, refuses a line out of order, a field past its cap or text that is not base64url of UTF-8, skips an action line it cannot read, drops a notification whose next line has not come within 30 s, and keeps at most 16 half-assembled per phone. In memory only; the capability nt.
  • WearLinkWrist and WearLinkWristServer — the way back, from the watch to the phone: the NT_DISMISS, NT_ACT and NT_REPLY lines, the phone's answers to the watch's hello (OK <version>, UNAUTHORIZED, VERSION, ERROR) and to a request (END 0 0, ERROR gone, ERROR bad_request), a reply's chunking and the phone's ReplyAssembler (the lines of one connection, in order, at most 500 characters); the phone's server, which takes a hello only from a peer its handler names (WearLinkWristHandler.peersAt) with the token that hello carries, compared in constant time, under the link's watchdogs; and the watch's client, one request a connection. The phone listens on PHONE_SERVICE_UUID and says so with nb.
  • WearLinkEntries — the LG line of an entry made on the watch (WearLinkEntry): its time, a type token (water, weight, bp, mindful, hr, hrv, bodyfat, spo2, breath, temp, glucose, height, lean, bodywater; a later one is skipped by a build that does not know it, which is why a phone announces bc in its HELLO once it knows the last two, and a watch logs them only for a phone that did), the value and the second value in whole thousandths of the type's unit (the diastolic of bp), and m for a value a sensor measured or h for one entered by hand. The watch serves it to SINCE lg.
  • WearLinkLines — the framing, defined once for both ends: UTF-8 lines, \n terminated, a trailing \r tolerated, a line over 512 bytes closes the connection. The reader takes the socket's bytes a chunk at a time (up to 4 KB, whatever has arrived) and keeps what follows a line for the next, so a connection has one reader.
  • WearLinkToken — the secret a phone presents on every connection: 32 random bytes as Base64, compared in constant time. The bond says the devices know each other; the token says this app on this phone is the one the wearer allowed. The phone keeps one per added watch (WearOsLinkStore, keyed by the address the watch was added under, since pairing again can list the bond under another address) and drops it when the watch is removed; the watch keeps one per phone address. A known phone presenting another token, as after a reinstall, is asked about again like a new one, and allowing it replaces the old token.
  • SecretSeal — how both apps keep a secret at rest: AES-GCM under a key made in and held by the Android Keystore (core/security/KeystoreSecretKey on the phone, WearSecretKey on the watch), stored as v1: and Base64. It seals the link tokens on both sides and the scale's bind key. A value from before sealing reads as it is and is sealed on that read; a value whose Keystore key is gone opens to nothing, so the watch asks the wearer again and the scale screen asks for the key.

Its one dependency is health-calculations (api: WorkoutMetrics takes its body profile and returns its results), a composite build of plain Kotlin like this module, so neither app gains a library by it. Its tests run in both gates (verifyCiUnitTest and verifyWearCi depend on :wearlink:test), its lockfile is wearlink/gradle.lockfile, and the file-size ratchet holds its files to the same limit as the phone app's.

Module :core:data

The data the phone keeps, an Android library in the app's packages: the Room database (data/local: OpenWatchDatabase, its migrations, the entities and DAOs of the five tables), the registry over it (BleDeviceRepository), the per-device state (DeviceStateStore), OpenWatchPreferences and BodyProfileProvider. The database name, version, migrations and the exported schemas are the ones the app has always had; the schemas moved with the database to core/data/schemas, where room.schemaLocation points, and the migration test reads them from the module's ci assets. The module depends on no device family: a family's own table or preference contract is the family's (GarminWellnessRepository, ScaleWeighInRepository, GarminActivityPreferences, WearOsSyncPreferences), and the app implements it over this module's DAO or store, in its data/repository. The Hilt bindings, the database among them, are the app's (di/AppModule, di/RepositoryModule). Its test fixtures, the registry and the body profile in memory, are what the screens' tests build on.

Module :devices:core

The device layer's shared platform half, in devices/core/: an Android library (openwatch.android.library, namespace tech.mmarca.openwatch.devices.core) in the app's package devices/core, so an import does not say which module a class is in. Beside it are the phone's sources a watch relays, in their own packages: devices/notifications (with data/repository/WatchNotificationPrefsStore), devices/media, devices/weather and comaps (devices/notifications); the FIT activity file import, activityimport, with the strings of its exercise types; and core/performance/AppForegroundGate, which the Garmin bridge and the app's gateway read. It holds what every family uses and no family owns: the radio lease, DeviceLog, ble/BlePermissions, ble/GattLink and ble/BleScanner, the pairing implementations with OpenWatchCompanionDeviceService (declared in the module's manifest, merged into the app's), and the sync machinery (DeviceSyncController, WatchAutoSyncScheduler and WatchAutoSyncWorker, SyncBudget, AndroidSyncWakeLock, EstimatedSleepRecord). The worker keeps its class name and package (WorkManager stores the name), and its work keeps its names.

It depends on :core:devices-api and :core:health-api (api: their types are in its signatures), on WorkManager, AndroidX Activity (the companion dialog's result launcher) and Hilt, with KSP: the companion service is an @AndroidEntryPoint and the worker's entry point an @EntryPoint, which Hilt aggregates into the app's graph from the module's classes. It declares no Hilt module; the app's di/DevicesModule.kt binds its pieces. DeviceLog.isEnabled is its build config's DEVICE_DEBUG_LOGS, set to match the app's BuildConfig.DEBUG (a library's own DEBUG is true in the debug APK the release pipeline publishes, which is not debuggable). Its tests (:devices:core:testCiUnitTest, in verifyCiUnitTest: the lease, the controller over FakeDeviceRegistry, the link's redial, the grants) and its lint (lintCi, in verifyCiLint) run in the phone gate; its lockfile is devices/core/gradle.lockfile. Its lint sees the module's manifest, not the permissions the app declares, so the calls that need a grant carry @SuppressLint("MissingPermission") and check it at run time, as before. It also holds the notification icon the device services and the OpenLink streaming notice share (ic_stat_activity_recording), and its test fixtures are what the device modules' tests and the app's share: devices/FakeSharedPreferences and core/security/testSeal() (a SecretSeal on a software key).

Module :wear:recording-core

The watch app's code that needs no Android, in wear/recording-core/: plain Kotlin on the JDK, like :wearlink, compiled into :wear only. Package names are the watch app's (tech.mmarca.openwatch.wear and .wear.workout), so an import does not say which module a class is in. It holds what the recorders decide and compute, and nothing that reads a sensor, a preference or the store:

  • RecorderPlan and the Recorder interface the recorders implement, HeartRateSchedule, WornGate, BedtimeHold, BedtimeWindow, SleepHold and SleepHoldBudget.
  • MinuteAggregator (the sleep-minute rows), StepMinuteCounter, AscentMinuteCounter and NightHrvSchedule.
  • WearMetric and WearMetrics, the series the store keeps: keys, line codecs, retention. The store itself (MetricStore, SQLite) stays in :wear, and so does EntryLog, the entries' writer.
  • EntryDays, the entries made on the watch by local day: the water by the hour, the weights, the newest value of a type.
  • Stillness, whether the arm stayed still through a spot HRV, from the accelerometer, and SensorClaim, one user of a sensor at a time (the night's HRV window or a spot HRV).
  • WatchSensors, what the watch has to measure with, and SpotKind, the spot measurements as plain kinds, with SpotEvent, SpotFailure and SpotRules, when a measurement has its reading and what it is.
  • SyncRetention, when the wearer is warned that unpulled rows are about to go. PhonePulls (the preferences) and SyncReminder (the notification) stay in :wear.
  • WatchPreferences, WatchAbilities (what the watch offers the phone: the sources a wearer could choose now, whether it has a skin temperature and an SpO2 source, and the two grants) and WearPreferenceCodec, the settings as one value and as the GET_PREF/SET_PREF tokens (the zones' heart rates and the body profile a workout's figures need, body_hg, body_cm, birth_year and sex, which the phone sets, among them; WatchPreferences.bodyProfile() reads the latter as health-calculations' BodyProfile), MeasurementSource, the raw sensors or the Samsung platform, and UnitSystem, with its water conversion. WearSettings keeps them in its preferences file, in :wear, and names the source WearSettings.Source, a type alias, so the entry names it stores do not change.
  • TileDay and TileHeartRate, the tiles' day axis and headline.
  • Choices, an ordered choice the wearer edits (the dashboard's tiles, the quick log's entries): stored as names, switched, moved past the items not shown. WearTilePreferences keeps the tiles' choice in :wear, WearQuickLogPreferences the quick log's. QuickLogItem, the entries the quick log can offer, each by the entry type it logs.
  • workout/: WorkoutTracker, WorkoutCheckpoint, and WorkoutStore over the WorkoutRows interface, which :wear implements on the store (MetricStoreWorkoutRows); AutoPause (a stop and a start from the GPS speed), RestDetector (a rest from the accelerometer), RecoveryPlan (what a stop does about the heart rate recovery, RecoveryAtStop, on health-calculations' zones) and ActivityDetector (a walk or a run in the step minutes). ActivityDetectionMonitor, which offers what the detector sees, stays in :wear.

What stays in :wear though it is plain Kotlin: the UI state (WearUiState, WorkoutState, WearLinkState, the status screen's), which the screens and the coroutines around them own, and the Samsung client's point parsers in vendor/samsung/, whose recorded-callback fixtures the device test shares. Its dependencies are api on :wearlink (its rows are in the public signatures) and implementation on health-calculations; its lockfile is wear/recording-core/gradle.lockfile. The watch gate runs its tests, on the JVM with no Robolectric, and Android lint over it (com.android.lint, with the Android modules' rules from build-logic/ and its own lint-baseline.xml), since lint checked these files in :wear.

The source ratchets in :app's architecture tests (file size, function length, the log callers and the log interpolation, runBlocking, runCatching around an await) read the watch app and this module as they read the phone app, and the watch gate runs them (:app:architectureTest). WearPackageDirectionTest holds the watch app's package direction, as PackageDirectionTest holds the phone's: the screens (features, ui) sit on top and only the activity and the navigation host import them, and what only one watch vendor has sits in that vendor's package: vendor/samsung (the Samsung Health Platform's client, the raw PPG sensor's window source and its research logger, the diagnostics consent) and vendor/google (the Pixel Watch's skin temperature sensor), each handing back the contracts of sources (HeartRateSource, HrvWindowSource with NightWindowResult, SpotSource with its readings and SourceFailure). Only vendor/Vendors.kt may import a vendor's package and only WearGraph the chooser; a vendor's package and sources import from the rest of the watch app only a named few (DebugProtocol, SensorTime, the resources, the pure core's types), so either can become a module without a rename. Each vendor's package has one entry (SamsungSources, GoogleSources) that says what of that vendor's this watch has, as a VendorSources of sources (the heart rate's alternatives, the HRV's options, the skin temperature and SpO2 sources, the platform's own spot measurements as PlatformSpots, the bedtime switch, what the recording settings offer as SourceChoices, the status screen's lines, a research capture and the device report's facts; a part the watch lacks is null or empty); Vendors joins them, the first to offer a part winning, so the Pixel Watch's skin sensor comes before the Samsung platform's tracker, and WearGraph.vendor is all the graph, the recorders and the screens see. docs/engineering/watch-vendors.md lists each vendor, what is reached and under which grant. WearVendorNamesRatchetTest holds what an import cannot show: outside vendor/, in the pure core and in the link, no identifier or string names a vendor, no vendor sensor type, package or settings key is written, and Build.MANUFACTURER and its like are read only for the report; its list of today's files only shrinks, but for the stored and sent names (MeasurementSource, the link's tokens).

health-calculations (composite build health-calculations/)

The health calculations OpenWatch and OpenVitals share live in their own repository, Hale-MTU/health-calculations, a git submodule at health-calculations/ taken as a composite build (includeBuild("health-calculations"), dependency tech.mmarca.healthcalculations:health-calculations). It is plain Kotlin on the JDK with no dependency, so the phone app and the watch app take the same code: :core:model and :wearlink with api (so :app sees it, and both apps' workout figures are WorkoutMetrics'), :wear and :wear:recording-core with implementation.

The submodule's pointer must name a commit on the library's default branch: merge the library's pull request first, then move the pointer, here and in OpenVitals. A pointer at a commit that only a pull request branch holds builds until that branch is deleted, and then no fresh clone can check the submodule out. scripts/ci-submodule-pointers.sh checks every submodule and is a job of the gate (submodule-pointers in verify.yml), so a pull request that points at an unmerged library branch stays red until the library is merged.

The phone app reads its insights (the Wear OS night, the nocturnal resting heart rate, body composition, workout and walking energy, the activity type a file names), its model (the exercise session, the sleep-minute rows) and its preferences (the body profile). The watch reads its signal package (beats from the PPG, RMSSD, respiratory rate, the accelerometer's minute features, the Samsung inter-beat intervals) and insights/AscentCredit, which the phone's floors import reads too, so both count the same climb. The recorders, holds and gates that decide when a sensor runs stay in the watch app (:wear, the pure ones in :wear:recording-core): they control the device, they compute no figure.

Health Connect's exercise and segment types are copied in the library under their Health Connect names; ExerciseTypeMirrorTest in :app, the module with Health Connect on its test classpath, checks every value against the real classes, both ways. A calculation is changed in the library and reaches the apps when the submodule moves; it moves in OpenVitals in the same step, so both apps give the same number.

OpenLink host (link/, composite build openlink/)

OpenVitals, and any app the user allows, reaches OpenWatch through OpenLink, a bound service with an AIDL interface. The library is a git submodule at openlink/ taken as a composite build (includeBuild("openlink"), dependency tech.mmarca.openlink:host); its protocol and trust rules are openlink/docs/spec.md. Health data still travels through Health Connect; OpenLink carries the body profile, the device list with "sync now", the shared settings, recording sessions and live readings.

The units are the one setting a connected app decides rather than shares: OpenVitals sends units.system, OpenWatch never sets it, and LinkSharedUnits keeps which app sent it. While that app is installed (InstalledApps, which follows the package broadcasts), trusted and allowed settings, its choice is core/model's SharedUnits, which OpenWatchPreferences shows the screens in and Settings shows locked, with the app's name; otherwise OpenWatch's own choice holds.

The host is the module :link-host (link-host/, package link), an Android library: the service, declared in the module's manifest, the capabilities, the first-party list (res/values/openlink.xml) and the streaming notification with its strings. It depends on :core:data (the registry, the body profile), :devices:core (the families, the sync controller) and :core:ui (the notification's list of names), never on a device family or a screen. The trust store and the binder are built in the app's di/LinkModule, which also makes the one way in that names the app's activity: ConnectedAppsIntent, the Connected apps screen a consent request and the notification open.

  • OpenWatchLinkService is exported with no permission (a custom one is granted only if OpenWatch was installed first, and a normal one protects nothing); the trust is decided per call by OpenLinkHostCore from the caller's signing certificate. res/values/openlink.xml lists the certificates trusted without asking (OpenVitals' release upload key and its Play app-signing key); any other app waits on the Connected apps screen.
  • OpenWatchLinkCapabilities answers from memory on the binder thread: LinkDevices (a StateFlow over the registry, each device's family for what it can do and whether its link is up, and the sync controller; every device goes by its registry id, the scale's included, so no address leaves the phone; kind and integration are OpenLink's open sets, so a new family goes by its own persisted name, and a client on an older library leaves it out), LinkProfileSync (last writer wins, stamped in openlink_profile), and LinkLiveSessions.
  • A recording session cannot start a workout on either watch; it keeps the watch's live readings flowing, from the device's family (DeviceFamily.liveReadings: a Garmin held link with its heart-rate and steps streams on, through GarminNotificationBridge.holdLiveForSession, without touching the user's switch; the Wear OS app's live heart rate) and reports RECORDING on the first reading. A live subscription batches those readings once a second to the app that owns the session.
  • A pending app gets no card on the home screen: any app can say hello, and MainActivity is exported, so a card could be raised from outside. Pending apps head the Connected apps list, and a client opens that screen from a tap through its consentIntent.
  • Only a first-party package name (openlink_first_party_packages) under one of openlink_known_signers is trusted without asking (FirstPartyApps); the same key under another name asks like any app. A first-party name that came under another key gets a warning on its card, and so does an app whose label carries a first-party name (openlink_first_party_names, ignoring case, spaces and punctuation) under another package. Every card but a first-party client's shows the package and the signer's first 64 bits (signerFingerprint), since a label is the app's own choice. What the user switches off stays off through the app's next hello.
  • While the Connected apps screen shows, MainActivity drops touches that came through another app's window (Compose ignores a view's filterTouchesWhenObscured), and from API 31 other apps' overlays are hidden.
  • Connected apps shows per app "In use now" (OpenLinkHost.connected) or the last connection, each session's state (OpenLinkHost.activeSessions joined with LinkLiveSessions.activity in linkSessionStatuses), and the last profile received. LinkStreamingNotifier keeps a silent notification up while any session holds a watch ("Streaming heart rate to OpenVitals").
  • OpenWatchLinkPublisher, started with the app, sends device and local profile changes to bound clients.

Proposed, not built: security fixes and workouts the watch records itself, in openlink-recording-proposal.md.

Cross-Cutting Rules

These rules hold app-wide. Breaking one is not a local decision.

1. One foreground service, and only for the scale

The bathroom scale is the one service the app starts without a tap. When Android reports the associated scale awake, XiaomiScaleListener starts ScaleListeningService (connectedDevice, silent notification) for at most 45 seconds, because a background app's scan is too slow to catch a result that is on the air for two seconds. Someone stepping on a scale is the user's action; nothing else in the app may copy this. ScaleListeningForeground.raise starts nothing when the app is already at foreground importance.

A Garmin watch sync runs with no foreground service of its own; its process-priority story is the companion-device association. WatchAutoSyncWorker is a plain CoroutineWorker, never an expedited or foreground one, as is the scale's half-hourly ScaleListenerWorker.

2. One BLE radio, leased per address

Every subsystem that opens a BLE link to a device goes through RadioLeaseRegistry. The six owners are SYNC, FIND, SETTINGS, NOTIFICATIONS, PROBE (the add-a-device flow reading a device's GATT services) and LIVE (a live stream, held while someone collects it), and on a given address they mutually exclude: a file sync, a find-my-watch ring, an open settings link, the notification forwarder and a probe cannot hold the same watch at once. GattConnectionRatchetTest keeps connectGatt( to GattLink, whose owners hold the lease for the link's life, and to the add-a-device probe, which holds PROBE.

  • Leases expire, so a crashed holder cannot wedge the radio. A fresh lease lasts 30 s, a renewed one 15 s.
  • request() registers a waiter; the current holder's next renew then fails, which is its cue to drop the link. That is how the indefinitely-held notification forwarder and settings link yield to a sync. A waiter expires after 10 s.
  • Work with an end (withRadioLease: a sync, a find, an upload) renews with yieldToWaiter = false and keeps the radio until it is done.
  • release() leaves a short settle window rather than clearing the entry.

A lease guards a link. The scale listener opens none: it only scans. The Wear OS link is RFCOMM on the Classic radio and takes no lease either.

3. Health Connect is reached through HealthConnectGateway only

HealthConnectGateway is the one class that holds the client. It is the module :core:health (core/health), with the record sink's implementation (ImportedRecordRepository), the activity write path (ActivityRecordWriter, ActivityWriteRepository), the sync switch's gate, the intents into Health Connect's own screens and HealthDataCatalog with its strings; it depends on :devices:core for one class, the foreground gate that drops the cached grants. A device never takes it: it takes the contracts of :core:health-api (core/health-api, an Android library since Health Connect's records are the signatures), bound in di/RepositoryModule. It reads through HealthConnectReads, which the gateway implements, and writes through the record sink HealthRecordStore, which ImportedRecordRepository implements, with the helpers of ImportedRecordWrites.kt (outcomes per record, batches of at most MaxRecordsPerInsert). The paused-sync exception and isHealthConnectRateLimit are the module's too; FakeHealthRecordStore, its test fixture, is Health Connect's writes in memory as measured. The devices write through ImportedRecordRepository.insertImportedRecords with a deterministic clientRecordId, so a re-sync upserts; Health Connect replaces a record only when its clientRecordVersion is higher, so a record that is rewritten as it grows carries a rising version. Activities go through ActivityWriteRepository and ActivityRecordWriter, the write path copied from OpenVitals so the records are the same ones.

A reader is strict. Every read in the gateway throws when it fails. Nothing here turns a refusal into an empty list, because every caller saves what it read: a null weight would skip an estimate, an empty session list would double-count a workout.

A writer checks that it can see other apps' data. In the background, without the background-read grant, Health Connect answers a read with this app's own records only, and raises nothing. HealthConnectGateway.readsOtherAppsDataNow() is the test: a started Activity, or the grant. Code that saves what it read while no screen is up calls it first and skips the pass when it is false.

There is no rate-limit backoff, no call pacer and no call tally: the devices issue a handful of reads per sync, and there is no dashboard fanning out dozens. If a quota refusal is ever seen, OpenVitals' HealthConnectRateLimit.kt is the shape to copy.

4. A missing permission is a type, not a message

Throwable.isPermissionFailure() (core/presentation/PermissionFailure.kt in :core:model, so the device modules share it) is the single predicate for "this failed because a permission is missing". It walks the cause chain looking for SecurityException, because Health Connect throws that for an ungranted read or write and the repositories throw the same type when they short-circuit a call whose permission they know is missing. ScreenErrorHandler.handle checks that predicate first and returns ScreenError.PermissionDenied, which the screens render as a grant affordance. Reuse it; do not pattern-match on exception messages.

Any other failure becomes the screen's translated fallback (ScreenError.Text), never the exception's own text, which is English and meant for the log. A state holder that catches a failure puts it in its state as error: ScreenError? and the screen shows it with ScreenErrorContent; it never turns a failed read into "nothing there". SwallowedFailureRatchetTest fails on a ViewModel that catches an exception without a name.

5. Nothing waits on the main thread

  • Health Connect and Room calls are suspend and run on dispatchers.io. Inject DispatcherProvider so tests can swap it.
  • No runBlocking in src/main. NoRunBlockingRatchetTest holds the (empty) allow-list.
  • A receiver never holds a broadcast for a Health Connect read. A scale broadcast is stored first: ScaleWeighInIngest folds the frame into Room, then writes to Health Connect on its own scope.

6. Text that leaves the app is structure, not data

A log line never splices in a value: log a count, a class name, or pass the throwable as the last argument. LogMessageInterpolationRatchetTest holds the count of log calls that splice in an exception message, and it may only fall. On the watch, a line that has to carry a value for diagnosis (a reading, a time, a sensor's name) goes through DebugProtocol.log, which writes only in a debuggable build and never builds the text otherwise; R8 also strips Log.i and Log.d from a release (wear/proguard-rules.pro), but a build that skipped R8 would keep them. Nothing in OpenWatch builds a report or a crash draft; if one is added, it must seed sentinel values in a test and assert none comes out, as OpenVitals' reports do.


Generated from docs/engineering/architecture.md. Edit it there; changes made here are overwritten.

Clone this wiki locally