Compare commits
11
Commits
ece218a163
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e69a3bcfd7 | ||
|
|
2761b44ab2 | ||
|
|
09c3eb2806 | ||
|
|
02ce542196 | ||
|
|
b674a87d64 | ||
|
|
e407ab79e3 | ||
|
|
9fffe5fe36 | ||
|
|
5cb3945e98 | ||
|
|
16015cc45f | ||
|
|
d5a37d3009 | ||
|
|
370f4ae94e |
@@ -1 +1,3 @@
|
|||||||
.arduino-build/
|
.arduino-build/
|
||||||
|
breath_button_monitor/breathmonitor_v3 with server/server/.gradle/
|
||||||
|
breath_button_monitor/breathmonitor_v3 with server/server/build/
|
||||||
|
|||||||
Generated
+10
@@ -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
|
||||||
@@ -2,8 +2,8 @@
|
|||||||
|
|
||||||
This group contains Waveshare ESP32-S3-Touch-AMOLED-2.16 breath-monitor sketches.
|
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.
|
- `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.
|
- 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 <mode>` from this folder to compile or flash.
|
- Run `./burn.sh <mode>` from this folder to compile or flash.
|
||||||
|
|||||||
@@ -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`
|
|
||||||
|
|
||||||
## Язык экрана
|
|
||||||
|
|
||||||
Экранные строки в скетче оставлять на английском языке.
|
|
||||||
@@ -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
|
|
||||||
```
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Download append-only events.bin over ESP32 USB serial. pip install pyserial"""
|
||||||
|
import argparse, serial, time
|
||||||
|
p=argparse.ArgumentParser()
|
||||||
|
p.add_argument('port',help='e.g. /dev/ttyACM0')
|
||||||
|
p.add_argument('-o','--output',default='events.bin')
|
||||||
|
p.add_argument('--baud',type=int,default=115200)
|
||||||
|
a=p.parse_args()
|
||||||
|
with serial.Serial(a.port,a.baud,timeout=10) as dev:
|
||||||
|
time.sleep(4)
|
||||||
|
dev.reset_input_buffer()
|
||||||
|
dev.write(b'LOG DOWNLOAD\n')
|
||||||
|
header=''
|
||||||
|
for _ in range(20):
|
||||||
|
header=dev.readline().decode(errors='replace').strip()
|
||||||
|
if header.startswith('LOG BEGIN '): break
|
||||||
|
if header.startswith('LOG ERROR '): raise SystemExit(header)
|
||||||
|
else: raise SystemExit('Device did not respond: '+repr(header))
|
||||||
|
expected=int(header.split()[-1]); result=bytearray()
|
||||||
|
while True:
|
||||||
|
line=dev.readline().strip().decode(errors='replace')
|
||||||
|
if line=='LOG END': break
|
||||||
|
if not line: raise SystemExit('Timeout during transfer')
|
||||||
|
try: result.extend(bytes.fromhex(line))
|
||||||
|
except ValueError: raise SystemExit('Invalid transfer line: '+repr(line))
|
||||||
|
if len(result)!=expected: raise SystemExit(f'Incomplete transfer: {len(result)} of {expected}')
|
||||||
|
with open(a.output,'wb') as file: file.write(result)
|
||||||
|
print(f'Saved {len(result)} bytes into {a.output}')
|
||||||
@@ -0,0 +1,866 @@
|
|||||||
|
#include <Arduino.h>
|
||||||
|
#include <Wire.h>
|
||||||
|
#include <Preferences.h>
|
||||||
|
#include <WiFi.h>
|
||||||
|
#include <time.h>
|
||||||
|
#include <sys/time.h>
|
||||||
|
#include <FFat.h>
|
||||||
|
#include <esp_sntp.h>
|
||||||
|
#include <Arduino_GFX_Library.h>
|
||||||
|
#include <TouchDrvCSTXXX.hpp>
|
||||||
|
#include <lvgl.h>
|
||||||
|
#define XPOWERS_CHIP_AXP2101
|
||||||
|
#include <XPowersLib.h>
|
||||||
|
#include "ESP_I2S.h"
|
||||||
|
#include "es8311.h"
|
||||||
|
|
||||||
|
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 };
|
||||||
|
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;
|
||||||
|
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="";
|
||||||
|
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 gAutoSync=true,gTimeValid=false,gNtpPending=false,gFileReady=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;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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 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;}
|
||||||
|
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);
|
||||||
|
File f=FFat.open("/events.bin","a");if(!f)return false;
|
||||||
|
bool ok=f.write((const uint8_t*)&e,sizeof(e))==sizeof(e);f.flush();f.close();return ok;
|
||||||
|
}
|
||||||
|
static void initEvents(){
|
||||||
|
gFileReady=FFat.begin(false);
|
||||||
|
if(!gFileReady){
|
||||||
|
Serial.println("FFat mount failed; formatting filesystem");
|
||||||
|
gFileReady=FFat.begin(true);
|
||||||
|
}
|
||||||
|
if(!gFileReady){Serial.println("FFat unavailable; recording disabled");return;}
|
||||||
|
File f=FFat.open("/events.bin","r");if(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);
|
||||||
|
}f.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;i<count;i++)data[i]=Wire.read();return true;
|
||||||
|
}
|
||||||
|
static bool imuWrite(uint8_t reg,uint8_t val){Wire.beginTransmission(gImuAddr);Wire.write(reg);Wire.write(val);return Wire.endTransmission()==0;}
|
||||||
|
static void initImu(){for(uint8_t addr:{(uint8_t)0x6A,(uint8_t)0x6B}){
|
||||||
|
gImuAddr=addr;uint8_t id;if(imuRead(0x00,&id,1)&&id==0x05){
|
||||||
|
imuWrite(0x02,0x60); // auto-increment + little endian for burst
|
||||||
|
imuWrite(0x03,0x05); // accelerometer 2g, 125Hz
|
||||||
|
imuWrite(0x08,0x01); // enable accelerometer only
|
||||||
|
gImuOk=true;break;
|
||||||
|
}
|
||||||
|
}if(!gImuOk)Serial.println("QMI8658 unavailable; rotation disabled");
|
||||||
|
}
|
||||||
|
static void pollOrientation();
|
||||||
|
static lv_color_t color(uint32_t c) { return lv_color_hex(c); }
|
||||||
|
static void flush(lv_disp_drv_t *d, const lv_area_t *a, lv_color_t *p) {
|
||||||
|
uint32_t w = a->x2-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<gCycleCount;i++) total+=gCycles[i]; return gCycleCount ? (uint32_t)((total+gCycleCount/2)/gCycleCount) : 0; }
|
||||||
|
static void loadSettings() { gPrefs.begin("manual-lvgl",false); gLimit=min<uint8_t>(4,gPrefs.getUChar("limit",2)); gTick=min<uint8_t>(10,gPrefs.getUChar("tick",3)); gAlert=min<uint8_t>(10,gPrefs.getUChar("alert",10)); gScreenTimeout=min<uint8_t>(3,gPrefs.getUChar("screen",1));gRotation=gPrefs.getBool("rotation",false);gAutoSync=gPrefs.getBool("autosync",true);gTimezoneMinutes=gPrefs.getShort("timezone",60);gWifiEnabled=gPrefs.getBool("wifi_on",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.putBool("autosync",gAutoSync);gPrefs.putShort("timezone",gTimezoneMinutes);gPrefs.putBool("wifi_on",gWifiEnabled); }
|
||||||
|
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<uint16_t>(count,1600); for(uint16_t i=0;i<count;i++){int16_t v=(int16_t)(sinf(6.2831853f*hz*i/16000.0f)*amp);buf[i*2]=v;buf[i*2+1]=v;} gI2s.write((uint8_t *)buf,count*4); }
|
||||||
|
static void quiet() { beep(880,480,TICK_VOLUME[gTick]); } static void loud(){beep(1200,1600,ALERT_VOLUME[gAlert]);}
|
||||||
|
static void batteryUi() { if(!gBatteryText)return; int p=battery(); char t[8]; snprintf(t,sizeof(t),p<0?"--":"%d%%",p); lv_label_set_text(gBatteryText,t); if(gBatteryFill)lv_obj_set_width(gBatteryFill,p>0?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=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,132,42,0x214D69,[](lv_event_t *){wifiScreen(nullptr);});
|
||||||
|
button(gRoot,"TIME",173,383,132,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,"BACK",322,383,132,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){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(!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<uint32_t>(65535,(inhaleMs+50)/100),exh10=min<uint32_t>(65535,(ms-inhaleMs+50)/100);
|
||||||
|
uint16_t avg10=min<uint32_t>(65535,(a+50)/100);
|
||||||
|
uint16_t missing=min<uint32_t>(65535,ms<LIMITS[gLimit]*1000UL?(LIMITS[gLimit]*1000UL-ms+50)/100:0);
|
||||||
|
appendEvent(1,gCycleUtcMs,inh10,exh10,avg10,missing);
|
||||||
|
if(a && a<LIMITS[gLimit]*1000UL){
|
||||||
|
gShortStreak=min<uint8_t>(5,gShortStreak+1);
|
||||||
|
for(uint8_t i=0;i<gShortStreak;i++){loud();delay(80);}
|
||||||
|
}else gShortStreak=0;
|
||||||
|
}
|
||||||
|
static void phase(bool inhale){
|
||||||
|
if(gPaused)return;
|
||||||
|
uint32_t now=millis();
|
||||||
|
if(inhale){
|
||||||
|
if(gBreath==BreathState::Inhale)return;
|
||||||
|
if(gBreath==BreathState::Exhale)addCycle(now-gCycleStarted,gInhaleDuration);
|
||||||
|
gBreath=BreathState::Inhale;gCycleStarted=now;gPhaseStarted=now;gCycleUtcMs=unixMs();gInhaleExceeded=false;gExhaleExceeded=false;quiet();
|
||||||
|
}else{
|
||||||
|
if(gBreath!=BreathState::Inhale)return;
|
||||||
|
gInhaleDuration=now-gPhaseStarted;gBreath=BreathState::Exhale;gPhaseStarted=now;quiet();
|
||||||
|
}
|
||||||
|
gLastReminder=now;
|
||||||
|
}
|
||||||
|
static void poll(Button &b,bool inhale){
|
||||||
|
uint32_t now=millis();bool raw=digitalRead(b.pin)==LOW;
|
||||||
|
if(raw!=b.raw){b.raw=raw;b.changed=now;}
|
||||||
|
if(b.stable==b.raw||now-b.changed<DEBOUNCE_MS){
|
||||||
|
if(!inhale&&b.stable&&!gExhaleLongDone&&now-b.pressed>=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: none"));
|
||||||
|
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<gCycleCount){uint8_t index=(gCycleNext+5-gCycleCount+i)%5;
|
||||||
|
snprintf(t,sizeof(t),"%lu.%01lu",(unsigned long)(gCycles[index]/1000),
|
||||||
|
(unsigned long)((gCycles[index]%1000)/100));}
|
||||||
|
else snprintf(t,sizeof(t),"--");
|
||||||
|
lv_label_set_text(gHistory[i],t);
|
||||||
|
}
|
||||||
|
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);
|
||||||
|
// LVGL owns all drawing; do not overwrite its tiles through direct GFX writes.
|
||||||
|
}
|
||||||
|
static void reminders(){
|
||||||
|
if(gPaused||gBreath==BreathState::Waiting||gScreen!=Screen::Monitor)return;
|
||||||
|
uint32_t now=millis(),age=now-gPhaseStarted;
|
||||||
|
if(age>=LOUD_START_MS){
|
||||||
|
if(gBreath==BreathState::Inhale&&!gInhaleExceeded){gInhaleExceeded=true;appendEvent(7);}
|
||||||
|
if(gBreath==BreathState::Exhale&&!gExhaleExceeded){gExhaleExceeded=true;appendEvent(8);}
|
||||||
|
}
|
||||||
|
if(age<QUIET_START_MS||now-gLastReminder<((age<SLOW_LOUD_MS)?5000:15000))return;
|
||||||
|
gLastReminder=now;
|
||||||
|
if(age<LOUD_START_MS)quiet();else if(age<POWER_OFF_MS)loud();
|
||||||
|
else{appendEvent(3);gfx->setBrightness(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 = gWifiPrefs.getBool("enabled",false);
|
||||||
|
WiFi.mode(gWifiEnabled?WIFI_STA:WIFI_OFF);
|
||||||
|
WiFi.setAutoReconnect(false); // All known networks are selected by our own state machine.
|
||||||
|
WiFi.persistent(false);
|
||||||
|
}
|
||||||
|
static void wifiEnable(bool enabled){
|
||||||
|
gWifiEnabled=enabled;gWifiPrefs.putBool("enabled",enabled);gPrefs.putBool("wifi_on",enabled);
|
||||||
|
gWifiScanActive=false;gWifiConnecting=false;gWifiManual=false;
|
||||||
|
if(!enabled){WiFi.scanDelete();WiFi.disconnect(true,false);WiFi.mode(WIFI_OFF);gWifiNotice="Wi-Fi disabled";}
|
||||||
|
else{WiFi.mode(WIFI_STA);WiFi.setAutoReconnect(false);gAttemptMask=0;gWifiNextScan=millis()+250;gWifiNotice="Wi-Fi enabled";}
|
||||||
|
}
|
||||||
|
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;j<gScannedCount;j++){
|
||||||
|
int index=wifiKnown(gScannedSsid[j]);
|
||||||
|
if(index<0 || (gAttemptMask&(1u<<index)))continue;
|
||||||
|
if(gScannedRssi[j]>bestRssi){bestRssi=gScannedRssi[j];best=index;}
|
||||||
|
}
|
||||||
|
if(best>=0){gAttemptedSaved=best;gAttemptMask|=(1u<<best);
|
||||||
|
wifiConnect(gSavedSsid[best],gSavedPass[best],false);
|
||||||
|
}else{gAttemptMask=0;gWifiNextScan=millis()+20000;gWifiNotice="No saved network available";}
|
||||||
|
}
|
||||||
|
static void wifiTick(){
|
||||||
|
if(!gWifiEnabled)return;
|
||||||
|
const uint32_t now=millis();
|
||||||
|
if(gWifiConnecting){
|
||||||
|
if(WiFi.status()==WL_CONNECTED){
|
||||||
|
gWifiConnecting=false;gAttemptMask=0;gWifiNotice=String("Connected: ")+WiFi.SSID();
|
||||||
|
if(gWifiManual)wifiRemember(WiFi.SSID(),gPendingPassword);
|
||||||
|
if(gAutoSync)requestNtp(); // NTP on every new connection
|
||||||
|
if(gScreen==Screen::Wifi||gScreen==Screen::WifiPassword)wifiScreen(nullptr);
|
||||||
|
}else if(now-gWifiStarted>12000){
|
||||||
|
gWifiConnecting=false;WiFi.disconnect(false,false);gWifiNotice="Connection failed";
|
||||||
|
if(!gWifiManual)wifiTryAvailable();
|
||||||
|
if(gScreen==Screen::Wifi||gScreen==Screen::WifiPassword)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;i<result && gScannedCount<20;i++){
|
||||||
|
String ssid=WiFi.SSID(i);if(ssid.isEmpty())continue;
|
||||||
|
bool repeated=false;for(int j=0;j<gScannedCount;j++)if(gScannedSsid[j]==ssid){repeated=true;break;}
|
||||||
|
if(repeated)continue;
|
||||||
|
gScannedSsid[gScannedCount]=ssid;gScannedRssi[gScannedCount]=WiFi.RSSI(i);gScannedCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
WiFi.scanDelete();gWifiNotice=String("Found networks: ")+gScannedCount;
|
||||||
|
if(gWifiManual){if(gScreen==Screen::Wifi)wifiScreen(nullptr);}
|
||||||
|
else wifiTryAvailable();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if(WiFi.status()==WL_CONNECTED)return;
|
||||||
|
if((int32_t)(now-gWifiNextScan)>=0){gAttemptMask=0;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(old>=0){gPendingPassword=gSavedPass[old];wifiConnect(gSelectedSsid,gSavedPass[old],true);wifiScreen(nullptr);}
|
||||||
|
else {gKbValue="";gKbPage=false;gKbSymbols=false;gKbShift=false;gKbShowPassword=false;wifiPasswordScreen();}
|
||||||
|
}
|
||||||
|
static void wifiStartScan(lv_event_t *){
|
||||||
|
if(gWifiConnecting||gWifiScanActive)return;
|
||||||
|
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 *check=lv_checkbox_create(gRoot);lv_checkbox_set_text(check,"Wi-Fi enabled");lv_obj_set_pos(check,24,120);
|
||||||
|
if(gWifiEnabled)lv_obj_add_state(check,LV_STATE_CHECKED);
|
||||||
|
lv_obj_add_event_cb(check,[](lv_event_t *e){wifiEnable(lv_obj_has_state(lv_event_get_target(e),LV_STATE_CHECKED));wifiScreen(nullptr);},LV_EVENT_VALUE_CHANGED,nullptr);
|
||||||
|
button(gRoot,"SCAN",24,167,200,43,0x214D69,wifiStartScan);
|
||||||
|
button(gRoot,"FORGET ALL",238,167,218,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<gScannedCount;i++){
|
||||||
|
String n=gScannedSsid[i];if(wifiKnown(n)>=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 *){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,"<SAVE>")){
|
||||||
|
String ssid=gSelectedSsid, pass=gKbValue;
|
||||||
|
wifiConnect(ssid,pass,true);
|
||||||
|
gPendingPassword=pass;
|
||||||
|
gWifiNotice="Connecting...";
|
||||||
|
wifiScreen(nullptr);return;
|
||||||
|
}
|
||||||
|
if(!strcmp(key,"<CANCEL>")){wifiScreen(nullptr);return;}
|
||||||
|
if(!strcmp(key,"<MODE>")){gKbSymbols=!gKbSymbols;gKbPage=false;wifiPasswordScreen();return;}
|
||||||
|
if(!strcmp(key,"<PAGE>")){gKbPage=!gKbPage;wifiPasswordScreen();return;}
|
||||||
|
if(!strcmp(key,"<SHIFT>")){gKbShift=!gKbShift;wifiPasswordScreen();return;}
|
||||||
|
if(!strcmp(key,"<SHOW>")){gKbShowPassword=!gKbShowPassword;lv_textarea_set_password_mode(gPasswordField,!gKbShowPassword);return;}
|
||||||
|
if(!strcmp(key,"<DEL>")){if(gKbValue.length())gKbValue.remove(gKbValue.length()-1);kbRefreshField();return;}
|
||||||
|
if(!strcmp(key,"<CLEAR>")){gKbValue="";kbRefreshField();return;}
|
||||||
|
if(gKbValue.length()>=63)return;
|
||||||
|
String ch=(!strcmp(key,"<SPACE>"))?" ":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("Wi-Fi password");
|
||||||
|
lv_obj_t *name=label(gRoot,gSelectedSsid.c_str(),&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,!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","<MODE>",18,347,79,47,0x5C6F82);
|
||||||
|
kbButton(gKbShift?"SHIFT*":"SHIFT","<SHIFT>",109,347,79,47,0x7A5C9B,14);
|
||||||
|
kbButton(gKbPage?"< 1/2":"2/2 >","<PAGE>",200,347,80,47,0x365873);
|
||||||
|
kbButton("SPACE","<SPACE>",292,347,79,47,0x365873,14);
|
||||||
|
kbButton("DEL","<DEL>",383,347,79,47,0x7D3A3A);
|
||||||
|
kbButton(gKbShowPassword?"HIDE":"SHOW","<SHOW>",18,406,79,54,0x53606B,14);
|
||||||
|
kbButton("CLEAR","<CLEAR>",109,406,79,54,0x7D3A3A,14);
|
||||||
|
kbButton("CANCEL","<CANCEL>",200,406,118,54,0x5A6570,14);
|
||||||
|
kbButton("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);
|
||||||
|
gAutoCheck=lv_checkbox_create(gRoot);lv_checkbox_set_text(gAutoCheck,"Auto sync on Wi-Fi connect");
|
||||||
|
lv_obj_set_pos(gAutoCheck,26,160);if(gAutoSync)lv_obj_add_state(gAutoCheck,LV_STATE_CHECKED);
|
||||||
|
lv_obj_add_event_cb(gAutoCheck,[](lv_event_t *e){gAutoSync=lv_obj_has_state(lv_event_get_target(e),LV_STATE_CHECKED);saveSettings();},LV_EVENT_VALUE_CHANGED,nullptr);
|
||||||
|
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 *){requestNtp();});
|
||||||
|
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);
|
||||||
|
lv_label_set_text(gTimeStatus,gNtpPending?"Synchronizing...":(gTimeValid?"Clock available (RTC / NTP)":"Clock not synchronized"));
|
||||||
|
}
|
||||||
|
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:((az<horiz*0.700f)?1:-1);
|
||||||
|
// Edge selection is only relevant in rotation mode while the monitor is visible.
|
||||||
|
// A stable upward-pointing TOP edge holds the screen on. Other edges turn it off.
|
||||||
|
int8_t edge=-1;
|
||||||
|
if(detected==1){
|
||||||
|
float ax=fabsf((float)x),ay=fabsf((float)y);
|
||||||
|
if(ay>ax*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 CDC serial protocol: LOG INFO / LOG DOWNLOAD; records stay on device.
|
||||||
|
static String gUsbCommand="";
|
||||||
|
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(gUsbCommand=="LOG INFO"){
|
||||||
|
if(!gFileReady){Serial.println("LOG ERROR FS");}
|
||||||
|
else{File f=FFat.open("/events.bin","r");size_t sz=f?f.size():0;if(f)f.close();
|
||||||
|
Serial.printf("LOG INFO %u %u\n",(unsigned)sz,(unsigned)gEventSeq);}
|
||||||
|
}else if(gUsbCommand=="LOG DOWNLOAD"){
|
||||||
|
if(!gFileReady){Serial.println("LOG ERROR FS");}
|
||||||
|
else{File f=FFat.open("/events.bin","r");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");}
|
||||||
|
}else if(gUsbCommand.length()){Serial.println("LOG ERROR COMMAND");}
|
||||||
|
gUsbCommand="";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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();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();enterMonitor(nullptr);gWifiNextScan=millis()+1500;}
|
||||||
|
void loop(){uint32_t now=millis();poll(gInhale,true);poll(gExhale,false);pollPowerKey();pollOrientation();usbCommands();wifiTick();ntpTick();reminders();if(now-gLastUi>=UI_MS){gLastUi=now;refresh();timeUiTick();}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&&(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);}
|
||||||
@@ -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`.
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
# BreathMonitor — автономный прибор + Java/SQLite сервер
|
||||||
|
|
||||||
|
**Комплект для развёртывания** · 24 октября 2026 года
|
||||||
|
Адрес API и сайта уже задан: **https://breathmonitor.shineup.me**
|
||||||
|
|
||||||
|
Это рабочая интеграционная версия: сервер собирается локально на JDK 17 через Gradle, а JAR переносится на VPS без сборки на VPS. Прошивка проверена сборкой и загружена на подключённую ESP32-S3.
|
||||||
|
|
||||||
|
## Содержимое
|
||||||
|
|
||||||
|
```text
|
||||||
|
firmware/firmware.ino — изменённый скетч (UI, измерения, RTC, OTA)
|
||||||
|
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 статистика
|
||||||
|
server/src/main/resources/firmware/ — стабильная 1.4 прошивка внутри JAR
|
||||||
|
deploy/Caddyfile.fragment — пример секции для Caddy
|
||||||
|
deploy/breathmonitor.service — пример службы systemd
|
||||||
|
```
|
||||||
|
|
||||||
|
## 1. Изменения прибора
|
||||||
|
|
||||||
|
- **Без постоянного Wi-Fi.** После загрузки радиомодуль выключен. Операция `TIME → SYNC NOW` подключает известную сеть, синхронизирует NTP+RTC, выключает Wi-Fi. `ONLINE → UPLOAD` делает то же самое для передачи журналов. `Wi-Fi → TEST` проверяет доступность сети и отключает модуль.
|
||||||
|
- На главном экране Wi-Fi не показывается. В `SETTINGS` дыхание, счётчики и звуковые напоминания продолжаются; сверху видны текущая фаза, её длительность и кнопка `PAUSE`/`RESUME`. Надписи легенды: слева `EXHALE`, справа `INHALE`; процент заряда расположен справа от значка батареи.
|
||||||
|
- При нажатии `PAUSE` запускается таймер: если прибор остаётся на паузе 15 минут, он сохраняет событие выключения, гасит экран и выключается. При `RESUME` таймер отменяется.
|
||||||
|
- До восьми сохранённых 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` содержит только переход в `ONLINE SETTINGS`. В `ONLINE SETTINGS` находятся `UPLOAD` (отправляет сегодняшний файл), адрес сайта `https://breathmonitor.shineup.me`, `ACCOUNT`, `TIME`, `Wi-Fi`, `FIRMWARE`.
|
||||||
|
- `ACCOUNT → CHANGE ACCOUNT` сначала предупреждает об удалении локальных данных. Старые данные и настройки заменяются только после успешной авторизации нового аккаунта; при отмене или ошибке ничего не меняется. Серверный аккаунт `ivan` создан с паролем `1`.
|
||||||
|
- `FIRMWARE` показывает установленную версию и доступные стабильную/тестовую версии; перед OTA обновлением требуется подтверждение. Стабильная версия `1.4` доступна на `/firmware/manifest.json` и внутри JAR.
|
||||||
|
- Передача 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/<login>/<device-id>/<login>_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 SETTINGS → UPLOAD` отправляет только сегодняшний файл; старые журналы остаются на приборе и не отправляются автоматически.
|
||||||
|
|
||||||
|
## 8. Проверки до ежедневного использования
|
||||||
|
|
||||||
|
- Питание OFF/ON посреди дня → количество 32-байтных записей в текущем файле увеличивается, записи не исчезают.
|
||||||
|
- Переход через полночь по настроенному времени → создаётся новый датированный файл.
|
||||||
|
- Сохранённая Wi-Fi сеть недоступна → устройство предлагает список сетей и затем продолжает именно TIME/UPLOAD.
|
||||||
|
- Отключение интернет-кабеля во время отправки → файл на приборе остаётся, повторная синхронизация работает.
|
||||||
|
- Повторный `UPLOAD` без новых циклов → нет дублей статистики.
|
||||||
|
- Появление новых циклов во время отправки → в следующей синхронизации сервер получает расширенный файл.
|
||||||
|
- Сброс часов RTC → новые события идут в `undated.bin` до синхронизации.
|
||||||
|
- Новый пользователь/новый токен → доступ только к своим файлам, публичный рейтинг по умолчанию пустой.
|
||||||
|
- Перед прошивкой заранее выгрузить старый `/events.bin` по USB и сравнить запись после миграции.
|
||||||
|
|
||||||
|
### Локальный тест Java без JDBC
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd server
|
||||||
|
javac --release 17 BreathServer.java RecordFixtureTest.java
|
||||||
|
java RecordFixtureTest
|
||||||
|
```
|
||||||
|
|
||||||
|
Ожидаемый ответ: `PASS: 32-byte little-endian event, duration and CRC32 validation`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**После первого запуска** я рекомендую следующий этап: сделать диагностический экран «свободно FFat / не выгружено / ошибка последней передачи» и веб-функцию загрузки журнала вручную с компьютера. Это облегчит восстановление и сопровождение приборов, когда пользователей станет больше.
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
breathmonitor.shineup.me {
|
||||||
|
encode zstd gzip
|
||||||
|
reverse_proxy 127.0.0.1:8090
|
||||||
|
}
|
||||||
@@ -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
|
||||||
+31
@@ -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-----
|
||||||
+5
-5
@@ -2,12 +2,12 @@
|
|||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
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"
|
DEMO_BASE="$WORKSPACE_DIR/SHiNE-product/ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/official-demo/examples/Arduino-v3.3.5"
|
||||||
PORT="${PORT:-}"
|
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}"
|
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"
|
BUILD_DIR="$ROOT_DIR/../../.arduino-build/breathmonitor-v3"
|
||||||
OUT_DIR="$ROOT_DIR/../../.arduino-build/out-breath-dual-mode-monitor"
|
OUT_DIR="$ROOT_DIR/../../.arduino-build/out-breathmonitor-v3"
|
||||||
|
|
||||||
if [[ ! -d "$DEMO_BASE/libraries" ]]; then
|
if [[ ! -d "$DEMO_BASE/libraries" ]]; then
|
||||||
echo "Missing Waveshare libraries: $DEMO_BASE/libraries" >&2
|
echo "Missing Waveshare libraries: $DEMO_BASE/libraries" >&2
|
||||||
@@ -23,7 +23,7 @@ compile_args=(
|
|||||||
--library "$DEMO_BASE/libraries/XPowersLib"
|
--library "$DEMO_BASE/libraries/XPowersLib"
|
||||||
--library "$DEMO_BASE/libraries/lvgl"
|
--library "$DEMO_BASE/libraries/lvgl"
|
||||||
--library "$DEMO_BASE/libraries/Mylibrary"
|
--library "$DEMO_BASE/libraries/Mylibrary"
|
||||||
"$ROOT_DIR"
|
"$ROOT_DIR/firmware.ino"
|
||||||
)
|
)
|
||||||
|
|
||||||
if ! arduino-cli compile "${compile_args[@]}"; then
|
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
|
echo "Set PORT=/dev/ttyACM0 or use NO_UPLOAD=1." >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
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"
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -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 является нормальным и ожидаемым состоянием.
|
||||||
@@ -0,0 +1,466 @@
|
|||||||
|
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<String, LoginThrottle> 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 <login> | reset-password <login>]");
|
||||||
|
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;pos<body.length;pos+=RECORD){
|
||||||
|
int version=body[pos]&255, type=body[pos+1]&255;
|
||||||
|
if(version!=1||type<1||type>10)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<prior.length || !MessageDigest.isEqual(Arrays.copyOf(body,prior.length),prior))
|
||||||
|
throw new HttpError(409,"Upload does not extend stored journal; reconcile manually");
|
||||||
|
}
|
||||||
|
Path tmp=Files.createTempFile(dest.getParent(),"upload-",".part");
|
||||||
|
try {
|
||||||
|
Files.write(tmp,body,StandardOpenOption.WRITE,StandardOpenOption.TRUNCATE_EXISTING);
|
||||||
|
try{Files.move(tmp,dest,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);}
|
||||||
|
catch(AtomicMoveNotSupportedException err){Files.move(tmp,dest,StandardCopyOption.REPLACE_EXISTING);}
|
||||||
|
}finally{Files.deleteIfExists(tmp);}
|
||||||
|
// Repeated identical uploads are idempotent thanks to the per-device/date PRIMARY KEY.
|
||||||
|
try(Connection c=connection();PreparedStatement p=c.prepareStatement("""
|
||||||
|
INSERT INTO uploads(user_id,device_id,day,bytes,sha256,cycles,duration_ms,inhale_ms,exhale_ms,max_cycle_ms,updated_at)
|
||||||
|
VALUES(?,?,?,?,?,?,?,?,?,?,?)
|
||||||
|
ON CONFLICT(user_id,device_id,day) DO UPDATE SET
|
||||||
|
bytes=excluded.bytes, sha256=excluded.sha256,cycles=excluded.cycles,
|
||||||
|
duration_ms=excluded.duration_ms,inhale_ms=excluded.inhale_ms,
|
||||||
|
exhale_ms=excluded.exhale_ms,max_cycle_ms=excluded.max_cycle_ms,updated_at=excluded.updated_at
|
||||||
|
""")){
|
||||||
|
p.setLong(1,user.id());p.setString(2,device);p.setString(3,day);p.setInt(4,body.length);
|
||||||
|
p.setString(5,hash);p.setLong(6,summary.cycles());p.setLong(7,summary.durationMs());
|
||||||
|
p.setLong(8,summary.inhaleMs());p.setLong(9,summary.exhaleMs());
|
||||||
|
p.setLong(10,summary.maxCycleMs());p.setLong(11,System.currentTimeMillis());p.executeUpdate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
json(x,200,"{\"ok\":true,\"bytes\":"+body.length+",\"cycles\":"+summary.cycles()+"}");
|
||||||
|
}
|
||||||
|
private static void stats(HttpExchange x) throws Exception {
|
||||||
|
User user=loggedIn(x);
|
||||||
|
StringBuilder daily=new StringBuilder("[");
|
||||||
|
String sql="""
|
||||||
|
SELECT day,SUM(cycles),SUM(duration_ms),SUM(inhale_ms),SUM(exhale_ms),MAX(max_cycle_ms)
|
||||||
|
FROM uploads WHERE user_id=? AND day <> '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 {
|
||||||
|
if(path.equals("/firmware/manifest.json")){byte[] bytes="{\"current\":\"1.4\",\"stable\":{\"version\":\"1.4\",\"file\":\"breathmonitor-v1.4.bin\"},\"test\":{\"version\":\"1.2\",\"file\":\"breathmonitor-v1.2.bin\"}}".getBytes(StandardCharsets.UTF_8);if(method.equals("HEAD")){x.getResponseHeaders().set("Content-Type","application/json; charset=utf-8");x.sendResponseHeaders(200,-1);}else send(x,200,"application/json; charset=utf-8",bytes);return;}
|
||||||
|
if(path.startsWith("/firmware/")){String resource=path.substring("/firmware/".length());if(!resource.matches("breathmonitor-v1\\.(1|2|3|4)\\.bin"))throw new HttpError(404,"Firmware not found");try(InputStream in=BreathServer.class.getResourceAsStream("/firmware/"+resource)){if(in==null)throw new HttpError(404,"Firmware not installed");byte[] bytes=in.readAllBytes();if(method.equals("HEAD")){x.getResponseHeaders().set("Content-Type","application/octet-stream");x.sendResponseHeaders(200,-1);}else send(x,200,"application/octet-stream",bytes);return;}}
|
||||||
|
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);}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 }
|
||||||
@@ -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"
|
||||||
Vendored
BIN
Binary file not shown.
Vendored
+6
@@ -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
|
||||||
+234
@@ -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" "$@"
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion><groupId>me.shineup</groupId><artifactId>breathmonitor</artifactId><version>1.0.0</version><packaging>jar</packaging>
|
||||||
|
<properties><maven.compiler.release>21</maven.compiler.release><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties>
|
||||||
|
<dependencies>
|
||||||
|
<dependency><groupId>org.xerial</groupId><artifactId>sqlite-jdbc</artifactId><version>3.50.3.0</version></dependency>
|
||||||
|
<dependency><groupId>org.slf4j</groupId><artifactId>slf4j-nop</artifactId><version>2.0.16</version></dependency>
|
||||||
|
</dependencies>
|
||||||
|
<build><sourceDirectory>${project.basedir}</sourceDirectory><plugins>
|
||||||
|
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.13.0</version><configuration><includes><include>BreathServer.java</include></includes></configuration></plugin>
|
||||||
|
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-shade-plugin</artifactId><version>3.6.0</version><executions><execution><phase>package</phase><goals><goal>shade</goal></goals><configuration><createDependencyReducedPom>false</createDependencyReducedPom><transformers><transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"><mainClass>BreathServer</mainClass></transformer></transformers></configuration></execution></executions></plugin>
|
||||||
|
</plugins></build>
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
pluginManagement {
|
||||||
|
repositories {
|
||||||
|
gradlePluginPortal()
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rootProject.name = 'breathmonitor'
|
||||||
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -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 "$@"
|
||||||
@@ -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<series.length;i++){
|
||||||
|
const x=47+i*span,bar=series[i].value/max*base;
|
||||||
|
ctx.fillStyle=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='Не удалось загрузить рейтинг.';});
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="ru"><head>
|
||||||
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<meta name="theme-color" content="#111e2d"><title>BreathMonitor · Статистика дыхания</title>
|
||||||
|
<link rel="stylesheet" href="/style.css">
|
||||||
|
</head><body>
|
||||||
|
<header class="nav"><div class="brand"><span class="logo">◉</span><div>BreathMonitor<small>Дыхательные практики</small></div></div>
|
||||||
|
<div class="right"><span id="userName"></span><button id="logout" class="subtle hidden">Выход</button></div></header>
|
||||||
|
<main>
|
||||||
|
<section class="hero"><div><span class="eyebrow">BREATH DATA · LIVE DASHBOARD</span><h1>Прогресс начинается<br>с каждого вдоха.</h1><p>Автономная запись на устройстве. Синхронизация по запросу. История, которая остаётся с вами.</p></div>
|
||||||
|
<div class="pulse"><div class="orb"></div><span>INHALE · EXHALE</span></div></section>
|
||||||
|
<section id="loginPanel" class="panel auth"><div><div class="eyebrow">ЛИЧНЫЙ КАБИНЕТ</div><h2>Войти в статистику</h2><p>Аккаунт создаётся администратором сервера. Логин и пароль используются также для привязки прибора.</p></div>
|
||||||
|
<form id="loginForm"><label>Логин<input name="login" required minlength="3" maxlength="24" autocomplete="username" placeholder="например, aidar"></label>
|
||||||
|
<label>Пароль<input name="password" type="password" required autocomplete="current-password" placeholder="••••••••••••"></label>
|
||||||
|
<button type="submit" class="primary">Войти →</button><p id="loginError" class="error" role="alert"></p></form></section>
|
||||||
|
<section id="dashboard" class="hidden">
|
||||||
|
<div class="section-title"><div><span class="eyebrow">МОЯ СТАТИСТИКА</span><h2>Обзор практики</h2></div><span id="syncedAt" class="pill">Не синхронизировано</span></div>
|
||||||
|
<div class="stat-grid"><div class="stat"><span>Всего циклов</span><strong id="totalCycles">—</strong></div><div class="stat"><span>Всего времени</span><strong id="totalHours">—</strong></div>
|
||||||
|
<div class="stat"><span>Активных дней</span><strong id="activeDays">—</strong></div><div class="stat"><span>Средний цикл</span><strong id="avgCycle">—</strong></div></div>
|
||||||
|
<div class="grid"><section class="panel chart"><div class="panel-head"><div><h3>Регулярность</h3><p>Минуты практики за последние 30 дней</p></div></div>
|
||||||
|
<canvas id="chart" width="900" height="300" aria-label="Время практики по дням"></canvas></section>
|
||||||
|
<section class="panel"><div class="panel-head"><h3>Последние дни</h3><span>История</span></div><div id="dailyList" class="days"></div></section></div>
|
||||||
|
<section class="panel privacy"><div><h3>Открытый рейтинг</h3><p>По умолчанию ваши данные скрыты. Вы можете добровольно включить публичный показ общего результата. Детальные графики остаются личными.</p></div><label class="toggle"><input id="published" type="checkbox"><span>Показывать меня в рейтинге</span></label></section>
|
||||||
|
<p id="notice" class="hint"></p>
|
||||||
|
</section>
|
||||||
|
<div class="section-title"><div><span class="eyebrow">СООБЩЕСТВО</span><h2>Рейтинг участников</h2></div><span class="pill">По общему времени практики</span></div>
|
||||||
|
<section class="panel"><div id="leaderboard" class="leaders"><p class="empty">Загрузка рейтинга…</p></div></section>
|
||||||
|
<footer>BreathMonitor · Время практики рассчитывается по завершённым зарегистрированным циклам. Данные обновляются после ручной синхронизации прибора.</footer>
|
||||||
|
</main><script src="/app.js" defer></script></body></html>
|
||||||
File diff suppressed because one or more lines are too long
@@ -1,191 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
set -Eeuo pipefail
|
|
||||||
|
|
||||||
# Build a source bundle ZIP while excluding credentials, private keys,
|
|
||||||
# local state, generated artifacts and other likely secrets.
|
|
||||||
#
|
|
||||||
# Usage:
|
|
||||||
# ./bundle.sh
|
|
||||||
# ./bundle.sh path/to/output.zip
|
|
||||||
#
|
|
||||||
# Run from anywhere inside the project; the script resolves its own directory.
|
|
||||||
|
|
||||||
ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
|
||||||
cd "$ROOT"
|
|
||||||
|
|
||||||
DEFAULT_OUT=0
|
|
||||||
if [[ $# -gt 0 ]]; then
|
|
||||||
OUT="$1"
|
|
||||||
else
|
|
||||||
DEFAULT_OUT=1
|
|
||||||
OUT="SHiNE-bundle-$(date +%Y.%m.%d-%H.%M.%S).zip"
|
|
||||||
fi
|
|
||||||
case "$OUT" in
|
|
||||||
/*) ;;
|
|
||||||
*) OUT="$ROOT/$OUT" ;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
if ! command -v zip >/dev/null 2>&1; then
|
|
||||||
echo "ERROR: 'zip' is required." >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
TMP="$(mktemp -d)"
|
|
||||||
LIST="$TMP/files.txt"
|
|
||||||
SAFE_LIST="$TMP/safe-files.txt"
|
|
||||||
trap 'rm -rf "$TMP"' EXIT
|
|
||||||
|
|
||||||
# Paths / filenames that must never be bundled.
|
|
||||||
is_denied_path() {
|
|
||||||
local p="/$1"
|
|
||||||
|
|
||||||
case "$p" in
|
|
||||||
*/.git/*|*/.git|\
|
|
||||||
*/.gradle/*|*/.gradle|\
|
|
||||||
*/.gradle-home/*|*/.gradle-home|\
|
|
||||||
*/.idea/*|*/.idea|\
|
|
||||||
*/.vscode/*|*/.vscode|\
|
|
||||||
*/node_modules/*|*/node_modules|\
|
|
||||||
*/target/*|*/target|\
|
|
||||||
*/build/*|*/build|\
|
|
||||||
*/out/*|*/out|\
|
|
||||||
*/bin/*|*/bin|\
|
|
||||||
*/logs/*|*/logs|\
|
|
||||||
*/data/*|*/data|\
|
|
||||||
*/test-ledger/*|*/test-ledger|\
|
|
||||||
*/.anchor/*|*/.anchor|\
|
|
||||||
*/.yarn/*|*/.yarn|\
|
|
||||||
*/.vendor/*|*/.vendor|\
|
|
||||||
*/.agents/*|*/.agents|\
|
|
||||||
*/.codex/*|*/.codex|\
|
|
||||||
*/.claude/*|*/.claude|\
|
|
||||||
*/deploy/backup/archive/*|\
|
|
||||||
*/scripts/*/runs/*|\
|
|
||||||
*/scripts/*/keypairs/*|\
|
|
||||||
*/keys/*|\
|
|
||||||
*/.git-local-backup/*)
|
|
||||||
return 0
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
local base="${p##*/}"
|
|
||||||
local lower
|
|
||||||
lower="$(printf '%s' "$base" | tr '[:upper:]' '[:lower:]')"
|
|
||||||
|
|
||||||
case "$lower" in
|
|
||||||
.env|.env.*|\
|
|
||||||
.debug-token|\
|
|
||||||
.npmrc|.pypirc|.netrc|\
|
|
||||||
credentials|credentials.*|\
|
|
||||||
secrets|secrets.*|\
|
|
||||||
secret|secret.*|\
|
|
||||||
id_rsa|id_dsa|id_ecdsa|id_ed25519|\
|
|
||||||
*.pem|*.key|*.p12|*.pfx|*.jks|*.keystore|\
|
|
||||||
*keypair*.json|\
|
|
||||||
service-account*.json|\
|
|
||||||
firebase-adminsdk*.json|\
|
|
||||||
google-services.json|\
|
|
||||||
validator.log)
|
|
||||||
return 0
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
case "$lower" in
|
|
||||||
*.class|*.jar|*.war|*.ear|*.o|*.a|*.so|*.dll|*.dylib|\
|
|
||||||
*.elf|*.map|*.uf2|*.bin|*.merged.bin|\
|
|
||||||
*.log|*.bak|*.bak.png|*.tmp|*.swp|*.swo|\
|
|
||||||
.ds_store)
|
|
||||||
return 0
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
|
|
||||||
# Collect files. Prefer Git because it naturally avoids most ignored local files.
|
|
||||||
if command -v git >/dev/null 2>&1 && git -C "$ROOT" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
|
|
||||||
git -C "$ROOT" ls-files -co --exclude-standard -z > "$TMP/files.z"
|
|
||||||
else
|
|
||||||
find "$ROOT" -type f -print0 > "$TMP/files.z"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Convert to project-relative paths and enforce hard deny rules.
|
|
||||||
: > "$LIST"
|
|
||||||
while IFS= read -r -d '' f; do
|
|
||||||
if [[ "$f" = /* ]]; then
|
|
||||||
rel="${f#"$ROOT"/}"
|
|
||||||
else
|
|
||||||
rel="$f"
|
|
||||||
fi
|
|
||||||
|
|
||||||
[[ "$rel" == "$OUT" ]] && continue
|
|
||||||
[[ -z "$rel" ]] && continue
|
|
||||||
|
|
||||||
if is_denied_path "$rel"; then
|
|
||||||
continue
|
|
||||||
fi
|
|
||||||
|
|
||||||
printf '%s\n' "$rel" >> "$LIST"
|
|
||||||
done < "$TMP/files.z"
|
|
||||||
|
|
||||||
sort -u "$LIST" -o "$LIST"
|
|
||||||
|
|
||||||
# Always include Gradle wrapper bootstrap, even though generic JARs are denied.
|
|
||||||
if [[ -f "$ROOT/SHiNE-server/gradle/wrapper/gradle-wrapper.jar" ]]; then
|
|
||||||
if ! grep -Fxq 'SHiNE-server/gradle/wrapper/gradle-wrapper.jar' "$LIST"; then
|
|
||||||
printf '%s\n' 'SHiNE-server/gradle/wrapper/gradle-wrapper.jar' >> "$LIST"
|
|
||||||
sort -u "$LIST" -o "$LIST"
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Content scan: fail closed on common credential/private-key patterns.
|
|
||||||
# We scan only text-ish files; grep -I skips binary data.
|
|
||||||
SECRET_RE='-----BEGIN ([A-Z0-9 ]+ )?PRIVATE KEY-----|AKIA[0-9A-Z]{16}|ASIA[0-9A-Z]{16}|gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}|sk-[A-Za-z0-9_-]{20,}|xox[baprs]-[A-Za-z0-9-]{10,}|AIza[0-9A-Za-z_-]{30,}|(^|[^A-Za-z0-9])(password|passwd|pwd|secret|api[_-]?key|access[_-]?token|auth[_-]?token|private[_-]?key)[[:space:]]*[:=][[:space:]]*["'\'']?[^${[:space:]]{][^[:space:]]{7,}'
|
|
||||||
|
|
||||||
: > "$SAFE_LIST"
|
|
||||||
found_secret=0
|
|
||||||
|
|
||||||
while IFS= read -r rel; do
|
|
||||||
[[ -f "$ROOT/$rel" ]] || continue
|
|
||||||
|
|
||||||
# Files that contain examples/templates can legitimately mention secret keys
|
|
||||||
# with placeholders. They are scanned too, but placeholder-looking values
|
|
||||||
# are less likely to match the regex above.
|
|
||||||
if LC_ALL=C grep -IEnq "$SECRET_RE" "$ROOT/$rel" 2>/dev/null; then
|
|
||||||
echo "BLOCKED: possible secret in $rel" >&2
|
|
||||||
LC_ALL=C grep -IEn "$SECRET_RE" "$ROOT/$rel" 2>/dev/null \
|
|
||||||
| sed -E 's/(:[[:space:]]*).*/\1[REDACTED]/' \
|
|
||||||
| head -n 3 >&2 || true
|
|
||||||
found_secret=1
|
|
||||||
continue
|
|
||||||
fi
|
|
||||||
|
|
||||||
printf '%s\n' "$rel" >> "$SAFE_LIST"
|
|
||||||
done < "$LIST"
|
|
||||||
|
|
||||||
if (( found_secret != 0 )); then
|
|
||||||
echo >&2
|
|
||||||
echo "Bundle NOT created because possible secrets were detected." >&2
|
|
||||||
echo "Move secrets to ignored/local files or adjust the scanner only after review." >&2
|
|
||||||
exit 2
|
|
||||||
fi
|
|
||||||
|
|
||||||
if [[ ! -s "$SAFE_LIST" ]]; then
|
|
||||||
echo "ERROR: no files left to bundle." >&2
|
|
||||||
exit 3
|
|
||||||
fi
|
|
||||||
|
|
||||||
if (( DEFAULT_OUT == 1 )); then
|
|
||||||
rm -f -- "$ROOT"/SHiNE-bundle-*.zip
|
|
||||||
else
|
|
||||||
rm -f -- "$OUT"
|
|
||||||
fi
|
|
||||||
|
|
||||||
(
|
|
||||||
cd "$ROOT"
|
|
||||||
zip -q -9 "$OUT" -@ < "$SAFE_LIST"
|
|
||||||
)
|
|
||||||
|
|
||||||
echo "Created: $OUT"
|
|
||||||
echo "Files: $(wc -l < "$SAFE_LIST" | tr -d ' ')"
|
|
||||||
echo "Size: $(du -h "$OUT" | awk '{print $1}')"
|
|
||||||
@@ -1,284 +0,0 @@
|
|||||||
#include <Arduino.h>
|
|
||||||
#include <Wire.h>
|
|
||||||
#include <Preferences.h>
|
|
||||||
#include <Arduino_GFX_Library.h>
|
|
||||||
#include <TouchDrvCSTXXX.hpp>
|
|
||||||
#include <lvgl.h>
|
|
||||||
#define XPOWERS_CHIP_AXP2101
|
|
||||||
#include <XPowersLib.h>
|
|
||||||
#include "ESP_I2S.h"
|
|
||||||
#include "es8311.h"
|
|
||||||
|
|
||||||
void setup();
|
|
||||||
void loop();
|
|
||||||
|
|
||||||
// Manual Monitor LVGL V3.2: keep display awake when leaving settings with KEY1.
|
|
||||||
#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};
|
|
||||||
enum class Screen : uint8_t { Home, Monitor, Settings };
|
|
||||||
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;
|
|
||||||
|
|
||||||
static lv_color_t color(uint32_t c) { return lv_color_hex(c); }
|
|
||||||
static void flush(lv_disp_drv_t *d, const lv_area_t *a, lv_color_t *p) {
|
|
||||||
uint32_t w = a->x2-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<gCycleCount;i++) total+=gCycles[i]; return gCycleCount ? (uint32_t)((total+gCycleCount/2)/gCycleCount) : 0; }
|
|
||||||
static void loadSettings() { gPrefs.begin("manual-lvgl",false); gLimit=min<uint8_t>(4,gPrefs.getUChar("limit",2)); gTick=min<uint8_t>(10,gPrefs.getUChar("tick",3)); gAlert=min<uint8_t>(10,gPrefs.getUChar("alert",10)); gScreenTimeout=min<uint8_t>(3,gPrefs.getUChar("screen",1)); }
|
|
||||||
static void saveSettings() { gPrefs.putUChar("limit",gLimit); gPrefs.putUChar("tick",gTick); gPrefs.putUChar("alert",gAlert); gPrefs.putUChar("screen",gScreenTimeout); }
|
|
||||||
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<uint16_t>(count,1600); for(uint16_t i=0;i<count;i++){int16_t v=(int16_t)(sinf(6.2831853f*hz*i/16000.0f)*amp);buf[i*2]=v;buf[i*2+1]=v;} gI2s.write((uint8_t *)buf,count*4); }
|
|
||||||
static void quiet() { beep(880,480,TICK_VOLUME[gTick]); } static void loud(){beep(1200,1600,ALERT_VOLUME[gAlert]);}
|
|
||||||
static void batteryUi() { if(!gBatteryText)return; int p=battery(); char t[8]; snprintf(t,sizeof(t),p<0?"--":"%d%%",p); lv_label_set_text(gBatteryText,t); if(gBatteryFill)lv_obj_set_width(gBatteryFill,p>0?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) { label(gRoot,title,&lv_font_montserrat_24,0xFFFFFF); lv_obj_align(lv_obj_get_child(gRoot,0),LV_ALIGN_TOP_LEFT,26,49); 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=nullptr; }
|
|
||||||
static void legend() {
|
|
||||||
lv_obj_t *l=label(gRoot,"INHALE",&lv_font_montserrat_14,0x38B26D);lv_obj_set_pos(l,24,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_align(l,LV_ALIGN_TOP_RIGHT,-24,12);
|
|
||||||
}
|
|
||||||
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("MANUAL MONITOR");
|
|
||||||
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) { 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,nullptr);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);*v=lv_slider_get_value(lv_event_get_target(e));saveSettings();}
|
|
||||||
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,334);
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
button(gRoot,"BACK",150,435,180,36,0x214D69,[](lv_event_t *){
|
|
||||||
if(gPaused){gPaused=false;gBreath=BreathState::Waiting;}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::Settings){if(gPaused){gPaused=false;gBreath=BreathState::Waiting;}enterMonitor(nullptr);}
|
|
||||||
else settings(nullptr);
|
|
||||||
}
|
|
||||||
static void keyLong(){
|
|
||||||
wakeDisplayFromKey1();
|
|
||||||
if(!gPaused){gPaused=true;gBreath=BreathState::Waiting;gCycleStarted=0;gPhaseStarted=0;}
|
|
||||||
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){
|
|
||||||
if(!ms)return;
|
|
||||||
gCompletedMs+=ms;gCycles[gCycleNext]=ms;gCycleNext=(gCycleNext+1)%5;
|
|
||||||
if(gCycleCount<5)gCycleCount++;
|
|
||||||
uint32_t a=average();if(a && a<LIMITS[gLimit]*1000UL){
|
|
||||||
gShortStreak=min<uint8_t>(5,gShortStreak+1);
|
|
||||||
for(uint8_t i=0;i<gShortStreak;i++){loud();delay(80);}
|
|
||||||
}else gShortStreak=0;
|
|
||||||
}
|
|
||||||
static void phase(bool inhale){
|
|
||||||
if(gPaused)return;
|
|
||||||
uint32_t now=millis();
|
|
||||||
if(inhale){
|
|
||||||
if(gBreath==BreathState::Inhale)return;
|
|
||||||
if(gBreath==BreathState::Exhale)addCycle(now-gCycleStarted);
|
|
||||||
gBreath=BreathState::Inhale;gCycleStarted=now;gPhaseStarted=now;quiet();
|
|
||||||
}else{
|
|
||||||
if(gBreath!=BreathState::Inhale)return;
|
|
||||||
gBreath=BreathState::Exhale;gPhaseStarted=now;quiet();
|
|
||||||
}
|
|
||||||
gLastReminder=now;
|
|
||||||
}
|
|
||||||
static void poll(Button &b,bool inhale){
|
|
||||||
uint32_t now=millis();bool raw=digitalRead(b.pin)==LOW;
|
|
||||||
if(raw!=b.raw){b.raw=raw;b.changed=now;}
|
|
||||||
if(b.stable==b.raw||now-b.changed<DEBOUNCE_MS)return;
|
|
||||||
b.stable=b.raw;if(b.stable){b.pressed=now;gLastActivity=now;
|
|
||||||
if(!gScreenOn){gScreenOn=true;gfx->setBrightness(220);}
|
|
||||||
phase(inhale);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
static void refresh(){
|
|
||||||
if(gScreen!=Screen::Monitor)return;
|
|
||||||
uint32_t now=millis();char t[24];
|
|
||||||
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<gCycleCount){uint8_t index=(gCycleNext+5-gCycleCount+i)%5;
|
|
||||||
snprintf(t,sizeof(t),"%lu.%01lu",(unsigned long)(gCycles[index]/1000),
|
|
||||||
(unsigned long)((gCycles[index]%1000)/100));}
|
|
||||||
else snprintf(t,sizeof(t),"--");
|
|
||||||
lv_label_set_text(gHistory[i],t);
|
|
||||||
}
|
|
||||||
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);
|
|
||||||
// LVGL owns all drawing; do not overwrite its tiles through direct GFX writes.
|
|
||||||
}
|
|
||||||
static void reminders(){
|
|
||||||
if(gPaused||gBreath==BreathState::Waiting||gScreen!=Screen::Monitor)return;
|
|
||||||
uint32_t now=millis(),age=now-gPhaseStarted;
|
|
||||||
if(age<QUIET_START_MS||now-gLastReminder<((age<SLOW_LOUD_MS)?5000:15000))return;
|
|
||||||
gLastReminder=now;
|
|
||||||
if(age<LOUD_START_MS)quiet();else if(age<POWER_OFF_MS)loud();
|
|
||||||
else{gfx->setBrightness(0);if(gPowerReady)gPower.shutdown();esp_deep_sleep_start();}
|
|
||||||
}
|
|
||||||
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();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();enterMonitor(nullptr);}
|
|
||||||
void loop(){uint32_t now=millis();poll(gInhale,true);poll(gExhale,false);pollPowerKey();reminders();if(now-gLastUi>=UI_MS){gLastUi=now;refresh();}if(now-gLastBatt>=BATT_MS){gLastBatt=now;batteryUi();}uint32_t timeout=SCREEN_TIMEOUTS[gScreenTimeout];if(gScreenOn&&gScreen!=Screen::Settings&&(int32_t)(now-gKey1WakeUntil)>=0&&timeout&&now-gLastActivity>=timeout){gScreenOn=false;gfx->setBrightness(0);}lv_timer_handler();if((int32_t)(millis()-gKey1WakeUntil)<0){gScreenOn=true;gfx->setBrightness(220);}delay(5);}
|
|
||||||
Reference in New Issue
Block a user