Saatten Telemetri Oku, Bulutta Düşün, Telegram'da Eğit.
Read Telemetry from the Watch, Think in the Cloud, Coach on Telegram.
Akıllı saat ve bantlardan gelen uyku evreleri, adımlar ve Strava antrenmanlarını Android Health Connect üzerinden cihazda toplayan; Supabase Postgres & Edge Functions ile 7/24 bulutta işleyen ve EVREN LLM API ile sesli/yazılı kişisel antrenörlük sunan açık kaynaklı tam yığın sistem mimarisi.
An open, full-stack architecture that collects sleep stages, steps and Strava workouts from smartwatches and bands on the device via Android Health Connect, processes them in the cloud 24/7 with Supabase Postgres & Edge Functions, and delivers voice and text personal coaching through the EVREN LLM API.
Sensörden Telegram'a: Veri Nasıl Akar?
From Sensor to Telegram: How the Data Flows
Tescilli üçüncü taraf bulutlara kilitlenmeden, cihaz içi Health Connect ile kurulan güvenli veri hattı.
A secure pipeline built on on-device Health Connect, without lock-in to proprietary third-party clouds.
Giyilebilir CihazlarWearables
Xiaomi Watch, Strava, Garmin veya Samsung Health, kalp atım hızı, adım ve uyku seanslarını üretir.
Xiaomi Watch, Strava, Garmin or Samsung Health produce heart rate, steps and sleep sessions.
Health Connect
Android'in yerel şifreli sağlık veritabanı. Cihaz dışına veri çıkmaz, her sensör türü ayrı izinle korunur.
Android's local, encrypted health database. Data stays on the device and each data type sits behind its own permission.
Android Bridge App
Arka plan WorkManager ile 15 dakikada bir çalışır; uyku evrelerini ve adımları toplayıp Supabase'e REST ile iletir.
Runs every 15 minutes via background WorkManager, collecting sleep stages and steps and sending them to Supabase over REST.
Supabase Engine
Postgres üzerinde RLS ile saklanır; pg_cron zamanlayıcıları sabah ve öğün atlama uyarılarını yönetir.
Stored in Postgres behind RLS; pg_cron schedules handle the morning briefing and skipped-meal nudges.
EVREN LLM & Telegram
Qwen3.8-Flash-Next modeli 10 araçla veriyi yorumlar, ses kaydını dinler ve Telegram Webhook üzerinden yanıtlar.
The Qwen3.8-Flash-Next model interprets the data with 10 tools, listens to voice notes and replies through a Telegram webhook.
Android Health Connect Köprüsü Nasıl Çalışır?
How the Android Health Connect Bridge Works
com.ptcoach.bridge paketinin arka planda telemetriyi okuma ve buluta güvenli aktarma mantığı.
How the com.ptcoach.bridge package reads telemetry in the background and ships it securely to the cloud.
Cihaz İçi İzinler ve Veri TürleriOn-Device Permissions and Data Types
Android 14+ ile sistemin çekirdeğine dahil edilen Health Connect API kullanılır. Uygulama yalnızca okuma yetkisi talep eder:
It uses the Health Connect API, built into the OS since Android 14. The app only requests read access:
SleepSessionRecord: Başlangıç/bitiş zamanı ve evreler (Uyanık, Hafif, Derin, REM).StepsRecord: Günlük periyotlarla toplanan adım toplamları (AggregateGroupByPeriod).HeartRateRecord: Dinlenik ve ortalama gün içi nabız verisi.ExerciseSessionRecord: Strava veya saatten gelen seans türü, süre ve rota bilgisi.
SleepSessionRecord: start/end time and stages (Awake, Light, Deep, REM).StepsRecord: step totals aggregated per day (AggregateGroupByPeriod).HeartRateRecord: resting and average daytime heart rate.ExerciseSessionRecord: session type, duration and route from Strava or the watch.
Xiaomi Mi Fitness gibi üreticilerin yazdığı çift/çakışan kayıtlar için süresi en uzun olan kaydı seçen akıllı tekilleştirme (deduplication) algoritması barındırır.
Includes a deduplication step that keeps the longest record when vendors such as Xiaomi Mi Fitness write duplicate or overlapping entries.
// Kotlin: HealthSync.kt - Veri Okuma ve Senkronizasyon
suspend fun syncHealthData(context: Context) = withContext(Dispatchers.IO) {
val client = HealthConnectClient.getOrCreate(context)
val startTime = Instant.now().minus(Duration.ofDays(7))
val endTime = Instant.now()
// 1. Günlük Adımları Dilimleyerek Topla
val stepsRequest = AggregateGroupByPeriodRequest(
metrics = setOf(StepsRecord.COUNT_TOTAL),
timeRangeFilter = TimeRangeFilter.between(startTime, endTime),
timeRangeSlicer = Period.ofDays(1)
)
val steps = client.aggregateGroupByPeriod(stepsRequest)
// 2. Uyku Evrelerini (Derin/REM/Uyanık) Oku
val sleepRecords = client.readRecords(
ReadRecordsRequest(
recordType = SleepSessionRecord::class,
timeRangeFilter = TimeRangeFilter.between(startTime, endTime)
)
).records
// 3. Supabase Edge Ingestion Endpoint'ine İlet
postPayloadToSupabase(steps, sleepRecords)
}
// Kotlin: HealthSync.kt - Read and Sync
suspend fun syncHealthData(context: Context) = withContext(Dispatchers.IO) {
val client = HealthConnectClient.getOrCreate(context)
val startTime = Instant.now().minus(Duration.ofDays(7))
val endTime = Instant.now()
// 1. Aggregate daily steps
val stepsRequest = AggregateGroupByPeriodRequest(
metrics = setOf(StepsRecord.COUNT_TOTAL),
timeRangeFilter = TimeRangeFilter.between(startTime, endTime),
timeRangeSlicer = Period.ofDays(1)
)
val steps = client.aggregateGroupByPeriod(stepsRequest)
// 2. Read sleep stages (Deep/REM/Awake)
val sleepRecords = client.readRecords(
ReadRecordsRequest(
recordType = SleepSessionRecord::class,
timeRangeFilter = TimeRangeFilter.between(startTime, endTime)
)
).records
// 3. Send to the Supabase Edge ingestion endpoint
postPayloadToSupabase(steps, sleepRecords)
}
Etkileşimli Mimari İncelemesi
Interactive Architecture Walkthrough
Her katmanın üstüne tıklayarak görevlerini ve dosya bağlantılarını inceleyin.
Click any module to see what it does and where it lives in the code.
Modelin Kullandığı 12 Çekirdek Araç
The 12 Core Tools the Model Uses
LLM'in halüsinasyon görmeden doğrudan doğrulanmış veritabanı kayıtlarıyla konuşmasını sağlayan araç seti.
A toolset that keeps the LLM grounded in verified database records instead of guessing.
| Araç AdıTool | Tetiklenme AmacıTriggered By | Veri KaynağıData Source | Çıktı & EtkiOutput & Effect |
|---|
Koçun Karar Algoritması Neye Dayanır?
What the Coach's Decisions Are Based On
Spor bilimleri ve beslenme literatüründen (ISSN, ACSM, PubMed) alınan değişmez kurallar.
Fixed rules taken from the sports science and nutrition literature (ISSN, ACSM, PubMed).
Bazal Metabolizma Hızı (BMR): 10×Kilo + 6.25×Boy - 5×Yaş + 5. Sağlıklı yağ yakımı için TDEE'nin %15-20 altı (~400-450 kcal açık) hedeflenir.
Basal Metabolic Rate (BMR): 10×Weight + 6.25×Height - 5×Age + 5. For healthy fat loss it targets 15-20% below TDEE (a ~400-450 kcal deficit).
Kalori açığında kas kaybını engellemek için hedef kilo başına 1.8–2.0 g/kg protein. Öğün başına 25–40g lösin içeriği yüksek protein dağılımı.
1.8–2.0 g/kg of target body weight in protein to prevent muscle loss in a deficit, spread as 25–40 g of leucine-rich protein per meal.
Son 7 günün antrenman yükü (akut) ile son 28 günün ortalaması (kronik) karşılaştırılır. 0.8–1.3 arası güvenli gelişim, 1.5+ sakatlık alarmıdır.
Compares the last 7 days of training load (acute) with the 28-day average (chronic). 0.8–1.3 is safe progress; 1.5+ is an injury warning.
Net 7 saat altı uyku ghrelin (açlık) hormonunu artırır. Derin uyku kas tamirini (%15-25), REM zihinsel toparlanmayı (%20-25) sağlar.
Less than 7 hours of net sleep raises ghrelin (the hunger hormone). Deep sleep (15-25%) drives muscle repair; REM (20-25%) drives mental recovery.
Koç Neyi, Hangi Kaynağa Dayanarak Söylüyor?
What the Coach Says, and Which Source Backs It
Botun bilgi bankası üç kısa protokol dosyası ve aşağıdaki bilimsel kaynaklardan oluşur. Hepsi NotebookLM'e yüklenip tek bir not defterinde toplanır; search_knowledge_base aracı cevap verirken bu kaynaklara işaret eder.
The bot's knowledge base is three short protocol files plus the scientific sources below. They all go into a single NotebookLM notebook, and the search_knowledge_base tool points back to them when it answers.
Günlük Hazırlık Karar Ağacı (Uyku + HRV + Nabız)Daily Readiness Decision Tree (Sleep + HRV + Resting HR)
Tek günlük mutlak HRV değerine değil, kişinin kendi 30 günlük bazalinden yüzde sapmasına bakılır. Sabah brifingi bu tabloya göre şekillenir.
It looks at the percentage deviation from the person's own 30-day baseline, not at a single day's absolute HRV. The morning briefing follows this table.
| SinyalSignal | KriterCriteria | O günün kararıDecision for the day |
|---|---|---|
| Yeşil · HazırGreen · Ready | Net uyku ≥ 6.5 sa, HRV bazale yakın (> −%5), dinlenik nabız normal (< +3 bpm)Net sleep ≥ 6.5 h, HRV near baseline (> −5%), resting HR normal (< +3 bpm) | Planlanan ana antrenman tam kapasite. Normal kalori açığı korunur.Planned main session at full capacity. Normal calorie deficit stays. |
| Sarı · DikkatliAmber · Caution | Net uyku 5.5–6.5 sa VEYA HRV bazalden %5–12 düşük VEYA nabız +3–4 bpmNet sleep 5.5–6.5 h OR HRV 5–12% below baseline OR resting HR +3–4 bpm | Yüksek yoğunluk yerine 30–45 dk Zone 2 veya hacmi %15–20 düşürülmüş teknik antrenman.Swap high intensity for 30–45 min of Zone 2, or a technique session with 15–20% less volume. |
| Kırmızı · ToparlanmaRed · Recover | Net uyku < 5.5 sa VEYA HRV bazalden %12'den fazla düşük VEYA nabız ≥ +5 bpmNet sleep < 5.5 h OR HRV more than 12% below baseline OR resting HR ≥ +5 bpm | Ağır antrenman iptal; 20–30 dk hafif yürüyüş + mobilite. Kalori açığı o gün zorlanmaz, protein ve su yüksek tutulur.Hard session cancelled; 20–30 min easy walk + mobility. No pushing the deficit that day; protein and fluids stay high. |
| KodCode | KaynakSource | Bot ne için kullanıyorWhat the bot uses it for |
|---|---|---|
ISSN-DIET | ISSN Position Stand: Diets and Body CompositionAragon et al. · JISSN 2017 | Kalori açığında kas koruma, 1.6–2.4 g/kg proteinPreserving muscle in a deficit, 1.6–2.4 g/kg protein |
ISSN-PROTEIN | ISSN Position Stand: Protein and ExerciseJäger et al. · JISSN 2017 | Öğün başına 20–40 g protein, lösin eşiği20–40 g protein per meal, leucine threshold |
ACSM | ACSM Physical Activity GuidelinesAmerican College of Sports Medicine | Haftalık 150+ dk kardiyo, 2–3 gün kuvvet150+ min cardio a week, 2–3 strength days |
MIFFLIN-BMR | A new predictive equation for resting energy expenditureMifflin et al. · Am J Clin Nutr 1990 | BMR ve TDEE hesabıBMR and TDEE calculation |
ACWR-LOAD | The training-injury prevention paradoxGabbett · Br J Sports Med 2016 | Akut:kronik yük oranı, 0.8–1.3 güvenli bölgeAcute:chronic workload ratio, 0.8–1.3 safe zone |
HRV-TRAINING | HRV-guided endurance training: a SWOT analysis for load management2026 | HRV ile günlük antrenman şiddeti ayarıAdjusting daily training intensity with HRV |
HRV-MOBILE | Monitoring training adaptation and recovery using HRV via mobile devicesNarrative review · 2025 | Saat ve telefonla ölçülen HRV'nin güvenilirliğiHow reliable watch- and phone-based HRV is |
SLEEP-ATHLETE | Sleep and the athlete: 2021 expert consensus recommendationsWalsh et al. · Br J Sports Med | Uyku süresi hedefleri ve performansSleep duration targets and performance |
SLEEP-MUSCLE | Sleep and muscle recovery: endocrinological and molecular basisDattilo et al. · Med Hypotheses 2011 | Derin uyku, büyüme hormonu ve kas onarımıDeep sleep, growth hormone and muscle repair |
SLEEP-APPETITE | Sleep curtailment, leptin, ghrelin and appetiteSpiegel et al. · Ann Intern Med 2004 | Kısa uykunun ertesi gün iştaha etkisiHow short sleep drives next-day appetite |
⚠️ Bu sayfa bir yazılım mimarisi örneğidir; tıbbi, beslenme veya antrenman tavsiyesi değildir. Değerler genel literatür aralıklarıdır. Sağlık durumunuza özel kararlar için bir hekime veya diyetisyene danışın.
⚠️ This page is a software architecture example, not medical, nutrition or training advice. The values are general ranges from the literature. Talk to a doctor or dietitian about decisions specific to your health.
Geliştirirken Karşılaşılan Kritik Zorluklar ve Çözümleri
Critical Engineering Pitfalls and How We Solved Them
7/24 otonom çalışan bir LLM spor koçunu gerçek dünyada devreye alırken tecrübe ettiğimiz en büyük darboğazlar ve mimari çözümleri.
The most significant bottlenecks and architectural workarounds encountered while deploying a 24/7 autonomous LLM personal trainer in production.
Yutulan Callback Query OlaylarıSilent Drops of Callback Queries
Problem: Telegram varsayılan Webhook yapılandırmasında yalnızca message güncellemelerini yönlendirir. Su kaydı ve mobilite kartlarındaki interaktif butonlara tıklandığında oluşan callback_query olayları sunucuya hiç ulaşmıyordu ve butonlar yanıtsız kalıyordu.
Problem: By default, Telegram webhooks only subscribe to message updates. Button clicks on hydration cards and mobility checklists emit callback_query payloads, which were silently dropped before reaching the Edge Function.
Çözüm: setWebhook çağrısı allowed_updates: ["message", "edited_message", "callback_query"] ile açıkça güncellendi. Buton tıklandığında 3 saniye içinde answerCallbackQuery ile toast bildirimi verildi ve editMessageText ile butonlar kaldırılarak kart yerinde güncellendi.
Solution: Explicitly registered allowed_updates: ["message", "edited_message", "callback_query"] via the Telegram API, acknowledged clicks within 3 seconds using answerCallbackQuery, and edited messages in-place with editMessageText.
JSON Kod Bloklarının Metne SızmasıRaw Action Blocks Leaking into Text
Problem: Açık kaynak modeller bazen standart OpenAI tool_calls yapısı yerine metin gövdesi içine [[START_OF_FRONTEND_ACTION_BLOCK]] {"tool": "log_meal", ...} basar. Model araç çağırmamış sayıldığından işlem veritabanına yazılmıyor ve kullanıcıya ham JSON gidiyordu.
Problem: Certain open-weights models occasionally emit [[START_OF_FRONTEND_ACTION_BLOCK]] JSON payloads directly into message content rather than invoking native function calling. The tool wasn't triggered and raw JSON leaked to the user.
Çözüm: Gelen yanıt gövdesinde regex tabanlı aksiyon bloğu yakalayıcı kuruldu; metin içindeki JSON otomatik sentetik bir tool_call'a dönüştürülüp çalıştırıldı. Ayrıca tüm son kullanıcı yanıtları için regex temizleme filtresi devreye alındı.
Solution: Implemented a content-level interceptor that detects raw action blocks, converts them on the fly into synthetic function calls, and applies a strict user-facing sanitizer to strip any technical markup.
Tek Harfli Yanıt Döngüleri (**K, G)Single-Token Echo Loops
Problem: Model bir turda yarım kalan veya tek harfli bir cevap (örn. • **K) ürettiğinde, bu metin konuşma geçmişine (coach_messages) yazılıyor ve model sonraki her mesajda geçmişteki bu bozuk yapıyı taklit ederek kesik yanıtlar üretmeye devam ediyordu.
Problem: If a response stopped prematurely (e.g. • **K), saving it to conversation history caused subsequent turns to echo the broken pattern, collapsing future dialogue into single characters or broken markdown tags.
Çözüm: Çift yönlü filtreleme: Kapanmamış markdown tag'i içeren veya 15 karakterden kısa yanıtlar hafızaya alınmadan reddedildi. Hafıza okunurken de bozuk kayıtlar filtrelenerek modele temiz bir bağlam sunuldu.
Solution: Two-way sanity filters: assistant responses shorter than 15 chars or ending in unclosed markdown tags are discarded and retried; dirty records are pruned prior to prompt construction.
Büyük Modellerin Süre Aşımı (503/Timeout)High Latency and Service Outages
Problem: Yoğun saatlerde veya büyük modellerde (31B+) akıl yürütme (reasoning) süresi Supabase Edge Function'ın ve Telegram webhook'unun sınırlarını aşıyordu. Bir model kilitlendiğinde tüm sistem cevapsız kalıyordu.
Problem: Large models (31B+) or thinking-heavy prompts exceeded Edge Function execution budgets during peak loads, stalling the webhook and triggering gateway timeouts.
Çözüm: Hiyerarşik model havuzu oluşturuldu (qwen3.8-flash-next öncelikli, auto ve gemma-4-31b yedekli). Her HTTP çağrısına 9.5 saniyelik AbortSignal.timeout eklenerek takılan model anında sonraki hızlı alternatife devredildi.
Solution: Established a multi-model fallback cascade with a 9.5s AbortSignal.timeout per request, falling back from ultra-fast qwen3.8-flash-next (~1.8s) to dynamic auto routing.
"Yumurta Ekmek Falan" Serbest DiliConversational & Unspecified Portions
Problem: Kullanıcı "yumurta ekmek falan yedim" gibi gramajsız konuştuğunda, modelin sürekli soru sorarak diyaloğu kilitlemesi kullanıcı deneyimini zedeliyordu.
Problem: Casual meal descriptions (e.g. "had some eggs and bread") caused conversational deadlocks when the LLM interrogated the user for exact grams before logging.
Çözüm: Standart Türk mutfağı porsiyon kütüphanesi sisteme entegre edildi (2 yumurta + 1 dilim ekmek = 235 kcal, 16g P). Koç varsaydığı porsiyonu şeffafça söyleyerek anında kaydı gerçekleştirir.
Solution: Calibrated reasonable Turkish defaults (2 eggs + 1 slice of bread = 235 kcal, 16g protein), allowing instant database logging while transparently stating the assumed portion.
Mesai Ortasında Koşu Önerisi ÇelişkisiIll-Timed Midday Workout Suggestions
Problem: Botun hafta içi mesai saatlerinin (08:00 - 18:00) ortasında kullanıcıya dışarıda koşu veya ağır antrenman önermesi gerçek hayat ritmiyle çelişiyordu.
Problem: The AI occasionally recommended outdoor runs during 08:00-18:00 office hours, violating the athlete's work schedule.
Çözüm: Hafta içi mesai saatleri kuralı bağlama eklendi: Hafta içi koşu ve ana antrenmanlar daima 18:00 paydos sonrasına planlanır. 15:30'da masabaşı mobilite ve 17:45'te mesai çıkışı koşu brifingi otomatik tetiklenir.
Solution: Embedded strict work hours (08:00-18:00) into the prompt context: workouts are strictly scheduled post-18:00, paired with a 15:30 desk mobility alert and a 17:45 pre-run briefing.
Supabase Veritabanı ve Cron Yapılandırması
Supabase Database and Cron Setup
Sistemi kendi Supabase projenizde ayağa kaldırmak için gereken SQL şeması.
The SQL schema you need to stand the system up in your own Supabase project.
-- 1. Koçluk ve Telemetri Tabloları1. Coaching and Telemetry Tables
create table if not exists public.daily_metrics (
day date primary key,
steps integer,
resting_hr integer,
weight_kg numeric(5,2),
updated_at timestamptz not null default now()
);
create table if not exists public.sleep_sessions (
id uuid primary key default gen_random_uuid(),
start_time timestamptz not null,
end_time timestamptz not null,
duration_min integer not null,
stages jsonb,
source text not null
);
create table if not exists public.meal_logs (
id bigint generated always as identity primary key,
day date not null default current_date,
meal_type text not null, -- kahvalti, ogle, aksam, ara_ogun
description text not null,
calories integer not null,
protein_g numeric(6,1) not null default 0,
carbs_g numeric(6,1) not null default 0,
fat_g numeric(6,1) not null default 0,
created_at timestamptz not null default now()
);
create table if not exists public.water_logs (
id bigint generated always as identity primary key,
day date not null default current_date,
amount_ml integer not null default 250,
created_at timestamptz not null default now()
);
-- 2. 7/24 Proaktif pg_cron Tetikleyicileri (Türkiye Saati / UTC+3)2. 24/7 proactive pg_cron triggers (Türkiye time / UTC+3)
-- Sabah 08:30 TR (05:30 UTC): Uyku & Hava Durumu BrifingiMorning 08:30 TR (05:30 UTC): sleep & weather briefing
select cron.schedule('pt_morning', '30 5 * * *',
$$select net.http_post(url := 'https://[PROJECT].supabase.co/functions/v1/telegram-bot?cron=morning')$$);
-- Mesai İçi Su Hatırlatma Kartları (Hafta İçi 10:30, 12:30, 14:30, 16:30 TR)Desk Hours Water Reminder Cards (Weekdays 10:30, 12:30, 14:30, 16:30 TR)
select cron.schedule('pt_water_card_1', '30 7 * * 1-5',
$$select net.http_post(url := 'https://[PROJECT].supabase.co/functions/v1/telegram-bot?cron=water_card')$$);
-- Masabaşı Mobilite Molası (Hafta İçi 15:30 TR / 12:30 UTC)Desk Mobility Micro-Break (Weekdays 15:30 TR / 12:30 UTC)
select cron.schedule('pt_mobility', '30 12 * * 1-5',
$$select net.http_post(url := 'https://[PROJECT].supabase.co/functions/v1/telegram-bot?cron=mobility')$$);
-- Mesai Bitimi & Koşu Öncesi Brifingi (Hafta İçi 17:45 TR / 14:45 UTC)Work End & Pre-Run Briefing (Weekdays 17:45 TR / 14:45 UTC)
select cron.schedule('pt_pre_run', '45 14 * * 1-5',
$$select net.http_post(url := 'https://[PROJECT].supabase.co/functions/v1/telegram-bot?cron=pre_run')$$);
-- Öğle 13:45 TR: Öğün Atlama & Metabolizma KontrolüLunch 13:45 TR: skipped-meal & metabolism check
select cron.schedule('pt_lunch', '45 10 * * *',
$$select net.http_post(url := 'https://[PROJECT].supabase.co/functions/v1/telegram-bot?cron=lunch_check')$$);
-- Akşam 19:45 TR: Akşam Yemeği & Kapanış ÖzetiEvening 19:45 TR: dinner & remaining budget
select cron.schedule('pt_dinner', '45 16 * * *',
$$select net.http_post(url := 'https://[PROJECT].supabase.co/functions/v1/telegram-bot?cron=dinner_check')$$);