Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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).
1 change: 1 addition & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,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
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
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
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.pulseloop.coach.orchestration

import com.pulseloop.R
import com.pulseloop.util.L10n
import com.pulseloop.coach.context.CoachContextPacket
import com.pulseloop.coach.schema.CoachConfidence
import com.pulseloop.coach.schema.CoachResponse
Expand All @@ -15,10 +17,10 @@ object CoachFallbacks {
/** Used after an API failure or unrepairable output. */
fun fallback(): CoachResponse = CoachResponse(
responseType = CoachResponseType.ERROR_RECOVERY,
title = "I had trouble with that",
summary = "I checked your data but couldn't finish preparing the answer. Try asking again, or narrow the question.",
dataQualityNote = "No changes were made.",
followUpChips = listOf("How am I doing today?", "Summarize my week", "What data is missing?"),
title = L10n.get(R.string.fb_trouble_title),
summary = L10n.get(R.string.fb_trouble),
dataQualityNote = L10n.get(R.string.fb_no_changes),
followUpChips = listOf(L10n.get(R.string.coach_suggest_today), L10n.get(R.string.coach_suggest_week), L10n.get(R.string.fb_chip_missing)),
confidence = CoachConfidence.LOW,
)

Expand All @@ -30,37 +32,37 @@ object CoachFallbacks {
val avgSteps = if (steps7d.isNotEmpty()) steps7d.average().toInt() else 0

val bullets = mutableListOf<String>()
if (todaySteps > 0) bullets.add("Steps today: ${todaySteps}")
if (avgSteps > 0) bullets.add("7-day average: ${avgSteps} steps/day")
if (todaySteps > 0) bullets.add(L10n.get(R.string.fb_steps_today, todaySteps))
if (avgSteps > 0) bullets.add(L10n.plural(R.plurals.fb_steps_avg, avgSteps, avgSteps))

if (bullets.isEmpty()) {
return CoachResponse(
responseType = CoachResponseType.DATA_MISSING,
title = "No activity synced yet",
summary = "I don't have today's activity from the ring yet. Sync the ring or take a measurement and I'll summarize what comes in. (The AI coach is off — add an OpenAI key in Settings to enable full coaching.)",
title = L10n.get(R.string.fb_no_activity_title),
summary = L10n.get(R.string.fb_no_activity),
dataQualityNote = packet.dataQualityWarnings.firstOrNull(),
followUpChips = listOf("Is my ring connected?", "What data is missing?"),
followUpChips = listOf(L10n.get(R.string.fb_chip_connected), L10n.get(R.string.fb_chip_missing)),
confidence = CoachConfidence.LOW,
)
}

return CoachResponse(
responseType = CoachResponseType.INSIGHT,
title = "Here's where you are today",
summary = "You're at ${todaySteps} steps so far today. The AI coach is off — add an OpenAI key in Settings for trends and tailored guidance.",
title = L10n.get(R.string.fb_today_title),
summary = L10n.plural(R.plurals.fb_today, todaySteps, todaySteps),
bullets = bullets,
dataQualityNote = packet.dataQualityWarnings.lastOrNull(),
followUpChips = listOf("How does today compare to yesterday?", "What's my heart rate trend?"),
followUpChips = listOf(L10n.get(R.string.fb_chip_compare), L10n.get(R.string.fb_chip_hr_trend)),
confidence = CoachConfidence.MEDIUM,
)
}

/** Parser failure — couldn't decode model output. */
fun parseError(): CoachResponse = CoachResponse(
responseType = CoachResponseType.ERROR_RECOVERY,
title = "Parse Error",
summary = "I had trouble formatting my response. Please try again.",
followUpChips = listOf("Try again", "Summarize my day", "What's new?"),
title = L10n.get(R.string.fb_parse_title),
summary = L10n.get(R.string.fb_parse),
followUpChips = listOf(L10n.get(R.string.action_try_again), L10n.get(R.string.fb_chip_day), L10n.get(R.string.fb_chip_new)),
confidence = CoachConfidence.LOW,
)
}
Loading