diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..30cf57e --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,10 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Ignored default folder with query files +/queries/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/breath_button_monitor/AGENTS.md b/breath_button_monitor/AGENTS.md index aed4269..19f6d78 100644 --- a/breath_button_monitor/AGENTS.md +++ b/breath_button_monitor/AGENTS.md @@ -2,8 +2,8 @@ This group contains Waveshare ESP32-S3-Touch-AMOLED-2.16 breath-monitor sketches. -- `breath_button_monitor` is the original external-button monitor. +- `breathmonitor_v1 button_monitor` is the original external-button monitor. - `breath_dual_mode_monitor` supports USB sensor and manual-button modes. -- `manual_monitor_lvgl_v2` is the current LVGL manual monitor. +- `breathmonitor_v2 lvgl` is the current LVGL manual monitor. - Each AMOLED sketch needs Waveshare's common libraries from the adjacent `SHiNE-product` checkout; its local `es8311` files are included beside the sketch when required. - Run `./burn.sh ` from this folder to compile or flash. diff --git a/breath_button_monitor/breath_dual_mode_monitor/AGENTS.md b/breath_button_monitor/breath_dual_mode_monitor/AGENTS.md deleted file mode 100644 index 36fa0cf..0000000 --- a/breath_button_monitor/breath_dual_mode_monitor/AGENTS.md +++ /dev/null @@ -1,28 +0,0 @@ -# AGENTS - -## Назначение папки - -Эта папка содержит отдельный ESP32-скетч `breath_dual_mode_monitor.ino` для Waveshare `ESP32-S3-Touch-AMOLED-2.16`. - -Скетч совмещает два режима измерения дыхания: - -- `START USB SENSOR` — датчик-сухой контакт на USB `D- / D+`; -- `START MANUAL MONITOR` — ручной монитор с двумя внешними кнопками пользователя `KEY3 / GPIO18` и `BOOT / GPIO0`. -- `START POT 3-WIRE` — тест переменного резистора по 3-проводной схеме через `USB D- / D+ / GND`. -- `START POT 2-WIRE` — грубый тест переменного резистора по двум контактам `USB D- / D+`. -- `START POT CAL` — калиброванный грубый тест переменного резистора по двум контактам `USB D- / D+`. -- `START PIN DIAG` — диагностика возможности использовать `USB D- / D+` как GPIO/ADC. - -## Обязательная синхронизация - -При любом изменении `breath_dual_mode_monitor.ino` обязательно обновлять рядом лежащий `README.md`. - -Если меняются экранные тексты, кнопки, режимы старта, пины, настройки, звуковые сигналы, правила подсчёта циклов или поведение тревоги после 60 секунд, описание в `README.md` должно быть обновлено в том же наборе изменений. - -Также при изменении поведения скетча обновлять общий reference-документ: - -- `../../../../reference/usb_contact_sensor_test_spec.md` - -## Язык экрана - -Экранные строки в скетче оставлять на английском языке. diff --git a/breath_button_monitor/breath_dual_mode_monitor/README.md b/breath_button_monitor/breath_dual_mode_monitor/README.md deleted file mode 100644 index a3fff66..0000000 --- a/breath_button_monitor/breath_dual_mode_monitor/README.md +++ /dev/null @@ -1,160 +0,0 @@ -# Breath Dual Mode Monitor - -Dual-mode breath monitor для Waveshare `ESP32-S3-Touch-AMOLED-2.16`. - -## Режимы - -На стартовом экране есть кнопки выбора режима: - -- `START USB SENSOR` — использует USB `D- / D+` как сухой контакт. -- `START MANUAL MONITOR` — ручной монитор, использующий две внешние кнопки пользователя. -- `START POT 3-WIRE` — использует USB `D- / D+` и `USB GND` для проверки переменного резистора. -- `START POT 2-WIRE` — грубо оценивает положение переменного резистора только по `D- / D+`. -- `START POT CAL` — калиброванный грубый режим по двум контактам `D- / D+`, показывает положение внутри реально увиденного диапазона. -- `START PIN DIAG` — диагностирует, могут ли USB `D- / D+` реально работать как GPIO/ADC. - -`START MANUAL MONITOR` является большой основной кнопкой. Все остальные режимы находятся ниже как компактные служебные кнопки. - -## USB Sensor Mode - -- `GPIO19 / USB D-` переводится в `OUTPUT LOW`. -- `GPIO20 / USB D+` переводится в `INPUT_PULLUP`. -- Замкнутый контакт считается `EXHALE`. -- Разомкнутый контакт считается `INHALE`. -- Короткие USB-циклы меньше 3 секунд не считаются завершённым циклом: время текущего цикла продолжает идти от предыдущего принятого `EXHALE`. -- Короткое нажатие `KEY3 / GPIO18` открывает или закрывает settings в USB-режиме. -- Внизу рабочего экрана USB-режима показываются длительности последних пяти засчитанных циклов. -- После старта USB data-линии заняты GPIO-режимом до перезагрузки. - -## Buttons Mode - -- `KEY3 / GPIO18` — `INHALE`, active LOW. -- `BOOT / GPIO0` — `EXHALE`, active LOW. -- `BOOT` нельзя удерживать во время включения или reset платы. -- На рабочем экране нет touch-кнопок `INHALE` / `EXHALE`: дыхание переключается только внешними кнопками. -- Долгое удержание `KEY3 / INHALE` около 850 мс открывает settings и одновременно считается нажатием `INHALE`. -- Когда settings открыты, следующее нажатие `KEY3 / INHALE` закрывает settings и тоже считается нажатием `INHALE`. -- В правом верхнем углу показываются заряд батареи и значок молнии во время зарядки. Данные читает AXP2101. -- Дисплей гаснет после выбранного времени без касания экрана или внешней кнопки. Измерение, кнопки и предупреждения продолжают работать; касание или кнопка сразу включает подсветку обратно. -- Если после принятой фазы нет следующей корректной противоположной кнопки: первые 30 секунд скетч молчит, затем 30 секунд тихо сигналит каждые 5 секунд, следующие 30 секунд громко сигналит каждые 5 секунд, затем ещё 5 минут громко сигналит раз в 15 секунд. После этого AXP2101 выключает прибор. - -## Pot Test Mode - -Режим для проверки переменного резистора `RP 6045-B50K` на 50 kΩ по 3-проводной схеме: - -- `USB D- / GPIO19` — источник `3.3V`, подключается к одному крайнему выводу резистора. -- `USB D+ / GPIO20` — ADC-вход, подключается к средней ножке/ползунку. -- `USB GND` — земля, подключается ко второму крайнему выводу резистора. - -На экране показываются: - -- положение ползунка `0..100%`; -- горизонтальная шкала; -- напряжение на `D+`; -- raw ADC; -- примерное сопротивление участка `0..50 kΩ`. - -Программная защита best-effort: - -- если ADC насыщается или показывает опасно высокое напряжение, скетч переводит `D-` и `D+` в `INPUT`, пищит и показывает `USB/PIN FAULT`; -- это не делает 5V на GPIO безопасными: ESP32-S3 GPIO не являются 5V tolerant; -- после fault нужно отключить неправильное подключение и перезагрузить плату. - -## Pot 2-Wire Test Mode - -Грубый режим для проверки переменного резистора по двум контактам: - -- `USB D- / GPIO19` — источник `3.3V`; -- `USB D+ / GPIO20` — ADC-вход с внутренней подтяжкой вниз; -- подключить два вывода потенциометра между `D-` и `D+`: средний ползунок и один крайний вывод. - -Ограничения: - -- измерение грубое, потому что внутренняя подтяжка ESP32 имеет большой разброс; -- положение и сопротивление могут быть нелинейными и отличаться между платами; -- для проверки движения ползунка и примерного края диапазона режим подходит; -- для будущей точной логики дыхания лучше использовать `START POT 3-WIRE`. - -## Pot Cal Test Mode - -Калиброванный грубый режим для случаев, когда USB-линии дают маленький или смещённый диапазон, но движение всё равно видно: - -- `USB D- / GPIO19` — источник `3.3V`; -- `USB D+ / GPIO20` — ADC-вход с внутренней подтяжкой вниз; -- подключить два вывода потенциометра между `D-` и `D+`: средний ползунок и один крайний вывод. - -На экране показываются: - -- процент `0..100%` внутри автоматически найденного диапазона; -- текущие `mV` и raw ADC; -- найденный диапазон `min-max`; -- состояние `CALIBRATING`, `SMALL RANGE`, `LOW EDGE`, `MID` или `HIGH EDGE`. - -Как пользоваться: - -- открыть `START POT CAL`; -- медленно провести ползунок от одного края до другого, чтобы скетч запомнил минимум и максимум; -- если нужно начать калибровку заново, нажать `KEY3 / GPIO18`. - -Этот режим не измеряет настоящее сопротивление. Он нужен, чтобы понять, можно ли получить хотя бы относительное положение ползунка на проблемной USB-паре. - -## USB Pin Diag Mode - -Режим для проверки, не удерживает ли USB PHY/кабель линии `D- / D+` около нуля. - -Тесты: - -- `Test A`: `D- / GPIO19` переводится в `OUTPUT HIGH`, `D+ / GPIO20` читается как ADC. -- `Test B`: `D+ / GPIO20` переводится в `OUTPUT HIGH`, `D- / GPIO19` читается как ADC. - -Как пользоваться: - -- открыть `START PIN DIAG`; -- замкнуть `D-` и `D+` напрямую; -- смотреть, появляется ли около `3.3V` / высокий ADC хотя бы в одном направлении. - -Если оба теста остаются около нуля, значит USB-линии, вероятно, удерживаются USB-подключением, USB PHY или платной обвязкой, и использовать этот разъём как аналоговый датчик при таком подключении нельзя. - -## Логика дыхания - -- Цикл считается от одного `EXHALE` до следующего `EXHALE`. -- `INHALE` до первого `EXHALE` не создаёт цикл. -- В ручном режиме учитывается каждый полный цикл, включая длительности меньше 3 секунд. -- Ручной монитор принимает фазы только в порядке `INHALE -> EXHALE -> INHALE`. Повторное нажатие текущей кнопки и `EXHALE` до первого `INHALE` полностью игнорируются: не меняют фазу, не сбрасывают таймер и не подают звук. -- Каждое принятое нажатие даёт один тихий подтверждающий сигнал. В ручном режиме поле `Phase time` показывает длительность именно текущего вдоха или выдоха. -- В USB Sensor Mode циклы короче 3 секунд игнорируются без сброса текущего таймера цикла. -- Среднее считается с округлением по миллисекундам по последним 5 завершённым циклам и выводится до десятых секунды. -- После принятого `EXHALE` добавляется полный цикл, пересчитывается среднее и при среднем ниже лимита срабатывает предупреждение. -- Внизу экрана всегда показаны те же последние 5 измерений, из которых считается среднее. -- Нижние два числовых поля (`From start` и `Limit`) выводятся увеличенным размером. - -## Settings - -Settings сохраняются в NVS: - -- limit: `5 / 7 / 10 / 15 / 20` секунд; -- quiet cycle tick volume: `0..10`; -- alert volume: `0..10`. -- screen timeout: `10s / 30s / 60s / Always`. - -Настройки прокручиваются вертикальным свайпом, чтобы поместить все четыре пункта. - -## Тревоги - -- Если среднее последних циклов меньше выбранного лимита, звучат предупреждения как в USB breath monitor: серия растёт до 5 сигналов. -- В USB-режиме длинный цикл с 60 секунд использует 5 громких сигналов с повтором каждые 5 секунд. -- В ручном мониторе используется отдельная экономная лестница напоминаний, описанная выше, с выключением питания через 6 минут 30 секунд без корректной следующей фазы. - -## Прошивка - -Из этой папки: - -```bash -./burn.sh -``` - -Только проверить сборку, не прошивая плату: - -```bash -NO_UPLOAD=1 ./burn.sh -``` diff --git a/breath_button_monitor/breath_dual_mode_monitor/breath_dual_mode_monitor.ino b/breath_button_monitor/breath_dual_mode_monitor/breath_dual_mode_monitor.ino deleted file mode 100644 index 01ef423..0000000 --- a/breath_button_monitor/breath_dual_mode_monitor/breath_dual_mode_monitor.ino +++ /dev/null @@ -1,1327 +0,0 @@ -#include -#include -#include -#include -#include -#include -#define XPOWERS_CHIP_AXP2101 -#include "XPowersLib.h" -#include "ESP_I2S.h" -#include "es8311.h" - -#define PIN_LCD_CS 12 -#define PIN_LCD_SCLK 38 -#define PIN_LCD_D0 4 -#define PIN_LCD_D1 5 -#define PIN_LCD_D2 6 -#define PIN_LCD_D3 7 -#define PIN_LCD_RST 2 -#define PIN_I2C_SDA 15 -#define PIN_I2C_SCL 14 -#define PIN_TP_INT 11 -#define PIN_INHALE 18 -#define PIN_EXHALE 0 -#define PIN_PA 46 -#define PIN_I2S_BCLK 9 -#define PIN_I2S_LRCK 45 -#define PIN_I2S_DOUT 8 -#define PIN_I2S_DIN 10 -#define PIN_I2S_MCLK 42 - -#define DISP_W 480 -#define DISP_H 480 - -static constexpr uint32_t kUiPeriodMs = 200; -static constexpr uint32_t kSampleRate = 16000; -static constexpr uint32_t kUsbMinCycleMs = 3000; -static constexpr uint32_t kPauseAfterMs = 60000; -static constexpr uint32_t kLongPressMs = 850; -static constexpr uint32_t kButtonDebounceMs = 45; -static constexpr uint32_t kContactDebounceMs = 80; -static constexpr uint32_t kRepeatAlertMs = 5000; -static constexpr uint32_t kBatteryUiPeriodMs = 5000; -static constexpr uint32_t kManualQuietStartMs = 30000; -static constexpr uint32_t kManualLoudStartMs = 60000; -static constexpr uint32_t kManualSlowLoudStartMs = 90000; -static constexpr uint32_t kManualPowerOffMs = 390000; -static constexpr uint32_t kPotUiPeriodMs = 120; -static constexpr uint32_t kPotSamples = 24; -static constexpr uint32_t kPinDiagPeriodMs = 350; -static constexpr uint32_t kPotOvervoltageMv = 3400; -static constexpr float kPotOhms = 50000.0f; -static constexpr float kApproxInternalPulldownOhms = 45000.0f; -static constexpr int kUsbDmPin = 19; -static constexpr int kUsbDpPin = 20; - -#define C_BG 0x0841u -#define C_PANEL 0x1082u -#define C_CARD 0x18C3u -#define C_BORDER 0x39C7u -#define C_TEXT 0xFFFFu -#define C_MUTE 0xBDF7u -#define C_ACCENT 0x5D5Fu -#define C_OK 0x3666u -#define C_BAD 0xD145u -#define C_BUTTON 0x2145u - -Arduino_DataBus *gBus = new Arduino_ESP32QSPI( - PIN_LCD_CS, PIN_LCD_SCLK, PIN_LCD_D0, PIN_LCD_D1, PIN_LCD_D2, PIN_LCD_D3); -Arduino_CO5300 *gfx = new Arduino_CO5300( - gBus, PIN_LCD_RST, 0, DISP_W, DISP_H, 0, 0, 0, 0); - -TouchDrvCST92xx gTouch; -I2SClass gI2s; -XPowersPMU gPower; -Preferences gPrefs; - -struct Rect { - int16_t x; - int16_t y; - int16_t w; - int16_t h; -}; - -struct DebouncedButton { - int pin; - bool rawPressed = false; - bool stablePressed = false; - uint32_t rawChangedMs = 0; - uint32_t pressedAtMs = 0; -}; - -enum class InputMode : uint8_t { - None, - UsbContact, - ExternalButtons, - PotTest, - PotTwoWireTest, - UsbPinDiag, - PotCalTest, -}; - -static const Rect kStartButtonsButton = {44, 196, 392, 66}; -static const Rect kStartUsbButton = {44, 282, 188, 30}; -static const Rect kStartPotButton = {248, 282, 188, 30}; -static const Rect kStartPot2Button = {44, 322, 188, 30}; -static const Rect kStartPotCalButton = {248, 322, 188, 30}; -static const Rect kStartPinDiagButton = {44, 362, 392, 30}; -static const Rect kLimitSlider = {42, 158, 396, 44}; -static const Rect kTickSlider = {42, 270, 396, 44}; -static const Rect kAlertSlider = {42, 382, 396, 44}; -static const Rect kScreenSlider = {42, 494, 396, 44}; -static const uint16_t kLimitsSec[] = {5, 7, 10, 15, 20}; -static const uint32_t kScreenTimeoutMs[] = {10000, 30000, 60000, 0}; -static const char *kScreenTimeoutNames[] = {"10s", "30s", "60s", "Always"}; -static const int16_t kTickAmpByVolume[] = {0, 40, 80, 140, 220, 320, 440, 580, 720, 800, 1600}; -static const int16_t kAlertAmpByVolume[] = {0, 150, 300, 500, 800, 12000, 12000, 12000, 12000, 12000, 12000}; - -static bool gStarted = false; -static InputMode gInputMode = InputMode::None; -static bool gSettingsOpen = false; -static bool gAudioReady = false; -static bool gPowerReady = false; -static bool gScreenOn = true; -static bool gInExhale = false; -static bool gButtonPhaseKnown = false; -static bool gInhalePressClosedSettings = false; -static bool gNeedRedraw = true; -static bool gNeedStaticRedraw = true; -static bool gStaticDrawn = false; -static bool gLastDrawnExhale = true; -static bool gLongPauseActive = false; -static bool gLastDrawnPaused = true; -static bool gTouchDown = false; -static bool gPotFault = false; -static bool gLastRawClosed = false; -static uint32_t gLastRawChangeMs = 0; -static DebouncedButton gInhaleButton{PIN_INHALE}; -static DebouncedButton gExhaleButton{PIN_EXHALE}; -static int16_t gTouchStartX = 0; -static int16_t gTouchStartY = 0; -static int16_t gTouchLastX = 0; -static int16_t gTouchLastY = 0; -static uint32_t gTouchDownMs = 0; -static uint32_t gStartedMs = 0; -static uint32_t gLastCycleStartMs = 0; -static uint32_t gPhaseStartMs = 0; -static uint32_t gLastUiMs = 0; -static uint32_t gLastBatteryUiMs = 0; -static uint32_t gLastScreenActivityMs = 0; -static uint32_t gLastPotUiMs = 0; -static uint32_t gLastPinDiagUiMs = 0; -static uint32_t gPotCalMinMv = 0xFFFFFFFF; -static uint32_t gPotCalMaxMv = 0; -static uint32_t gCycleMs[5] = {}; -static uint8_t gCycleCount = 0; -static uint8_t gCycleNext = 0; -static uint8_t gLimitIndex = 2; -static uint8_t gTickVolume = 3; -static uint8_t gAlertVolume = 10; -static uint8_t gScreenTimeoutIndex = 1; -static uint8_t gSettingsScroll = 0; -static uint8_t gShortStreak = 0; -static uint16_t gShortAvgEvents = 0; -static uint16_t gLongPauseEvents = 0; -static uint32_t gLastRepeatAlertMs = 0; -static uint8_t gLastManualReminderSlot = 0; -static char gLastTopLine[56] = ""; -static char gLastBottomLine[64] = ""; - -static void releaseUsbPins() { - pinMode(kUsbDmPin, INPUT); - pinMode(kUsbDpPin, INPUT); -} - -static void drawPanel(int x, int y, int w, int h, uint16_t fill, uint16_t border, int radius = 10) { - gfx->fillRoundRect(x, y, w, h, radius, fill); - gfx->drawRoundRect(x, y, w, h, radius, border); -} - -static void drawText(int x, int y, const char *text, uint16_t color, uint8_t size = 2) { - gfx->setFont(); - gfx->setTextSize(size); - gfx->setTextColor(color); - gfx->setCursor(x, y); - gfx->print(text); -} - -static void drawCenteredText(int x, int y, int w, const char *text, uint16_t color, uint8_t size = 2) { - int textW = strlen(text) * 6 * size; - int textX = x + (w - textW) / 2; - if (textX < x + 8) { - textX = x + 8; - } - drawText(textX, y, text, color, size); -} - -static void drawButton(const Rect &rect, const char *label, uint16_t fill, uint8_t size = 2) { - drawPanel(rect.x, rect.y, rect.w, rect.h, fill, C_BORDER, 12); - drawCenteredText(rect.x, rect.y + 15, rect.w, label, C_TEXT, size); -} - -static bool pollPressedEdge(DebouncedButton &button, uint32_t now) { - bool raw = (digitalRead(button.pin) == LOW); - if (raw != button.rawPressed) { - button.rawPressed = raw; - button.rawChangedMs = now; - } - - if (button.stablePressed != button.rawPressed && - (uint32_t)(now - button.rawChangedMs) >= kButtonDebounceMs) { - button.stablePressed = button.rawPressed; - if (button.stablePressed) { - button.pressedAtMs = now; - } - return button.stablePressed; - } - - return false; -} - -static bool pollReleasedEdge(DebouncedButton &button, uint32_t now, uint32_t &heldMs) { - bool raw = (digitalRead(button.pin) == LOW); - if (raw != button.rawPressed) { - button.rawPressed = raw; - button.rawChangedMs = now; - } - - if (button.stablePressed != button.rawPressed && - (uint32_t)(now - button.rawChangedMs) >= kButtonDebounceMs) { - button.stablePressed = button.rawPressed; - if (!button.stablePressed) { - heldMs = now - button.pressedAtMs; - return true; - } - } - - return false; -} - -static void pollButtonEvent(DebouncedButton &button, uint32_t now, - bool &pressed, bool &released, uint32_t &heldMs) { - pressed = false; - released = false; - heldMs = 0; - - bool raw = (digitalRead(button.pin) == LOW); - if (raw != button.rawPressed) { - button.rawPressed = raw; - button.rawChangedMs = now; - } - - if (button.stablePressed == button.rawPressed || - (uint32_t)(now - button.rawChangedMs) < kButtonDebounceMs) { - return; - } - - button.stablePressed = button.rawPressed; - if (button.stablePressed) { - button.pressedAtMs = now; - pressed = true; - } else { - heldMs = now - button.pressedAtMs; - released = true; - } -} - -static bool contains(const Rect &rect, int16_t x, int16_t y) { - return x >= rect.x && x < rect.x + rect.w && y >= rect.y && y < rect.y + rect.h; -} - -static void initPowerManagement() { - gPowerReady = gPower.begin(Wire, AXP2101_SLAVE_ADDRESS, PIN_I2C_SDA, PIN_I2C_SCL); - if (!gPowerReady) return; - gPower.disableIRQ(XPOWERS_AXP2101_ALL_IRQ); - gPower.setChargeTargetVoltage(3); - gPower.clearIrqStatus(); - gPower.enableTemperatureMeasure(); - gPower.enableBattDetection(); - gPower.enableBattVoltageMeasure(); - gPower.enableVbusVoltageMeasure(); - gPower.enableSystemVoltageMeasure(); -} - -static int batteryPercentValue() { - if (!gPowerReady || !gPower.isBatteryConnect()) return -1; - return constrain(gPower.getBatteryPercent(), 0, 100); -} - -static bool batteryIsChargingNow() { - return gPowerReady && gPower.isBatteryConnect() && gPower.isCharging(); -} - -static void drawBatteryStatus() { - gfx->fillRect(344, 14, 104, 24, C_PANEL); - int battery = batteryPercentValue(); - bool charging = batteryIsChargingNow(); - char text[12]; - snprintf(text, sizeof(text), battery >= 0 ? "%d%%" : "--", battery); - drawText(344, 18, text, C_MUTE, 1); - int x = 390; - int y = 18; - gfx->drawRoundRect(x, y, 30, 15, 3, C_MUTE); - gfx->fillRect(x + 30, y + 4, 3, 7, C_MUTE); - if (battery > 0) { - int width = max(2, min(26, battery * 26 / 100)); - uint16_t color = battery <= 10 ? C_BAD : C_OK; - gfx->fillRoundRect(x + 2, y + 2, width, 11, 2, color); - } - if (charging) { - gfx->drawLine(428, 16, 423, 25, C_ACCENT); - gfx->drawLine(423, 25, 427, 25, C_ACCENT); - gfx->drawLine(427, 25, 424, 35, C_ACCENT); - } -} - -static void noteScreenActivity() { - gLastScreenActivityMs = millis(); - if (!gScreenOn) { - gScreenOn = true; - gfx->setBrightness(220); - gNeedStaticRedraw = true; - gNeedRedraw = true; - } -} - -static void pollScreenTimeout() { - uint32_t timeout = kScreenTimeoutMs[gScreenTimeoutIndex]; - if (!gScreenOn || timeout == 0 || millis() - gLastScreenActivityMs < timeout) return; - gScreenOn = false; - gfx->setBrightness(0); -} - -static void turnOffDevice() { - gfx->setBrightness(0); - digitalWrite(PIN_PA, LOW); - if (gPowerReady) { - gPower.shutdown(); - delay(100); - } - esp_deep_sleep_start(); -} - -static void clearArea(int x, int y, int w, int h, uint16_t fill) { - gfx->fillRect(x, y, w, h, fill); -} - -static void formatSec(char *out, size_t outSize, uint32_t ms) { - snprintf(out, outSize, "%lu.%01lus", (unsigned long)(ms / 1000), (unsigned long)((ms % 1000) / 100)); -} - -static void formatClock(char *out, size_t outSize, uint32_t ms) { - uint32_t sec = ms / 1000; - snprintf(out, outSize, "%02lu:%02lu", (unsigned long)(sec / 60), (unsigned long)(sec % 60)); -} - -static uint32_t averageCycleMs() { - if (gCycleCount == 0) { - return 0; - } - uint64_t sum = 0; - for (uint8_t i = 0; i < gCycleCount; i++) { - sum += gCycleMs[i]; - } - return (uint32_t)((sum + gCycleCount / 2) / gCycleCount); -} - -static uint32_t minCycleMsForCurrentMode() { - return gInputMode == InputMode::UsbContact ? kUsbMinCycleMs : 0; -} - -static const char *modeTitle() { - if (gInputMode == InputMode::UsbContact) return "USB BREATH"; - if (gInputMode == InputMode::ExternalButtons) return "MANUAL MONITOR"; - if (gInputMode == InputMode::PotTest) return "POT TEST"; - if (gInputMode == InputMode::PotTwoWireTest) return "POT 2W TEST"; - if (gInputMode == InputMode::UsbPinDiag) return "USB PIN DIAG"; - if (gInputMode == InputMode::PotCalTest) return "POT CAL TEST"; - return "BREATH MONITOR"; -} - -static uint32_t readPotMilliVolts(uint32_t *rawOut) { - uint32_t rawSum = 0; - uint32_t mvSum = 0; - for (uint32_t i = 0; i < kPotSamples; i++) { - rawSum += analogRead(kUsbDpPin); - mvSum += analogReadMilliVolts(kUsbDpPin); - delayMicroseconds(250); - } - if (rawOut) { - *rawOut = rawSum / kPotSamples; - } - return mvSum / kPotSamples; -} - -static uint32_t readAdcMilliVolts(int pin, uint32_t *rawOut) { - uint32_t rawSum = 0; - uint32_t mvSum = 0; - for (uint32_t i = 0; i < kPotSamples; i++) { - rawSum += analogRead(pin); - mvSum += analogReadMilliVolts(pin); - delayMicroseconds(250); - } - if (rawOut) { - *rawOut = rawSum / kPotSamples; - } - return mvSum / kPotSamples; -} - -static void formatLastFiveCycles(char *out, size_t outSize) { - if (gCycleCount == 0) { - snprintf(out, outSize, "Last 5: --"); - return; - } - - size_t used = snprintf(out, outSize, "Last 5:"); - for (uint8_t i = 0; i < gCycleCount && used < outSize; i++) { - uint8_t idx = (gCycleNext + 5 - gCycleCount + i) % 5; - uint32_t ms = gCycleMs[idx]; - used += snprintf(out + used, outSize - used, " %lu.%lus", - (unsigned long)(ms / 1000), - (unsigned long)((ms % 1000) / 100)); - } -} - -static void resetCachedUiText() { - gLastTopLine[0] = '\0'; - gLastBottomLine[0] = '\0'; -} - -static void loadSettings() { - gPrefs.begin("manual-br", false); - gLimitIndex = gPrefs.getUChar("limit", gLimitIndex); - gTickVolume = gPrefs.getUChar("tick", gTickVolume); - gAlertVolume = gPrefs.getUChar("alert", gAlertVolume); - gScreenTimeoutIndex = gPrefs.getUChar("screen", gScreenTimeoutIndex); - if (gLimitIndex > 4) gLimitIndex = 2; - if (gTickVolume > 10) gTickVolume = 3; - if (gAlertVolume > 10) gAlertVolume = 10; - if (gScreenTimeoutIndex > 3) gScreenTimeoutIndex = 1; -} - -static void saveSettings() { - gPrefs.putUChar("limit", gLimitIndex); - gPrefs.putUChar("tick", gTickVolume); - gPrefs.putUChar("alert", gAlertVolume); - gPrefs.putUChar("screen", gScreenTimeoutIndex); -} - -static esp_err_t codecInit() { - es8311_handle_t esHandle = es8311_create(0, ES8311_ADDRRES_0); - if (!esHandle) return ESP_FAIL; - const es8311_clock_config_t clk = { - .mclk_inverted = false, - .sclk_inverted = false, - .mclk_from_mclk_pin = true, - .mclk_frequency = (int)kSampleRate * 256, - .sample_frequency = (int)kSampleRate, - }; - if (es8311_init(esHandle, &clk, ES8311_RESOLUTION_16, ES8311_RESOLUTION_16) != ESP_OK) { - return ESP_FAIL; - } - es8311_voice_volume_set(esHandle, 100, nullptr); - es8311_voice_mute(esHandle, false); - return ESP_OK; -} - -static void initAudio() { - pinMode(PIN_PA, OUTPUT); - digitalWrite(PIN_PA, HIGH); - gI2s.setPins(PIN_I2S_BCLK, PIN_I2S_LRCK, PIN_I2S_DOUT, PIN_I2S_DIN, PIN_I2S_MCLK); - if (!gI2s.begin(I2S_MODE_STD, kSampleRate, I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_STEREO, I2S_STD_SLOT_BOTH)) { - Serial.println("I2S init failed"); - return; - } - gAudioReady = (codecInit() == ESP_OK); - Serial.println(gAudioReady ? "Audio init OK" : "Audio codec init failed"); -} - -static void playBeep(uint16_t freq, uint16_t samples, int16_t amp) { - if (!gAudioReady || amp <= 0) return; - static int16_t toneBuf[1600 * 2]; - if (samples > 1600) samples = 1600; - for (int i = 0; i < samples; i++) { - float s = sinf(2.0f * 3.1415926f * (float)freq * ((float)i / (float)kSampleRate)); - int16_t v = (int16_t)(s * amp); - toneBuf[i * 2] = v; - toneBuf[i * 2 + 1] = v; - } - gI2s.write((uint8_t *)toneBuf, samples * 2 * sizeof(int16_t)); -} - -static void playCycleTick() { - playBeep(880, 480, kTickAmpByVolume[gTickVolume]); -} - -static void playAlertBeep() { - playBeep(1200, 1600, kAlertAmpByVolume[gAlertVolume]); -} - -static void playFiveAlertBeeps() { - for (uint8_t i = 0; i < 5; i++) { - playAlertBeep(); - delay(80); - } -} - -static void alertIfNeeded() { - if (gShortStreak == 0) return; - uint8_t count = min(gShortStreak, 5); - for (uint8_t i = 0; i < count; i++) { - playAlertBeep(); - delay(80); - } -} - -static void addCycle(uint32_t cycleMs) { - gCycleMs[gCycleNext] = cycleMs; - gCycleNext = (gCycleNext + 1) % 5; - if (gCycleCount < 5) { - gCycleCount++; - } - - uint32_t avgMs = averageCycleMs(); - if (avgMs > 0 && avgMs < (uint32_t)kLimitsSec[gLimitIndex] * 1000UL) { - if (gShortStreak < 5) gShortStreak++; - gShortAvgEvents++; - } else { - gShortStreak = 0; - } -} - -static void drawReadyScreen() { - gfx->fillScreen(C_BG); - drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16); - drawText(28, 42, "BREATH MONITOR", C_TEXT, 3); - drawText(28, 78, "Choose input mode", C_MUTE, 2); - drawPanel(34, 106, 412, 72, C_CARD, C_BORDER, 14); - drawCenteredText(34, 126, 412, "Main mode", C_MUTE, 1); - drawCenteredText(34, 150, 412, "manual breath buttons", C_TEXT, 2); - drawButton(kStartButtonsButton, "START MANUAL MONITOR", C_OK, 3); - drawText(44, 268, "Service modes", C_MUTE, 1); - drawButton(kStartUsbButton, "USB SENSOR", C_BUTTON, 1); - drawButton(kStartPotButton, "POT 3-WIRE", C_ACCENT, 1); - drawButton(kStartPot2Button, "POT 2-WIRE", C_BUTTON, 1); - drawButton(kStartPotCalButton, "POT CAL", C_OK, 1); - drawButton(kStartPinDiagButton, "USB PIN DIAG", C_BAD, 1); -} - -static void drawSlider(const Rect &rect, const char *title, const char *value, uint8_t pos, uint8_t maxPos) { - drawText(rect.x, rect.y - 28, title, C_TEXT, 2); - drawText(rect.x + 278, rect.y - 28, value, C_ACCENT, 2); - drawPanel(rect.x, rect.y, rect.w, rect.h, C_BUTTON, C_BORDER, 12); - int trackX = rect.x + 22; - int trackW = rect.w - 44; - int trackY = rect.y + rect.h / 2 - 3; - gfx->fillRect(trackX, trackY, trackW, 6, C_BORDER); - int knobX = trackX + (trackW * pos) / max(1, maxPos); - gfx->fillRoundRect(knobX - 10, rect.y + 8, 20, rect.h - 16, 8, C_ACCENT); -} - -static void drawSettingsScreen() { - char value[24]; - int yOffset = gSettingsScroll * 112; - gfx->fillScreen(C_BG); - drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16); - drawText(28, 32, "SETTINGS", C_TEXT, 3); - drawText(28, 68, "Swipe up/down INHALE closes", C_MUTE, 1); - - snprintf(value, sizeof(value), "%us", kLimitsSec[gLimitIndex]); - Rect limit = kLimitSlider; - limit.y -= yOffset; - drawSlider(limit, "Limit", value, gLimitIndex, 4); - snprintf(value, sizeof(value), "%u/10", gTickVolume); - Rect tick = kTickSlider; - tick.y -= yOffset; - drawSlider(tick, "Cycle tick volume", value, gTickVolume, 10); - snprintf(value, sizeof(value), "%u/10", gAlertVolume); - Rect alert = kAlertSlider; - alert.y -= yOffset; - drawSlider(alert, "Alert volume", value, gAlertVolume, 10); - Rect screen = kScreenSlider; - screen.y -= yOffset; - drawSlider(screen, "Screen timeout", kScreenTimeoutNames[gScreenTimeoutIndex], gScreenTimeoutIndex, 3); - - gStaticDrawn = false; - gNeedStaticRedraw = true; -} - -static void drawMonitorStatic() { - gfx->fillScreen(C_BG); - drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16); - drawText(28, 32, modeTitle(), C_TEXT, 2); - drawPanel(28, 102, 424, 96, C_CARD, C_BORDER, 14); - drawPanel(28, 216, 200, 72, C_CARD, C_BORDER, 10); - drawText(42, 236, gInputMode == InputMode::ExternalButtons ? "Phase time" : "Current", C_MUTE, 1); - drawPanel(252, 216, 200, 72, C_CARD, C_BORDER, 10); - drawText(266, 236, "Average 5", C_MUTE, 1); - drawPanel(28, 304, 200, 64, C_CARD, C_BORDER, 10); - drawText(42, 322, "From start", C_MUTE, 1); - drawPanel(252, 304, 200, 64, C_CARD, C_BORDER, 10); - drawText(266, 322, "Limit", C_MUTE, 1); - gStaticDrawn = true; - gLastDrawnExhale = !gInExhale; - gLastDrawnPaused = !gLongPauseActive; - resetCachedUiText(); -} - -static void drawPotStatic() { - gfx->fillScreen(C_BG); - drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16); - drawText(28, 32, modeTitle(), C_TEXT, 3); - drawText(28, 72, - gInputMode == InputMode::PotTwoWireTest ? "D-=3.3V D+=wiper/edge rough" : "D-=3.3V D+=wiper GND=edge", - C_MUTE, 1); - drawPanel(28, 112, 424, 88, C_CARD, C_BORDER, 14); - drawPanel(28, 220, 424, 44, C_CARD, C_BORDER, 10); - drawPanel(28, 288, 200, 72, C_CARD, C_BORDER, 10); - drawText(42, 308, "Voltage", C_MUTE, 1); - drawPanel(252, 288, 200, 72, C_CARD, C_BORDER, 10); - drawText(266, 308, "ADC raw", C_MUTE, 1); - drawPanel(28, 378, 424, 54, C_CARD, C_BORDER, 10); - drawText(42, 394, "Estimated resistance", C_MUTE, 1); - gStaticDrawn = true; - resetCachedUiText(); -} - -static void updatePotValues(bool force) { - if (gInputMode != InputMode::PotTest && gInputMode != InputMode::PotTwoWireTest) return; - - uint32_t raw = 0; - uint32_t mv = readPotMilliVolts(&raw); - if (!gPotFault && (mv >= kPotOvervoltageMv || raw >= 4090)) { - gPotFault = true; - releaseUsbPins(); - playFiveAlertBeeps(); - force = true; - } - - char line[64]; - if (gPotFault) { - clearArea(42, 128, 396, 58, C_CARD); - drawCenteredText(28, 126, 424, "USB/PIN FAULT", C_BAD, 3); - drawCenteredText(28, 166, 424, "pins released; reboot to retry", C_MUTE, 1); - clearArea(38, 232, 404, 20, C_CARD); - drawText(42, 234, "Possible overvoltage or USB host connection", C_BAD, 1); - return; - } - - float percent = 0.0f; - float ohms = 0.0f; - if (gInputMode == InputMode::PotTwoWireTest) { - if (mv < 20) { - ohms = kPotOhms; - } else { - ohms = kApproxInternalPulldownOhms * ((3300.0f / (float)mv) - 1.0f); - ohms = constrain(ohms, 0.0f, kPotOhms); - } - percent = 100.0f - constrain(ohms * 100.0f / kPotOhms, 0.0f, 100.0f); - } else { - percent = constrain((float)mv * 100.0f / 3300.0f, 0.0f, 100.0f); - ohms = kPotOhms * percent / 100.0f; - } - - clearArea(42, 128, 396, 58, C_CARD); - snprintf(line, sizeof(line), "%u%%", (unsigned)(percent + 0.5f)); - drawCenteredText(28, 126, 424, line, C_ACCENT, 4); - - int barX = 48; - int barY = 234; - int barW = 384; - int fillW = (int)((barW * percent) / 100.0f); - gfx->fillRect(barX, barY, barW, 16, C_BORDER); - gfx->fillRect(barX, barY, fillW, 16, C_ACCENT); - - clearArea(42, 326, 160, 28, C_CARD); - snprintf(line, sizeof(line), "%lumV", (unsigned long)mv); - drawText(42, 328, line, C_TEXT, 2); - - clearArea(266, 326, 160, 28, C_CARD); - snprintf(line, sizeof(line), "%lu", (unsigned long)raw); - drawText(266, 328, line, C_TEXT, 2); - - clearArea(42, 414, 360, 16, C_CARD); - snprintf(line, sizeof(line), "%.1fk / 50.0k%s", ohms / 1000.0f, - gInputMode == InputMode::PotTwoWireTest ? " rough" : ""); - drawText(42, 414, line, C_TEXT, 2); - - (void)force; -} - -static void resetPotCal() { - gPotCalMinMv = 0xFFFFFFFF; - gPotCalMaxMv = 0; - resetCachedUiText(); -} - -static void drawPotCalStatic() { - gfx->fillScreen(C_BG); - drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16); - drawText(28, 32, "POT CAL TEST", C_TEXT, 3); - drawText(28, 72, "D-=HIGH D+=ADC KEY3 resets min/max", C_MUTE, 1); - drawPanel(28, 112, 424, 88, C_CARD, C_BORDER, 14); - drawPanel(28, 220, 424, 44, C_CARD, C_BORDER, 10); - drawPanel(28, 288, 200, 72, C_CARD, C_BORDER, 10); - drawText(42, 308, "Now", C_MUTE, 1); - drawPanel(252, 288, 200, 72, C_CARD, C_BORDER, 10); - drawText(266, 308, "Range", C_MUTE, 1); - drawPanel(28, 378, 424, 54, C_CARD, C_BORDER, 10); - drawText(42, 394, "State", C_MUTE, 1); - gStaticDrawn = true; - resetCachedUiText(); -} - -static void updatePotCalValues() { - if (gInputMode != InputMode::PotCalTest) return; - - uint32_t raw = 0; - uint32_t mv = readPotMilliVolts(&raw); - if (mv < gPotCalMinMv) gPotCalMinMv = mv; - if (mv > gPotCalMaxMv) gPotCalMaxMv = mv; - - uint32_t span = (gPotCalMaxMv > gPotCalMinMv) ? (gPotCalMaxMv - gPotCalMinMv) : 0; - uint8_t percent = 0; - if (span >= 5 && mv >= gPotCalMinMv) { - percent = (uint8_t)constrain(((mv - gPotCalMinMv) * 100UL + span / 2) / span, 0UL, 100UL); - } - - const char *state = "CALIBRATING"; - uint16_t stateColor = C_MUTE; - if (span >= 50) { - if (percent < 20) { - state = "LOW EDGE"; - stateColor = C_ACCENT; - } else if (percent > 80) { - state = "HIGH EDGE"; - stateColor = C_OK; - } else { - state = "MID"; - stateColor = C_TEXT; - } - } else if (span > 0) { - state = "SMALL RANGE"; - stateColor = C_BAD; - } - - char line[80]; - clearArea(42, 128, 396, 58, C_CARD); - snprintf(line, sizeof(line), "%u%%", percent); - drawCenteredText(28, 126, 424, line, span >= 50 ? C_ACCENT : C_MUTE, 4); - - int barX = 48; - int barY = 234; - int barW = 384; - int fillW = (barW * percent) / 100; - gfx->fillRect(barX, barY, barW, 16, C_BORDER); - gfx->fillRect(barX, barY, fillW, 16, span >= 50 ? C_ACCENT : C_BAD); - - clearArea(42, 326, 160, 28, C_CARD); - snprintf(line, sizeof(line), "%lumV r%lu", (unsigned long)mv, (unsigned long)raw); - drawText(42, 328, line, C_TEXT, 1); - - clearArea(266, 326, 170, 28, C_CARD); - snprintf(line, sizeof(line), "%lu-%lu", (unsigned long)gPotCalMinMv, (unsigned long)gPotCalMaxMv); - drawText(266, 328, line, C_TEXT, 1); - - clearArea(42, 414, 360, 16, C_CARD); - snprintf(line, sizeof(line), "%s span %lumV", state, (unsigned long)span); - drawText(42, 414, line, stateColor, 2); -} - -static void drawPinDiagStatic() { - gfx->fillScreen(C_BG); - drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16); - drawText(28, 32, "USB PIN DIAG", C_TEXT, 3); - drawText(28, 72, "Short D- and D+ to test GPIO drive", C_MUTE, 1); - drawPanel(28, 110, 424, 128, C_CARD, C_BORDER, 14); - drawText(42, 128, "Test A: D- HIGH, D+ ADC", C_ACCENT, 2); - drawPanel(28, 260, 424, 128, C_CARD, C_BORDER, 14); - drawText(42, 278, "Test B: D+ HIGH, D- ADC", C_ACCENT, 2); - drawPanel(28, 410, 424, 36, C_CARD, C_BORDER, 10); - gStaticDrawn = true; - resetCachedUiText(); -} - -static void updatePinDiagValues() { - if (gInputMode != InputMode::UsbPinDiag) return; - - char line[80]; - uint32_t rawA = 0; - uint32_t rawB = 0; - - pinMode(kUsbDpPin, INPUT); - pinMode(kUsbDmPin, OUTPUT); - digitalWrite(kUsbDmPin, HIGH); - delay(8); - uint32_t mvA = readAdcMilliVolts(kUsbDpPin, &rawA); - int dmReadA = digitalRead(kUsbDmPin); - int dpReadA = digitalRead(kUsbDpPin); - - pinMode(kUsbDmPin, INPUT); - pinMode(kUsbDpPin, OUTPUT); - digitalWrite(kUsbDpPin, HIGH); - delay(8); - uint32_t mvB = readAdcMilliVolts(kUsbDmPin, &rawB); - int dpReadB = digitalRead(kUsbDpPin); - int dmReadB = digitalRead(kUsbDmPin); - - releaseUsbPins(); - - clearArea(42, 158, 380, 66, C_CARD); - snprintf(line, sizeof(line), "D+ %lumV raw %lu", (unsigned long)mvA, (unsigned long)rawA); - drawText(42, 160, line, mvA > 2500 ? C_OK : C_BAD, 2); - snprintf(line, sizeof(line), "D- read %d D+ read %d", dmReadA, dpReadA); - drawText(42, 194, line, C_TEXT, 2); - - clearArea(42, 308, 380, 66, C_CARD); - snprintf(line, sizeof(line), "D- %lumV raw %lu", (unsigned long)mvB, (unsigned long)rawB); - drawText(42, 310, line, mvB > 2500 ? C_OK : C_BAD, 2); - snprintf(line, sizeof(line), "D+ read %d D- read %d", dpReadB, dmReadB); - drawText(42, 344, line, C_TEXT, 2); - - clearArea(42, 424, 380, 16, C_CARD); - if (mvA < 500 && mvB < 500) { - drawText(42, 424, "Both low: USB PHY/cable may hold pins", C_BAD, 1); - } else if (mvA > 2500 || mvB > 2500) { - drawText(42, 424, "High seen: short should change ADC", C_OK, 1); - } else { - drawText(42, 424, "Weak/partial drive detected", C_MUTE, 1); - } -} - -static void pollBreathAlerts() { - if (!gStarted || gSettingsOpen || gInputMode == InputMode::PotTest || - gInputMode == InputMode::PotTwoWireTest || gInputMode == InputMode::PotCalTest || - gInputMode == InputMode::UsbPinDiag) { - return; - } - - uint32_t now = millis(); - uint32_t activeStartMs = gInputMode == InputMode::ExternalButtons ? gPhaseStartMs : gLastCycleStartMs; - if (activeStartMs == 0) return; - uint32_t elapsedMs = now - activeStartMs; - - if (gInputMode == InputMode::ExternalButtons) { - if (elapsedMs >= kManualPowerOffMs) { - turnOffDevice(); - return; - } - - uint8_t slot = 0; - bool loud = false; - if (elapsedMs >= kManualSlowLoudStartMs) { - slot = 100 + (elapsedMs - kManualSlowLoudStartMs) / 15000; - loud = true; - } else if (elapsedMs >= kManualLoudStartMs) { - slot = 50 + (elapsedMs - kManualLoudStartMs) / 5000; - loud = true; - } else if (elapsedMs >= kManualQuietStartMs) { - slot = 10 + (elapsedMs - kManualQuietStartMs) / 5000; - } - if (slot != 0 && slot != gLastManualReminderSlot) { - gLastManualReminderSlot = slot; - if (loud) playAlertBeep(); - else playCycleTick(); - } - gLongPauseActive = elapsedMs >= kManualLoudStartMs; - return; - } - - if (elapsedMs < kPauseAfterMs) return; - if (!gLongPauseActive) { - gLongPauseActive = true; - gLongPauseEvents++; - gLastRepeatAlertMs = now; - playFiveAlertBeeps(); - } else if ((uint32_t)(now - gLastRepeatAlertMs) >= kRepeatAlertMs) { - gLastRepeatAlertMs = now; - playFiveAlertBeeps(); - } -} - -static void updateMonitorValues(bool force) { - char line[64]; - char value[16]; - uint32_t now = millis(); - uint32_t runMs = now - gStartedMs; - uint32_t activeStartMs = gInputMode == InputMode::ExternalButtons ? gPhaseStartMs : gLastCycleStartMs; - uint32_t currentMs = (activeStartMs == 0) ? 0 : now - activeStartMs; - uint32_t avgMs = averageCycleMs(); - - if (force || gLastDrawnExhale != gInExhale || gLastDrawnPaused != gLongPauseActive) { - clearArea(42, 120, 396, 66, C_CARD); - if (gLongPauseActive) { - drawCenteredText(28, 120, 424, "OVER 60S", C_BAD, 4); - drawCenteredText(28, 170, 424, "waiting for next phase", C_MUTE, 1); - } else { - drawCenteredText(28, 120, 424, gInExhale ? "EXHALE" : "INHALE", - gInExhale ? C_OK : C_ACCENT, 4); - drawCenteredText(28, 170, 424, - gInputMode == InputMode::UsbContact ? "USB contact sensor" : "external buttons", - C_MUTE, 1); - } - gLastDrawnExhale = gInExhale; - gLastDrawnPaused = gLongPauseActive; - } - - snprintf(line, sizeof(line), "%s Limit: %us", - gInputMode == InputMode::UsbContact ? "USB D-/D+" : "hold INHALE: settings", - kLimitsSec[gLimitIndex]); - if (strcmp(line, gLastTopLine) != 0) { - clearArea(28, 58, 424, 20, C_PANEL); - drawText(28, 60, line, C_MUTE, 1); - strncpy(gLastTopLine, line, sizeof(gLastTopLine) - 1); - gLastTopLine[sizeof(gLastTopLine) - 1] = '\0'; - } - - clearArea(42, 254, 160, 28, C_CARD); - formatSec(value, sizeof(value), currentMs); - drawText(42, 256, value, gLongPauseActive ? C_BAD : C_TEXT, 3); - - clearArea(266, 254, 160, 28, C_CARD); - if (avgMs > 0) { - formatSec(value, sizeof(value), avgMs); - } else { - snprintf(value, sizeof(value), "--"); - } - drawText(266, 256, value, C_TEXT, 3); - - clearArea(42, 336, 170, 30, C_CARD); - formatClock(value, sizeof(value), runMs); - drawText(42, 338, value, C_TEXT, 3); - - clearArea(266, 336, 160, 30, C_CARD); - snprintf(value, sizeof(value), "%us", kLimitsSec[gLimitIndex]); - drawText(266, 338, value, C_TEXT, 3); - - formatLastFiveCycles(line, sizeof(line)); - if (strcmp(line, gLastBottomLine) != 0) { - clearArea(24, 398, 432, 40, C_PANEL); - drawText(30, 402, line, (gLongPauseEvents || gShortAvgEvents) ? C_BAD : C_MUTE, 1); - strncpy(gLastBottomLine, line, sizeof(gLastBottomLine) - 1); - gLastBottomLine[sizeof(gLastBottomLine) - 1] = '\0'; - } -} - -static void redrawScreen() { - if (!gScreenOn) { - gNeedRedraw = false; - return; - } - if (gSettingsOpen) { - drawSettingsScreen(); - } else if (gInputMode == InputMode::PotTest || gInputMode == InputMode::PotTwoWireTest) { - if (gNeedStaticRedraw || !gStaticDrawn) { - drawPotStatic(); - gNeedStaticRedraw = false; - } - updatePotValues(true); - } else if (gInputMode == InputMode::PotCalTest) { - if (gNeedStaticRedraw || !gStaticDrawn) { - drawPotCalStatic(); - gNeedStaticRedraw = false; - } - updatePotCalValues(); - } else if (gInputMode == InputMode::UsbPinDiag) { - if (gNeedStaticRedraw || !gStaticDrawn) { - drawPinDiagStatic(); - gNeedStaticRedraw = false; - } - updatePinDiagValues(); - } else if (gStarted) { - if (gNeedStaticRedraw || !gStaticDrawn) { - drawMonitorStatic(); - gNeedStaticRedraw = false; - } - updateMonitorValues(true); - } else { - drawReadyScreen(); - } - drawBatteryStatus(); - gNeedRedraw = false; - gLastUiMs = millis(); -} - -static void startMonitor(InputMode mode) { - uint32_t now = millis(); - gStarted = true; - gInputMode = mode; - gPotFault = false; - gStartedMs = now; - gLastCycleStartMs = 0; - gPhaseStartMs = 0; - gInExhale = false; - gButtonPhaseKnown = false; - gInhalePressClosedSettings = false; - gLongPauseActive = false; - gCycleCount = 0; - gCycleNext = 0; - gShortStreak = 0; - gShortAvgEvents = 0; - gLongPauseEvents = 0; - gLastRepeatAlertMs = 0; - gLastManualReminderSlot = 0; - resetPotCal(); - memset(gCycleMs, 0, sizeof(gCycleMs)); - if (mode == InputMode::UsbContact) { - Serial.flush(); - delay(30); - pinMode(kUsbDmPin, OUTPUT); - digitalWrite(kUsbDmPin, LOW); - pinMode(kUsbDpPin, INPUT_PULLUP); - gLastRawClosed = (digitalRead(kUsbDpPin) == LOW); - gLastRawChangeMs = now; - gInExhale = gLastRawClosed; - if (gInExhale) { - gLastCycleStartMs = now; - playCycleTick(); - } - } else if (mode == InputMode::PotTest || mode == InputMode::PotTwoWireTest || mode == InputMode::PotCalTest) { - Serial.flush(); - delay(30); - pinMode(kUsbDmPin, OUTPUT); - digitalWrite(kUsbDmPin, HIGH); - pinMode(kUsbDpPin, (mode == InputMode::PotTwoWireTest || mode == InputMode::PotCalTest) ? INPUT_PULLDOWN : INPUT); - analogReadResolution(12); - analogSetPinAttenuation(kUsbDpPin, ADC_11db); - } else if (mode == InputMode::UsbPinDiag) { - Serial.flush(); - delay(30); - analogReadResolution(12); - analogSetPinAttenuation(kUsbDmPin, ADC_11db); - analogSetPinAttenuation(kUsbDpPin, ADC_11db); - releaseUsbPins(); - } - gNeedStaticRedraw = true; - gNeedRedraw = true; -} - -static void toggleSettings() { - if (!gStarted) startMonitor(InputMode::ExternalButtons); - gSettingsOpen = !gSettingsOpen; - if (gSettingsOpen) gSettingsScroll = 0; - gNeedStaticRedraw = true; - gNeedRedraw = true; - resetCachedUiText(); -} - -static bool handleBreathPress(bool exhale) { - if (!gStarted) startMonitor(InputMode::ExternalButtons); - - if (gInputMode == InputMode::ExternalButtons) { - // Manual phases must alternate. A repeated button press has no side effects. - if ((!gButtonPhaseKnown && exhale) || (gButtonPhaseKnown && exhale == gInExhale)) { - return false; - } - } - - uint32_t now = millis(); - bool shouldPlayTick = gInputMode == InputMode::ExternalButtons; - if (gLongPauseActive) { - gLongPauseActive = false; - gLastRepeatAlertMs = 0; - } - if (exhale) { - if (gLastCycleStartMs != 0) { - uint32_t cycleMs = now - gLastCycleStartMs; - if (cycleMs >= kPauseAfterMs) { - gLongPauseActive = false; - gLastCycleStartMs = now; - shouldPlayTick = true; - } else if (cycleMs >= minCycleMsForCurrentMode()) { - addCycle(cycleMs); - gLastCycleStartMs = now; - gLongPauseActive = false; - shouldPlayTick = true; - alertIfNeeded(); - } - } else { - gLastCycleStartMs = now; - gLongPauseActive = false; - shouldPlayTick = true; - } - gInExhale = true; - } else { - gInExhale = false; - } - - if (gInputMode == InputMode::ExternalButtons) { - gButtonPhaseKnown = true; - gPhaseStartMs = now; - gLastManualReminderSlot = 0; - } - if (shouldPlayTick) playCycleTick(); - - if (!gSettingsOpen) gNeedRedraw = true; - return true; -} - -static uint8_t sliderValueFromX(const Rect &rect, int16_t x, uint8_t maxValue) { - int16_t left = rect.x + 22; - int16_t right = rect.x + rect.w - 22; - if (x < left) x = left; - if (x > right) x = right; - return (uint8_t)(((uint32_t)(x - left) * maxValue + (right - left) / 2) / (right - left)); -} - -static void handleSettingsTouch(int16_t x, int16_t y) { - int16_t contentY = y + gSettingsScroll * 112; - if (contains(kLimitSlider, x, contentY)) { - uint8_t next = sliderValueFromX(kLimitSlider, x, 4); - if (next == gLimitIndex) return; - gLimitIndex = next; - } else if (contains(kTickSlider, x, contentY)) { - uint8_t next = sliderValueFromX(kTickSlider, x, 10); - if (next == gTickVolume) return; - gTickVolume = next; - playCycleTick(); - } else if (contains(kAlertSlider, x, contentY)) { - uint8_t next = sliderValueFromX(kAlertSlider, x, 10); - if (next == gAlertVolume) return; - gAlertVolume = next; - playAlertBeep(); - } else if (contains(kScreenSlider, x, contentY)) { - uint8_t next = sliderValueFromX(kScreenSlider, x, 3); - if (next == gScreenTimeoutIndex) return; - gScreenTimeoutIndex = next; - } else { - return; - } - saveSettings(); - gNeedRedraw = true; -} - -static void handleTap(int16_t x, int16_t y, uint32_t heldMs) { - if (gSettingsOpen) { - handleSettingsTouch(x, y); - return; - } - - if (!gStarted && contains(kStartUsbButton, x, y)) { - startMonitor(InputMode::UsbContact); - return; - } - if (!gStarted && contains(kStartButtonsButton, x, y)) { - startMonitor(InputMode::ExternalButtons); - return; - } - if (!gStarted && contains(kStartPotButton, x, y)) { - startMonitor(InputMode::PotTest); - return; - } - if (!gStarted && contains(kStartPot2Button, x, y)) { - startMonitor(InputMode::PotTwoWireTest); - return; - } - if (!gStarted && contains(kStartPotCalButton, x, y)) { - startMonitor(InputMode::PotCalTest); - return; - } - if (!gStarted && contains(kStartPinDiagButton, x, y)) { - startMonitor(InputMode::UsbPinDiag); - return; - } - - (void)heldMs; -} - -static void pollExternalButtons() { - if (!gStarted) return; - - uint32_t now = millis(); - bool pressed = false; - bool released = false; - uint32_t heldMs = 0; - pollButtonEvent(gInhaleButton, now, pressed, released, heldMs); - if (pressed) noteScreenActivity(); - if (gInputMode == InputMode::UsbContact) { - if (pressed) { - toggleSettings(); - } - return; - } - if (gInputMode == InputMode::PotCalTest) { - if (pressed) { - resetPotCal(); - gNeedRedraw = true; - } - return; - } - if (gInputMode != InputMode::ExternalButtons) return; - - if (pressed) { - gInhalePressClosedSettings = gSettingsOpen; - handleBreathPress(false); - if (gInhalePressClosedSettings) toggleSettings(); - } - if (released) { - if (!gInhalePressClosedSettings && heldMs >= kLongPressMs) { - toggleSettings(); - } - gInhalePressClosedSettings = false; - } - pollButtonEvent(gExhaleButton, now, pressed, released, heldMs); - if (pressed) { - noteScreenActivity(); - handleBreathPress(true); - } -} - -static void pollUsbContact() { - if (!gStarted || gInputMode != InputMode::UsbContact) return; - - bool rawClosed = (digitalRead(kUsbDpPin) == LOW); - uint32_t now = millis(); - if (rawClosed != gLastRawClosed) { - gLastRawClosed = rawClosed; - gLastRawChangeMs = now; - } - if ((now - gLastRawChangeMs) >= kContactDebounceMs && rawClosed != gInExhale) { - handleBreathPress(rawClosed); - } -} - -static void pollTouch() { - int16_t x = 0; - int16_t y = 0; - bool touching = gTouch.getPoint(&x, &y, 1) > 0; - if (touching && !gTouchDown) { - noteScreenActivity(); - gTouchDown = true; - gTouchStartX = x; - gTouchStartY = y; - gTouchLastX = x; - gTouchLastY = y; - gTouchDownMs = millis(); - return; - } - if (touching && gTouchDown) { - gTouchLastX = x; - gTouchLastY = y; - return; - } - if (!touching && gTouchDown) { - gTouchDown = false; - int dx = abs(gTouchLastX - gTouchStartX); - int dy = abs(gTouchLastY - gTouchStartY); - if (dx >= 18 || dy >= 18) { - if (gSettingsOpen && dy >= 18) { - if (gTouchLastY < gTouchStartY && gSettingsScroll == 0) { - gSettingsScroll = 1; - gNeedRedraw = true; - } else if (gTouchLastY > gTouchStartY && gSettingsScroll == 1) { - gSettingsScroll = 0; - gNeedRedraw = true; - } - } - return; - } - handleTap(gTouchLastX, gTouchLastY, millis() - gTouchDownMs); - } -} - -void setup() { - Serial.begin(115200); - Wire.begin(PIN_I2C_SDA, PIN_I2C_SCL); - pinMode(PIN_INHALE, INPUT_PULLUP); - pinMode(PIN_EXHALE, INPUT_PULLUP); - initPowerManagement(); - loadSettings(); - initAudio(); - - gfx->begin(); - gBus->writeC8D8(0x36, 0xA0); - gfx->setBrightness(220); - gfx->fillScreen(C_BG); - gLastScreenActivityMs = millis(); - - gTouch.setPins(PIN_TP_INT, -1); - bool touchOk = gTouch.begin(Wire, CST92XX_SLAVE_ADDRESS, PIN_I2C_SDA, PIN_I2C_SCL); - gTouch.setMaxCoordinates(DISP_W, DISP_H); - gTouch.setSwapXY(true); - gTouch.setMirrorXY(true, false); - - Serial.println("Dual mode breath monitor ready."); - Serial.println(touchOk ? "Touch init OK" : "Touch init failed"); - gNeedRedraw = true; -} - -void loop() { - pollTouch(); - pollExternalButtons(); - pollUsbContact(); - pollBreathAlerts(); - pollScreenTimeout(); - if (gScreenOn && gStarted && !gSettingsOpen && - (gInputMode == InputMode::PotTest || gInputMode == InputMode::PotTwoWireTest) && - millis() - gLastPotUiMs >= kPotUiPeriodMs) { - updatePotValues(false); - gLastPotUiMs = millis(); - } - if (gScreenOn && gStarted && !gSettingsOpen && gInputMode == InputMode::PotCalTest && - millis() - gLastPotUiMs >= kPotUiPeriodMs) { - updatePotCalValues(); - gLastPotUiMs = millis(); - } - if (gScreenOn && gStarted && !gSettingsOpen && gInputMode == InputMode::UsbPinDiag && - millis() - gLastPinDiagUiMs >= kPinDiagPeriodMs) { - updatePinDiagValues(); - gLastPinDiagUiMs = millis(); - } - if (gScreenOn && gStarted && !gSettingsOpen && - gInputMode != InputMode::PotTest && gInputMode != InputMode::PotTwoWireTest && - gInputMode != InputMode::PotCalTest && - gInputMode != InputMode::UsbPinDiag && - millis() - gLastUiMs >= kUiPeriodMs) { - updateMonitorValues(false); - gLastUiMs = millis(); - } - if (gScreenOn && millis() - gLastBatteryUiMs >= kBatteryUiPeriodMs) { - drawBatteryStatus(); - gLastBatteryUiMs = millis(); - } - if (gNeedRedraw) { - redrawScreen(); - } - delay(10); -} diff --git a/breath_button_monitor/breath_button_monitor/README.md b/breath_button_monitor/breathmonitor_v1 button_monitor/README.md similarity index 100% rename from breath_button_monitor/breath_button_monitor/README.md rename to breath_button_monitor/breathmonitor_v1 button_monitor/README.md diff --git a/breath_button_monitor/breath_button_monitor/breath_button_monitor.ino b/breath_button_monitor/breathmonitor_v1 button_monitor/breath_button_monitor.ino similarity index 100% rename from breath_button_monitor/breath_button_monitor/breath_button_monitor.ino rename to breath_button_monitor/breathmonitor_v1 button_monitor/breath_button_monitor.ino diff --git a/breath_button_monitor/breath_button_monitor/burn.sh b/breath_button_monitor/breathmonitor_v1 button_monitor/burn.sh similarity index 100% rename from breath_button_monitor/breath_button_monitor/burn.sh rename to breath_button_monitor/breathmonitor_v1 button_monitor/burn.sh diff --git a/breath_button_monitor/breath_button_monitor/es8311.c b/breath_button_monitor/breathmonitor_v1 button_monitor/es8311.c similarity index 100% rename from breath_button_monitor/breath_button_monitor/es8311.c rename to breath_button_monitor/breathmonitor_v1 button_monitor/es8311.c diff --git a/breath_button_monitor/breath_button_monitor/es8311.h b/breath_button_monitor/breathmonitor_v1 button_monitor/es8311.h similarity index 100% rename from breath_button_monitor/breath_button_monitor/es8311.h rename to breath_button_monitor/breathmonitor_v1 button_monitor/es8311.h diff --git a/breath_button_monitor/breath_button_monitor/es8311_reg.h b/breath_button_monitor/breathmonitor_v1 button_monitor/es8311_reg.h similarity index 100% rename from breath_button_monitor/breath_button_monitor/es8311_reg.h rename to breath_button_monitor/breathmonitor_v1 button_monitor/es8311_reg.h diff --git a/breath_button_monitor/manual_monitor_lvgl_v2/AGENTS.md b/breath_button_monitor/breathmonitor_v2 lvgl/AGENTS.md similarity index 100% rename from breath_button_monitor/manual_monitor_lvgl_v2/AGENTS.md rename to breath_button_monitor/breathmonitor_v2 lvgl/AGENTS.md diff --git a/breath_button_monitor/manual_monitor_lvgl_v2/README.md b/breath_button_monitor/breathmonitor_v2 lvgl/README.md similarity index 100% rename from breath_button_monitor/manual_monitor_lvgl_v2/README.md rename to breath_button_monitor/breathmonitor_v2 lvgl/README.md diff --git a/breath_button_monitor/manual_monitor_lvgl_v2/burn.sh b/breath_button_monitor/breathmonitor_v2 lvgl/burn.sh similarity index 100% rename from breath_button_monitor/manual_monitor_lvgl_v2/burn.sh rename to breath_button_monitor/breathmonitor_v2 lvgl/burn.sh diff --git a/breath_button_monitor/manual_monitor_lvgl_v2/download_breath_log.py b/breath_button_monitor/breathmonitor_v2 lvgl/download_breath_log.py similarity index 100% rename from breath_button_monitor/manual_monitor_lvgl_v2/download_breath_log.py rename to breath_button_monitor/breathmonitor_v2 lvgl/download_breath_log.py diff --git a/breath_button_monitor/breath_dual_mode_monitor/es8311.c b/breath_button_monitor/breathmonitor_v2 lvgl/es8311.c similarity index 100% rename from breath_button_monitor/breath_dual_mode_monitor/es8311.c rename to breath_button_monitor/breathmonitor_v2 lvgl/es8311.c diff --git a/breath_button_monitor/breath_dual_mode_monitor/es8311.h b/breath_button_monitor/breathmonitor_v2 lvgl/es8311.h similarity index 100% rename from breath_button_monitor/breath_dual_mode_monitor/es8311.h rename to breath_button_monitor/breathmonitor_v2 lvgl/es8311.h diff --git a/breath_button_monitor/breath_dual_mode_monitor/es8311_reg.h b/breath_button_monitor/breathmonitor_v2 lvgl/es8311_reg.h similarity index 100% rename from breath_button_monitor/breath_dual_mode_monitor/es8311_reg.h rename to breath_button_monitor/breathmonitor_v2 lvgl/es8311_reg.h diff --git a/breath_button_monitor/manual_monitor_lvgl_v2/manual_monitor_lvgl_v2.ino b/breath_button_monitor/breathmonitor_v2 lvgl/manual_monitor_lvgl_v2.ino similarity index 100% rename from breath_button_monitor/manual_monitor_lvgl_v2/manual_monitor_lvgl_v2.ino rename to breath_button_monitor/breathmonitor_v2 lvgl/manual_monitor_lvgl_v2.ino diff --git a/breath_button_monitor/breathmonitor_v3 with server/AGENTS.md b/breath_button_monitor/breathmonitor_v3 with server/AGENTS.md new file mode 100644 index 0000000..6c35483 --- /dev/null +++ b/breath_button_monitor/breathmonitor_v3 with server/AGENTS.md @@ -0,0 +1,130 @@ +# AGENTS — BreathMonitor v3 + +## Назначение + +Эта папка содержит третью версию автономного ESP32-монитора дыхания и отдельный Java/SQLite-сервер. + +- `firmware/` — прошивка для Waveshare ESP32-S3-Touch-AMOLED-2.16. +- `server/` — исходники Java-сервера, Gradle-сборка и веб-интерфейс. +- `deploy/` — шаблон systemd-службы и отдельный фрагмент Caddy. + +## Обязательные правила + +- Все изменения этого проекта относятся к репозиторию `SKETCH`, не смешивать их с коммитами `SHiNE-product`. +- Основной язык документации и пояснений — русский. +- Не удалять FFat при обновлении прошивки. Не использовать `Erase All Flash`, если нужно сохранить локальные журналы. +- Если при старте появляется `STORAGE ERROR`, нажимать `FORMAT FFat` только после проверки/резервирования локальных журналов; без подтверждения прошивка форматирование не выполняет. +- Перед прошивкой убедиться, что выбрана схема `app3M_fat9M_16MB`. +- Не менять формат записей журналов и API без отдельного согласования: сервер проверяет 32-байтные записи, CRC32 и префиксную целостность загрузок. +- Не хранить пароли, токены, SQLite-базу и реальные серверные секреты в git. + +## Прошивка + +Плата и библиотеки такие же, как у `breathmonitor_v2 lvgl`. `firmware/burn.sh` использует библиотеки из: + +`SHiNE-product/ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/official-demo/examples/Arduino-v3.3.5/libraries` + +Сборка без загрузки: + +```bash +cd "SKETCH/breath_button_monitor/breathmonitor_v3 with server/firmware" +NO_UPLOAD=1 ./burn.sh +``` + +Загрузка на подключённую плату: + +```bash +PORT=/dev/ttyACM0 ./burn.sh +``` + +Скрипт использует ESP32 core 3.3.5, FQBN с 16 MB Flash, PSRAM OPI и разделом `app3M_fat9M_16MB`. Перед загрузкой проверить порт командой `arduino-cli board list`. + +## Серверная сборка + +Сервер всегда собирается локально. VPS не должен запускать Maven, Gradle или компилятор. + +```bash +cd "SKETCH/breath_button_monitor/breathmonitor_v3 with server/server" +./gradlew --no-daemon clean shadowJar +``` + +Требуется JDK 17. Результат: + +`server/build/libs/breathmonitor-1.0.0.jar` + +Проверить локально запуск и health можно так: + +```bash +BREATH_DATA_DIR="$PWD/.local-data" \ +BREATH_WEB_DIR="$PWD/web" \ +PUBLIC_ORIGIN="https://breathmonitor.shineup.me" \ +java -jar build/libs/breathmonitor-1.0.0.jar +``` + +Для VPS передаётся только готовый JAR и при необходимости статические файлы `web/`. Не выполнять на VPS `build.sh`, `gradlew`, `mvn` или компиляцию. + +## Деплой сервера + +Целевой адрес: `breathmonitor.shineup.me`, VPS: `178.208.90.249`. SSH-пользователь текущего тестового контура — `player`. + +Постоянные пути на VPS: + +- приложение: `/opt/breathmonitor/server` +- JAR: `/opt/breathmonitor/server/build/libs/breathmonitor-1.0.0.jar` +- данные SQLite и журналы: `/var/lib/breathmonitor` +- systemd unit: `/etc/systemd/system/breathmonitor.service` +- Caddy: `/etc/caddy/Caddyfile` +- внутренний HTTP-порт: `127.0.0.1:8090` + +Безопасный порядок обновления: + +1. Локально собрать и проверить JAR. +2. Передать только JAR во временный файл на VPS через `rsync`. +3. Сделать копию текущего JAR и проверить права. +4. Атомарно заменить JAR, не удаляя `/var/lib/breathmonitor`. +5. Перезапустить только `breathmonitor.service`. +6. Проверить `systemctl status breathmonitor` и `curl https://breathmonitor.shineup.me/api/health`. +7. Caddy не перезапускать при обычном обновлении JAR. Перезагрузка Caddy нужна только при изменении его конфигурации. + +Пример передачи готового артефакта: + +```bash +rsync -az server/build/libs/breathmonitor-1.0.0.jar \ + player@178.208.90.249:/tmp/breathmonitor-1.0.0.jar +``` + +Дальнейшая замена требует SSH/sudo-доступа и выполняется отдельно от сборки. При недоступном VPS не повторять сборку удалённо и не трогать существующие сервисы. + +## Первый запуск и аккаунт + +Сервис запускается от системного пользователя `breathmonitor` и использует `BREATH_DATA_DIR=/var/lib/breathmonitor`. + +Создание аккаунта выполняется один раз на VPS с тем же каталогом данных: + +```bash +sudo -u breathmonitor env BREATH_DATA_DIR=/var/lib/breathmonitor \ + /opt/breathmonitor/server/start.sh create-user aidar +``` + +Текущая версия допускает пароль длиной от 1 до 63 символов. Короткие пароли допустимы только для закрытого тестового контура; для публичного использования нужен длинный пароль. + +## Проверки после обновления + +```bash +curl -fsS https://breathmonitor.shineup.me/api/health +sudo systemctl is-active breathmonitor +sudo journalctl -u breathmonitor -n 70 --no-pager +``` + +После прошивки на приборе проверить Wi-Fi, синхронизацию времени, `ONLINE → ACCOUNT`, `PAIR`, затем `UPLOAD`. Журналы на устройстве не удалять при диагностике; использовать USB-команды `LOG INFO`, `LOG LIST` и `LOG DOWNLOAD <дата>`. + +## Резервирование + +Резервировать нужно SQLite-базу с учётом WAL и каталог журналов: + +- `/var/lib/breathmonitor/statistics.db` +- `/var/lib/breathmonitor/statistics.db-wal` +- `/var/lib/breathmonitor/statistics.db-shm` +- `/var/lib/breathmonitor/logs/` + +Не заменять каталог данных при обновлении приложения и не выполнять `rsync --delete` по `/var/lib/breathmonitor`. diff --git a/breath_button_monitor/breathmonitor_v3 with server/README_RU.md b/breath_button_monitor/breathmonitor_v3 with server/README_RU.md new file mode 100644 index 0000000..5389ef9 --- /dev/null +++ b/breath_button_monitor/breathmonitor_v3 with server/README_RU.md @@ -0,0 +1,186 @@ +# BreathMonitor — автономный прибор + Java/SQLite сервер + +**Комплект для развёртывания** · 24 октября 2026 года +Адрес API и сайта уже задан: **https://breathmonitor.shineup.me** + +Это исходники готовой первой интеграционной версии, а не подтверждённая сборка для конкретной платы: Java-код и парсер рассчитаны на JDK 17, но `.ino` требуется собрать в Arduino IDE с исходными библиотеками и проверить на физическом ESP32-S3. Интернет в среде сборки отсутствовал, поэтому готовый исполняемый JAR с SQLite JDBC не вложен: `server/build.sh` соберёт его Gradle, скачав зависимости из Maven Central. + +## Содержимое + +```text +firmware/breathmonitor_lvgl.ino — изменённый скетч (исходный UI, измерения, RTC) +firmware/ISRG_Root_X1_reference.pem — копия публичного корневого сертификата (он уже встроен в .ino) +server/BreathServer.java — один Java-класс: API, SQLite, HTTPS через Caddy, веб-сайт +server/RecordFixtureTest.java — тест бинарного формата/CRC32 без JDBC +server/build.gradle — зависимости SQLite JDBC, SLF4J и сборка jar +server/build.sh — Gradle package +server/start.sh — запуск и админ-команды +server/web/ — независимая HTML/CSS/JavaScript статистика +deploy/Caddyfile.fragment — пример секции для Caddy +deploy/breathmonitor.service — пример службы systemd +``` + +## 1. Изменения прибора + +- **Без постоянного Wi-Fi.** После загрузки радиомодуль выключен. Операция `TIME → SYNC NOW` подключает известную сеть, синхронизирует NTP+RTC, выключает Wi-Fi. `ONLINE → UPLOAD` делает то же самое для передачи журналов. `Wi-Fi → TEST` проверяет доступность сети и отключает модуль. +- До восьми сохранённых SSID и паролей перенесены из старой прошивки без изменения ключей `manual-wifi`. +- Если известные Wi-Fi недоступны, открывается список сетей; после выбора/ввода пароля ранее запрошенная операция продолжается автоматически. +- **Журнал по дням:** `/logs/20261024.bin` и т. п., записи по 32 байта, версия 1 + CRC32. Запись только в конец, существующие дневные файлы продолжаются после перезагрузки. `/logs/undated.bin` — события при недостоверном времени. +- `/events.bin` из исходной прошивки **не удаляется**. При первом запуске записи переносятся в дневные файлы, успешный перенос фиксируется `/migration.done`. При аварийном выключении перенос пробуется снова; старый исходный файл остаётся. Неверные CRC в старом файле пропускаются, но остаются в оригинале для диагностики. +- Автоформатирование FFat отключено (`FFat.begin(false)`). Если FFat не монтируется, прибор показывает на экране подтверждение `FORMAT FFat`; форматирование выполняется только после явного нажатия и удаляет локальные журналы. +- `ONLINE → ACCOUNT`: ввести логин и пароль учётной записи сайта, затем `PAIR` или сразу `UPLOAD`. Введённый пароль живёт в RAM до авторизации; хранится отдельный токен устройства в Preferences. После перезагрузки пароль не нужен. +- `ONLINE → REUPLOAD` очищает **только индекс отправленных размеров** `/sync.state`, не сами журналы. При следующем `UPLOAD` прибор повторно отправит все дневные файлы (сервер не дублирует циклы). +- Передача HTTPS в отдельной FreeRTOS-задаче; измерения и обновление LVGL продолжаются в основном цикле. Отправляется зафиксированный на момент начала передачи размер файла: новые записи попадут в следующую синхронизацию. +- Публичный ключ SSL не выключен: прошивка доверяет **ISRG Root X1**. Caddy должен получить совместимый сертификат Let's Encrypt. При смене удостоверяющего центра нужно обновить доверенный сертификат в прошивке. + +**USB CDC:** доступны `LOG INFO`, `LOG LIST`, `LOG DOWNLOAD 20261024`, `LOG DOWNLOAD undated`, `LOG DOWNLOAD LEGACY`. `LOG DOWNLOAD` без указания даты больше не поддерживается. Бинарные данные передаются HEX-строками между `LOG BEGIN ...` и `LOG END`. + +**Важно при прошивке:** используйте тот же раздел/Partition Scheme, который содержал исходный FFat, и не выбирайте `Erase All Flash`. Перепрошивка с изменением разметки может стереть старые журналы. До прошивки сделайте резервную копию `/events.bin` через исходную команду `LOG DOWNLOAD`. + +## 2. Установка Java + SQLite (Ubuntu) + +На сервере с Caddy и доступом в интернет: + +```bash +sudo apt update +sudo apt install -y openjdk-17-jdk gradle +# Скопируйте папку server в /opt/breathmonitor/server +cd /opt/breathmonitor/server +chmod +x build.sh start.sh +./build.sh +``` + +Сборка создаёт `target/breathmonitor-1.0.0.jar`. Это самодостаточный shaded JAR, включающий SQLite JDBC и SLF4J. Другой процесс базы данных не нужен. + +Для первого запуска от текущего пользователя: + +```bash +cd /opt/breathmonitor/server +./start.sh create-user aidar +# Введите пароль длиной 1–63 символа +./start.sh create-user anna +./start.sh +``` + +Админ-команда сброса пароля: + +```bash +./start.sh reset-password aidar +``` + +**Сброс пароля отзывает все веб-сессии и токены привязанных устройств**; пароль и привязку придётся ввести заново. + +По умолчанию: +- Java-сервер слушает **только** `127.0.0.1:8090`, так что он не доступен напрямую из интернета. +- База данных находится в `server/data/statistics.db`, журналы в `server/data/logs///_YYYYMMDD.bin`. +- Файлы фронтенда читаются из `server/web`. +- Значения настраиваются переменными `BREATH_PORT`, `BREATH_BIND`, `BREATH_DATA_DIR`, `BREATH_WEB_DIR`, `PUBLIC_ORIGIN`. + +### Служба systemd + +Для постоянного запуска рекомендуется отдельный системный пользователь и каталог данных: + +```bash +sudo useradd --system --user-group --no-create-home --shell /usr/sbin/nologin breathmonitor || true +sudo mkdir -p /var/lib/breathmonitor +sudo chown -R breathmonitor:breathmonitor /var/lib/breathmonitor +sudo chown -R root:root /opt/breathmonitor/server +sudo cp /opt/breathmonitor/deploy/breathmonitor.service /etc/systemd/system/ +sudo systemctl daemon-reload +# Сначала создайте пользователей, используя то же BREATH_DATA_DIR и от имени breathmonitor: +sudo -u breathmonitor env BREATH_DATA_DIR=/var/lib/breathmonitor bash -c 'cd /opt/breathmonitor/server && ./start.sh create-user aidar' +sudo systemctl enable --now breathmonitor +sudo journalctl -u breathmonitor -n 70 --no-pager +``` + +Не создавайте сначала пользователей в `server/data/`, а потом не переключайтесь на `/var/lib/breathmonitor`: это **разные** базы данных. При необходимости перенесите каталог данных до запуска службы. + +## 3. Caddy / HTTPS / DNS + +Настройте DNS-запись `A` (и при необходимости `AAAA`) для `breathmonitor.shineup.me` на адрес вашего сервера. В вашем существующем Caddyfile добавьте блок из `deploy/Caddyfile.fragment`, не перезаписывая остальные сайты. Прибор всегда использует `https://breathmonitor.shineup.me` — адрес уже в `.ino`. + +```bash +sudo caddy fmt --overwrite /etc/caddy/Caddyfile +sudo caddy validate --config /etc/caddy/Caddyfile +sudo systemctl reload caddy +curl -i https://breathmonitor.shineup.me/api/health +``` + +Ответ должен быть HTTP 200 и `{"ok":true}`. Затем откройте сайт в браузере, войдите под созданным логином и паролем. + +Текущая версия Caddy сама использует стандартный Let's Encrypt. Это важно, поскольку `ROOT_CA` прошивки содержит только ISRG Root X1; другой TLS-издатель может не пройти проверку. Если у вас уже есть отдельный wildcard-сертификат, сначала проверьте его цепочку доверия и при необходимости обновите `ROOT_CA`. + +## 4. Первое подключение прибора + +1. Установить обновлённую прошивку без стирания FFat/Preferences. +2. `SETTINGS → Wi-Fi → SCAN`: выбрать свою сеть, ввести пароль, дождаться успешной проверки. Сеть сохранится. +3. `SETTINGS → TIME → SYNC NOW`: получить точное время и выключить Wi-Fi. После NTP аппаратные часы продолжают работать автономно. +4. `SETTINGS → ONLINE → ACCOUNT → LOGIN`: ввести **тот же** логин, что создали командой `create-user`. +5. `PASSWORD`: ввести пароль аккаунта; `PAIR` — одноразово получить токен (или просто `ONLINE → UPLOAD`, и привязка выполнится при первой выгрузке). +6. Сделать несколько циклов дыхания и нажать `ONLINE → UPLOAD`. Увидеть сообщение `Done: ... uploaded`. Через браузер обновить страницу статистики. +7. Последующие загрузки выполняются одним нажатием `UPLOAD`; пароль повторно не вводится. + +На приборах с заводским/сброшенным RTC перед защищённой отправкой автоматически выполняется NTP. Если отсутствует интернет/NTP, файлы продолжают сохраняться локально; при неудачной синхронизации не удаляются. + +## 5. Формат API (для отладки) + +| Метод и путь | Назначение | Авторизация | +|---|---|---| +| `GET /api/health` | проверка сервера | нет | +| `POST /api/device/login` | `login\npassword\nDEVICEID` → 64 шестнадцатеричных символа токена | пароль пользователя | +| `PUT /api/device/upload?date=20261024` | сырое тело `.bin`, заголовки `Authorization: Bearer TOKEN` и `X-Device-ID: <12 hex>` | токен устройства | +| `POST /api/login` | логин в браузере | пароль пользователя; cookie с Secure/HttpOnly | +| `GET /api/me` | профиль | cookie | +| `GET /api/stats` | личная статистика | cookie | +| `GET /api/leaderboard` | открытый рейтинг только согласившихся | нет | +| `POST /api/privacy` | тело `true` или `false`, включение публичного рейтинга | cookie + проверка Origin | +| `POST /api/logout` | выход | cookie + проверка Origin | + +Сервер проверяет каждую 32-байтную запись и CRC32. Если файл уже существует, новая версия обязана **полностью содержать старый файл как начальный префикс**. Повторная отправка идентичной версии не добавляет циклы; изменение/уменьшение журнала отклоняется с HTTP 409. После проверки файл атомарно заменяется, а суточная статистика пересчитывается и записывается в SQLite через UPSERT. Для разных устройств одного пользователя файлы лежат в отдельных папках. + +## 6. Конфиденциальность, администрирование, резервные копии + +- По умолчанию **все аккаунты приватные**; другие люди не видят их результаты. Пользователь может включить публичный рейтинг в личном кабинете. В рейтинг попадают только агрегированные показатели, не подробные записи. +- Password storage: PBKDF2-HMAC-SHA256 с солью и 210 тыс. итераций. Веб-сессии и токены устройств в БД хранятся как SHA-256-хеши. Базовые ограничения на перебор логина — до 12 попыток с IP за минуту (для публичного большого проекта позже нужен усиленный anti-abuse перед Caddy). +- Важно делать резервные копии **и `statistics.db` (с учётом SQLite WAL), и `data/logs/`**. При работающем сервере лучше снимать транзакционный SQLite backup, а не просто копировать открытый файл базы без `-wal`. +- Долговременное сохранение FFat зависит от носителя и состояния питания. Базовую защиту обеспечивают append-only журналы, контроль CRC и серверные копии; для критичных данных нужен дополнительный журнал транзакций/резервирование. +- Сайт не утверждает, что измеряет здоровье или качество медитации. Он показывает только события, зафиксированные прибором. + +## 7. Известные ограничения первой версии + +1. `.ino` пока не прошёл аппаратную компиляцию, прошивку и испытания на вашей конкретной плате. Исходный LVGL UI, сенсор, IMU и аудио сохранены, но реальный тест кнопок, Wi-Fi и FFat обязателен. +2. Серверный Java-класс синтаксически компилируется; двоичный тест CRC и декодирования цикла пройден. Полный тест запуска SQLite/JDBC требует загрузки зависимостей Gradle из Maven Central. +3. Для простоты передаётся **целиком изменившийся суточный файл** (а не только его добавленный хвост); при типичном размере десятки КБ это нормально. Загрузка ограничена 16 МиБ на файл. +4. Если текущий дневной файл физически повреждён или содержит неполную запись, отправка этого файла отклоняется; прибор не удаляет файл автоматически. Нужна ручная диагностика через `LOG LIST`/USB. +5. При недостоверных часах события попадают в `undated.bin`. Автоматически приписывать им выдуманную дату нельзя: их можно учесть в общей сумме, но не привязать надёжно к календарному дню без дополнительной информации. +6. Суточная дата задаётся **фиксированным** UTC-смещением в настройках прибора (автоматический переход на летнее/зимнее время пока не предусмотрен). +7. Изменение времени/смещения суток не переименовывает уже записанные файлы. В случае некорректного времени возможен дневной файл с неправильной датой; хранящиеся в каждой записи UTC и флаг доверия дают возможность дальнейшей коррекции. +8. Устройства на одном аккаунте считаются вместе. Разные физические устройства должны иметь разные ID ESP32. В **первой версии прибор рассчитан на одного владельца**: после успешной привязки вход в другой аккаунт с того же прибора заблокирован, чтобы не загрузить личную историю прежнего владельца в чужой аккаунт. Для передачи устройства другому человеку нужно сначала экспортировать/архивировать журналы и безопасно сбросить локальное хранилище и Preferences (реализация безопасного сброса — отдельная задача). +9. Регистрация пользователей выполняется администратором через CLI; самостоятельная регистрация на сайте не реализована. +10. В `ONLINE → REUPLOAD` удаляется только локальный индекс выгрузок. Если сервер получил отличающуюся старую историю, он вернёт HTTP 409: безопаснее исследовать конфликт, чем автоматически переписать старые данные. + +## 8. Проверки до ежедневного использования + +- Питание OFF/ON посреди дня → количество 32-байтных записей в текущем файле увеличивается, записи не исчезают. +- Переход через полночь по настроенному времени → создаётся новый датированный файл. +- Сохранённая Wi-Fi сеть недоступна → устройство предлагает список сетей и затем продолжает именно TIME/UPLOAD. +- Отключение интернет-кабеля во время отправки → файл на приборе остаётся, повторная синхронизация работает. +- Повторный `UPLOAD` без новых циклов → нет дублей статистики. +- Появление новых циклов во время отправки → в следующей синхронизации сервер получает расширенный файл. +- Сброс часов RTC → новые события идут в `undated.bin` до синхронизации. +- Новый пользователь/новый токен → доступ только к своим файлам, публичный рейтинг по умолчанию пустой. +- Перед прошивкой заранее выгрузить старый `/events.bin` по USB и сравнить запись после миграции. + +### Локальный тест Java без JDBC + +```bash +cd server +javac --release 21 BreathServer.java RecordFixtureTest.java +java RecordFixtureTest +``` + +Ожидаемый ответ: `PASS: 32-byte little-endian event, duration and CRC32 validation`. + +--- + +**После первого запуска** я рекомендую следующий этап: сделать диагностический экран «свободно FFat / не выгружено / ошибка последней передачи» и веб-функцию загрузки журнала вручную с компьютера. Это облегчит восстановление и сопровождение приборов, когда пользователей станет больше. diff --git a/breath_button_monitor/breathmonitor_v3 with server/deploy/Caddyfile.fragment b/breath_button_monitor/breathmonitor_v3 with server/deploy/Caddyfile.fragment new file mode 100644 index 0000000..3eaa97a --- /dev/null +++ b/breath_button_monitor/breathmonitor_v3 with server/deploy/Caddyfile.fragment @@ -0,0 +1,4 @@ +breathmonitor.shineup.me { + encode zstd gzip + reverse_proxy 127.0.0.1:8090 +} diff --git a/breath_button_monitor/breathmonitor_v3 with server/deploy/breathmonitor.service b/breath_button_monitor/breathmonitor_v3 with server/deploy/breathmonitor.service new file mode 100644 index 0000000..eaab10d --- /dev/null +++ b/breath_button_monitor/breathmonitor_v3 with server/deploy/breathmonitor.service @@ -0,0 +1,22 @@ +[Unit] +Description=BreathMonitor lightweight Java server +After=network-online.target +Wants=network-online.target +[Service] +Type=simple +User=breathmonitor +Group=breathmonitor +WorkingDirectory=/opt/breathmonitor/server +ExecStart=/opt/breathmonitor/server/start.sh +Environment=BREATH_DATA_DIR=/var/lib/breathmonitor +Environment=BREATH_WEB_DIR=/opt/breathmonitor/server/web +Environment=PUBLIC_ORIGIN=https://breathmonitor.shineup.me +Restart=on-failure +RestartSec=5 +NoNewPrivileges=true +ProtectSystem=strict +ProtectHome=true +ReadWritePaths=/var/lib/breathmonitor +PrivateTmp=true +[Install] +WantedBy=multi-user.target diff --git a/breath_button_monitor/breathmonitor_v3 with server/firmware/ISRG_Root_X1_reference.pem b/breath_button_monitor/breathmonitor_v3 with server/firmware/ISRG_Root_X1_reference.pem new file mode 100644 index 0000000..b85c803 --- /dev/null +++ b/breath_button_monitor/breathmonitor_v3 with server/firmware/ISRG_Root_X1_reference.pem @@ -0,0 +1,31 @@ +-----BEGIN CERTIFICATE----- +MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw +TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh +cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4 +WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu +ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY +MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc +h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+ +0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U +A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW +T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH +B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC +B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv +KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn +OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn +jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw +qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI +rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq +hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL +ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ +3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK +NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5 +ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur +TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC +jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc +oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq +4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA +mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d +emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc= +-----END CERTIFICATE----- diff --git a/breath_button_monitor/breath_dual_mode_monitor/burn.sh b/breath_button_monitor/breathmonitor_v3 with server/firmware/burn.sh similarity index 84% rename from breath_button_monitor/breath_dual_mode_monitor/burn.sh rename to breath_button_monitor/breathmonitor_v3 with server/firmware/burn.sh index cd0bb7b..5e523dd 100755 --- a/breath_button_monitor/breath_dual_mode_monitor/burn.sh +++ b/breath_button_monitor/breathmonitor_v3 with server/firmware/burn.sh @@ -2,12 +2,12 @@ set -euo pipefail ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -WORKSPACE_DIR="$(cd "$ROOT_DIR/../../../" && pwd)" +WORKSPACE_DIR="$(cd "$ROOT_DIR/../../../../" && pwd)" DEMO_BASE="$WORKSPACE_DIR/SHiNE-product/ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/official-demo/examples/Arduino-v3.3.5" PORT="${PORT:-}" FQBN="${FQBN:-esp32:esp32:esp32s3:USBMode=hwcdc,CDCOnBoot=cdc,UploadSpeed=921600,CPUFreq=240,FlashMode=dio,FlashSize=16M,PartitionScheme=app3M_fat9M_16MB,PSRAM=opi}" -BUILD_DIR="$ROOT_DIR/../../.arduino-build/breath-dual-mode-monitor" -OUT_DIR="$ROOT_DIR/../../.arduino-build/out-breath-dual-mode-monitor" +BUILD_DIR="$ROOT_DIR/../../.arduino-build/breathmonitor-v3" +OUT_DIR="$ROOT_DIR/../../.arduino-build/out-breathmonitor-v3" if [[ ! -d "$DEMO_BASE/libraries" ]]; then echo "Missing Waveshare libraries: $DEMO_BASE/libraries" >&2 @@ -23,7 +23,7 @@ compile_args=( --library "$DEMO_BASE/libraries/XPowersLib" --library "$DEMO_BASE/libraries/lvgl" --library "$DEMO_BASE/libraries/Mylibrary" - "$ROOT_DIR" + "$ROOT_DIR/firmware.ino" ) if ! arduino-cli compile "${compile_args[@]}"; then @@ -40,4 +40,4 @@ if [[ -z "$PORT" ]]; then echo "Set PORT=/dev/ttyACM0 or use NO_UPLOAD=1." >&2 exit 1 fi -arduino-cli upload --fqbn "$FQBN" -p "$PORT" --input-dir "$OUT_DIR" "$ROOT_DIR" +arduino-cli upload --fqbn "$FQBN" -p "$PORT" --input-dir "$OUT_DIR" "$ROOT_DIR/firmware.ino" diff --git a/breath_button_monitor/manual_monitor_lvgl_v2/es8311.c b/breath_button_monitor/breathmonitor_v3 with server/firmware/es8311.c similarity index 100% rename from breath_button_monitor/manual_monitor_lvgl_v2/es8311.c rename to breath_button_monitor/breathmonitor_v3 with server/firmware/es8311.c diff --git a/breath_button_monitor/manual_monitor_lvgl_v2/es8311.h b/breath_button_monitor/breathmonitor_v3 with server/firmware/es8311.h similarity index 100% rename from breath_button_monitor/manual_monitor_lvgl_v2/es8311.h rename to breath_button_monitor/breathmonitor_v3 with server/firmware/es8311.h diff --git a/breath_button_monitor/manual_monitor_lvgl_v2/es8311_reg.h b/breath_button_monitor/breathmonitor_v3 with server/firmware/es8311_reg.h similarity index 100% rename from breath_button_monitor/manual_monitor_lvgl_v2/es8311_reg.h rename to breath_button_monitor/breathmonitor_v3 with server/firmware/es8311_reg.h diff --git a/breath_button_monitor/breathmonitor_v3 with server/firmware/firmware.ino b/breath_button_monitor/breathmonitor_v3 with server/firmware/firmware.ino new file mode 100644 index 0000000..259af02 --- /dev/null +++ b/breath_button_monitor/breathmonitor_v3 with server/firmware/firmware.ino @@ -0,0 +1,1172 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#define XPOWERS_CHIP_AXP2101 +#include +#include "ESP_I2S.h" +#include "es8311.h" + +struct EventRecord; + +void setup(); +void loop(); + +// Manual Monitor LVGL V2.1: swapped physical buttons, inverted orientation phases, edge-controlled AMOLED. +#define PIN_LCD_CS 12 +#define PIN_LCD_SCLK 38 +#define PIN_LCD_D0 4 +#define PIN_LCD_D1 5 +#define PIN_LCD_D2 6 +#define PIN_LCD_D3 7 +#define PIN_LCD_RST 2 +#define PIN_I2C_SDA 15 +#define PIN_I2C_SCL 14 +#define PIN_TP_INT 11 +#define PIN_INHALE 18 +#define PIN_EXHALE 0 +#define PIN_PA 46 +#define PIN_I2S_BCLK 9 +#define PIN_I2S_LRCK 45 +#define PIN_I2S_DOUT 8 +#define PIN_I2S_DIN 10 +#define PIN_I2S_MCLK 42 + +static constexpr uint16_t DISP_W = 480, DISP_H = 480; +static constexpr uint32_t LVGL_TICK_MS = 2, UI_MS = 120; +static constexpr uint32_t DEBOUNCE_MS = 45, BATT_MS = 5000; +static constexpr uint32_t QUIET_START_MS = 30000, LOUD_START_MS = 60000; +static constexpr uint32_t SLOW_LOUD_MS = 90000, POWER_OFF_MS = 390000; +static constexpr uint16_t LIMITS[] = {5, 7, 10, 15, 20}; +static constexpr uint32_t SCREEN_TIMEOUTS[] = {10000, 30000, 60000, 0}; +static const char *SCREEN_TIMEOUT_NAMES[] = {"10 sec", "30 sec", "60 sec", "Always on"}; +static const int16_t TICK_VOLUME[] = {0, 40, 80, 140, 220, 320, 440, 580, 720, 800, 1600}; +static const int16_t ALERT_VOLUME[] = {0, 150, 300, 500, 800, 12000, 12000, 12000, 12000, 12000, 12000}; + +Arduino_DataBus *gBus = new Arduino_ESP32QSPI(PIN_LCD_CS, PIN_LCD_SCLK, PIN_LCD_D0, PIN_LCD_D1, PIN_LCD_D2, PIN_LCD_D3); +Arduino_CO5300 *gfx = new Arduino_CO5300(gBus, PIN_LCD_RST, 0, DISP_W, DISP_H, 0, 0, 0, 0); +TouchDrvCST92xx gTouch; +XPowersPMU gPower; +I2SClass gI2s; +Preferences gPrefs; + +struct Button { int pin; bool raw = false; bool stable = false; uint32_t changed = 0; uint32_t pressed = 0; }; +static Button gInhale{PIN_INHALE}, gExhale{PIN_EXHALE}; +static bool gRotation=false,gImuOk=false,gRotationArmed=false; +static bool gWifiEnabled=false; +static int8_t gOrientation=-1,gOrientationCandidate=-1; +static uint32_t gOrientationChanged=0,gOrientationSample=0; +// QMI8658 screen-axis mapping: change sign if the TOP edge maps to negative Y. +static constexpr int8_t IMU_TOP_EDGE_Y_SIGN = 1; +// 0: face up/down; 1: edge up; 2: screen top edge up; 3: another edge up. +static int8_t gScreenEdgeOrientation=-1,gScreenEdgeCandidate=-1; +static uint32_t gScreenEdgeChanged=0; +static bool gExhaleLongDone=false; +enum class Screen : uint8_t { Home, Monitor, Settings, Wifi, WifiPassword, Time, ManualTime, Online, Account }; +static Screen gScreen = Screen::Home; +static bool gPowerReady = false, gAudioReady = false, gTouchDown = false; +static uint32_t gLastPowerLong = 0; +static uint32_t gKey1WakeUntil = 0; +static bool gScreenOn = true, gPaused = false; +enum class BreathState : uint8_t { Waiting, Inhale, Exhale }; +static BreathState gBreath = BreathState::Waiting; +static uint64_t gCompletedMs = 0; +static uint32_t gPhaseStarted = 0, gCycleStarted = 0, gLastActivity = 0, gLastUi = 0, gLastBatt = 0, gLastReminder = 0; +static uint8_t gLimit = 2, gTick = 3, gAlert = 10, gScreenTimeout = 1; +static uint32_t gCycles[5] = {}; static uint8_t gCycleCount = 0, gCycleNext = 0, gShortStreak = 0; +static lv_disp_draw_buf_t gDrawBuf; static lv_color_t *gBuf1 = nullptr, *gBuf2 = nullptr; +static lv_obj_t *gRoot=nullptr, *gState=nullptr, *gPhaseTime=nullptr, *gCycleValue=nullptr; +static lv_obj_t *gAverageValue=nullptr, *gElapsedValue=nullptr, *gLimitValue=nullptr; +static lv_obj_t *gHistory[5]={}, *gPausedBanner=nullptr; +static lv_obj_t *gBatteryText=nullptr, *gBatteryFill=nullptr, *gBolt=nullptr, *gWifiText=nullptr,*gClockText=nullptr,*gRotationMark=nullptr; +static lv_obj_t *gTimeCurrent=nullptr,*gTimeStatus=nullptr,*gAutoCheck=nullptr,*gTzDropdown=nullptr; +static lv_obj_t *gManualPreview=nullptr, *gOnlineStatus=nullptr; +static int gTzDraft=60, gManualField=0; +static int gManualParts[5]={2026,1,1,12,0}; +static String gManualDigits=""; +static lv_obj_t *gWifiList=nullptr, *gPasswordField=nullptr, *gPasswordKeyboard=nullptr; +static bool gKbSymbols=false,gKbShift=false,gKbPage=false,gKbShowPassword=false; +static String gKbValue=""; +enum class InputTarget : uint8_t { WifiPass, AccountLogin, AccountPass }; +static InputTarget gInputTarget=InputTarget::WifiPass; +enum class NetOperation : uint8_t { None, Test, Time, Upload, Pair }; +static NetOperation gNetOperation=NetOperation::None; +static uint32_t gNetStarted=0; +static Screen gOperationReturn=Screen::Wifi; +static void networkStart(NetOperation); +static void networkFinish(const String &); +static void onlineScreen(lv_event_t * = nullptr); +static void accountScreen(lv_event_t * = nullptr); +static void networkTick(); +static String gAccountLogin="", gDeviceToken="", gAccountPassword=""; +static String gDeviceId=""; +static Preferences gAccountPrefs; +static volatile bool gWorkerActive=false, gWorkerDone=false, gWorkerSuccess=false; +static char gWorkerMessage[128]={}; +static portMUX_TYPE gWorkerMux=portMUX_INITIALIZER_UNLOCKED; +static void workerSet(const String &msg, bool done=false, bool success=false){ + portENTER_CRITICAL(&gWorkerMux); + snprintf(gWorkerMessage,sizeof(gWorkerMessage),"%s",msg.c_str()); + if(done){gWorkerSuccess=success;gWorkerDone=true;} + portEXIT_CRITICAL(&gWorkerMux); +} +static String workerMessage(){char local[128];portENTER_CRITICAL(&gWorkerMux);strncpy(local,gWorkerMessage,sizeof(local));local[sizeof(local)-1]=0;portEXIT_CRITICAL(&gWorkerMux);return String(local);} +// Production HTTPS: this CA trusts Let's Encrypt certificates, including Caddy's default. +// If Caddy uses a different issuer, replace this PEM and rebuild the firmware. +static const char SERVER_URL[]="https://breathmonitor.shineup.me"; +static const char ROOT_CA[] PROGMEM = R"CERT( +-----BEGIN CERTIFICATE----- +MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw +TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh +cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4 +WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu +ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY +MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc +h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+ +0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U +A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW +T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH +B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC +B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv +KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn +OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn +jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw +qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI +rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq +hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL +ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ +3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK +NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5 +ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur +TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC +jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc +oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq +4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA +mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d +emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc= +-----END CERTIFICATE----- +)CERT"; +static void wifiPasswordScreen(); +static String gSavedSsid[8], gSavedPass[8], gScannedSsid[20], gSelectedSsid; +static int32_t gScannedRssi[20]; +static uint8_t gScannedCount=0; +static bool gWifiScanActive=false, gWifiConnecting=false, gWifiManual=false; +static void wifiEnable(bool enabled); +static int8_t gAttemptedSaved=-1; +static uint8_t gAttemptMask=0; +static uint32_t gWifiStarted=0, gWifiNextScan=0, gWifiLastStatus=0; +static String gWifiNotice="", gPendingPassword=""; +static void wifiScreen(lv_event_t * = nullptr); +static void wifiPasswordScreen(); +static void wifiTick(); +static void wifiScan(bool manual); +static void wifiConnect(const String &ssid,const String &password,bool manual); +static void wifiLoad(); +static void timeScreen(lv_event_t * = nullptr); +static void manualTimeScreen(); +static void timeUiTick(); +static bool gTimeValid=false,gNtpPending=false,gFileReady=false,gFileMountFailed=false; +static int16_t gTimezoneMinutes=60; +static uint32_t gNtpStart=0,gLastNtp=0,gEventSeq=0; +static uint64_t gCycleUtcMs=0; +static bool appendEvent(uint8_t type,uint64_t timestamp=UINT64_MAX,uint16_t inh=0,uint16_t exh=0,uint16_t avg=0,uint16_t deficit=0,int16_t val=0); +static uint32_t gInhaleDuration=0; +static bool gInhaleExceeded=false,gExhaleExceeded=false; + + +// RTC PCF85063A/T (I2C 0x51). Keep RTC and stored event timestamps in UTC. +static uint8_t bcd(uint8_t v){return (v/10)*16+(v%10);} +static uint8_t unbcd(uint8_t v){return (v>>4)*10+(v&15);} +static bool rtcRead(time_t &epoch){ + Wire.beginTransmission(0x51);Wire.write(0x04); + if(Wire.endTransmission(false)!=0 || Wire.requestFrom((uint8_t)0x51,(uint8_t)7)!=7)return false; + uint8_t d[7];for(int i=0;i<7;i++)d[i]=Wire.read(); + if(d[0]&0x80)return false; // oscillator stopped: unreliable calendar + tm t={};t.tm_sec=unbcd(d[0]&0x7f);t.tm_min=unbcd(d[1]&0x7f);t.tm_hour=unbcd(d[2]&0x3f); + t.tm_mday=unbcd(d[3]&0x3f);t.tm_mon=unbcd(d[5]&0x1f)-1;t.tm_year=unbcd(d[6])+100; + if(t.tm_year<124||t.tm_year>199||t.tm_mon<0||t.tm_mon>11||t.tm_mday<1||t.tm_mday>31||t.tm_hour>23||t.tm_min>59||t.tm_sec>59)return false; + // Convert Gregorian UTC date to Unix seconds without non-portable timegm(). + int y=t.tm_year+1900,m=t.tm_mon+1,day=t.tm_mday; + y -= m<=2; + const int era=(y>=0?y:y-399)/400; + const unsigned yoe=(unsigned)(y-era*400); + const unsigned mp=(unsigned)(m+(m>2?-3:9)); + const unsigned doy=(153*mp+2)/5+(unsigned)day-1; + const unsigned doe=yoe*365+yoe/4-yoe/100+doy; + int64_t days=(int64_t)era*146097+(int64_t)doe-719468; + epoch=(time_t)(days*86400+t.tm_hour*3600+t.tm_min*60+t.tm_sec); + return epoch>1700000000; +} +static bool rtcWrite(time_t epoch){ + tm t={};gmtime_r(&epoch,&t); + if(t.tm_year<100||t.tm_year>199)return false; + Wire.beginTransmission(0x51);Wire.write(0x04); + uint8_t d[7]={bcd(t.tm_sec),bcd(t.tm_min),bcd(t.tm_hour),bcd(t.tm_mday),bcd(t.tm_wday),bcd(t.tm_mon+1),bcd(t.tm_year-100)}; + Wire.write(d,7);return Wire.endTransmission()==0; +} +static uint64_t unixMs(){if(!gTimeValid)return 0;timeval tv={};gettimeofday(&tv,nullptr);return (uint64_t)tv.tv_sec*1000ULL+tv.tv_usec/1000;} +static void initClock(){time_t v;if(rtcRead(v)){timeval tv={};tv.tv_sec=v;settimeofday(&tv,nullptr);gTimeValid=true;}} +static void requestNtp(){if(WiFi.status()!=WL_CONNECTED)return;gNtpPending=true;gNtpStart=millis(); + // configTime starts SNTP asynchronously; system timezone remains UTC. + configTime(0,0,"pool.ntp.org","time.google.com"); +} +static void ntpTick(){ + if(!gNtpPending)return; + if(millis()-gNtpStart>18000){gNtpPending=false;if(gNetOperation==NetOperation::Time||gNetOperation==NetOperation::Upload||gNetOperation==NetOperation::Pair)networkFinish("NTP timeout");return;} + time_t e=time(nullptr); + if(e>1750000000 && sntp_get_sync_status()==SNTP_SYNC_STATUS_COMPLETED){ + rtcWrite(e);gTimeValid=true;gNtpPending=false;gLastNtp=millis();appendEvent(9); + if(gNetOperation==NetOperation::Time)networkFinish("Time synchronized"); + } +} +// FFat append-only record. Fixed 32 bytes, versioned + CRC32; zero UTC flags untrusted clock. +// All numerical fields little-endian on ESP32. CRC is over first 28 bytes. +// type:1 cycle,2 boot,3 shutdown,4 pause,5 resume,6 limit,7 inhaleLong,8 exhaleLong,9 sync,10 rotation. +struct __attribute__((packed)) EventRecord { + uint8_t version,type,flags,reserved; + uint32_t seq; + uint64_t utcMs; + uint16_t inhale10,exhale10,avg10,shortfall10; + int16_t value; + uint16_t spare; + uint32_t crc; +}; +static_assert(sizeof(EventRecord)==32,"Event size should be 32 bytes"); +static uint32_t crc32(const uint8_t *data,size_t size){uint32_t c=~0u;while(size--){c^=*data++;for(int j=0;j<8;j++)c=(c>>1)^((c&1)?0xedb88320u:0u);}return ~c;} +// File date is local calendar day according to the fixed offset selected in TIME. +// Raw timestamps remain UTC. An invalid RTC uses a separate undated journal. +static String dayFor(uint64_t utc,uint8_t flags){ + if(!(flags&1)||utc<1704067200000ULL)return "undated"; + time_t t=(time_t)(utc/1000ULL)+(int32_t)gTimezoneMinutes*60; + tm val={};gmtime_r(&t,&val); + if(val.tm_year<124||val.tm_year>199)return "undated"; + char name[12];snprintf(name,sizeof(name),"%04d%02d%02d",val.tm_year+1900,val.tm_mon+1,val.tm_mday); + return String(name); +} +static String journalPath(const String &day){return String("/logs/")+day+".bin";} +static bool appendRaw(const String &path, const EventRecord &e){ + File f=FFat.open(path.c_str(),"a");if(!f)return false; + bool ok=f.write((const uint8_t*)&e,sizeof(e))==sizeof(e);f.flush();f.close();return ok; +} +static bool appendEvent(uint8_t type,uint64_t timestamp,uint16_t inh,uint16_t exh,uint16_t avg,uint16_t deficit,int16_t val){ + if(!gFileReady)return false; + EventRecord e={};e.version=1;e.type=type;e.flags=gTimeValid?1:0;e.seq=++gEventSeq; + e.utcMs=(timestamp==UINT64_MAX)?unixMs():timestamp; + if(e.utcMs==0)e.flags=0; + e.inhale10=inh;e.exhale10=exh;e.avg10=avg;e.shortfall10=deficit;e.value=val; + e.crc=crc32((const uint8_t*)&e,28); + if(!appendRaw(journalPath(dayFor(e.utcMs,e.flags)),e)){ + Serial.println("LOG ERROR append failed");return false; + } + return true; +} +static void scanSequenceFile(File &f){ + EventRecord e;while(f.available()>=(int)sizeof(e)){ + if(f.read((uint8_t*)&e,sizeof(e))!=sizeof(e))break; + if(e.version==1 && e.crc==crc32((const uint8_t*)&e,28))gEventSeq=max(gEventSeq,e.seq); + } +} +// Import the V2.1 /events.bin to date files. Never delete the original. +// Last migrated seq in each date file prevents duplicates after interrupted boots. +static bool migrateLegacy(){ + if(!FFat.exists("/events.bin")||FFat.exists("/migration.done"))return true; + File old=FFat.open("/events.bin","r");if(!old)return false; + uint32_t migrated=0,broken=0,lastSeq=0;String lastDay=""; + EventRecord e; + while(old.available()>=(int)sizeof(e)){ + if(old.read((uint8_t*)&e,sizeof(e))!=sizeof(e)){old.close();return false;} + if(e.version!=1||e.crc!=crc32((const uint8_t*)&e,28)){broken++;continue;} + String day=dayFor(e.utcMs,e.flags); + if(day!=lastDay){ + lastDay=day;lastSeq=0; + File f=FFat.open(journalPath(day).c_str(),"r"); + if(f){if(f.size()%sizeof(e)!=0){f.close();old.close();return false;} + if(f.size()>=sizeof(e)){f.seek(f.size()-sizeof(e));EventRecord last; + if(f.read((uint8_t*)&last,sizeof(last))==sizeof(last)&&last.version==1&&last.crc==crc32((const uint8_t*)&last,28))lastSeq=last.seq; + }f.close();} + } + if(e.seq<=lastSeq)continue; + if(!appendRaw(journalPath(day),e)){old.close();return false;} + lastSeq=e.seq;migrated++; + } + // A corrupt legacy trailing fragment must be retained, not silently marked migrated. + if(old.size()%sizeof(e)!=0){old.close();return false;} + old.close(); + File mark=FFat.open("/migration.done","w");if(!mark)return false; + mark.printf("migrated=%lu invalid=%lu\n",(unsigned long)migrated,(unsigned long)broken); + mark.close(); + Serial.printf("Legacy migration: %lu records, %lu invalid CRC/version records\n",(unsigned long)migrated,(unsigned long)broken); + return true; +} +static void initEvents(){ + gFileReady=FFat.begin(false); + if(!gFileReady){gFileMountFailed=true;Serial.println("FFat mount failed; waiting for user format confirmation");return;} + if(!FFat.exists("/logs")&&!FFat.mkdir("/logs")){gFileReady=false;Serial.println("Cannot create /logs");return;} + if(!migrateLegacy())Serial.println("WARNING: legacy migration incomplete, /events.bin retained; retry next boot"); + File dir=FFat.open("/logs"); + if(dir){File f=dir.openNextFile();while(f){if(!f.isDirectory())scanSequenceFile(f);f.close();f=dir.openNextFile();}dir.close();} + // On a migration error old seq must still remain higher than any new seq. + File old=FFat.open("/events.bin","r");if(old){scanSequenceFile(old);old.close();} +} +// QMI8658: I2C 0x6A/0x6B; accelerometer +/-2g, 125Hz ODR (register defaults tested by WHO_AM_I). +static uint8_t gImuAddr=0; +static bool imuRead(uint8_t reg,uint8_t *data,uint8_t count){ + Wire.beginTransmission(gImuAddr);Wire.write(reg); + if(Wire.endTransmission(false)!=0||Wire.requestFrom(gImuAddr,count)!=count)return false; + for(int i=0;ix2-a->x1+1, h = a->y2-a->y1+1; +#if LV_COLOR_16_SWAP != 0 + gfx->draw16bitBeRGBBitmap(a->x1,a->y1,(uint16_t *)&p->full,w,h); +#else + gfx->draw16bitRGBBitmap(a->x1,a->y1,(uint16_t *)&p->full,w,h); +#endif + lv_disp_flush_ready(d); +} +// CO5300 QSPI: align LVGL partial-refresh rectangles to whole RGB565 pixel pairs. +// This prevents odd-width transfer regions from potentially shifting successive rows. +static void rounder(lv_disp_drv_t *d, lv_area_t *a) { + (void)d; + a->x1 &= ~1; + a->x2 |= 1; + if (a->x1 < 0) a->x1 = 0; + if (a->x2 >= DISP_W) a->x2 = DISP_W - 1; +} +static void tick(void *) { lv_tick_inc(LVGL_TICK_MS); } +static void touchRead(lv_indev_drv_t *, lv_indev_data_t *d) { + int16_t x=0,y=0; bool down = gTouch.getPoint(&x,&y,1)>0; + if (down && !gTouchDown) { gTouchDown=true; gLastActivity=millis(); if (!gScreenOn) { gfx->setBrightness(220); gScreenOn=true; } } + if (!down) gTouchDown=false; + d->state=down ? LV_INDEV_STATE_PR : LV_INDEV_STATE_REL; d->point.x=x; d->point.y=y; +} +static void card(lv_obj_t *o, uint32_t bg=0x142331) { lv_obj_set_style_bg_color(o,color(bg),0); lv_obj_set_style_border_color(o,color(0x365264),0); lv_obj_set_style_border_width(o,1,0); lv_obj_set_style_radius(o,14,0); lv_obj_clear_flag(o,LV_OBJ_FLAG_SCROLLABLE); } +static lv_obj_t *label(lv_obj_t *p,const char *s,const lv_font_t *f,uint32_t c) { + lv_obj_t *o=lv_label_create(p); + lv_label_set_text(o,s); + lv_obj_set_style_text_font(o,f,0); + lv_obj_set_style_text_color(o,color(c),0); + return o; +} +static lv_obj_t *panel(int x,int y,int w,int h,uint32_t bg=0x142331) { lv_obj_t *o=lv_obj_create(gRoot); lv_obj_set_pos(o,x,y); lv_obj_set_size(o,w,h); card(o,bg); return o; } +static void fmt(char *out,size_t n,uint32_t ms) { snprintf(out,n,"%lu.%01lu s",(unsigned long)(ms/1000),(unsigned long)((ms%1000)/100)); } +static uint32_t average() { uint64_t total=0; for(uint8_t i=0;i(4,gPrefs.getUChar("limit",2)); gTick=min(10,gPrefs.getUChar("tick",3)); gAlert=min(10,gPrefs.getUChar("alert",10)); gScreenTimeout=min(3,gPrefs.getUChar("screen",1));gRotation=gPrefs.getBool("rotation",false);gTimezoneMinutes=gPrefs.getShort("timezone",60);gWifiEnabled=false; } +static void saveSettings() { gPrefs.putUChar("limit",gLimit); gPrefs.putUChar("tick",gTick); gPrefs.putUChar("alert",gAlert); gPrefs.putUChar("screen",gScreenTimeout);gPrefs.putBool("rotation",gRotation);gPrefs.putShort("timezone",gTimezoneMinutes); } +static void initPower() { gPowerReady=gPower.begin(Wire,AXP2101_SLAVE_ADDRESS,PIN_I2C_SDA,PIN_I2C_SCL); if(!gPowerReady)return; gPower.disableIRQ(XPOWERS_AXP2101_ALL_IRQ); gPower.setChargeTargetVoltage(3); gPower.setPowerKeyPressOffTime(XPOWERS_POWEROFF_10S); + // AXP2101 IRQ hold threshold: 0=1s, 1=1.5s, 2=2s, 3=2.5s (reg 0x27, bits 5:4). + Wire.beginTransmission(AXP2101_SLAVE_ADDRESS); Wire.write(0x27); + if(Wire.endTransmission(false)==0 && Wire.requestFrom((uint8_t)AXP2101_SLAVE_ADDRESS,(uint8_t)1)==1){ + uint8_t reg=Wire.read(); Wire.beginTransmission(AXP2101_SLAVE_ADDRESS); + Wire.write(0x27);Wire.write((uint8_t)((reg & ~0x30u)|0x10u));Wire.endTransmission(); + } + gPower.clearIrqStatus(); gPower.enableIRQ(XPOWERS_AXP2101_PKEY_SHORT_IRQ | XPOWERS_AXP2101_PKEY_LONG_IRQ); gPower.enableBattDetection(); gPower.enableBattVoltageMeasure(); gPower.enableVbusVoltageMeasure(); } +static int battery() { if(!gPowerReady || !gPower.isBatteryConnect())return -1; int percent=constrain(gPower.getBatteryPercent(),0,100); uint16_t mv=gPower.getBattVoltage(); if(percent==0 && mv>=3300) return constrain((int)((mv-3300UL)*100UL/900UL),1,100); return percent; } +static void initAudio() { pinMode(PIN_PA,OUTPUT); digitalWrite(PIN_PA,HIGH); gI2s.setPins(PIN_I2S_BCLK,PIN_I2S_LRCK,PIN_I2S_DOUT,PIN_I2S_DIN,PIN_I2S_MCLK); if(!gI2s.begin(I2S_MODE_STD,16000,I2S_DATA_BIT_WIDTH_16BIT,I2S_SLOT_MODE_STEREO,I2S_STD_SLOT_BOTH))return; es8311_handle_t h=es8311_create(0,ES8311_ADDRRES_0); if(!h)return; es8311_clock_config_t c={false,false,true,4096000,16000}; gAudioReady=es8311_init(h,&c,ES8311_RESOLUTION_16,ES8311_RESOLUTION_16)==ESP_OK; if(gAudioReady){es8311_voice_volume_set(h,100,nullptr);es8311_voice_mute(h,false);} } +static void beep(uint16_t hz,uint16_t count,int16_t amp) { if(!gAudioReady||amp<=0)return; static int16_t buf[1600*2]; count=min(count,1600); for(uint16_t i=0;i0?max(2,min(26,p*26/100)):0); if(gBolt)lv_obj_set_style_opa(gBolt,(gPowerReady&&gPower.isCharging())?LV_OPA_COVER:LV_OPA_TRANSP,0); } +static void topBar(const char *title) { + // On the monitor: Wi-Fi on the left, battery on the right. Other pages: page title. + if(gScreen==Screen::Monitor){ + gRotationMark=label(gRoot,"",&lv_font_montserrat_16,0x38B26D);lv_obj_set_pos(gRotationMark,14,51); + gWifiText=label(gRoot,"Wi-Fi: --",&lv_font_montserrat_16,0x9EB4C2); + lv_obj_set_pos(gWifiText,39,51); + lv_obj_set_width(gWifiText,188); + gClockText=label(gRoot,"--:--",&lv_font_montserrat_16,0xFFFFFF);lv_obj_set_pos(gClockText,234,51); + lv_label_set_long_mode(gWifiText,LV_LABEL_LONG_DOT); + }else{ + lv_obj_t *heading=label(gRoot,title,&lv_font_montserrat_20,0xFFFFFF); + lv_obj_set_pos(heading,24,48); + } + gBatteryText=label(gRoot,"--",&lv_font_montserrat_16,0xC9D3DE);lv_obj_set_pos(gBatteryText,297,51); + if(gPowerReady){static const lv_point_t bolt[]={{6,0},{1,9},{5,9},{2,18},{10,7},{6,7}};gBolt=lv_line_create(gRoot);lv_line_set_points(gBolt,bolt,6);lv_obj_set_pos(gBolt,337,46);lv_obj_set_style_line_width(gBolt,2,0);lv_obj_set_style_line_color(gBolt,color(0xFFD34D),0);lv_obj_set_style_line_rounded(gBolt,true,0);} + lv_obj_t *b=lv_obj_create(gRoot);lv_obj_set_pos(b,349,53);lv_obj_set_size(b,32,16);lv_obj_set_style_bg_opa(b,LV_OPA_TRANSP,0);lv_obj_set_style_border_color(b,color(0xC9D3DE),0);lv_obj_set_style_border_width(b,2,0);lv_obj_set_style_radius(b,4,0);lv_obj_clear_flag(b,LV_OBJ_FLAG_SCROLLABLE); + lv_obj_t *cap=lv_obj_create(gRoot);lv_obj_set_pos(cap,381,57);lv_obj_set_size(cap,4,8);lv_obj_set_style_bg_color(cap,color(0xC9D3DE),0);lv_obj_set_style_border_width(cap,0,0);lv_obj_set_style_radius(cap,2,0); + gBatteryFill=lv_obj_create(gRoot);lv_obj_set_pos(gBatteryFill,352,56);lv_obj_set_size(gBatteryFill,2,10);lv_obj_set_style_bg_color(gBatteryFill,color(0x38B26D),0);lv_obj_set_style_border_width(gBatteryFill,0,0);lv_obj_set_style_radius(gBatteryFill,2,0);batteryUi(); +} +static void clearUi() { lv_obj_clean(lv_scr_act()); gRoot=lv_scr_act(); lv_obj_set_style_bg_color(gRoot,color(0x08111B),0);lv_obj_set_style_bg_opa(gRoot,LV_OPA_COVER,0);lv_obj_set_style_pad_all(gRoot,0,0); gBatteryText=gBatteryFill=gBolt=gWifiText=gWifiList=gPasswordField=gPasswordKeyboard=gOnlineStatus=nullptr;gClockText=gRotationMark=gTimeCurrent=gTimeStatus=gAutoCheck=gTzDropdown=gManualPreview=nullptr; } +static void legend() { + lv_obj_t *l=label(gRoot,"INHALE",&lv_font_montserrat_14,0x38B26D);lv_obj_set_pos(l,90,12); + l=label(gRoot,"SETTINGS",&lv_font_montserrat_14,0xC9D3DE);lv_obj_align(l,LV_ALIGN_TOP_MID,0,12); + l=label(gRoot,"EXHALE",&lv_font_montserrat_14,0x4FB3FF);lv_obj_set_pos(l,338,12); + static const lv_point_t rule[]={{0,0},{432,0}}; + lv_obj_t *line=lv_line_create(gRoot);lv_line_set_points(line,rule,2); + lv_obj_set_pos(line,24,37);lv_obj_set_style_line_width(line,1,0); + lv_obj_set_style_line_color(line,color(0x365264),0); +} +static lv_obj_t *metric(int x,int y,const char *caption,uint32_t valueColor) { + lv_obj_t *p=panel(x,y,204,100);lv_obj_t *l=label(p,caption,&lv_font_montserrat_14,0x9EB4C2); + lv_obj_align(l,LV_ALIGN_TOP_MID,0,7); + l=label(p,"--",&lv_font_montserrat_28,valueColor);lv_obj_align(l,LV_ALIGN_CENTER,0,12); + return l; +} +static void enterMonitor(lv_event_t *) { + gScreen=Screen::Monitor;gLastActivity=millis();clearUi();legend();topBar(""); + lv_obj_t *hero=panel(24,92,432,73,0x102A36); + gState=label(hero,"WAITING",&lv_font_montserrat_28,0x4FB3FF); + gPhaseTime=label(hero,"",&lv_font_montserrat_28,0xFFFFFF); + gCycleValue=metric(24,182,"CYCLE",0xFFFFFF); + gAverageValue=metric(252,182,"AVG 5",0xFFFFFF); + gElapsedValue=metric(24,298,"ELAPSED",0xFFFFFF); + gLimitValue=metric(252,298,"LIMIT",0xFFD34D); + lv_obj_t *history=panel(24,413,432,53); + lv_obj_t *title=label(history,"HISTORY",&lv_font_montserrat_14,0xC9D3DE);lv_obj_set_pos(title,7,3); + for(int i=0;i<5;i++){gHistory[i]=label(history,"--",&lv_font_montserrat_16,0xFFFFFF); + lv_obj_set_pos(gHistory[i],78+i*68,3);} +} +static void home(lv_event_t *); static void settings(lv_event_t *); +static lv_obj_t *button(lv_obj_t *p,const char *text,int x,int y,int w,int h,uint32_t bg,lv_event_cb_t cb,void *userData=nullptr) { lv_obj_t *b=lv_btn_create(p);lv_obj_set_pos(b,x,y);lv_obj_set_size(b,w,h);card(b,bg);lv_obj_add_event_cb(b,cb,LV_EVENT_CLICKED,userData);lv_obj_t *l=label(b,text,&lv_font_montserrat_20,0xFFFFFF);lv_obj_center(l);return b; } +static void home(lv_event_t *) {enterMonitor(nullptr);} +static void settingChanged(lv_event_t *e){ + uint8_t *v=(uint8_t *)lv_event_get_user_data(e); + uint8_t old=*v;*v=lv_slider_get_value(lv_event_get_target(e)); + if(old!=*v)saveSettings(); +} +static void settingReleased(lv_event_t *e){ + if(lv_event_get_user_data(e)==&gLimit)appendEvent(6,UINT64_MAX,0,0,0,0,LIMITS[gLimit]*10); +} +static void refresh(); +static void settings(lv_event_t *) { + gScreen=Screen::Settings;clearUi();legend();topBar("SETTINGS"); + if(gPaused){gPausedBanner=label(gRoot,"PAUSED",&lv_font_montserrat_20,0xFFD34D); + lv_obj_align(gPausedBanner,LV_ALIGN_TOP_MID,0,32);} + lv_obj_t *list=lv_obj_create(gRoot);lv_obj_set_pos(list,20,91);lv_obj_set_size(list,440,280); + card(list,0x10202D);lv_obj_set_style_pad_all(list,10,0);lv_obj_set_flex_flow(list,LV_FLEX_FLOW_COLUMN); + lv_obj_set_style_pad_row(list,9,0); + struct Item{const char *name;uint8_t *v;uint8_t max;}; + Item items[]={{"Breath limit",&gLimit,4},{"Cycle tick",&gTick,10},{"Alert volume",&gAlert,10},{"Screen timeout",&gScreenTimeout,3}}; + for(auto &it:items){lv_obj_t *row=lv_obj_create(list);lv_obj_set_size(row,400,67);card(row,0x172C3C); + lv_obj_t *n=label(row,it.name,&lv_font_montserrat_16,0xFFFFFF);lv_obj_set_pos(n,12,6); + lv_obj_t *sl=lv_slider_create(row);lv_obj_set_pos(sl,12,36);lv_obj_set_size(sl,376,16); + lv_slider_set_range(sl,0,it.max);lv_slider_set_value(sl,*it.v,LV_ANIM_OFF); + lv_obj_add_event_cb(sl,settingChanged,LV_EVENT_VALUE_CHANGED,it.v); + if(it.v==&gLimit)lv_obj_add_event_cb(sl,settingReleased,LV_EVENT_RELEASED,it.v); + } + button(gRoot,"Wi-Fi",24,383,100,42,0x214D69,[](lv_event_t *){if(!gWifiEnabled)wifiEnable(true);wifiScreen(nullptr);}); + button(gRoot,"TIME",132,383,100,42,0x214D69,[](lv_event_t *){timeScreen(nullptr);}); + lv_obj_t *rot=lv_checkbox_create(gRoot);lv_checkbox_set_text(rot,"ROTATION CONTROL");lv_obj_set_pos(rot,32,437); + if(gRotation)lv_obj_add_state(rot,LV_STATE_CHECKED); + lv_obj_add_event_cb(rot,[](lv_event_t *e){gRotation=lv_obj_has_state(lv_event_get_target(e),LV_STATE_CHECKED);gRotationArmed=false;gOrientation=-1;gScreenEdgeOrientation=-1;gScreenEdgeCandidate=-1;saveSettings();appendEvent(10,UINT64_MAX,0,0,0,0,gRotation);},LV_EVENT_VALUE_CHANGED,nullptr); + button(gRoot,"ONLINE",240,383,110,42,0x214D69,[](lv_event_t *){onlineScreen(nullptr);}); + button(gRoot,"BACK",358,383,98,42,0x214D69,[](lv_event_t *){ + if(gPaused){gPaused=false;gBreath=BreathState::Waiting;gRotationArmed=false;gOrientation=-1;gScreenEdgeOrientation=-1;gScreenEdgeCandidate=-1;appendEvent(5);}enterMonitor(nullptr); + }); +} +// PMU power key can blank the AMOLED independently of our timeout flag. +// Explicitly wake the panel for any accepted KEY1 action. +static void wakeDisplayFromKey1() { + gLastActivity=millis(); + gKey1WakeUntil=gLastActivity+1500; + gScreenOn=true; + gfx->setBrightness(220); +} +static void keyShort(){ + wakeDisplayFromKey1(); + if(gScreen==Screen::WifiPassword||gScreen==Screen::Wifi||gScreen==Screen::Time||gScreen==Screen::ManualTime||gScreen==Screen::Online||gScreen==Screen::Account){ + if(!gWorkerActive && (gScreen==Screen::Wifi || + (gScreen==Screen::WifiPassword && gInputTarget==InputTarget::WifiPass)))networkFinish("Wi-Fi off"); + settings(nullptr); + } + else if(gScreen==Screen::Settings){if(gPaused){gPaused=false;gBreath=BreathState::Waiting;gRotationArmed=false;gOrientation=-1;gScreenEdgeOrientation=-1;gScreenEdgeCandidate=-1;appendEvent(5);}enterMonitor(nullptr);} + else settings(nullptr); +} +static void keyLong(){ + wakeDisplayFromKey1(); + if(gWifiEnabled&&!gWorkerActive)networkFinish("Wi-Fi off"); + if(!gPaused){gPaused=true;gBreath=BreathState::Waiting;gCycleStarted=0;gPhaseStarted=0;gRotationArmed=false;gOrientation=-1;gScreenEdgeOrientation=-1;gScreenEdgeCandidate=-1;appendEvent(4);} + settings(nullptr); +} +// Key1 is PMU PWRON (AXP2101), not a GPIO. Handle short/long PMU IRQs. +static void pollPowerKey(){ + if(!gPowerReady)return; + gPower.getIrqStatus(); + bool longPress=gPower.isPekeyLongPressIrq(); + bool shortPress=gPower.isPekeyShortPressIrq(); + if(longPress||shortPress){gPower.clearIrqStatus();wakeDisplayFromKey1(); + if(longPress){gLastPowerLong=millis();keyLong();} + else if(millis()-gLastPowerLong>750)keyShort();} +} +static void addCycle(uint32_t ms,uint32_t inhaleMs){ + if(!ms)return; + gCompletedMs+=ms;gCycles[gCycleNext]=ms;gCycleNext=(gCycleNext+1)%5; + if(gCycleCount<5)gCycleCount++; + uint32_t a=average(); + uint16_t inh10=min(65535,(inhaleMs+50)/100),exh10=min(65535,(ms-inhaleMs+50)/100); + uint16_t avg10=min(65535,(a+50)/100); + uint16_t missing=min(65535,ms(5,gShortStreak+1); + for(uint8_t i=0;i=2000){ + gExhaleLongDone=true;gRotation=true;gRotationArmed=false;gOrientation=-1;gScreenEdgeOrientation=-1;gScreenEdgeCandidate=-1;saveSettings();appendEvent(10,UINT64_MAX,0,0,0,0,gRotation); + }return;} + b.stable=b.raw;if(b.stable){b.pressed=now;if(!inhale)gExhaleLongDone=false;gLastActivity=now; + if(gRotation){gRotation=false;gRotationArmed=false;gOrientation=-1;gScreenEdgeOrientation=-1;gScreenEdgeCandidate=-1;gOrientationCandidate=-1;saveSettings();appendEvent(10,UINT64_MAX,0,0,0,0,0);} + if(!gScreenOn){gScreenOn=true;gfx->setBrightness(220);} + phase(inhale); + } +} +static void refresh(){ + if(gScreen!=Screen::Monitor)return; + uint32_t now=millis();char t[24]; + if(gRotationMark)lv_label_set_text(gRotationMark,gRotation?"✓":""); + if(gClockText){time_t e=time(nullptr);char clockbuf[12]="--:--";if(gTimeValid&&e>1700000000){e+=(int32_t)gTimezoneMinutes*60;tm tmv={};gmtime_r(&e,&tmv);snprintf(clockbuf,sizeof(clockbuf),"%02d:%02d",tmv.tm_hour,tmv.tm_min);}lv_label_set_text(gClockText,clockbuf);} + if(gWifiText){ + String wi = !gWifiEnabled?String("Wi-Fi: off"):(WiFi.status()==WL_CONNECTED ? String("Wi-Fi: ")+WiFi.SSID() : (gWifiConnecting?"Wi-Fi: connecting":"Wi-Fi: scanning")); + lv_label_set_text(gWifiText,wi.c_str()); + lv_obj_set_style_text_color(gWifiText,color(WiFi.status()==WL_CONNECTED?0x38B26D:0x9EB4C2),0); + } + const char *state=gBreath==BreathState::Waiting?"WAITING":gBreath==BreathState::Inhale?"INHALE":"EXHALE"; + lv_label_set_text(gState,state); + lv_obj_set_style_text_color(gState,color(gBreath==BreathState::Inhale?0x38B26D:0x4FB3FF),0); + if(gBreath==BreathState::Waiting)lv_label_set_text(gPhaseTime,""); + else{fmt(t,sizeof(t),now-gPhaseStarted);lv_label_set_text(gPhaseTime,t);} + // Center phase and white phase timer as one horizontal group. + lv_obj_update_layout(gState);lv_obj_update_layout(gPhaseTime); + int w=lv_obj_get_width(gState)+(gBreath==BreathState::Waiting?0:14+lv_obj_get_width(gPhaseTime)); + lv_obj_set_pos(gState,(432-w)/2,14); + lv_obj_set_pos(gPhaseTime,(432-w)/2+lv_obj_get_width(gState)+14,14); + lv_obj_align(gCycleValue,LV_ALIGN_CENTER,0,12); + lv_obj_align(gAverageValue,LV_ALIGN_CENTER,0,12); + lv_obj_align(gElapsedValue,LV_ALIGN_CENTER,0,12); + lv_obj_align(gLimitValue,LV_ALIGN_CENTER,0,12); + uint32_t cycle=gBreath==BreathState::Waiting?0:now-gCycleStarted; + fmt(t,sizeof(t),cycle);lv_label_set_text(gCycleValue,t); + if(gCycleCount){fmt(t,sizeof(t),average());lv_label_set_text(gAverageValue,t);} + else lv_label_set_text(gAverageValue,"--"); + uint64_t seconds=gCompletedMs/1000; + if(seconds>=3600)snprintf(t,sizeof(t),"%llu:%02llu:%02llu", + (unsigned long long)(seconds/3600),(unsigned long long)((seconds/60)%60),(unsigned long long)(seconds%60)); + else snprintf(t,sizeof(t),"%02llu:%02llu",(unsigned long long)(seconds/60),(unsigned long long)(seconds%60)); + lv_label_set_text(gElapsedValue,t); + snprintf(t,sizeof(t),"%u.0 s",LIMITS[gLimit]);lv_label_set_text(gLimitValue,t); + for(uint8_t i=0;i<5;i++){ + if(i=LOUD_START_MS){ + if(gBreath==BreathState::Inhale&&!gInhaleExceeded){gInhaleExceeded=true;appendEvent(7);} + if(gBreath==BreathState::Exhale&&!gExhaleExceeded){gExhaleExceeded=true;appendEvent(8);} + } + if(agesetBrightness(0);if(gPowerReady)gPower.shutdown();esp_deep_sleep_start();} +} + +// Wi-Fi credentials use the same key layout as shine_homeserver_main.ino, +// but an isolated Preferences namespace to avoid modifying the other application. +static Preferences gWifiPrefs; +static void wifiLoad(){ + gWifiPrefs.begin("manual-wifi",false); + for(int i=0;i<8;i++){ + String k=String("wifi_ssid_")+i,p=String("wifi_pass_")+i; + gSavedSsid[i]=gWifiPrefs.getString(k.c_str(),""); + gSavedPass[i]=gWifiPrefs.getString(p.c_str(),""); + } + gWifiEnabled=false; + WiFi.mode(WIFI_OFF);WiFi.setAutoReconnect(false);WiFi.persistent(false); +} +static void wifiEnable(bool enabled){ + gWifiEnabled=enabled;gWifiScanActive=false;gWifiConnecting=false;gWifiManual=false; + if(!enabled){WiFi.scanDelete();WiFi.disconnect(true,false);WiFi.mode(WIFI_OFF);} + else{WiFi.mode(WIFI_STA);WiFi.setAutoReconnect(false);gAttemptMask=0;gWifiNextScan=millis()+100;} +} +static void networkFinish(const String &message){ + NetOperation op=gNetOperation; + gNetOperation=NetOperation::None;gNtpPending=false; + wifiEnable(false);gWifiNotice=message; + if(op==NetOperation::Time){timeScreen(nullptr);} + else if(op==NetOperation::Upload||op==NetOperation::Pair){onlineScreen(nullptr);} + else if(gScreen==Screen::Wifi){wifiScreen(nullptr);} +} +static void networkStart(NetOperation op){ + if(gWorkerActive||gNetOperation!=NetOperation::None)return; + gNetOperation=op;gOperationReturn=gScreen;gNetStarted=millis();gAttemptMask=0;gWifiNotice="Finding saved Wi-Fi..."; + wifiEnable(true);gWifiNextScan=millis(); +} +static int wifiKnown(const String &ssid){for(int i=0;i<8;i++)if(gSavedSsid[i]==ssid)return i;return -1;} +static void wifiRemember(const String &ssid,const String &pass){ + int i=wifiKnown(ssid); + if(i<0){for(i=0;i<8 && gSavedSsid[i].length();i++);if(i>=8){ + for(int j=0;j<7;j++){gSavedSsid[j]=gSavedSsid[j+1];gSavedPass[j]=gSavedPass[j+1];}i=7; + }} + gSavedSsid[i]=ssid;gSavedPass[i]=pass; + String k=String("wifi_ssid_")+i,p=String("wifi_pass_")+i; + gWifiPrefs.putString(k.c_str(),ssid);gWifiPrefs.putString(p.c_str(),pass); +} +static void wifiConnect(const String &ssid,const String &password,bool manual){ + if(!gWifiEnabled)return; + if(ssid.isEmpty())return; + gWifiManual=manual;gWifiConnecting=true;gWifiStarted=millis(); + gWifiNotice=String("Connecting: ")+ssid; + WiFi.mode(WIFI_STA); + WiFi.begin(ssid.c_str(),password.c_str()); // asynchronous: WiFi.status() polled in loop() +} +static void wifiScan(bool manual){ + if(!gWifiEnabled)return; + if(gWifiScanActive||gWifiConnecting)return; + gWifiManual=manual;gWifiNotice="Scanning..."; + gScannedCount=0; + int result=WiFi.scanNetworks(true,false); // asynchronous scanning + gWifiScanActive=(result==WIFI_SCAN_RUNNING || result==-1); + if(!gWifiScanActive)gWifiNextScan=millis()+15000; +} +static void wifiTryAvailable(){ + int best=-1,bestRssi=-9999; + for(int j=0;jbestRssi){bestRssi=gScannedRssi[j];best=index;} + } + if(best>=0){gAttemptedSaved=best;gAttemptMask|=(1u<12000){ + gWifiConnecting=false;WiFi.disconnect(false,false);gWifiNotice="Connection failed"; + if(!gWifiManual)wifiTryAvailable(); + else wifiScreen(nullptr); + } + return; + } + if(gWifiScanActive){ + int result=WiFi.scanComplete(); + if(result==WIFI_SCAN_RUNNING||result==-1)return; + gWifiScanActive=false; + if(result>0){ + for(int i=0;i90000){ + networkFinish("Wi-Fi timeout");return; + } + if((int32_t)(now-gWifiNextScan)>=0 && gNetOperation!=NetOperation::None){gWifiNextScan=now+60000;wifiScan(false);} +} +static void wifiSelect(lv_event_t *e){ + uint32_t i=(uintptr_t)lv_event_get_user_data(e);if(i>=gScannedCount)return; + gSelectedSsid=gScannedSsid[i];int old=wifiKnown(gSelectedSsid); + if(gNetOperation==NetOperation::None)gNetOperation=NetOperation::Test; + if(old>=0){gPendingPassword=gSavedPass[old];wifiConnect(gSelectedSsid,gSavedPass[old],true);wifiScreen(nullptr);} + else {gInputTarget=InputTarget::WifiPass;gKbValue="";gKbPage=false;gKbSymbols=false;gKbShift=false;gKbShowPassword=false;wifiPasswordScreen();} +} +static void wifiStartScan(lv_event_t *){ + if(gWifiConnecting||gWifiScanActive)return; + if(!gWifiEnabled)wifiEnable(true); + wifiScan(true);wifiScreen(nullptr); +} +static void wifiForget(lv_event_t *){ + for(int i=0;i<8;i++){ + gSavedSsid[i]="";gSavedPass[i]=""; + String a=String("wifi_ssid_")+i,b=String("wifi_pass_")+i; + gWifiPrefs.remove(a.c_str());gWifiPrefs.remove(b.c_str()); + } + WiFi.disconnect(false,false);gWifiConnecting=false;gWifiNextScan=millis()+1500; + gWifiNotice="Saved networks cleared";wifiScreen(nullptr); +} +static void wifiScreen(lv_event_t *){ + gScreen=Screen::Wifi;clearUi();legend();topBar("Wi-Fi"); + String connected=WiFi.status()==WL_CONNECTED?String("Connected: ")+WiFi.SSID(): + (gWifiConnecting?gWifiNotice:String("Not connected")); + lv_obj_t *status=label(gRoot,connected.c_str(),&lv_font_montserrat_16,0xC9D3DE); + lv_obj_set_pos(status,24,88);lv_obj_set_width(status,432);lv_label_set_long_mode(status,LV_LABEL_LONG_DOT); + lv_obj_t *note=label(gRoot,"Wi-Fi turns off after each operation",&lv_font_montserrat_14,0x9EB4C2); + lv_obj_set_pos(note,24,123); + button(gRoot,"SCAN",24,167,132,43,0x214D69,wifiStartScan); + button(gRoot,"TEST",164,167,132,43,0x214D69,[](lv_event_t *){networkStart(NetOperation::Test);wifiScreen(nullptr);}); + button(gRoot,"FORGET",304,167,152,43,0x553442,wifiForget); + gWifiList=lv_obj_create(gRoot);lv_obj_set_pos(gWifiList,24,222);lv_obj_set_size(gWifiList,432,191);card(gWifiList); + lv_obj_set_style_pad_all(gWifiList,8,0); + lv_obj_set_flex_flow(gWifiList,LV_FLEX_FLOW_COLUMN); + lv_obj_set_style_pad_row(gWifiList,7,0); + lv_obj_add_flag(gWifiList,LV_OBJ_FLAG_SCROLLABLE); + if(!gScannedCount){label(gWifiList,!gWifiEnabled?"Enable Wi-Fi first":(gWifiScanActive?"Scanning networks...":"Tap SCAN to find networks"),&lv_font_montserrat_16,0xC9D3DE);} + for(int i=0;i=0)n+=" [saved]"; + lv_obj_t *item=lv_btn_create(gWifiList);lv_obj_set_size(item,390,43);card(item,0x203E50); + lv_obj_add_event_cb(item,wifiSelect,LV_EVENT_CLICKED,(void *)(uintptr_t)i); + lv_obj_t *name=label(item,n.c_str(),&lv_font_montserrat_16,0xFFFFFF); + lv_obj_set_width(name,365);lv_label_set_long_mode(name,LV_LABEL_LONG_DOT);lv_obj_center(name); + } + button(gRoot,"BACK",140,431,200,39,0x214D69,[](lv_event_t *){if(!gWorkerActive)networkFinish("Wi-Fi off");settings(nullptr);}); + batteryUi(); +} +static void wifiPasswordEvent(lv_event_t *e){ + lv_event_code_t code=lv_event_get_code(e); + if(code==LV_EVENT_CANCEL){wifiScreen(nullptr);return;} + if(code!=LV_EVENT_READY)return; + String password=lv_textarea_get_text(gPasswordField); + // Copy before cleaning the screen (LVGL destroys the textarea). + String ssid=gSelectedSsid; + wifiConnect(ssid,password,true); + // Password only becomes persistent after a successful connection. + // Retain temporarily in RAM during connection. + gPendingPassword=password; + gWifiNotice="Connecting..."; + wifiScreen(nullptr); +} +// Compact SHiNE keyboard: alpha/symbol pages, shift, delete, show password, save/cancel. +// Password stays in RAM until Wi-Fi confirms a successful connection. +static void kbRefreshField(){ + if(!gPasswordField)return; + lv_textarea_set_text(gPasswordField,gKbValue.c_str()); + lv_textarea_set_cursor_pos(gPasswordField,LV_TEXTAREA_CURSOR_LAST); +} +static void kbClicked(lv_event_t *e){ + const char *key=(const char*)lv_event_get_user_data(e); + if(!key)return; + if(!strcmp(key,"")){ + if(gInputTarget==InputTarget::AccountLogin){ + String v=gKbValue;v.toLowerCase(); + bool valid=v.length()>=3 && v.length()<=24; + for(size_t i=0;i='a'&&v[i]<='z')||(v[i]>='0'&&v[i]<='9')||v[i]=='_'||v[i]=='-'))valid=false; + if(!valid){gWifiNotice="Login: 3-24 letters/digits/_/-";accountScreen(nullptr);return;} + // Journals are bound to one owner. Do not silently upload past records to another account. + if(gDeviceToken.length() && v!=gAccountLogin){ + gWifiNotice="Device linked: account change requires archival/reset"; + onlineScreen(nullptr);return; + } + if(v!=gAccountLogin)gAccountPassword=""; + gAccountLogin=v;gAccountPrefs.putString("login",v); + if(gDeviceToken.isEmpty())gAccountPrefs.remove("token"); + accountScreen(nullptr);return; + } + if(gInputTarget==InputTarget::AccountPass){gAccountPassword=gKbValue;gDeviceToken="";gAccountPrefs.remove("token");accountScreen(nullptr);return;} + String ssid=gSelectedSsid,pass=gKbValue;gPendingPassword=pass; + wifiConnect(ssid,pass,true);gWifiNotice="Connecting...";wifiScreen(nullptr);return; + } + if(!strcmp(key,"")){if(gInputTarget==InputTarget::WifiPass)wifiScreen(nullptr);else accountScreen(nullptr);return;} + if(!strcmp(key,"")){gKbSymbols=!gKbSymbols;gKbPage=false;wifiPasswordScreen();return;} + if(!strcmp(key,"")){gKbPage=!gKbPage;wifiPasswordScreen();return;} + if(!strcmp(key,"")){gKbShift=!gKbShift;wifiPasswordScreen();return;} + if(!strcmp(key,"")){gKbShowPassword=!gKbShowPassword;lv_textarea_set_password_mode(gPasswordField,!gKbShowPassword);return;} + if(!strcmp(key,"")){if(gKbValue.length())gKbValue.remove(gKbValue.length()-1);kbRefreshField();return;} + if(!strcmp(key,"")){gKbValue="";kbRefreshField();return;} + if(gKbValue.length()>=(gInputTarget==InputTarget::AccountLogin?24:63))return; + String ch=(!strcmp(key,""))?" ":String(key); + if(!gKbSymbols&&gKbShift)ch.toUpperCase(); + gKbValue+=ch;kbRefreshField(); +} +static void kbButton(const char *title,const char *token,int x,int y,int w,int h,uint32_t bg,uint8_t fontsize=16){ + lv_obj_t *b=lv_btn_create(gRoot);lv_obj_set_pos(b,x,y);lv_obj_set_size(b,w,h); + lv_obj_set_style_radius(b,7,0);lv_obj_set_style_bg_color(b,color(bg),0); + lv_obj_set_style_pad_all(b,0,0); + lv_obj_add_event_cb(b,kbClicked,LV_EVENT_CLICKED,(void*)token); + const lv_font_t *font=fontsize==14?&lv_font_montserrat_14:&lv_font_montserrat_16; + lv_obj_t *txt=label(b,title,font,0xFFFFFF);lv_obj_center(txt); +} +static void wifiPasswordScreen(){ + gScreen=Screen::WifiPassword;clearUi();legend();topBar(gInputTarget==InputTarget::WifiPass?"Wi-Fi password":(gInputTarget==InputTarget::AccountLogin?"Account login":"Account password")); + lv_obj_t *name=label(gRoot,gInputTarget==InputTarget::WifiPass?gSelectedSsid.c_str():"breathmonitor.shineup.me",&lv_font_montserrat_20,0xFFFFFF); + lv_obj_set_pos(name,18,73);lv_obj_set_width(name,444);lv_label_set_long_mode(name,LV_LABEL_LONG_DOT); + gPasswordField=lv_textarea_create(gRoot); + lv_obj_set_pos(gPasswordField,18,109);lv_obj_set_size(gPasswordField,444,51); + lv_textarea_set_one_line(gPasswordField,true); + lv_textarea_set_password_mode(gPasswordField,gInputTarget!=InputTarget::AccountLogin&&!gKbShowPassword); + lv_textarea_set_max_length(gPasswordField,63); + lv_obj_set_style_text_font(gPasswordField,&lv_font_montserrat_20,0); + kbRefreshField(); + // Same split-page layout as shine_homeserver_main.ino, rescaled for 480x480. + static const char *alphaA[3][5]={{"q","w","e","r","t"},{"a","s","d","f","g"},{"z","x","c","v","b"}}; + static const char *alphaB[3][5]={{"y","u","i","o","p"},{"h","j","k","l","."},{"n","m","-","_","@"}}; + static const char *symA[3][5]={{"1","2","3","4","5"},{"/",":","_","@","."},{"!","?","#","+","="}}; + static const char *symB[3][5]={{"6","7","8","9","0"},{"$","%","&","*","-"},{"(",")","[","]","~"}}; + const char *(*rows)[5]=gKbSymbols?(gKbPage?symB:symA):(gKbPage?alphaB:alphaA); + for(int row=0;row<3;row++)for(int col=0;col<5;col++){ + const char *token=rows[row][col];String cap=token; + if(!gKbSymbols&&gKbShift)cap.toUpperCase(); + kbButton(cap.c_str(),token,18+col*91,169+row*58,84,51,0x2A6F97); + } + kbButton(gKbSymbols?"ABC":"123","",18,347,79,47,0x5C6F82); + kbButton(gKbShift?"SHIFT*":"SHIFT","",109,347,79,47,0x7A5C9B,14); + kbButton(gKbPage?"< 1/2":"2/2 >","",200,347,80,47,0x365873); + kbButton("SPACE","",292,347,79,47,0x365873,14); + kbButton("DEL","",383,347,79,47,0x7D3A3A); + kbButton(gKbShowPassword?"HIDE":"SHOW","",18,406,79,54,0x53606B,14); + kbButton("CLEAR","",109,406,79,54,0x7D3A3A,14); + kbButton("CANCEL","",200,406,118,54,0x5A6570,14); + kbButton(gInputTarget==InputTarget::WifiPass?"CONNECT":"SAVE","",330,406,132,54,0x2A9D8F,14); +} + +static void timeScreen(lv_event_t *){ + gScreen=Screen::Time;clearUi();legend();topBar("TIME SETTINGS"); + gTimeCurrent=label(gRoot,"--.--.---- --:--:--",&lv_font_montserrat_24,0xFFFFFF); + lv_obj_align(gTimeCurrent,LV_ALIGN_TOP_MID,0,80); + gTimeStatus=label(gRoot,"Clock not synchronized",&lv_font_montserrat_14,0x9EB4C2); + lv_obj_align(gTimeStatus,LV_ALIGN_TOP_MID,0,123); + lv_obj_t *note=label(gRoot,"Wi-Fi is off except during sync",&lv_font_montserrat_16,0x9EB4C2); + lv_obj_set_pos(note,26,160); + lv_obj_t *tzTitle=label(gRoot,"Time zone (fixed UTC offset)",&lv_font_montserrat_16,0xC9D3DE);lv_obj_set_pos(tzTitle,26,205); + // Fixed selection avoids LVGL dropdown invalidation on screen changes. + gTzDraft=gTimezoneMinutes; + lv_obj_t *tz=label(gRoot,"",&lv_font_montserrat_20,0xFFFFFF);lv_obj_set_pos(tz,175,246);gTzDropdown=tz; + auto tzUpdate=[](){char txt[20];int m=abs(gTzDraft);snprintf(txt,sizeof(txt),"UTC%c%02d:%02d",gTzDraft<0?'-':'+',m/60,m%60);if(gTzDropdown)lv_label_set_text(gTzDropdown,txt);}; + tzUpdate(); + button(gRoot,"-",25,235,60,49,0x214D69,[](lv_event_t *){gTzDraft=max(-720,gTzDraft-15);char b[20];int m=abs(gTzDraft);snprintf(b,sizeof(b),"UTC%c%02d:%02d",gTzDraft<0?'-':'+',m/60,m%60);lv_label_set_text(gTzDropdown,b);}); + button(gRoot,"+",95,235,60,49,0x214D69,[](lv_event_t *){gTzDraft=min(840,gTzDraft+15);char b[20];int m=abs(gTzDraft);snprintf(b,sizeof(b),"UTC%c%02d:%02d",gTzDraft<0?'-':'+',m/60,m%60);lv_label_set_text(gTzDropdown,b);}); + button(gRoot,"SET",330,235,122,49,0x214D69,[](lv_event_t *){gTimezoneMinutes=gTzDraft;saveSettings();timeUiTick();}); + button(gRoot,"SYNC NOW",23,316,210,54,0x214D69,[](lv_event_t *){networkStart(NetOperation::Time);timeUiTick();}); + button(gRoot,"SET MANUALLY",245,316,209,54,0x214D69,[](lv_event_t *){ + time_t e=time(nullptr);if(!gTimeValid||e<1700000000)e=1760000000; + e+=(int32_t)gTimezoneMinutes*60;tm t={};gmtime_r(&e,&t); + gManualParts[0]=t.tm_year+1900;gManualParts[1]=t.tm_mon+1;gManualParts[2]=t.tm_mday;gManualParts[3]=t.tm_hour;gManualParts[4]=t.tm_min; + gManualField=0;gManualDigits="";manualTimeScreen(); + }); + button(gRoot,"BACK",140,399,200,52,0x214D69,[](lv_event_t *){settings(nullptr);}); +} +static bool manualValid(){ + int y=gManualParts[0],m=gManualParts[1],d=gManualParts[2],h=gManualParts[3],n=gManualParts[4]; + if(y<2024||y>2099||m<1||m>12||h<0||h>23||n<0||n>59)return false; + int nd[]={31,28,31,30,31,30,31,31,30,31,30,31}; + if((y%4==0&&y%100!=0)||y%400==0)nd[1]=29; + return d>=1&&d<=nd[m-1]; +} +static int64_t utcFromParts(int y,int m,int d,int h,int minute){ + y-=m<=2;int era=(y>=0?y:y-399)/400;unsigned yoe=y-era*400; + unsigned mp=m+(m>2?-3:9);unsigned doy=(153*mp+2)/5+d-1; + unsigned doe=yoe*365+yoe/4-yoe/100+doy; + return ((int64_t)era*146097+doe-719468)*86400+h*3600+minute*60; +} +static void manualRefresh(){ + if(!gManualPreview)return;char b[96]; + static const char *fieldNames[]={"YEAR","MONTH","DAY","HOUR","MINUTE"}; + snprintf(b,sizeof(b),"%04d.%02d.%02d %02d:%02d:00\nEditing: %s %s",gManualParts[0],gManualParts[1],gManualParts[2],gManualParts[3],gManualParts[4], + fieldNames[gManualField],gManualDigits.c_str()); + lv_label_set_text(gManualPreview,b); +} +static void manualKey(lv_event_t *e){ + const char *key=(const char*)lv_event_get_user_data(e);if(!key)return; + if(strcmp(key,"CANCEL")==0){timeScreen(nullptr);return;} + if(strcmp(key,"BACK")==0){if(!gManualDigits.isEmpty())gManualDigits.remove(gManualDigits.length()-1);manualRefresh();return;} + if(strcmp(key,"OK")==0){ + if(!gManualDigits.isEmpty())gManualParts[gManualField]=gManualDigits.toInt(); + gManualDigits=""; + if(gManualField<4){gManualField++;manualRefresh();return;} + if(!manualValid()){lv_label_set_text(gManualPreview,"Invalid date or time!\nEdit fields again.");gManualField=0;return;} + time_t utc=(time_t)(utcFromParts(gManualParts[0],gManualParts[1],gManualParts[2],gManualParts[3],gManualParts[4])-(int64_t)gTimezoneMinutes*60); + timeval tv={};tv.tv_sec=utc;tv.tv_usec=0;settimeofday(&tv,nullptr);rtcWrite(utc);gTimeValid=true;gNtpPending=false; + appendEvent(9);timeScreen(nullptr);return; + } + if(gManualDigits.length()<4){gManualDigits+=key;manualRefresh();} +} +static void manualTimeScreen(){ + gScreen=Screen::ManualTime;clearUi();legend();topBar("SET DATE AND TIME"); + gManualPreview=label(gRoot,"",&lv_font_montserrat_20,0xFFFFFF);lv_obj_set_pos(gManualPreview,44,86);manualRefresh(); + const char *keys[]={"1","2","3","4","5","6","7","8","9","BACK","0","OK"}; + for(int i=0;i<12;i++){ + int col=i%3,row=i/3; + button(gRoot,keys[i],30+col*147,173+row*61,126,53,0x214D69,manualKey,(void*)keys[i]); + } + button(gRoot,"CANCEL",133,424,214,45,0x553442,manualKey,(void*)"CANCEL"); +} +static void timeUiTick(){ + if(gScreen!=Screen::Time||!gTimeCurrent)return; + time_t now=time(nullptr);char buf[48]; + if(gTimeValid&&now>1700000000){now+=(int32_t)gTimezoneMinutes*60;tm t={};gmtime_r(&now,&t);snprintf(buf,sizeof(buf),"%02d.%02d.%04d %02d:%02d:%02d",t.tm_mday,t.tm_mon+1,t.tm_year+1900,t.tm_hour,t.tm_min,t.tm_sec);} + else snprintf(buf,sizeof(buf),"--.--.---- --:--:--"); + lv_label_set_text(gTimeCurrent,buf); + String st=gNetOperation==NetOperation::Time?(gNtpPending?"Synchronizing via NTP...":gWifiNotice):(gTimeValid?"Clock available (RTC / NTP)":"Clock not synchronized"); + if(gNetOperation==NetOperation::None&&gWifiNotice=="Time synchronized")st=gWifiNotice; + lv_label_set_text(gTimeStatus,st.c_str()); +} +static void onlineScreen(lv_event_t *){ + gScreen=Screen::Online;clearUi();legend();topBar("ONLINE SYNC"); + String account="Account: "+(gAccountLogin.length()?gAccountLogin:String("not set")); + lv_obj_t *a=label(gRoot,account.c_str(),&lv_font_montserrat_20,0xFFFFFF);lv_obj_set_pos(a,26,105); + lv_obj_t *url=label(gRoot,"breathmonitor.shineup.me",&lv_font_montserrat_16,0x9EB4C2);lv_obj_set_pos(url,26,154); + gOnlineStatus=label(gRoot,"Ready",&lv_font_montserrat_16,0xFFD34D);lv_obj_set_pos(gOnlineStatus,26,210); + lv_obj_set_width(gOnlineStatus,430);lv_label_set_long_mode(gOnlineStatus,LV_LABEL_LONG_WRAP); + button(gRoot,"UPLOAD",24,300,208,55,0x2A9D8F,[](lv_event_t *){ + if(gDeviceToken.isEmpty()&&(gAccountLogin.isEmpty()||gAccountPassword.isEmpty())){gWifiNotice="Set login + password in ACCOUNT";return;} + networkStart(NetOperation::Upload); + }); + button(gRoot,"ACCOUNT",248,300,208,55,0x214D69,[](lv_event_t *){accountScreen(nullptr);}); + button(gRoot,"REUPLOAD",24,377,208,50,0x553442,[](lv_event_t *){ + if(gWorkerActive||gNetOperation!=NetOperation::None){gWifiNotice="Upload in progress";return;} + if(!gFileReady){gWifiNotice="FFat unavailable";return;} + if(FFat.exists("/sync.state")&&!FFat.remove("/sync.state")){gWifiNotice="Cannot reset sync index";return;} + gWifiNotice="Sync index reset; tap UPLOAD"; + }); + button(gRoot,"BACK",248,377,208,50,0x214D69,[](lv_event_t *){settings(nullptr);}); +} +static void accountScreen(lv_event_t *){ + gScreen=Screen::Account;clearUi();legend();topBar("ACCOUNT"); + String title="Login: "+(gAccountLogin.length()?gAccountLogin:String("not set")); + lv_obj_t *a=label(gRoot,title.c_str(),&lv_font_montserrat_20,0xFFFFFF);lv_obj_set_pos(a,26,105); + lv_obj_t *paired=label(gRoot,gDeviceToken.length()?"Paired with server":"Not paired",&lv_font_montserrat_20,gDeviceToken.length()?0x38B26D:0xFFD34D);lv_obj_set_pos(paired,26,156); + lv_obj_t *explain=label(gRoot,"Password is kept in RAM only until pairing.\nToken is saved for subsequent uploads.",&lv_font_montserrat_14,0x9EB4C2); + lv_obj_set_pos(explain,26,205);lv_obj_set_width(explain,420); + button(gRoot,"LOGIN",24,280,208,51,0x214D69,[](lv_event_t *){ + gInputTarget=InputTarget::AccountLogin;gKbValue=gAccountLogin;gKbShowPassword=false;gKbSymbols=gKbPage=gKbShift=false;wifiPasswordScreen();}); + button(gRoot,"PASSWORD",248,280,208,51,0x214D69,[](lv_event_t *){ + gInputTarget=InputTarget::AccountPass;gKbValue="";gKbShowPassword=false;gKbSymbols=gKbPage=gKbShift=false;wifiPasswordScreen();}); + button(gRoot,"PAIR",24,348,208,51,0x2A9D8F,[](lv_event_t *){ + if(gAccountLogin.isEmpty()||gAccountPassword.isEmpty()){gWifiNotice="Enter login and password";onlineScreen(nullptr);return;} + networkStart(NetOperation::Pair);onlineScreen(nullptr);}); + button(gRoot,"BACK",248,348,208,51,0x214D69,[](lv_event_t *){onlineScreen(nullptr);}); +} +static void networkUiTick(){ + if(gScreen!=Screen::Online||!gOnlineStatus)return; + String msg=gWorkerActive?workerMessage():gWifiNotice; + if(msg.length()==0)msg=gDeviceToken.length()?"Paired. Ready to upload":"Set account login/password"; + lv_label_set_text(gOnlineStatus,msg.c_str()); +} +static int64_t lastSyncedBytes(const String &day){ + File f=FFat.open("/sync.state","r");if(!f)return -1; + int64_t result=-1;while(f.available()){ + String line=f.readStringUntil('\n');int x=line.indexOf(' '); + if(x>0 && line.substring(0,x)==day)result=strtoll(line.c_str()+x+1,nullptr,10); + } + f.close();return result; +} +static bool markSynced(const String &day,size_t sz){ + File f=FFat.open("/sync.state","a");if(!f)return false; + size_t n=f.printf("%s %u\n",day.c_str(),(unsigned)sz);f.flush();f.close();return n>0; +} +static bool doPair(WiFiClientSecure &secure){ + if(gAccountLogin.isEmpty()||gAccountPassword.isEmpty()){workerSet("Enter login and password");return false;} + workerSet("Authorizing device..."); + HTTPClient http;String url=String(SERVER_URL)+"/api/device/login"; + if(!http.begin(secure,url)){workerSet("HTTPS initialization failed");return false;} + http.setTimeout(15000);http.addHeader("Content-Type","text/plain; charset=utf-8"); + String body=gAccountLogin+"\n"+gAccountPassword+"\n"+gDeviceId; + int status=http.POST(body);String response=http.getString();http.end(); + if(status!=200||response.length()!=64){workerSet(String("Login failed: HTTP ")+status);return false;} + for(size_t i=0;i=0)fileName=fileName.substring(slash+1); + if(!f.isDirectory()&&fileName.endsWith(".bin")){ + String day=fileName.substring(0,fileName.length()-4); + if(day.length()==8||day=="undated"){ + size_t snapshot=f.size(); + if(snapshot%sizeof(EventRecord)!=0){workerSet(String("Incomplete journal: ")+day);ok=false;} + else if(snapshot==0 || lastSyncedBytes(day)==(int64_t)snapshot){skipped++;} + else{ + workerSet(String("Uploading ")+day+" ..."); + // Keep a second read-only handle bounded to the file length at start. + HTTPClient http;String url=String(SERVER_URL)+"/api/device/upload?date="+day; + if(!http.begin(secure,url)){workerSet("HTTPS initialization failed");ok=false;} + else{ + http.setTimeout(30000); + http.addHeader("Content-Type","application/octet-stream"); + http.addHeader("Authorization",String("Bearer ")+gDeviceToken); + http.addHeader("X-Device-ID",gDeviceId); + f.seek(0); + int status=http.sendRequest("PUT",&f,snapshot); + http.end(); + if(status!=200){workerSet(String("Upload ")+day+" HTTP "+status);ok=false;} + else if(!markSynced(day,snapshot)){workerSet("Upload OK but cannot save sync state");ok=false;} + else sent++; + } + } + } + } + f.close();if(!ok)break;f=dir.openNextFile(); + } + dir.close();if(ok)workerSet(String("Done: ")+sent+" uploaded, "+skipped+" unchanged"); + return ok; +} +static void networkWorker(void *){ + // HTTPS streaming runs on a separate FreeRTOS task, never on the LVGL/input task. + // ESP-IDF/WiFiClientSecure uses one TLS stream at a time. + WiFiClientSecure secure;secure.setCACert(ROOT_CA);secure.setTimeout(30); + NetOperation op=gNetOperation; + bool ok=(op==NetOperation::Pair)?doPair(secure):uploadFiles(secure); + workerSet(workerMessage(),true,ok);gWorkerActive=false; + vTaskDelete(nullptr); +} +static void networkTick(){ + if(gWorkerActive||gWorkerDone)return; + if(gNetOperation!=NetOperation::Upload&&gNetOperation!=NetOperation::Pair)return; + gWorkerActive=true;workerSet("Starting secure connection..."); + BaseType_t started=xTaskCreatePinnedToCore(networkWorker,"breath-sync",16384,nullptr,1,nullptr,0); + if(started!=pdPASS){gWorkerActive=false;networkFinish("Cannot start upload task");} +} +static void networkFinishTick(){ + if(!gWorkerDone)return; + bool ok=gWorkerSuccess;gWorkerDone=false; + String result=workerMessage(); + networkFinish(result.length()?result:(ok?"Completed":"Upload failed")); +} +static void applyRotationScreenPolicy(){ + if(!gRotation || !gImuOk || gPaused || gScreen!=Screen::Monitor)return; + // Keep on for the top edge; keep off for the other three edges. + // For flat orientations retain the ordinary configured screen timeout. + if(gScreenEdgeOrientation==2){ + if(!gScreenOn){gfx->setBrightness(220);gScreenOn=true;} + }else if(gScreenEdgeOrientation==3){ + if(gScreenOn){gfx->setBrightness(0);gScreenOn=false;} + } +} +static void pollOrientation(){ + if(!gRotation||!gImuOk||gPaused||gScreen!=Screen::Monitor)return; + uint32_t now=millis();if(now-gOrientationSample<70)return;gOrientationSample=now; + uint8_t data[6];if(!imuRead(0x35,data,6))return; + int16_t x=(int16_t)(data[0]|data[1]<<8),y=(int16_t)(data[2]|data[3]<<8),z=(int16_t)(data[4]|data[5]<<8); + float horiz=sqrtf((float)x*x+(float)y*y),az=fabsf((float)z); + if(horiz<100&&az<100)return; + // 0 = face up/down (EXHALE); 1 = any edge up (INHALE). + int8_t detected=(az>horiz*1.428f)?0:((azax*1.35f)edge=((int32_t)y*IMU_TOP_EDGE_Y_SIGN>0)?2:3; + else if(ax>ay*1.35f)edge=3; + } + if(edge!=gScreenEdgeCandidate){gScreenEdgeCandidate=edge;gScreenEdgeChanged=now;} + else if(now-gScreenEdgeChanged>=250 && edge!=gScreenEdgeOrientation){ + gScreenEdgeOrientation=edge; + applyRotationScreenPolicy(); + } + if(detected<0)return; + if(detected!=gOrientationCandidate){gOrientationCandidate=detected;gOrientationChanged=now;return;} + if(now-gOrientationChanged<250 || detected==gOrientation)return; + gOrientation=detected; + if(!gRotationArmed){ + gRotationArmed=true; + // Start a new measurement only when the device first reaches an inhale edge. + if(detected==1&&gBreath==BreathState::Waiting)phase(true); + return; + } + if(detected==0)phase(false);else phase(true); +} +// USB commands: LOG LIST, LOG INFO, LOG DOWNLOAD YYYYMMDD (or undated), LOG DOWNLOAD LEGACY. +static String gUsbCommand=""; +static void usbDownload(File f){ + size_t sz=f?f.size():0;Serial.printf("LOG BEGIN %u\n",(unsigned)sz); + if(f){const char hex[]="0123456789ABCDEF";char line[129];size_t n=0; + while(f.available()){int x=f.read();if(x<0)break;line[2*n]=hex[((uint8_t)x)>>4];line[2*n+1]=hex[((uint8_t)x)&15];n++; + if(n==64){line[128]=0;Serial.println(line);n=0;delay(1);}} + if(n){line[2*n]=0;Serial.println(line);}f.close();} + Serial.println("LOG END"); +} +static void usbCommands(){ + while(Serial.available()){ + char ch=(char)Serial.read();if(ch=='\r')continue; + if(ch!='\n'){if(gUsbCommand.length()<64)gUsbCommand+=ch;continue;} + gUsbCommand.trim(); + if(!gFileReady){Serial.println("LOG ERROR FS");} + else if(gUsbCommand=="LOG LIST"||gUsbCommand=="LOG INFO"){ + File d=FFat.open("/logs");File f=d?d.openNextFile():File();size_t bytes=0;unsigned count=0; + while(f){if(!f.isDirectory()){bytes+=f.size();count++;if(gUsbCommand=="LOG LIST")Serial.printf("LOG FILE %s %u\n",f.name(),(unsigned)f.size());}f.close();f=d.openNextFile();} + if(d)d.close();Serial.printf("LOG INFO %u %u %u\n",(unsigned)bytes,(unsigned)gEventSeq,count); + }else if(gUsbCommand.startsWith("LOG DOWNLOAD ")){ + String date=gUsbCommand.substring(13);String path; + if(date=="LEGACY")path="/events.bin"; + else if(date=="undated"||date.length()==8)path=journalPath(date); + else{Serial.println("LOG ERROR DATE");gUsbCommand="";continue;} + File f=FFat.open(path.c_str(),"r");if(!f)Serial.println("LOG ERROR NOT FOUND");else usbDownload(f); + }else if(gUsbCommand.length()){Serial.println("LOG ERROR COMMAND");} + gUsbCommand=""; + } +} +static void formatPromptScreen(){ + gScreen=Screen::Settings;clearUi();topBar("STORAGE ERROR"); + lv_obj_t *title=label(gRoot,"FFat storage is unavailable",&lv_font_montserrat_20,0xFFB86B);lv_obj_align(title,LV_ALIGN_TOP_MID,0,112); + lv_obj_t *text=label(gRoot,"The device cannot read its local logs.\nFormat storage to continue?\nFormatting deletes local logs.",&lv_font_montserrat_16,0xFFFFFF);lv_obj_align(text,LV_ALIGN_TOP_MID,0,160); + button(gRoot,"FORMAT FFat",28,318,196,62,0xA94747,[](lv_event_t *){ + if(!FFat.begin(true)){formatPromptScreen();return;} + if(!FFat.exists("/logs")&&!FFat.mkdir("/logs")){gFileReady=false;formatPromptScreen();return;} + gFileReady=true;gFileMountFailed=false;gEventSeq=0;enterMonitor(nullptr); + },nullptr); + button(gRoot,"CONTINUE",260,318,196,62,0x214D69,[](lv_event_t *){enterMonitor(nullptr);},nullptr); +} +void setup(){Serial.begin(115200);Wire.begin(PIN_I2C_SDA,PIN_I2C_SCL);initPower();pinMode(PIN_INHALE,INPUT_PULLUP);pinMode(PIN_EXHALE,INPUT_PULLUP);initAudio();gfx->begin();gBus->writeC8D8(0x36,0xA0);gfx->setBrightness(220);gTouch.setPins(PIN_TP_INT,-1);gTouch.begin(Wire,0x5A,PIN_I2C_SDA,PIN_I2C_SCL);gTouch.setMaxCoordinates(DISP_W,DISP_H);gTouch.setSwapXY(true);gTouch.setMirrorXY(true,false);loadSettings();initClock();initImu();initEvents();appendEvent(2);wifiLoad(); + gAccountPrefs.begin("breath-account",false); + gAccountLogin=gAccountPrefs.getString("login","");gDeviceToken=gAccountPrefs.getString("token",""); + uint64_t chip=ESP.getEfuseMac();char ident[20];snprintf(ident,sizeof(ident),"%012llX",(unsigned long long)chip);gDeviceId=ident; + lv_init();gBuf1=(lv_color_t *)heap_caps_malloc(DISP_W*40*sizeof(lv_color_t),MALLOC_CAP_DMA);gBuf2=(lv_color_t *)heap_caps_malloc(DISP_W*40*sizeof(lv_color_t),MALLOC_CAP_DMA);lv_disp_draw_buf_init(&gDrawBuf,gBuf1,gBuf2,DISP_W*40);static lv_disp_drv_t dd;lv_disp_drv_init(&dd);dd.hor_res=DISP_W;dd.ver_res=DISP_H;dd.flush_cb=flush;dd.rounder_cb=rounder;dd.draw_buf=&gDrawBuf;lv_disp_drv_register(&dd);static lv_indev_drv_t id;lv_indev_drv_init(&id);id.type=LV_INDEV_TYPE_POINTER;id.read_cb=touchRead;lv_indev_drv_register(&id);const esp_timer_create_args_t ta={.callback=&tick,.name="lvgl_tick"};esp_timer_handle_t timer;esp_timer_create(&ta,&timer);esp_timer_start_periodic(timer,LVGL_TICK_MS*1000);gLastActivity=millis();if(gFileMountFailed)formatPromptScreen();else enterMonitor(nullptr);} +void loop(){uint32_t now=millis();poll(gInhale,true);poll(gExhale,false);pollPowerKey();pollOrientation();usbCommands();wifiTick();ntpTick();networkFinishTick();reminders();if(now-gLastUi>=UI_MS){gLastUi=now;refresh();timeUiTick();networkUiTick();}if(now-gLastBatt>=BATT_MS){gLastBatt=now;batteryUi();}uint32_t timeout=SCREEN_TIMEOUTS[gScreenTimeout];if(gScreenOn&&!(gRotation && gImuOk && gScreenEdgeOrientation==2)&&gScreen!=Screen::Settings&&gScreen!=Screen::Wifi&&gScreen!=Screen::WifiPassword&&gScreen!=Screen::Time&&gScreen!=Screen::ManualTime&&gScreen!=Screen::Online&&gScreen!=Screen::Account&&(int32_t)(now-gKey1WakeUntil)>=0&&timeout&&now-gLastActivity>=timeout){gScreenOn=false;gfx->setBrightness(0);}lv_timer_handler();applyRotationScreenPolicy();if((int32_t)(millis()-gKey1WakeUntil)<0){gScreenOn=true;gfx->setBrightness(220);}delay(5);} diff --git a/breath_button_monitor/breathmonitor_v3 with server/server/AGENTS.md b/breath_button_monitor/breathmonitor_v3 with server/server/AGENTS.md new file mode 100644 index 0000000..2106f00 --- /dev/null +++ b/breath_button_monitor/breathmonitor_v3 with server/server/AGENTS.md @@ -0,0 +1,11 @@ +# AGENTS — BreathMonitor server + +- Сборка выполняется только локально через `./gradlew --no-daemon shadowJar` на JDK 17. +- VPS получает только `build/libs/breathmonitor-1.0.0.jar`; Maven/Gradle на VPS не запускать. +- Runtime-каталог данных задаётся `BREATH_DATA_DIR=/var/lib/breathmonitor` и не должен попадать в пакет приложения. +- Не менять `/var/lib/breathmonitor` при обновлении JAR. +- Не добавлять в git SQLite-файлы, логи, токены, пароли и временные `.gradle`/`build`-артефакты. +- При изменении REST API обновлять описание API в `README_RU.md` и проверять совместимость прошивки. +- При изменении схемы журналов обновлять документацию и тест `RecordFixtureTest.java`. +- Сервис слушает только `127.0.0.1:8090`; внешний HTTPS обслуживает Caddy. +- Production/test VPS не использовать для компиляции: отсутствие Maven/Gradle на VPS является нормальным и ожидаемым состоянием. diff --git a/breath_button_monitor/breathmonitor_v3 with server/server/BreathServer.java b/breath_button_monitor/breathmonitor_v3 with server/server/BreathServer.java new file mode 100644 index 0000000..0d1e922 --- /dev/null +++ b/breath_button_monitor/breathmonitor_v3 with server/server/BreathServer.java @@ -0,0 +1,464 @@ +import com.sun.net.httpserver.Headers; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; + +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; +import java.io.*; +import java.net.*; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.security.*; +import java.sql.*; +import java.time.*; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.concurrent.*; +import java.util.zip.CRC32; + +/** Lightweight standalone server: HTTP API, SQLite, immutable record parser and a static dashboard. + * Deploy behind a HTTPS reverse-proxy (Caddy); never expose the raw HTTP port publicly. + * JDK 21 + org.xerial:sqlite-jdbc (shaded by Gradle). No Spring, Node, or external database. + */ +public final class BreathServer { + private static final int RECORD = 32, MAX_UPLOAD = 16 * 1024 * 1024, ITERATIONS = 210_000; + private static final long SESSION_TTL = 14L * 24 * 3600 * 1000; + private static final SecureRandom RNG = new SecureRandom(); + private static final String DB_URL = "jdbc:sqlite:" + Path.of(System.getenv().getOrDefault("BREATH_DATA_DIR", "data"), "statistics.db").toAbsolutePath(); + private static final Path DATA = Path.of(System.getenv().getOrDefault("BREATH_DATA_DIR", "data")).toAbsolutePath(); + private static final Path WEB = Path.of(System.getenv().getOrDefault("BREATH_WEB_DIR", "web")).toAbsolutePath(); + private static final String ORIGIN = System.getenv().getOrDefault("PUBLIC_ORIGIN", "https://breathmonitor.shineup.me"); + private static final String BIND = System.getenv().getOrDefault("BREATH_BIND", "127.0.0.1"); + private static final int PORT = Integer.parseInt(System.getenv().getOrDefault("BREATH_PORT", "8090")); + private static final DateTimeFormatter DAY = DateTimeFormatter.BASIC_ISO_DATE; + private static final Map THROTTLES = new ConcurrentHashMap<>(); + private static final Object UPLOAD_LOCK = new Object(); + + record User(long id, String login, boolean published) {} + record FileSummary(long cycles, long durationMs, long inhaleMs, long exhaleMs, long maxCycleMs) {} + static final class HttpError extends Exception { + final int status; + HttpError(int status, String message) { super(message); this.status = status; } + } + static final class LoginThrottle { long start = System.currentTimeMillis(); int attempts; } + + public static void main(String[] args) throws Exception { + Files.createDirectories(DATA); + Class.forName("org.sqlite.JDBC"); + initialize(); + if (args.length > 0) { + if (args.length == 2 && args[0].equals("create-user")) { createUser(args[1]); return; } + if (args.length == 2 && args[0].equals("reset-password")) { resetPassword(args[1]); return; } + System.err.println("Usage: java -jar BreathServer.jar [create-user | reset-password ]"); + System.exit(2); + } + HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getByName(BIND), PORT), 64); + server.createContext("/", BreathServer::dispatch); + server.setExecutor(Executors.newFixedThreadPool(12)); + server.start(); + System.out.printf("BreathMonitor listening on http://%s:%d (public origin %s)%n", BIND, PORT, ORIGIN); + } + + private static Connection connection() throws SQLException { + Connection c = DriverManager.getConnection(DB_URL); + try (Statement s = c.createStatement()) { + s.execute("PRAGMA foreign_keys=ON"); + s.execute("PRAGMA busy_timeout=5000"); + } + return c; + } + private static void initialize() throws SQLException { + try (Connection c = connection(); Statement s = c.createStatement()) { + s.execute("PRAGMA journal_mode=WAL"); + s.execute(""" + CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY, login TEXT NOT NULL UNIQUE, + salt TEXT NOT NULL, password_hash TEXT NOT NULL, + published INTEGER NOT NULL DEFAULT 0) + """); + s.execute(""" + CREATE TABLE IF NOT EXISTS devices ( + user_id INTEGER NOT NULL, device_id TEXT NOT NULL, + token_hash TEXT NOT NULL, created_at INTEGER NOT NULL, + PRIMARY KEY(user_id,device_id), FOREIGN KEY(user_id) REFERENCES users(id)) + """); + s.execute("CREATE UNIQUE INDEX IF NOT EXISTS devices_tokens ON devices(token_hash)"); + s.execute(""" + CREATE TABLE IF NOT EXISTS sessions ( + token_hash TEXT PRIMARY KEY, user_id INTEGER NOT NULL, + expires_at INTEGER NOT NULL, FOREIGN KEY(user_id) REFERENCES users(id)) + """); + s.execute(""" + CREATE TABLE IF NOT EXISTS uploads ( + user_id INTEGER NOT NULL, device_id TEXT NOT NULL, day TEXT NOT NULL, + bytes INTEGER NOT NULL, sha256 TEXT NOT NULL, cycles INTEGER NOT NULL, + duration_ms INTEGER NOT NULL, inhale_ms INTEGER NOT NULL, + exhale_ms INTEGER NOT NULL, max_cycle_ms INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + PRIMARY KEY(user_id,device_id,day), FOREIGN KEY(user_id) REFERENCES users(id)) + """); + } + } + private static String readPassword(String prompt) throws IOException { + Console console = System.console(); + if (console != null) { + char[] p = console.readPassword("%s", prompt); + if (p == null) throw new IOException("Password input cancelled"); + String result = new String(p); Arrays.fill(p, '\0'); return result; + } + System.out.print(prompt); + BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); + String result = reader.readLine(); + if (result == null) throw new IOException("Password input cancelled"); + return result; + } + private static void createUser(String login) throws Exception { + validLogin(login); + String pwd = readPassword("New password (1..63 characters): "); + if (pwd.isEmpty() || pwd.length() > 63) throw new IllegalArgumentException("Password must contain 1..63 characters"); + String salt = tokenBytes(16), hash = passwordHash(pwd, salt); + try (Connection c = connection(); PreparedStatement p = c.prepareStatement("INSERT INTO users(login,salt,password_hash) VALUES(?,?,?)")) { + p.setString(1, login); p.setString(2, salt); p.setString(3, hash); p.executeUpdate(); + } + System.out.println("Created user: " + login + ". Sign in on the dashboard, then pair the device."); + } + private static void resetPassword(String login) throws Exception { + validLogin(login); String pwd = readPassword("New password (1..63 characters): "); + if (pwd.isEmpty() || pwd.length() > 63) throw new IllegalArgumentException("Password must contain 1..63 characters"); + String salt = tokenBytes(16), hash = passwordHash(pwd, salt); + try (Connection c = connection()) { + c.setAutoCommit(false); + try (PreparedStatement p = c.prepareStatement("UPDATE users SET salt=?,password_hash=? WHERE login=?")) { + p.setString(1, salt); p.setString(2, hash); p.setString(3, login); + if (p.executeUpdate() != 1) throw new IllegalArgumentException("Unknown user: " + login); + } + try (PreparedStatement p = c.prepareStatement("DELETE FROM sessions WHERE user_id=(SELECT id FROM users WHERE login=?)")) { + p.setString(1, login); p.executeUpdate(); + } + try (PreparedStatement p = c.prepareStatement("DELETE FROM devices WHERE user_id=(SELECT id FROM users WHERE login=?)")) { + p.setString(1, login); p.executeUpdate(); + } + c.commit(); + } + System.out.println("Password updated, web sessions and device tokens revoked."); + } + private static byte[] fromHex(String hex) { return HexFormat.of().parseHex(hex); } + private static String tokenBytes(int n) { byte[] v = new byte[n]; RNG.nextBytes(v); return HexFormat.of().formatHex(v); } + private static String sha(byte[] b) { + try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(b)); } + catch (NoSuchAlgorithmException ex) { throw new AssertionError(ex); } + } + private static String sha(String v) { return sha(v.getBytes(StandardCharsets.UTF_8)); } + private static String passwordHash(String pwd, String salt) throws Exception { + PBEKeySpec spec = new PBEKeySpec(pwd.toCharArray(), fromHex(salt), ITERATIONS, 256); + try { return HexFormat.of().formatHex(SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded()); } + finally { spec.clearPassword(); } + } + private static void validLogin(String login) throws HttpError { + if (!login.matches("[a-z0-9_-]{3,24}")) throw new HttpError(400, "Login must be 3..24 lowercase characters, numbers, '_' or '-'"); + } + private static void validDevice(String device) throws HttpError { + if (!device.matches("[0-9A-F]{12}")) throw new HttpError(400, "Invalid device ID"); + } + private static void validDay(String day) throws HttpError { + if (day.equals("undated")) return; + if (!day.matches("20[2-9][0-9][0-1][0-9][0-3][0-9]")) throw new HttpError(400, "Invalid day"); + try { LocalDate.parse(day, DAY); } catch (Exception ex) { throw new HttpError(400, "Invalid calendar date"); } + } + private static void dispatch(HttpExchange x) { + try { + Headers h = x.getResponseHeaders(); + h.set("X-Content-Type-Options", "nosniff"); h.set("Referrer-Policy", "no-referrer"); + h.set("X-Frame-Options", "DENY"); h.set("Cache-Control", "no-store"); + h.set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'"); + String path = x.getRequestURI().getPath(), method = x.getRequestMethod(); + switch (path) { + case "/api/health" -> { if (!method.equals("GET")) throw new HttpError(405,"Method not allowed"); json(x,200,"{\"ok\":true}"); } + case "/api/device/login" -> { requireMethod(method,"POST"); deviceLogin(x); } + case "/api/device/upload" -> { requireMethod(method,"PUT"); deviceUpload(x); } + case "/api/login" -> { requireMethod(method,"POST"); requireBrowserOrigin(x); browserLogin(x); } + case "/api/logout" -> { requireMethod(method,"POST"); requireBrowserOrigin(x); browserLogout(x); } + case "/api/me" -> { requireMethod(method,"GET"); me(x); } + case "/api/stats" -> { requireMethod(method,"GET"); stats(x); } + case "/api/leaderboard" -> { requireMethod(method,"GET"); leaderboard(x); } + case "/api/privacy" -> { requireMethod(method,"POST"); requireBrowserOrigin(x); privacy(x); } + default -> { if (!method.equals("GET")&& !method.equals("HEAD")) throw new HttpError(405,"Method not allowed"); serveWeb(x,path,method); } + } + } catch (HttpError err) { sendError(x,err.status,err.getMessage()); } + catch (Exception err) { System.err.println("API error: " + err); sendError(x,500,"Internal error"); } + finally { x.close(); } + } + private static void requireMethod(String actual,String expected) throws HttpError { if (!actual.equals(expected))throw new HttpError(405,"Expected " + expected); } + private static void requireBrowserOrigin(HttpExchange x) throws HttpError { + String origin = x.getRequestHeaders().getFirst("Origin"); + if (!ORIGIN.equals(origin)) throw new HttpError(403,"Origin mismatch"); + } + private static byte[] readLimited(HttpExchange x, int limit) throws IOException, HttpError { + long len = 0; + try { len = Long.parseLong(Optional.ofNullable(x.getRequestHeaders().getFirst("Content-Length")).orElse("-1")); } + catch (NumberFormatException err) { throw new HttpError(400,"Invalid content length"); } + if (len > limit) throw new HttpError(413,"Payload too large"); + try (InputStream in = x.getRequestBody(); ByteArrayOutputStream out = new ByteArrayOutputStream()) { + byte[] buf = new byte[8192]; int n; + while ((n=in.read(buf))!=-1) { if (out.size()+n > limit) throw new HttpError(413,"Payload too large"); out.write(buf,0,n); } + return out.toByteArray(); + } + } + private static String[] credentials(HttpExchange x, boolean device) throws Exception { + String body = new String(readLimited(x, 1024),StandardCharsets.UTF_8); + String[] parts = body.split("\\n",-1); + if (parts.length != (device?3:2)) throw new HttpError(400,"Invalid credential payload"); + validLogin(parts[0]); + if (device) validDevice(parts[2]); + return parts; + } + private static String remoteAddress(HttpExchange x) { + // Caddy is trusted and the server binds to 127.0.0.1: use its Remote-IP as a throttle key. + String ip = x.getRequestHeaders().getFirst("X-Forwarded-For"); + return ip!=null && ip.length()<100 ? ip.split(",")[0].trim() : x.getRemoteAddress().getAddress().getHostAddress(); + } + private static void throttle(HttpExchange x) throws HttpError { + String ip=remoteAddress(x); long now=System.currentTimeMillis(); + LoginThrottle l=THROTTLES.computeIfAbsent(ip,key->new LoginThrottle()); + synchronized (l) { + if (now-l.start>60000){l.start=now;l.attempts=0;} + if (++l.attempts>12) throw new HttpError(429,"Too many login attempts, try again later"); + } + if (THROTTLES.size()>10000) THROTTLES.clear(); + } + private static User checkCredentials(String login,String pass) throws Exception { + try(Connection c=connection();PreparedStatement p=c.prepareStatement("SELECT id,salt,password_hash,published FROM users WHERE login=?")) { + p.setString(1,login); + try(ResultSet rs=p.executeQuery()){ + if(!rs.next())return null; + String actual=passwordHash(pass,rs.getString("salt")); + if (!MessageDigest.isEqual(fromHex(actual),fromHex(rs.getString("password_hash"))))return null; + return new User(rs.getLong("id"),login,rs.getInt("published")==1); + } + } + } + private static void deviceLogin(HttpExchange x) throws Exception { + throttle(x); + String[] values=credentials(x,true); + User user=checkCredentials(values[0],values[1]); + if(user==null) throw new HttpError(401,"Invalid credentials"); + String token=tokenBytes(32); + try(Connection c=connection(); PreparedStatement p=c.prepareStatement(""" + INSERT INTO devices(user_id,device_id,token_hash,created_at) VALUES(?,?,?,?) + ON CONFLICT(user_id,device_id) DO UPDATE SET token_hash=excluded.token_hash,created_at=excluded.created_at + """)) { + p.setLong(1,user.id());p.setString(2,values[2]);p.setString(3,sha(token));p.setLong(4,System.currentTimeMillis());p.executeUpdate(); + } + send(x,200,"text/plain; charset=utf-8",token.getBytes(StandardCharsets.UTF_8)); + } + private static void browserLogin(HttpExchange x) throws Exception { + throttle(x);String[] values=credentials(x,false); + User user=checkCredentials(values[0],values[1]); + if(user==null)throw new HttpError(401,"Invalid credentials"); + String token=tokenBytes(32);long expiry=System.currentTimeMillis()+SESSION_TTL; + try(Connection c=connection();PreparedStatement p=c.prepareStatement("INSERT INTO sessions(token_hash,user_id,expires_at) VALUES(?,?,?)")){ + p.setString(1,sha(token));p.setLong(2,user.id());p.setLong(3,expiry);p.executeUpdate(); + } + x.getResponseHeaders().add("Set-Cookie","bm_session="+token+"; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age="+(SESSION_TTL/1000)); + json(x,200,"{\"ok\":true}"); + } + private static User loggedIn(HttpExchange x) throws Exception { + String cookie=Optional.ofNullable(x.getRequestHeaders().getFirst("Cookie")).orElse(""); + String token=null; + for(String piece:cookie.split(";")){ + String s=piece.trim();if(s.startsWith("bm_session=")){token=s.substring("bm_session=".length());break;} + } + if(token==null || !token.matches("[0-9a-f]{64}"))throw new HttpError(401,"Please sign in"); + try(Connection c=connection(); PreparedStatement p=c.prepareStatement(""" + SELECT u.id,u.login,u.published FROM sessions s JOIN users u ON u.id=s.user_id + WHERE s.token_hash=? AND s.expires_at>? + """)){ + p.setString(1,sha(token));p.setLong(2,System.currentTimeMillis()); + try(ResultSet rs=p.executeQuery()){ + if(!rs.next())throw new HttpError(401,"Session expired"); + return new User(rs.getLong(1),rs.getString(2),rs.getInt(3)!=0); + } + } + } + private static void browserLogout(HttpExchange x) throws Exception { + try { loggedIn(x); } catch(HttpError e) { /* Expired sessions still get cookie cleared. */ } + String cookie=Optional.ofNullable(x.getRequestHeaders().getFirst("Cookie")).orElse(""); + for(String p:cookie.split(";")) { + String v=p.trim(); if(v.startsWith("bm_session=")){ + try(Connection c=connection();PreparedStatement s=c.prepareStatement("DELETE FROM sessions WHERE token_hash=?")){ + s.setString(1,sha(v.substring("bm_session=".length())));s.executeUpdate(); + } + } + } + x.getResponseHeaders().add("Set-Cookie","bm_session=; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=0"); + json(x,200,"{\"ok\":true}"); + } + private static void me(HttpExchange x) throws Exception { + User u=loggedIn(x); + json(x,200,"{\"login\":"+quoted(u.login())+",\"published\":"+u.published()+"}"); + } + private static void privacy(HttpExchange x) throws Exception { + User u=loggedIn(x);String body=new String(readLimited(x,16),StandardCharsets.US_ASCII).trim(); + if (!body.equals("true")&&!body.equals("false"))throw new HttpError(400,"Expected true or false"); + try(Connection c=connection();PreparedStatement p=c.prepareStatement("UPDATE users SET published=? WHERE id=?")){ + p.setInt(1,body.equals("true")?1:0);p.setLong(2,u.id());p.executeUpdate(); + } + json(x,200,"{\"ok\":true}"); + } + private static String param(HttpExchange x,String name) { + String q=x.getRequestURI().getRawQuery();if(q==null)return null; + for(String pair:q.split("&")) { + String[] kv=pair.split("=",2);if(kv[0].equals(name))return kv.length==2?URLDecoder.decode(kv[1],StandardCharsets.UTF_8):""; + } + return null; + } + private static User authorizeDevice(HttpExchange x,String device) throws Exception { + String auth=x.getRequestHeaders().getFirst("Authorization"); + if(auth==null||!auth.matches("Bearer [0-9a-f]{64}"))throw new HttpError(401,"Invalid bearer token"); + try(Connection c=connection();PreparedStatement p=c.prepareStatement(""" + SELECT u.id,u.login,u.published FROM devices d JOIN users u ON u.id=d.user_id + WHERE d.token_hash=? AND d.device_id=? + """)){ + p.setString(1,sha(auth.substring(7)));p.setString(2,device); + try(ResultSet rs=p.executeQuery()){ + if(!rs.next())throw new HttpError(401,"Unknown device or revoked token"); + return new User(rs.getLong(1),rs.getString(2),rs.getInt(3)!=0); + } + } + } + private static FileSummary verifyAndSummarize(byte[] body) throws HttpError { + if(body.length==0||body.length%RECORD!=0)throw new HttpError(400,"File must contain complete 32-byte records"); + long cycles=0,total=0,inhale=0,exhale=0,max=0; + CRC32 crc=new CRC32(); + for(int pos=0;pos10)throw new HttpError(400,"Invalid record type/version at offset "+pos); + crc.reset();crc.update(body,pos,28); + long got=ByteBuffer.wrap(body,pos+28,4).order(ByteOrder.LITTLE_ENDIAN).getInt()&0xffffffffL; + if(crc.getValue()!=got)throw new HttpError(400,"CRC32 mismatch at offset "+pos); + if(type==1){ + long i=((body[pos+16]&255)|((body[pos+17]&255)<<8))*100L; + long e=((body[pos+18]&255)|((body[pos+19]&255)<<8))*100L; + cycles++; inhale+=i;exhale+=e;total+=i+e;max=Math.max(max,i+e); + } + } + return new FileSummary(cycles,total,inhale,exhale,max); + } + private static void deviceUpload(HttpExchange x) throws Exception { + String day=param(x,"date");if(day==null)throw new HttpError(400,"Missing date");validDay(day); + String device=x.getRequestHeaders().getFirst("X-Device-ID");if(device==null)throw new HttpError(400,"Missing X-Device-ID");validDevice(device); + User user=authorizeDevice(x,device); + byte[] body=readLimited(x,MAX_UPLOAD); + FileSummary summary=verifyAndSummarize(body); + String hash=sha(body); + Path dest=DATA.resolve("logs").resolve(user.login()).resolve(device).resolve(user.login()+"_"+day+".bin"); + synchronized(UPLOAD_LOCK){ + Files.createDirectories(dest.getParent()); + if(Files.exists(dest)){ + byte[] prior=Files.readAllBytes(dest); + // Device journals are append-only: old bytes may never be replaced or truncated. + if(body.length 'undated' GROUP BY day ORDER BY day DESC LIMIT 400 + """; + long totalCycles=0,totalDuration=0,totalDays=0,lastSync=0,undated=0; + try(Connection c=connection()){ + try(PreparedStatement p=c.prepareStatement(sql)){ + p.setLong(1,user.id());try(ResultSet rs=p.executeQuery()){ + while(rs.next()){ + long cycles=rs.getLong(2),duration=rs.getLong(3); + if(daily.length()>1)daily.append(','); + daily.append("{\"day\":").append(quoted(rs.getString(1))) + .append(",\"cycles\":").append(cycles) + .append(",\"durationMs\":").append(duration) + .append(",\"inhaleMs\":").append(rs.getLong(4)) + .append(",\"exhaleMs\":").append(rs.getLong(5)) + .append(",\"maxCycleMs\":").append(rs.getLong(6)).append('}'); + } + } + } + try(PreparedStatement p=c.prepareStatement("SELECT COALESCE(SUM(cycles),0),COALESCE(SUM(duration_ms),0),COUNT(DISTINCT CASE WHEN day<>'undated' THEN day END),COALESCE(MAX(updated_at),0) FROM uploads WHERE user_id=?")){ + p.setLong(1,user.id());try(ResultSet rs=p.executeQuery()){rs.next();totalCycles=rs.getLong(1);totalDuration=rs.getLong(2);totalDays=rs.getLong(3);lastSync=rs.getLong(4);} + } + try(PreparedStatement p=c.prepareStatement("SELECT COALESCE(SUM(cycles),0) FROM uploads WHERE user_id=? AND day='undated'")){ + p.setLong(1,user.id());try(ResultSet rs=p.executeQuery()){rs.next();undated=rs.getLong(1);} + } + } + daily.append(']'); + json(x,200,"{\"login\":"+quoted(user.login())+",\"totalCycles\":"+totalCycles+ + ",\"totalDurationMs\":"+totalDuration+",\"activeDays\":"+totalDays+ + ",\"lastSyncMs\":"+lastSync+",\"undatedCycles\":"+undated+",\"daily\":"+daily+"}"); + } + private static void leaderboard(HttpExchange x) throws Exception { + StringBuilder b=new StringBuilder("[ "); + try(Connection c=connection();PreparedStatement p=c.prepareStatement(""" + SELECT u.login,COALESCE(SUM(f.cycles),0),COALESCE(SUM(f.duration_ms),0), + COUNT(DISTINCT CASE WHEN f.day<>'undated' THEN f.day END) + FROM users u LEFT JOIN uploads f ON f.user_id=u.id + WHERE u.published=1 GROUP BY u.id ORDER BY SUM(f.duration_ms) DESC LIMIT 100 + """);ResultSet rs=p.executeQuery()){ + boolean first=true; + while(rs.next()){ + if(!first)b.append(',');first=false; + b.append("{\"login\":").append(quoted(rs.getString(1))) + .append(",\"cycles\":").append(rs.getLong(2)) + .append(",\"durationMs\":").append(rs.getLong(3)) + .append(",\"activeDays\":").append(rs.getLong(4)).append('}'); + } + } + b.append(']');json(x,200,b.toString()); + } + private static String quoted(String s){return "\""+s.replace("\\","\\\\").replace("\"","\\\"")+"\"";} + private static void serveWeb(HttpExchange x,String path,String method) throws Exception { + String name = switch(path){case "/","/index.html" -> "index.html"; + case "/app.js" -> "app.js";case "/style.css" -> "style.css"; + default -> null;}; + if(name==null)throw new HttpError(404,"Not found"); + Path target=WEB.resolve(name);if(!Files.isRegularFile(target))throw new HttpError(404,"Frontend files not installed"); + String ct=name.endsWith(".js")?"application/javascript; charset=utf-8":name.endsWith(".css")?"text/css; charset=utf-8":"text/html; charset=utf-8"; + byte[] bytes=Files.readAllBytes(target); + if(method.equals("HEAD")){x.getResponseHeaders().set("Content-Type",ct);x.sendResponseHeaders(200,-1);return;} + send(x,200,ct,bytes); + } + private static void sendError(HttpExchange x,int status,String message) { + try {json(x,status,"{\"error\":"+quoted(message)+"}");}catch(IOException ignored){} + } + private static void json(HttpExchange x,int status,String json) throws IOException { + send(x,status,"application/json; charset=utf-8",json.getBytes(StandardCharsets.UTF_8)); + } + private static void send(HttpExchange x,int status,String type,byte[] bytes) throws IOException { + x.getResponseHeaders().set("Content-Type",type);x.sendResponseHeaders(status,bytes.length); + try(OutputStream o=x.getResponseBody()){o.write(bytes);} + } +} diff --git a/breath_button_monitor/breathmonitor_v3 with server/server/RecordFixtureTest.java b/breath_button_monitor/breathmonitor_v3 with server/server/RecordFixtureTest.java new file mode 100644 index 0000000..6cea114 --- /dev/null +++ b/breath_button_monitor/breathmonitor_v3 with server/server/RecordFixtureTest.java @@ -0,0 +1,25 @@ +import java.lang.reflect.*; +import java.nio.*; +import java.util.zip.CRC32; + +// Requires only JDK 21, not the SQLite JDBC jar; verifies compatibility with ESP32 binary layout. +final class RecordFixtureTest { + public static void main(String[] args) throws Exception { + byte[] r=new byte[32];r[0]=1;r[1]=1;r[2]=1; + ByteBuffer b=ByteBuffer.wrap(r).order(ByteOrder.LITTLE_ENDIAN); + b.putInt(4,100);b.putLong(8,1792828800000L); + b.putShort(16,(short)41);b.putShort(18,(short)55); + CRC32 crc=new CRC32();crc.update(r,0,28);b.putInt(28,(int)crc.getValue()); + Method m=BreathServer.class.getDeclaredMethod("verifyAndSummarize",byte[].class); + m.setAccessible(true); + Object summary=m.invoke(null,(Object)r); + Method cycles=summary.getClass().getDeclaredMethod("cycles");cycles.setAccessible(true); + Method duration=summary.getClass().getDeclaredMethod("durationMs");duration.setAccessible(true); + if((Long)cycles.invoke(summary)!=1||(Long)duration.invoke(summary)!=9600L) + throw new AssertionError("Cycle values not decoded correctly"); + r[16]^=1; + try {m.invoke(null,(Object)r);throw new AssertionError("Corrupted CRC accepted");} + catch(InvocationTargetException ex){if(!ex.getCause().getMessage().contains("CRC32"))throw ex;} + System.out.println("PASS: 32-byte little-endian event, duration and CRC32 validation"); + } +} diff --git a/breath_button_monitor/breathmonitor_v3 with server/server/build.gradle b/breath_button_monitor/breathmonitor_v3 with server/server/build.gradle new file mode 100644 index 0000000..6ff470c --- /dev/null +++ b/breath_button_monitor/breathmonitor_v3 with server/server/build.gradle @@ -0,0 +1,39 @@ +plugins { + id 'java' + id 'application' + id 'com.github.johnrengelman.shadow' version '8.1.1' +} + +group = 'me.shineup' +version = '1.0.0' + +repositories { mavenCentral() } + +java { + toolchain { languageVersion = JavaLanguageVersion.of(17) } +} + +dependencies { + implementation 'org.xerial:sqlite-jdbc:3.50.3.0' + implementation 'org.slf4j:slf4j-nop:2.0.16' +} + +sourceSets { + main { + java.srcDirs = ['.'] + java.includes = ['BreathServer.java'] + } +} + +application { mainClass = 'BreathServer' } +tasks.jar { enabled = false } + +shadowJar { + archiveBaseName = 'breathmonitor' + archiveVersion = '1.0.0' + archiveClassifier = '' + mergeServiceFiles() + manifest { attributes 'Main-Class': 'BreathServer' } +} + +tasks.build { dependsOn tasks.shadowJar } diff --git a/breath_button_monitor/breathmonitor_v3 with server/server/build.sh b/breath_button_monitor/breathmonitor_v3 with server/server/build.sh new file mode 100755 index 0000000..69d3af2 --- /dev/null +++ b/breath_button_monitor/breathmonitor_v3 with server/server/build.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")" +if [[ -x ./gradlew ]]; then + ./gradlew --no-daemon shadowJar +elif command -v gradle >/dev/null 2>&1; then + gradle --no-daemon shadowJar +else + echo 'Gradle is required (install Gradle or provide ./gradlew).' >&2 + exit 1 +fi +printf 'Built %s\n' "$(pwd)/build/libs/breathmonitor-1.0.0.jar" diff --git a/breath_button_monitor/breathmonitor_v3 with server/server/gradle/wrapper/gradle-wrapper.jar b/breath_button_monitor/breathmonitor_v3 with server/server/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/breath_button_monitor/breathmonitor_v3 with server/server/gradle/wrapper/gradle-wrapper.jar differ diff --git a/breath_button_monitor/breathmonitor_v3 with server/server/gradle/wrapper/gradle-wrapper.properties b/breath_button_monitor/breathmonitor_v3 with server/server/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..1eb48d1 --- /dev/null +++ b/breath_button_monitor/breathmonitor_v3 with server/server/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Oct 20 16:15:09 MSK 2025 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/breath_button_monitor/breathmonitor_v3 with server/server/gradlew b/breath_button_monitor/breathmonitor_v3 with server/server/gradlew new file mode 100755 index 0000000..1b6c787 --- /dev/null +++ b/breath_button_monitor/breathmonitor_v3 with server/server/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/breath_button_monitor/breathmonitor_v3 with server/server/pom.xml b/breath_button_monitor/breathmonitor_v3 with server/server/pom.xml new file mode 100644 index 0000000..0c4118d --- /dev/null +++ b/breath_button_monitor/breathmonitor_v3 with server/server/pom.xml @@ -0,0 +1,12 @@ + + 4.0.0me.shineupbreathmonitor1.0.0jar + 21UTF-8 + + org.xerialsqlite-jdbc3.50.3.0 + org.slf4jslf4j-nop2.0.16 + + ${project.basedir} + org.apache.maven.pluginsmaven-compiler-plugin3.13.0BreathServer.java + org.apache.maven.pluginsmaven-shade-plugin3.6.0packageshadefalseBreathServer + + diff --git a/breath_button_monitor/breathmonitor_v3 with server/server/settings.gradle b/breath_button_monitor/breathmonitor_v3 with server/server/settings.gradle new file mode 100644 index 0000000..df77872 --- /dev/null +++ b/breath_button_monitor/breathmonitor_v3 with server/server/settings.gradle @@ -0,0 +1,8 @@ +pluginManagement { + repositories { + gradlePluginPortal() + mavenCentral() + } +} + +rootProject.name = 'breathmonitor' diff --git a/breath_button_monitor/breathmonitor_v3 with server/server/start.sh b/breath_button_monitor/breathmonitor_v3 with server/server/start.sh new file mode 100755 index 0000000..36c4eed --- /dev/null +++ b/breath_button_monitor/breathmonitor_v3 with server/server/start.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")" +export BREATH_BIND="${BREATH_BIND:-127.0.0.1}" +export BREATH_PORT="${BREATH_PORT:-8090}" +export PUBLIC_ORIGIN="${PUBLIC_ORIGIN:-https://breathmonitor.shineup.me}" +exec java -jar build/libs/breathmonitor-1.0.0.jar "$@" diff --git a/breath_button_monitor/breathmonitor_v3 with server/server/web/app.js b/breath_button_monitor/breathmonitor_v3 with server/server/web/app.js new file mode 100644 index 0000000..6b1067b --- /dev/null +++ b/breath_button_monitor/breathmonitor_v3 with server/server/web/app.js @@ -0,0 +1,80 @@ +'use strict'; +const $ = (id) => document.getElementById(id); +const number = (value) => new Intl.NumberFormat('ru-RU').format(value || 0); +const duration = (ms) => { const min=Math.round(ms/60000); return min >= 60 ? `${Math.floor(min/60)} ч ${min%60} мин` : `${min} мин`; }; +const readableDay = (day) => `${day.slice(6,8)}.${day.slice(4,6)}.${day.slice(0,4)}`; +async function request(path, options) { + const result=await fetch(path,{credentials:'same-origin', ...options}); + let data; + try { data=await result.json(); } catch {throw new Error(`HTTP ${result.status}`);} + if(!result.ok)throw new Error(data.error||`HTTP ${result.status}`); + return data; +} +function showLoggedIn(yes){$('loginPanel').classList.toggle('hidden',yes);$('dashboard').classList.toggle('hidden',!yes);$('logout').classList.toggle('hidden',!yes);} +async function loadMe(){ + try { const me=await request('/api/me');showLoggedIn(true);$('userName').textContent=me.login; + $('published').checked=!!me.published;await loadStats(); } + catch { showLoggedIn(false);$('userName').textContent=''; } +} +async function loadStats(){ + const data=await request('/api/stats'); + $('totalCycles').textContent=number(data.totalCycles); + $('totalHours').textContent=duration(data.totalDurationMs); + $('activeDays').textContent=number(data.activeDays); + $('avgCycle').textContent=data.totalCycles?`${(data.totalDurationMs/data.totalCycles/1000).toFixed(1)} с`:'—'; + $('syncedAt').textContent=data.lastSyncMs?`Обновлено: ${new Date(data.lastSyncMs).toLocaleString('ru-RU')}`:'Пока нет загрузок'; + const days=[...data.daily].slice(0,12); + $('dailyList').replaceChildren(); + for(const d of days){const row=document.createElement('div');row.className='day'; + const label=document.createElement('div');label.textContent=readableDay(d.day); + const small=document.createElement('small');small.textContent=`${number(d.cycles)} циклов · ср. ${d.cycles?(d.durationMs/d.cycles/1000).toFixed(1):'—'} с`; + label.append(small);const value=document.createElement('strong');value.textContent=duration(d.durationMs);row.append(label,value);$('dailyList').append(row);} + if(!days.length)$('dailyList').textContent='Пока нет синхронизированных практик.'; + $('notice').textContent=data.undatedCycles?`Циклов без достоверной даты: ${number(data.undatedCycles)}. Синхронизируйте часы прибора.`:''; + renderChart(data.daily); +} +function renderChart(days){ + const canvas=$('chart'),ctx=canvas.getContext('2d'); + const w=canvas.width,h=canvas.height;ctx.clearRect(0,0,w,h); + const indexed=new Map(days.map(d=>[d.day,d.durationMs/60000])); + const today=new Date();const series=[]; + for(let n=29;n>=0;n--){const date=new Date(today.getFullYear(),today.getMonth(),today.getDate()-n); + const key=`${date.getFullYear()}${String(date.getMonth()+1).padStart(2,'0')}${String(date.getDate()).padStart(2,'0')}`; + series.push({date,value:indexed.get(key)||0});} + const max=Math.max(20,...series.map(s=>s.value)), top=25,bottom=260,base=bottom-top; + ctx.strokeStyle='#375163';ctx.lineWidth=1;ctx.fillStyle='#9bb0bf';ctx.font='17px system-ui'; + for(let i=0;i<=4;i++){const y=bottom-i*base/4;ctx.beginPath();ctx.moveTo(44,y);ctx.lineTo(w-10,y);ctx.stroke(); + ctx.fillText(`${Math.round(max*i/4)}м`,0,y+5);} + const span=(w-64)/30; + for(let i=0;i=27?'#51d4bb':'#4c87ac';ctx.fillRect(x,bottom-bar,Math.max(5,span-6),bar); + if(i%7===0||i===29){ctx.fillStyle='#9bb0bf';ctx.fillText(String(series[i].date.getDate()),x,bottom+25);} + } +} +async function loadLeaderboard(){ + const rows=await request('/api/leaderboard');const board=$('leaderboard');board.replaceChildren(); + if(!rows.length){const msg=document.createElement('p');msg.className='empty';msg.textContent='Пока никто не включил участие в рейтинге.';board.append(msg);return;} + rows.forEach((r,i)=>{ + const row=document.createElement('div');row.className='leader'; + const rank=document.createElement('span');rank.className='rank';rank.textContent=`#${i+1}`; + const login=document.createElement('b');login.textContent=r.login; + const time=document.createElement('span');time.className='value';time.textContent=duration(r.durationMs); + const cycles=document.createElement('span');cycles.className='cycles';cycles.textContent=`${number(r.cycles)} циклов`; + row.append(rank,login,time,cycles);board.append(row); + }); +} +$('loginForm').addEventListener('submit',async event=>{ + event.preventDefault();$('loginError').textContent=''; + const fd=new FormData(event.target); + try { + await request('/api/login',{method:'POST',headers:{'Content-Type':'text/plain; charset=utf-8'},body:`${fd.get('login')}\n${fd.get('password')}`}); + event.target.reset();await loadMe(); + }catch(e){$('loginError').textContent=e.message;} +}); +$('logout').addEventListener('click',async()=>{try{await request('/api/logout',{method:'POST'});}catch{}showLoggedIn(false);$('userName').textContent='';}); +$('published').addEventListener('change',async event=>{ + try{await request('/api/privacy',{method:'POST',headers:{'Content-Type':'text/plain'},body:String(event.target.checked)});await loadLeaderboard();} + catch(e){event.target.checked=!event.target.checked;$('notice').textContent=`Ошибка изменения видимости: ${e.message}`;} +}); +loadMe();loadLeaderboard().catch(()=>{$('leaderboard').textContent='Не удалось загрузить рейтинг.';}); diff --git a/breath_button_monitor/breathmonitor_v3 with server/server/web/index.html b/breath_button_monitor/breathmonitor_v3 with server/server/web/index.html new file mode 100644 index 0000000..c2e5812 --- /dev/null +++ b/breath_button_monitor/breathmonitor_v3 with server/server/web/index.html @@ -0,0 +1,29 @@ + + + + BreathMonitor · Статистика дыхания + + + +
+
BREATH DATA · LIVE DASHBOARD

