Skip to content
Open
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# PulseLoop Android

🇷🇺 [Русская версия README](README.ru.md)

> ⚠️ **Disclaimer:** This app is provided as-is and is not a medical application.
> The rings are not medical devices. This app does not replace professional
> healthcare. Always consult your doctor for any medical concerns.
Expand Down
114 changes: 114 additions & 0 deletions README.ru.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# PulseLoop Android

> ⚠️ **Важно:** приложение предоставляется «как есть» и не является медицинским.
> Кольца — не медицинские устройства. Приложение не заменяет врача: по любым
> вопросам здоровья обращайтесь к специалисту.

PulseLoop Android — порт [PulseLoop для iOS](https://github.com/saksham2001/PulseLoopiOS):
приложения-компаньона для недорогих смарт-колец на платформах 56ff/Jring и Colmi/Yawell QRing.
Приложение работает с кольцом напрямую по Bluetooth, без облака производителя и без аккаунта,
и добавляет поверх ваших данных ИИ-коуча. Полная документация — в [README на английском](README.md).

<p align="center">
<img src="docs/images/thumbnail.png" alt="PulseLoop">
</p>

## Русский язык в приложении

- **Весь интерфейс**: экраны «Сегодня», «Показатели», «Сон», «Активность», «Коуч»,
настройки и все их разделы, онбординг, подключение кольца, питание, тренировки, виджеты.
- **Уведомления**: сводки коуча, низкий заряд кольца, тренировка в реальном времени.
- **Описания зон и показателей**: нормы пульса, SpO₂, ВСР, давления, глюкозы, температуры,
стресса и усталости, а также анализ сна.
- **ИИ-коуч отвечает по-русски.** Промпты и описания инструментов остались на английском:
модели надёжнее работают с ними в оригинале, а часть ответов разбирается по точным
английским токенам. К каждому системному промпту добавляется указание писать ответ на
языке приложения. Это касается чата, карточек-сводок, уведомлений и ИИ-оценки еды.
- **Даты и время** выводятся по правилам языка: 24-часовой формат и порядок «11 нояб.».
- Склонение по числам (`1 шаг`, `3 шага`, `5 шагов`) сделано через plurals.

Остались на английском: экран для разработчиков (Debug), технические заметки автоопределения
локального LLM-сервера, названия моделей и их описания, а также журналы и экспорт
диагностики — они нужны для отчётов об ошибках в оригинальном проекте.

## Язык приложения

Язык берётся из системы. Если телефон на русском, приложение тоже будет на русском. В остальных
случаях оно останется на английском. На Android 13+ язык можно выбрать отдельно для приложения:
**Настройки Android → Приложения → PulseLoop → Язык**.

## Подключение кольца

1. При первом запуске мастер настройки проведёт через подключение: пролистайте карусель до
своей модели и нажмите **«Подключить кольцо»**.
2. Если мастер уже пройден, откройте **«Настройки»** и нажмите карточку устройства вверху.
3. Держите кольцо рядом и «разбудите» его (ненадолго снимите с зарядки), затем выберите его
в списке найденных.
4. Кольцо подключится, синхронизирует историю, и показатели начнут заполняться.

### Профиль и калибровка

Кольцам **56ff/Jring** для точной оценки сахара в крови и калорий нужен ваш профиль:
**возраст, рост, вес и пол**. Их можно указать при первой настройке или в
**«Настройки → Профиль»**. Данные хранятся **только на телефоне**.

Давление измеряется датчиком напрямую, и профиль для него не нужен. Кольцам **Colmi**
профиль не нужен вообще: давление и сахар они не поддерживают.

Для 56ff/Jring можно откалибровать давление по тонометру, а сахар — по результату анализа
или глюкометра: **«Настройки → Калибровка»**. Раздел показывается только для колец, которые
поддерживают эти показатели.

## Поддержка колец

| Возможность | 56ff / Jring | Colmi QRing |
|---|---|---|
| Пульс (разовый замер, в реальном времени, история) | ✅ | ✅ |
| SpO₂ (разовый замер, история) | ✅ | ✅ |
| Шаги, расстояние, калории | ✅ | ✅ |
| Сон (лёгкий, глубокий, бодрствование) | ✅ | ✅ |
| Сон (REM) | ❌ | ✅ |
| Давление | ✅ | ❌ |
| Сахар в крови | ✅ | ❌ |
| ВСР | ❌ | ✅ |
| Стресс | ✅ | ✅ |
| Усталость | ✅ | ✅ |
| Температура кожи | ❌ | ✅ |
| Заряд батареи | ✅ | ✅ |
| Поиск устройства | ✅ | ✅ |

Полный список моделей, особенности протоколов и раздел про диагностику — в
[README на английском](README.md).

## Известные проблемы

- **«Забыть кольцо» может не до конца очистить стек Bluetooth.** Тогда при следующем поиске
кольцо не видно ни PulseLoop, ни другим приложениям. **Помогает перезагрузка телефона.**

## Сборка

```bash
./gradlew assembleDebug
```

Минимальная версия: Android 8.0 (SDK 26).

## Как устроен перевод (для разработчиков)

- Строки лежат в `app/src/main/res/values/strings.xml` (английский) и
`app/src/main/res/values-ru/strings.xml` (русский).
- В Composable-функциях используется `stringResource(...)` / `pluralStringResource(...)`.
- Коду без `Context` (сервисы, построители состояния, движок порогов) строки отдаёт
`com.pulseloop.util.L10n`. В приложении он берёт их из ресурсов, а в JVM-юнит-тестах читает
английский `values/strings.xml`, поэтому тесты с английскими строками проходят без изменений.
- Даты форматирует `com.pulseloop.util.LocaleFormats` по шаблонам-«скелетам» Android.
- Язык ответов ИИ задаёт `com.pulseloop.coach.context.CoachLanguage` по строке `coach_language`
из того перевода, который Android реально выбрал. Если для языка телефона перевода нет,
интерфейс и коуч остаются на английском.

Чтобы добавить ещё один язык, создайте `values-<код>/strings.xml` (в `coach_language` укажите
английское название языка, например `German`) и добавьте код в `res/xml/locales_config.xml`.

## Лицензия

См. [README](README.md) и [родительский проект](https://github.com/saksham2001/PulseLoopiOS).
6 changes: 5 additions & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@
missing entirely, so every workout start crashed on API 34+. -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_HEALTH" />
<!-- GPS workouts (#139): a location-type foreground service keeps "while using the app"
location flowing with the screen off, so no background-location grant is needed. -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />

<!-- Self-update: fetch the GitHub release manifest/APK and install it -->
Expand Down Expand Up @@ -75,6 +78,7 @@
android:label="@string/app_name"
android:supportsRtl="true"
android:networkSecurityConfig="@xml/network_security_config"
android:localeConfig="@xml/locales_config"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:theme="@android:style/Theme.Material.Light.NoActionBar">
Expand Down Expand Up @@ -129,7 +133,7 @@
<!-- Phase 6: Workout foreground service -->
<service
android:name=".service.WorkoutForegroundService"
android:foregroundServiceType="health"
android:foregroundServiceType="health|location"
android:exported="false" />

<!-- Home-screen widgets (iOS #44): three Glance app widgets + the shared configure
Expand Down
4 changes: 3 additions & 1 deletion app/src/main/java/com/pulseloop/AppServices.kt
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ class AppServices private constructor(context: Context) {
val persistence = EventPersistenceSubscriber.shared(context)
val batteryAlerts = BatteryAlertMonitor(context)
val providerStore = CoachProviderSettingsStore(context)
val summaryCoordinator = CoachSummaryCoordinator(db, apiKeyStore, providerStore, stepSourcePrefs)
val summaryCoordinator = CoachSummaryCoordinator(db, apiKeyStore, providerStore, stepSourcePrefs) { sessionEndAt ->
com.pulseloop.settings.QuietHoursPrefs.nightInProgress(context, sessionEndAt)
}

// iOS #94: runs the due check-in slot the moment a full sync completes, so a slot the periodic
// worker skipped for stale data is delivered a few minutes later instead of being lost.
Expand Down
10 changes: 5 additions & 5 deletions app/src/main/java/com/pulseloop/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -111,26 +111,26 @@ class MainActivity : ComponentActivity() {
uri.getQueryParameter("error")?.takeIf { it.isNotBlank() }?.let { error ->
store.takePendingAuthState()
store.saveLastError(
if (error == "access_denied") "Strava authorization was declined." else "Strava denied authorization: $error"
if (error == "access_denied") getString(R.string.strava_auth_declined) else getString(R.string.strava_auth_denied, error)
)
return
}

// CSRF: the state we generated must come back. One-shot, cleared either way.
if (!StravaAuth.validateState(store, uri.getQueryParameter("state"))) {
store.saveLastError("Strava authorization could not be verified. Please try connecting again.")
store.saveLastError(getString(R.string.strava_auth_unverified))
return
}

// The consent screen lets the user untick "Upload your activities". Catch it here rather
// than letting every future upload fail with an opaque 401.
if (!StravaAuth.grantedScopeIncludesWrite(uri.getQueryParameter("scope"))) {
store.saveLastError("Strava did not grant upload permission. Reconnect and keep \"Upload your activities\" checked.")
store.saveLastError(getString(R.string.strava_auth_no_upload))
return
}

val code = uri.getQueryParameter("code")?.takeIf { it.isNotBlank() } ?: run {
store.saveLastError("Strava returned an unexpected authorization response.")
store.saveLastError(getString(R.string.strava_auth_unexpected))
return
}

Expand All @@ -140,7 +140,7 @@ class MainActivity : ComponentActivity() {
store.clearLastError()
} catch (e: Exception) {
// The code may have expired, or the configured secrets are wrong.
store.saveLastError("Could not complete the Strava sign-in: ${e.message ?: "unknown error"}")
store.saveLastError(getString(R.string.strava_auth_failed, e.message ?: getString(R.string.strava_unknown_error)))
}
}
}
Expand Down
1 change: 1 addition & 0 deletions app/src/main/java/com/pulseloop/PulseLoopApplication.kt
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class PulseLoopApplication : Application() {

override fun onCreate() {
super.onCreate()
com.pulseloop.util.L10n.init(this)
CrashLogger.install(this)
RWfitSleepJournal.init(this)
// Before any sync can read them: Bedtime tracking no longer needs the schedule (issue #126),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,48 @@ object CoachSleepSyncGate {
* a full sync completed at/after the night ended, or — for streaming devices
* with no full-sync stamp — a 2h-after-wake floor.
*/
fun sleepDaySafeToSummarize(sessionEndAt: Long, lastFullSyncAt: Long?, now: Long): Boolean {
fun sleepDaySafeToSummarize(
sessionEndAt: Long,
lastFullSyncAt: Long?,
now: Long,
nightInProgress: Boolean = false,
): Boolean {
if (now < sessionEndAt + 30 * 60_000L) return false
// #140: a ring hands a record over only once it closes, so a sync mid-night sees just the
// first part and the card was written from it (a 1h03m "night" at 02:04). While the
// wearer's Bedtime / quiet-hours window is still open the night isn't over, whatever the
// stored end says. Capped so an all-day DND can't hold the card back forever.
if (nightInProgress && now < sessionEndAt + NIGHT_IN_PROGRESS_CAP_MS) return false
return if (lastFullSyncAt != null) lastFullSyncAt >= sessionEndAt
else now >= sessionEndAt + 2 * 3600_000L
}

/** Longest a still-open Bedtime window may defer the card past the stored night's end. */
const val NIGHT_IN_PROGRESS_CAP_MS = 8 * 3600_000L

/** How much longer the night must get to skip the rewrite floor (#140): a re-sync's rounding
* or one more 15-minute packet is not worth another generation. */
const val GROWTH_SKIPS_FLOOR_MIN = 15

/**
* May an existing sleep card be rewritten? Not when nothing changed; yes once the rate floor
* has passed; and yes inside the floor when the night got at least [GROWTH_SKIPS_FLOOR_MIN]
* longer (#140), since that corrects a card written from a partial night rather than churning. The first signature field is
* the session's asleep minutes ([com.pulseloop.coach.summaries.CoachSummaryContextBuilder.sleepDay]).
*/
fun sleepCardRewriteDue(
existingSignature: String,
existingUpdatedAt: Long,
newSignature: String,
now: Long,
minIntervalMs: Long,
): Boolean {
if (existingSignature == newSignature) return false
if (com.pulseloop.coach.summaries.CoachSummaryContextBuilder.languageOf(existingSignature) !=
com.pulseloop.coach.summaries.CoachSummaryContextBuilder.languageOf(newSignature)) return true
if (now - existingUpdatedAt >= minIntervalMs) return true
val before = existingSignature.substringBefore('|').toIntOrNull() ?: return false
val after = newSignature.substringBefore('|').toIntOrNull() ?: return false
return after >= before + GROWTH_SKIPS_FLOOR_MIN
}
}
35 changes: 35 additions & 0 deletions app/src/main/java/com/pulseloop/coach/context/CoachLanguage.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.pulseloop.coach.context

import com.pulseloop.R
import com.pulseloop.util.L10n

/**
* The language the coach should write in: the language of the strings the app is showing.
*
* Prompts, tool schemas and tool results stay in English: the model reads English most
* reliably, and several parsers depend on exact English tokens. Only the *output language* is
* steered, by appending a directive to each system prompt that produces user-visible text
* (chat, summaries, check-in notifications, meal estimates). For English the directive is
* empty, so the prompts are byte-for-byte what they were before localization.
*
* The name comes from the `coach_language` string resource rather than from the device locale,
* so it follows whichever translation Android actually resolved. A phone set to a language the
* app has no translation for shows English UI and gets an English coach, not a coach in a
* language the rest of the app isn't speaking.
*/
object CoachLanguage {
/** English name of the app's resolved language ("Russian"), or null when it is English. */
fun languageName(): String? =
L10n.get(R.string.coach_language).trim().takeIf { it.isNotEmpty() && !it.equals("English", ignoreCase = true) }

/**
* A sentence to append to a system prompt, or "" for English. [what] names the output,
* e.g. "all replies" or "the meal name and assumptions".
*/
fun directive(what: String = "all replies"): String {
val language = languageName() ?: return ""
return "\n\nWrite $what in $language — the user's app language — even though these " +
"instructions and the data you receive are in English. Keep numbers, units and " +
"proper names as they are."
}
}
12 changes: 6 additions & 6 deletions app/src/main/java/com/pulseloop/coach/local/LocalEndpoint.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.pulseloop.coach.local

import com.pulseloop.R
import com.pulseloop.util.L10n
import java.net.URI

/**
Expand Down Expand Up @@ -78,13 +80,11 @@ object LocalEndpoint {

/** A short, user-facing explanation for a [Problem], for the Settings field. */
fun message(problem: Problem): String = when (problem) {
Problem.BLANK -> "Enter your server's address, e.g. http://192.168.1.50:11434"
Problem.MALFORMED -> "That doesn't look like a URL — use host:port or http://host:port"
Problem.UNSUPPORTED_SCHEME -> "Only http:// and https:// are supported."
Problem.BLANK -> L10n.get(R.string.le_blank)
Problem.MALFORMED -> L10n.get(R.string.le_malformed)
Problem.UNSUPPORTED_SCHEME -> L10n.get(R.string.le_scheme)
Problem.PUBLIC_CLEARTEXT ->
"Plain http:// is only allowed for a server on this device or your local network " +
"(an IP address, a plain hostname, or a .local / .lan / .ts.net name). " +
"Use https:// to reach one over the internet."
L10n.get(R.string.le_cleartext)
}

/**
Expand Down
Loading
Loading