Прогресс начинается
с каждого вдоха.

Автономная запись на устройстве. Синхронизация по запросу. История, которая остаётся с вами.

+
INHALE · EXHALE
+
ЛИЧНЫЙ КАБИНЕТ

Войти в статистику

Аккаунт создаётся администратором сервера. Логин и пароль используются также для привязки прибора.

+
+ +
+ +
СООБЩЕСТВО

Рейтинг участников

По общему времени практики
+

Загрузка рейтинга…

+
BreathMonitor · Время практики рассчитывается по завершённым зарегистрированным циклам. Данные обновляются после ручной синхронизации прибора.
+
diff --git a/breath_button_monitor/breathmonitor_v3 with server/server/web/style.css b/breath_button_monitor/breathmonitor_v3 with server/server/web/style.css new file mode 100644 index 0000000..f829e5e --- /dev/null +++ b/breath_button_monitor/breathmonitor_v3 with server/server/web/style.css @@ -0,0 +1 @@ +:root{color-scheme:dark;--bg:#09111c;--panel:#142232;--edge:#273e50;--ink:#ecf7fa;--muted:#92a9b8;--cyan:#50d5c2;--blue:#76aef8}*{box-sizing:border-box}body{margin:0;background:radial-gradient(circle at 85% 5%,#183146 0%,transparent 34%),var(--bg);color:var(--ink);font:16px/1.55 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}button,input{font:inherit}.hidden{display:none!important}.nav{height:86px;display:flex;justify-content:space-between;align-items:center;padding:0 max(5%,calc((100vw - 1170px)/2));border-bottom:1px solid #253947}.brand{display:flex;align-items:center;gap:12px;font-weight:800;font-size:19px;letter-spacing:.2px;line-height:1.2}.brand small{display:block;color:var(--muted);font-size:11px;font-weight:500;text-transform:uppercase;letter-spacing:1.5px;padding-top:4px}.logo{display:grid;place-items:center;width:43px;height:43px;color:#0c272b;background:var(--cyan);font-size:31px;border-radius:12px}.right{display:flex;align-items:center;gap:15px;color:var(--muted)}main{max-width:1170px;margin:auto;padding:0 24px 35px}.hero{min-height:325px;display:flex;align-items:center;justify-content:space-between;gap:30px}.hero h1{font-size:clamp(34px,4.2vw,59px);line-height:1.06;letter-spacing:-1.7px;margin:12px 0 20px;font-weight:750}.hero p{color:var(--muted);max-width:560px;font-size:16px;margin:0}.eyebrow{font-size:11px;font-weight:750;letter-spacing:2.2px;color:var(--cyan)}.pulse{width:220px;height:220px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:20px;color:var(--muted);font-size:10px;letter-spacing:3px}.orb{height:142px;width:142px;border-radius:50%;background:radial-gradient(circle at 38% 36%,#b8fff1 0%,#3ac6b8 35%,#1a4f7d 65%,#19304f 95%);box-shadow:0 0 75px #35ceb63a;animation:breathe 6s ease-in-out infinite}@keyframes breathe{50%{transform:scale(.73);filter:saturate(.85)}}.panel{background:linear-gradient(135deg,#152637 0%,#101e2c 100%);border:1px solid var(--edge);border-radius:20px;padding:24px;margin-bottom:22px}.auth{display:grid;grid-template-columns:1fr 1fr;gap:70px;align-items:center;padding:34px;margin-bottom:54px}.auth h2,.section-title h2{margin:8px 0 8px;font-size:29px}.auth p,.privacy p{color:var(--muted)}form{display:grid;gap:13px}form label{display:grid;gap:7px;font-size:13px;color:var(--muted)}input:not([type=checkbox]){width:100%;background:#0b1926;border:1px solid #345165;border-radius:10px;padding:13px;color:white;outline:none}input:focus{border-color:var(--cyan)}button{background:#204a5d;color:white;border:1px solid #356476;border-radius:10px;padding:10px 18px;cursor:pointer;transition:transform .15s,background .15s}button:hover{transform:translateY(-1px);background:#2b6070}button.primary{background:#4ad2bc;color:#09252b;font-weight:750;padding:13px}.subtle{background:transparent}.error{color:#ffa19a;margin:0;min-height:16px}.section-title{display:flex;justify-content:space-between;align-items:center;gap:12px;margin:22px 0}.section-title h2{font-size:26px}.pill{border:1px solid var(--edge);border-radius:99px;padding:8px 13px;color:var(--muted);font-size:12px}.stat-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:22px}.stat{border:1px solid var(--edge);background:var(--panel);border-radius:16px;padding:22px}.stat span{color:var(--muted);font-size:12px;display:block}.stat strong{display:block;font-size:30px;margin-top:13px;letter-spacing:-.4px}.grid{display:grid;grid-template-columns:1.7fr 1fr;gap:22px}.panel-head{display:flex;align-items:center;justify-content:space-between}.panel-head h3,h3{font-size:18px;margin:0 0 5px}.panel-head p,.panel-head span{color:var(--muted);font-size:13px;margin:0}.chart canvas{width:100%;height:auto;display:block;margin-top:20px}.days{display:grid;gap:10px;margin-top:22px;max-height:300px;overflow:auto}.day{display:flex;align-items:center;justify-content:space-between;padding:10px 0;border-bottom:1px solid #263e4d;gap:15px;font-size:14px}.day strong{white-space:nowrap}.day small{display:block;color:var(--muted)}.privacy{display:flex;align-items:center;justify-content:space-between;gap:35px}.privacy p{max-width:640px;margin:4px 0 0}.toggle{display:flex;align-items:center;gap:8px;color:var(--muted);font-size:13px;white-space:nowrap}.toggle input{accent-color:var(--cyan);width:18px;height:18px}.leaders{display:grid;gap:2px}.leader{display:grid;grid-template-columns:65px 1fr 150px 140px;align-items:center;gap:10px;border-bottom:1px solid #293e4e;padding:16px 12px}.leader:last-child{border-bottom:0}.leader .rank{font-size:20px;color:var(--cyan);font-weight:700}.leader .value{font-weight:700}.leader small{display:block;color:var(--muted);font-size:12px}.empty,.hint,footer{color:var(--muted);font-size:13px}footer{text-align:center;padding:45px 15px;border-top:1px solid #233443;margin-top:50px}@media(max-width:800px){.hero{min-height:275px}.pulse{display:none}.auth,.grid{grid-template-columns:1fr}.stat-grid{grid-template-columns:repeat(2,1fr)}.privacy{align-items:start;flex-direction:column}.leader{grid-template-columns:40px 1fr 110px}.leader .cycles{display:none}}@media(max-width:500px){main{padding:0 15px 25px}.hero h1{letter-spacing:-1px}.panel{padding:16px}.auth{gap:16px}.stat{padding:15px}.stat strong{font-size:25px}.section-title{align-items:start;flex-direction:column}.nav{padding:0 15px}.leader{padding:12px 4px}}