1219 lines
76 KiB
Arduino
1219 lines
76 KiB
Arduino
#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 <HTTPClient.h>
|
|
#include <Update.h>
|
|
#include <WiFiClientSecure.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"
|
|
|
|
struct EventRecord;
|
|
|
|
void setup();
|
|
void loop();
|
|
|
|
// Manual Monitor LVGL V2.1: swapped physical buttons, inverted orientation phases, edge-controlled AMOLED.
|
|
#define PIN_LCD_CS 12
|
|
#define PIN_LCD_SCLK 38
|
|
#define PIN_LCD_D0 4
|
|
#define PIN_LCD_D1 5
|
|
#define PIN_LCD_D2 6
|
|
#define PIN_LCD_D3 7
|
|
#define PIN_LCD_RST 2
|
|
#define PIN_I2C_SDA 15
|
|
#define PIN_I2C_SCL 14
|
|
#define PIN_TP_INT 11
|
|
#define PIN_INHALE 18
|
|
#define PIN_EXHALE 0
|
|
#define PIN_PA 46
|
|
#define PIN_I2S_BCLK 9
|
|
#define PIN_I2S_LRCK 45
|
|
#define PIN_I2S_DOUT 8
|
|
#define PIN_I2S_DIN 10
|
|
#define PIN_I2S_MCLK 42
|
|
|
|
static constexpr uint16_t DISP_W = 480, DISP_H = 480;
|
|
static constexpr uint32_t LVGL_TICK_MS = 2, UI_MS = 120;
|
|
static constexpr uint32_t DEBOUNCE_MS = 45, BATT_MS = 5000;
|
|
static constexpr uint32_t QUIET_START_MS = 30000, LOUD_START_MS = 60000;
|
|
static constexpr uint32_t SLOW_LOUD_MS = 90000, POWER_OFF_MS = 390000;
|
|
static constexpr uint16_t LIMITS[] = {5, 7, 10, 15, 20};
|
|
static constexpr uint32_t SCREEN_TIMEOUTS[] = {10000, 30000, 60000, 0};
|
|
static const char *SCREEN_TIMEOUT_NAMES[] = {"10 sec", "30 sec", "60 sec", "Always on"};
|
|
static const int16_t TICK_VOLUME[] = {0, 40, 80, 140, 220, 320, 440, 580, 720, 800, 1600};
|
|
static const int16_t ALERT_VOLUME[] = {0, 150, 300, 500, 800, 12000, 12000, 12000, 12000, 12000, 12000};
|
|
|
|
Arduino_DataBus *gBus = new Arduino_ESP32QSPI(PIN_LCD_CS, PIN_LCD_SCLK, PIN_LCD_D0, PIN_LCD_D1, PIN_LCD_D2, PIN_LCD_D3);
|
|
Arduino_CO5300 *gfx = new Arduino_CO5300(gBus, PIN_LCD_RST, 0, DISP_W, DISP_H, 0, 0, 0, 0);
|
|
TouchDrvCST92xx gTouch;
|
|
XPowersPMU gPower;
|
|
I2SClass gI2s;
|
|
Preferences gPrefs;
|
|
|
|
struct Button { int pin; bool raw = false; bool stable = false; uint32_t changed = 0; uint32_t pressed = 0; };
|
|
static Button gInhale{PIN_INHALE}, gExhale{PIN_EXHALE};
|
|
static bool gRotation=false,gImuOk=false,gRotationArmed=false;
|
|
static bool gWifiEnabled=false;
|
|
static int8_t gOrientation=-1,gOrientationCandidate=-1;
|
|
static uint32_t gOrientationChanged=0,gOrientationSample=0;
|
|
// QMI8658 screen-axis mapping: change sign if the TOP edge maps to negative Y.
|
|
static constexpr int8_t IMU_TOP_EDGE_Y_SIGN = 1;
|
|
// 0: face up/down; 1: edge up; 2: screen top edge up; 3: another edge up.
|
|
static int8_t gScreenEdgeOrientation=-1,gScreenEdgeCandidate=-1;
|
|
static uint32_t gScreenEdgeChanged=0;
|
|
static bool gExhaleLongDone=false;
|
|
enum class Screen : uint8_t { Home, Monitor, Settings, Wifi, WifiPassword, Time, ManualTime, Online, Account, Firmware, FirmwareConfirm };
|
|
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 *gTopPhase=nullptr,*gTopPhaseTime=nullptr,*gPauseButton=nullptr;
|
|
static lv_obj_t *gTimeCurrent=nullptr,*gTimeStatus=nullptr,*gAutoCheck=nullptr,*gTzDropdown=nullptr;
|
|
static lv_obj_t *gManualPreview=nullptr, *gOnlineStatus=nullptr;
|
|
static int gTzDraft=60, gManualField=0;
|
|
static int gManualParts[5]={2026,1,1,12,0};
|
|
static String gManualDigits="";
|
|
static lv_obj_t *gWifiList=nullptr, *gPasswordField=nullptr, *gPasswordKeyboard=nullptr;
|
|
static bool gKbSymbols=false,gKbShift=false,gKbPage=false,gKbShowPassword=false;
|
|
static String gKbValue="";
|
|
enum class InputTarget : uint8_t { WifiPass, AccountLogin, AccountPass };
|
|
static InputTarget gInputTarget=InputTarget::WifiPass;
|
|
enum class NetOperation : uint8_t { None, Test, Time, Upload, Pair, ChangeAccount, Firmware };
|
|
static NetOperation gNetOperation=NetOperation::None;
|
|
static uint32_t gNetStarted=0;
|
|
static Screen gOperationReturn=Screen::Wifi;
|
|
static void networkStart(NetOperation);
|
|
static void networkFinish(const String &);
|
|
static void onlineScreen(lv_event_t * = nullptr);
|
|
static void accountScreen(lv_event_t * = nullptr);
|
|
static void accountConfirmScreen(lv_event_t * = nullptr);
|
|
static void firmwareScreen(lv_event_t * = nullptr);
|
|
static void networkTick();
|
|
static String gAccountLogin="", gDeviceToken="", gAccountPassword="", gPendingAccountLogin="", gPendingAccountPassword="", gFirmwareTarget="";
|
|
static bool gChangingAccount=false;
|
|
static String gDeviceId="";
|
|
static Preferences gAccountPrefs;
|
|
static volatile bool gWorkerActive=false, gWorkerDone=false, gWorkerSuccess=false;
|
|
static char gWorkerMessage[128]={};
|
|
static portMUX_TYPE gWorkerMux=portMUX_INITIALIZER_UNLOCKED;
|
|
static void workerSet(const String &msg, bool done=false, bool success=false){
|
|
portENTER_CRITICAL(&gWorkerMux);
|
|
snprintf(gWorkerMessage,sizeof(gWorkerMessage),"%s",msg.c_str());
|
|
if(done){gWorkerSuccess=success;gWorkerDone=true;}
|
|
portEXIT_CRITICAL(&gWorkerMux);
|
|
}
|
|
static String workerMessage(){char local[128];portENTER_CRITICAL(&gWorkerMux);strncpy(local,gWorkerMessage,sizeof(local));local[sizeof(local)-1]=0;portEXIT_CRITICAL(&gWorkerMux);return String(local);}
|
|
// Production HTTPS: this CA trusts Let's Encrypt certificates, including Caddy's default.
|
|
// If Caddy uses a different issuer, replace this PEM and rebuild the firmware.
|
|
static const char SERVER_URL[]="https://breathmonitor.shineup.me";
|
|
static const char FIRMWARE_VERSION[]="1.1";
|
|
static const char ROOT_CA[] PROGMEM = R"CERT(
|
|
-----BEGIN CERTIFICATE-----
|
|
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
|
|
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
|
|
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
|
|
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
|
|
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
|
|
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
|
|
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
|
|
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
|
|
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
|
|
T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
|
|
B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
|
|
B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
|
|
KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
|
|
OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
|
|
jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
|
|
qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
|
|
rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
|
|
HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
|
|
hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
|
|
ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
|
|
3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
|
|
NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
|
|
ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
|
|
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
|
|
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
|
|
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
|
|
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
|
|
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
|
|
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
|
|
-----END CERTIFICATE-----
|
|
)CERT";
|
|
static void wifiPasswordScreen();
|
|
static String gSavedSsid[8], gSavedPass[8], gScannedSsid[20], gSelectedSsid;
|
|
static int32_t gScannedRssi[20];
|
|
static uint8_t gScannedCount=0;
|
|
static bool gWifiScanActive=false, gWifiConnecting=false, gWifiManual=false;
|
|
static void wifiEnable(bool enabled);
|
|
static int8_t gAttemptedSaved=-1;
|
|
static uint8_t gAttemptMask=0;
|
|
static uint32_t gWifiStarted=0, gWifiNextScan=0, gWifiLastStatus=0;
|
|
static String gWifiNotice="", gPendingPassword="";
|
|
static void wifiScreen(lv_event_t * = nullptr);
|
|
static void wifiPasswordScreen();
|
|
static void wifiTick();
|
|
static void wifiScan(bool manual);
|
|
static void wifiConnect(const String &ssid,const String &password,bool manual);
|
|
static void wifiLoad();
|
|
static void timeScreen(lv_event_t * = nullptr);
|
|
static void manualTimeScreen();
|
|
static void timeUiTick();
|
|
static bool gTimeValid=false,gNtpPending=false,gFileReady=false,gFileMountFailed=false;
|
|
static int16_t gTimezoneMinutes=60;
|
|
static uint32_t gNtpStart=0,gLastNtp=0,gEventSeq=0;
|
|
static uint64_t gCycleUtcMs=0;
|
|
static bool appendEvent(uint8_t type,uint64_t timestamp=UINT64_MAX,uint16_t inh=0,uint16_t exh=0,uint16_t avg=0,uint16_t deficit=0,int16_t val=0);
|
|
static uint32_t gInhaleDuration=0;
|
|
static bool gInhaleExceeded=false,gExhaleExceeded=false;
|
|
|
|
|
|
// RTC PCF85063A/T (I2C 0x51). Keep RTC and stored event timestamps in UTC.
|
|
static uint8_t bcd(uint8_t v){return (v/10)*16+(v%10);}
|
|
static uint8_t unbcd(uint8_t v){return (v>>4)*10+(v&15);}
|
|
static bool rtcRead(time_t &epoch){
|
|
Wire.beginTransmission(0x51);Wire.write(0x04);
|
|
if(Wire.endTransmission(false)!=0 || Wire.requestFrom((uint8_t)0x51,(uint8_t)7)!=7)return false;
|
|
uint8_t d[7];for(int i=0;i<7;i++)d[i]=Wire.read();
|
|
if(d[0]&0x80)return false; // oscillator stopped: unreliable calendar
|
|
tm t={};t.tm_sec=unbcd(d[0]&0x7f);t.tm_min=unbcd(d[1]&0x7f);t.tm_hour=unbcd(d[2]&0x3f);
|
|
t.tm_mday=unbcd(d[3]&0x3f);t.tm_mon=unbcd(d[5]&0x1f)-1;t.tm_year=unbcd(d[6])+100;
|
|
if(t.tm_year<124||t.tm_year>199||t.tm_mon<0||t.tm_mon>11||t.tm_mday<1||t.tm_mday>31||t.tm_hour>23||t.tm_min>59||t.tm_sec>59)return false;
|
|
// Convert Gregorian UTC date to Unix seconds without non-portable timegm().
|
|
int y=t.tm_year+1900,m=t.tm_mon+1,day=t.tm_mday;
|
|
y -= m<=2;
|
|
const int era=(y>=0?y:y-399)/400;
|
|
const unsigned yoe=(unsigned)(y-era*400);
|
|
const unsigned mp=(unsigned)(m+(m>2?-3:9));
|
|
const unsigned doy=(153*mp+2)/5+(unsigned)day-1;
|
|
const unsigned doe=yoe*365+yoe/4-yoe/100+doy;
|
|
int64_t days=(int64_t)era*146097+(int64_t)doe-719468;
|
|
epoch=(time_t)(days*86400+t.tm_hour*3600+t.tm_min*60+t.tm_sec);
|
|
return epoch>1700000000;
|
|
}
|
|
static bool rtcWrite(time_t epoch){
|
|
tm t={};gmtime_r(&epoch,&t);
|
|
if(t.tm_year<100||t.tm_year>199)return false;
|
|
Wire.beginTransmission(0x51);Wire.write(0x04);
|
|
uint8_t d[7]={bcd(t.tm_sec),bcd(t.tm_min),bcd(t.tm_hour),bcd(t.tm_mday),bcd(t.tm_wday),bcd(t.tm_mon+1),bcd(t.tm_year-100)};
|
|
Wire.write(d,7);return Wire.endTransmission()==0;
|
|
}
|
|
static uint64_t unixMs(){if(!gTimeValid)return 0;timeval tv={};gettimeofday(&tv,nullptr);return (uint64_t)tv.tv_sec*1000ULL+tv.tv_usec/1000;}
|
|
static void initClock(){time_t v;if(rtcRead(v)){timeval tv={};tv.tv_sec=v;settimeofday(&tv,nullptr);gTimeValid=true;}}
|
|
static void requestNtp(){if(WiFi.status()!=WL_CONNECTED)return;gNtpPending=true;gNtpStart=millis();
|
|
// configTime starts SNTP asynchronously; system timezone remains UTC.
|
|
configTime(0,0,"pool.ntp.org","time.google.com");
|
|
}
|
|
static void ntpTick(){
|
|
if(!gNtpPending)return;
|
|
if(millis()-gNtpStart>18000){gNtpPending=false;if(gNetOperation==NetOperation::Time||gNetOperation==NetOperation::Upload||gNetOperation==NetOperation::Pair)networkFinish("NTP timeout");return;}
|
|
time_t e=time(nullptr);
|
|
if(e>1750000000 && sntp_get_sync_status()==SNTP_SYNC_STATUS_COMPLETED){
|
|
rtcWrite(e);gTimeValid=true;gNtpPending=false;gLastNtp=millis();appendEvent(9);
|
|
if(gNetOperation==NetOperation::Time)networkFinish("Time synchronized");
|
|
}
|
|
}
|
|
// FFat append-only record. Fixed 32 bytes, versioned + CRC32; zero UTC flags untrusted clock.
|
|
// All numerical fields little-endian on ESP32. CRC is over first 28 bytes.
|
|
// type:1 cycle,2 boot,3 shutdown,4 pause,5 resume,6 limit,7 inhaleLong,8 exhaleLong,9 sync,10 rotation.
|
|
struct __attribute__((packed)) EventRecord {
|
|
uint8_t version,type,flags,reserved;
|
|
uint32_t seq;
|
|
uint64_t utcMs;
|
|
uint16_t inhale10,exhale10,avg10,shortfall10;
|
|
int16_t value;
|
|
uint16_t spare;
|
|
uint32_t crc;
|
|
};
|
|
static_assert(sizeof(EventRecord)==32,"Event size should be 32 bytes");
|
|
static uint32_t crc32(const uint8_t *data,size_t size){uint32_t c=~0u;while(size--){c^=*data++;for(int j=0;j<8;j++)c=(c>>1)^((c&1)?0xedb88320u:0u);}return ~c;}
|
|
// File date is local calendar day according to the fixed offset selected in TIME.
|
|
// Raw timestamps remain UTC. An invalid RTC uses a separate undated journal.
|
|
static String dayFor(uint64_t utc,uint8_t flags){
|
|
if(!(flags&1)||utc<1704067200000ULL)return "undated";
|
|
time_t t=(time_t)(utc/1000ULL)+(int32_t)gTimezoneMinutes*60;
|
|
tm val={};gmtime_r(&t,&val);
|
|
if(val.tm_year<124||val.tm_year>199)return "undated";
|
|
char name[12];snprintf(name,sizeof(name),"%04d%02d%02d",val.tm_year+1900,val.tm_mon+1,val.tm_mday);
|
|
return String(name);
|
|
}
|
|
static String journalPath(const String &day){return String("/logs/")+day+".bin";}
|
|
static bool appendRaw(const String &path, const EventRecord &e){
|
|
File f=FFat.open(path.c_str(),"a");if(!f)return false;
|
|
bool ok=f.write((const uint8_t*)&e,sizeof(e))==sizeof(e);f.flush();f.close();return ok;
|
|
}
|
|
static bool appendEvent(uint8_t type,uint64_t timestamp,uint16_t inh,uint16_t exh,uint16_t avg,uint16_t deficit,int16_t val){
|
|
if(!gFileReady)return false;
|
|
EventRecord e={};e.version=1;e.type=type;e.flags=gTimeValid?1:0;e.seq=++gEventSeq;
|
|
e.utcMs=(timestamp==UINT64_MAX)?unixMs():timestamp;
|
|
if(e.utcMs==0)e.flags=0;
|
|
e.inhale10=inh;e.exhale10=exh;e.avg10=avg;e.shortfall10=deficit;e.value=val;
|
|
e.crc=crc32((const uint8_t*)&e,28);
|
|
if(!appendRaw(journalPath(dayFor(e.utcMs,e.flags)),e)){
|
|
Serial.println("LOG ERROR append failed");return false;
|
|
}
|
|
return true;
|
|
}
|
|
static void scanSequenceFile(File &f){
|
|
EventRecord e;while(f.available()>=(int)sizeof(e)){
|
|
if(f.read((uint8_t*)&e,sizeof(e))!=sizeof(e))break;
|
|
if(e.version==1 && e.crc==crc32((const uint8_t*)&e,28))gEventSeq=max(gEventSeq,e.seq);
|
|
}
|
|
}
|
|
// Import the V2.1 /events.bin to date files. Never delete the original.
|
|
// Last migrated seq in each date file prevents duplicates after interrupted boots.
|
|
static bool migrateLegacy(){
|
|
if(!FFat.exists("/events.bin")||FFat.exists("/migration.done"))return true;
|
|
File old=FFat.open("/events.bin","r");if(!old)return false;
|
|
uint32_t migrated=0,broken=0,lastSeq=0;String lastDay="";
|
|
EventRecord e;
|
|
while(old.available()>=(int)sizeof(e)){
|
|
if(old.read((uint8_t*)&e,sizeof(e))!=sizeof(e)){old.close();return false;}
|
|
if(e.version!=1||e.crc!=crc32((const uint8_t*)&e,28)){broken++;continue;}
|
|
String day=dayFor(e.utcMs,e.flags);
|
|
if(day!=lastDay){
|
|
lastDay=day;lastSeq=0;
|
|
File f=FFat.open(journalPath(day).c_str(),"r");
|
|
if(f){if(f.size()%sizeof(e)!=0){f.close();old.close();return false;}
|
|
if(f.size()>=sizeof(e)){f.seek(f.size()-sizeof(e));EventRecord last;
|
|
if(f.read((uint8_t*)&last,sizeof(last))==sizeof(last)&&last.version==1&&last.crc==crc32((const uint8_t*)&last,28))lastSeq=last.seq;
|
|
}f.close();}
|
|
}
|
|
if(e.seq<=lastSeq)continue;
|
|
if(!appendRaw(journalPath(day),e)){old.close();return false;}
|
|
lastSeq=e.seq;migrated++;
|
|
}
|
|
// A corrupt legacy trailing fragment must be retained, not silently marked migrated.
|
|
if(old.size()%sizeof(e)!=0){old.close();return false;}
|
|
old.close();
|
|
File mark=FFat.open("/migration.done","w");if(!mark)return false;
|
|
mark.printf("migrated=%lu invalid=%lu\n",(unsigned long)migrated,(unsigned long)broken);
|
|
mark.close();
|
|
Serial.printf("Legacy migration: %lu records, %lu invalid CRC/version records\n",(unsigned long)migrated,(unsigned long)broken);
|
|
return true;
|
|
}
|
|
static void initEvents(){
|
|
gFileReady=FFat.begin(false);
|
|
if(!gFileReady){gFileMountFailed=true;Serial.println("FFat mount failed; waiting for user format confirmation");return;}
|
|
if(!FFat.exists("/logs")&&!FFat.mkdir("/logs")){gFileReady=false;Serial.println("Cannot create /logs");return;}
|
|
if(!migrateLegacy())Serial.println("WARNING: legacy migration incomplete, /events.bin retained; retry next boot");
|
|
File dir=FFat.open("/logs");
|
|
if(dir){File f=dir.openNextFile();while(f){if(!f.isDirectory())scanSequenceFile(f);f.close();f=dir.openNextFile();}dir.close();}
|
|
// On a migration error old seq must still remain higher than any new seq.
|
|
File old=FFat.open("/events.bin","r");if(old){scanSequenceFile(old);old.close();}
|
|
}
|
|
// QMI8658: I2C 0x6A/0x6B; accelerometer +/-2g, 125Hz ODR (register defaults tested by WHO_AM_I).
|
|
static uint8_t gImuAddr=0;
|
|
static bool imuRead(uint8_t reg,uint8_t *data,uint8_t count){
|
|
Wire.beginTransmission(gImuAddr);Wire.write(reg);
|
|
if(Wire.endTransmission(false)!=0||Wire.requestFrom(gImuAddr,count)!=count)return false;
|
|
for(int i=0;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);gTimezoneMinutes=gPrefs.getShort("timezone",60);gWifiEnabled=false; }
|
|
static void saveSettings() { gPrefs.putUChar("limit",gLimit); gPrefs.putUChar("tick",gTick); gPrefs.putUChar("alert",gAlert); gPrefs.putUChar("screen",gScreenTimeout);gPrefs.putBool("rotation",gRotation);gPrefs.putShort("timezone",gTimezoneMinutes); }
|
|
static void initPower() { gPowerReady=gPower.begin(Wire,AXP2101_SLAVE_ADDRESS,PIN_I2C_SDA,PIN_I2C_SCL); if(!gPowerReady)return; gPower.disableIRQ(XPOWERS_AXP2101_ALL_IRQ); gPower.setChargeTargetVoltage(3); gPower.setPowerKeyPressOffTime(XPOWERS_POWEROFF_10S);
|
|
// AXP2101 IRQ hold threshold: 0=1s, 1=1.5s, 2=2s, 3=2.5s (reg 0x27, bits 5:4).
|
|
Wire.beginTransmission(AXP2101_SLAVE_ADDRESS); Wire.write(0x27);
|
|
if(Wire.endTransmission(false)==0 && Wire.requestFrom((uint8_t)AXP2101_SLAVE_ADDRESS,(uint8_t)1)==1){
|
|
uint8_t reg=Wire.read(); Wire.beginTransmission(AXP2101_SLAVE_ADDRESS);
|
|
Wire.write(0x27);Wire.write((uint8_t)((reg & ~0x30u)|0x10u));Wire.endTransmission();
|
|
}
|
|
gPower.clearIrqStatus(); gPower.enableIRQ(XPOWERS_AXP2101_PKEY_SHORT_IRQ | XPOWERS_AXP2101_PKEY_LONG_IRQ); gPower.enableBattDetection(); gPower.enableBattVoltageMeasure(); gPower.enableVbusVoltageMeasure(); }
|
|
static int battery() { if(!gPowerReady || !gPower.isBatteryConnect())return -1; int percent=constrain(gPower.getBatteryPercent(),0,100); uint16_t mv=gPower.getBattVoltage(); if(percent==0 && mv>=3300) return constrain((int)((mv-3300UL)*100UL/900UL),1,100); return percent; }
|
|
static void initAudio() { pinMode(PIN_PA,OUTPUT); digitalWrite(PIN_PA,HIGH); gI2s.setPins(PIN_I2S_BCLK,PIN_I2S_LRCK,PIN_I2S_DOUT,PIN_I2S_DIN,PIN_I2S_MCLK); if(!gI2s.begin(I2S_MODE_STD,16000,I2S_DATA_BIT_WIDTH_16BIT,I2S_SLOT_MODE_STEREO,I2S_STD_SLOT_BOTH))return; es8311_handle_t h=es8311_create(0,ES8311_ADDRRES_0); if(!h)return; es8311_clock_config_t c={false,false,true,4096000,16000}; gAudioReady=es8311_init(h,&c,ES8311_RESOLUTION_16,ES8311_RESOLUTION_16)==ESP_OK; if(gAudioReady){es8311_voice_volume_set(h,100,nullptr);es8311_voice_mute(h,false);} }
|
|
static void beep(uint16_t hz,uint16_t count,int16_t amp) { if(!gAudioReady||amp<=0)return; static int16_t buf[1600*2]; count=min<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 lv_obj_t *button(lv_obj_t *,const char *,int,int,int,int,uint32_t,lv_event_cb_t,void * = nullptr);
|
|
static void togglePause(){
|
|
if(gPaused){gPaused=false;gBreath=BreathState::Waiting;gRotationArmed=false;gOrientation=-1;gScreenEdgeOrientation=-1;gScreenEdgeCandidate=-1;appendEvent(5);}
|
|
else {gPaused=true;gBreath=BreathState::Waiting;gCycleStarted=0;gPhaseStarted=0;gRotationArmed=false;gOrientation=-1;gScreenEdgeOrientation=-1;gScreenEdgeCandidate=-1;appendEvent(4);}
|
|
}
|
|
static void pauseClicked(lv_event_t *){togglePause();}
|
|
static void topBar(const char *title) {
|
|
// The main screen shows the clock; Wi-Fi is intentionally not shown because it is off by default.
|
|
if(gScreen==Screen::Monitor){
|
|
gRotationMark=label(gRoot,"",&lv_font_montserrat_16,0x38B26D);lv_obj_set_pos(gRotationMark,14,51);
|
|
gClockText=label(gRoot,"--:--",&lv_font_montserrat_16,0xFFFFFF);lv_obj_set_pos(gClockText,234,51);
|
|
}else if(gScreen==Screen::Settings){
|
|
gTopPhase=label(gRoot,"WAITING",&lv_font_montserrat_20,0x4FB3FF);lv_obj_set_pos(gTopPhase,24,48);
|
|
gTopPhaseTime=label(gRoot,"",&lv_font_montserrat_16,0xFFFFFF);lv_obj_set_pos(gTopPhaseTime,142,52);
|
|
gPauseButton=button(gRoot,gPaused?"RESUME":"PAUSE",220,44,92,31,0x214D69,pauseClicked);
|
|
}
|
|
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,390,51);
|
|
if(gPowerReady){static const lv_point_t bolt[]={{6,0},{1,9},{5,9},{2,18},{10,7},{6,7}};gBolt=lv_line_create(gRoot);lv_line_set_points(gBolt,bolt,6);lv_obj_set_pos(gBolt,337,46);lv_obj_set_style_line_width(gBolt,2,0);lv_obj_set_style_line_color(gBolt,color(0xFFD34D),0);lv_obj_set_style_line_rounded(gBolt,true,0);}
|
|
lv_obj_t *b=lv_obj_create(gRoot);lv_obj_set_pos(b,349,53);lv_obj_set_size(b,32,16);lv_obj_set_style_bg_opa(b,LV_OPA_TRANSP,0);lv_obj_set_style_border_color(b,color(0xC9D3DE),0);lv_obj_set_style_border_width(b,2,0);lv_obj_set_style_radius(b,4,0);lv_obj_clear_flag(b,LV_OBJ_FLAG_SCROLLABLE);
|
|
lv_obj_t *cap=lv_obj_create(gRoot);lv_obj_set_pos(cap,381,57);lv_obj_set_size(cap,4,8);lv_obj_set_style_bg_color(cap,color(0xC9D3DE),0);lv_obj_set_style_border_width(cap,0,0);lv_obj_set_style_radius(cap,2,0);
|
|
gBatteryFill=lv_obj_create(gRoot);lv_obj_set_pos(gBatteryFill,352,56);lv_obj_set_size(gBatteryFill,2,10);lv_obj_set_style_bg_color(gBatteryFill,color(0x38B26D),0);lv_obj_set_style_border_width(gBatteryFill,0,0);lv_obj_set_style_radius(gBatteryFill,2,0);batteryUi();
|
|
}
|
|
static void clearUi() { lv_obj_clean(lv_scr_act()); gRoot=lv_scr_act(); lv_obj_set_style_bg_color(gRoot,color(0x08111B),0);lv_obj_set_style_bg_opa(gRoot,LV_OPA_COVER,0);lv_obj_set_style_pad_all(gRoot,0,0); gBatteryText=gBatteryFill=gBolt=gWifiText=gWifiList=gPasswordField=gPasswordKeyboard=gOnlineStatus=nullptr;gClockText=gRotationMark=gTopPhase=gTopPhaseTime=gPauseButton=gTimeCurrent=gTimeStatus=gAutoCheck=gTzDropdown=gManualPreview=nullptr; }
|
|
static void legend() {
|
|
lv_obj_t *l=label(gRoot,"EXHALE",&lv_font_montserrat_14,0x4FB3FF);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,"INHALE",&lv_font_montserrat_14,0x38B26D);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 void onlineSettings(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) { 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");
|
|
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,"ONLINE SETTINGS",24,383,220,42,0x214D69,[](lv_event_t *){onlineSettings(nullptr);});
|
|
button(gRoot,"BACK",256,383,200,42,0x214D69,[](lv_event_t *){if(gPaused)togglePause();enterMonitor(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);
|
|
}
|
|
static void onlineSettings(lv_event_t *) {
|
|
gScreen=Screen::Settings;clearUi();legend();topBar("SETTINGS");
|
|
if(gPaused){gPausedBanner=label(gRoot,"PAUSED",&lv_font_montserrat_20,0xFFD34D);
|
|
lv_obj_align(gPausedBanner,LV_ALIGN_TOP_MID,0,32);}
|
|
lv_obj_t *list=lv_obj_create(gRoot);lv_obj_set_pos(list,20,91);lv_obj_set_size(list,440,280);
|
|
card(list,0x10202D);lv_obj_set_style_pad_all(list,10,0);lv_obj_set_flex_flow(list,LV_FLEX_FLOW_COLUMN);
|
|
lv_obj_set_style_pad_row(list,9,0);
|
|
struct Item{const char *name;uint8_t *v;uint8_t max;};
|
|
Item items[]={{"Breath limit",&gLimit,4},{"Cycle tick",&gTick,10},{"Alert volume",&gAlert,10},{"Screen timeout",&gScreenTimeout,3}};
|
|
for(auto &it:items){lv_obj_t *row=lv_obj_create(list);lv_obj_set_size(row,400,67);card(row,0x172C3C);
|
|
lv_obj_t *n=label(row,it.name,&lv_font_montserrat_16,0xFFFFFF);lv_obj_set_pos(n,12,6);
|
|
lv_obj_t *sl=lv_slider_create(row);lv_obj_set_pos(sl,12,36);lv_obj_set_size(sl,376,16);
|
|
lv_slider_set_range(sl,0,it.max);lv_slider_set_value(sl,*it.v,LV_ANIM_OFF);
|
|
lv_obj_add_event_cb(sl,settingChanged,LV_EVENT_VALUE_CHANGED,it.v);
|
|
if(it.v==&gLimit)lv_obj_add_event_cb(sl,settingReleased,LV_EVENT_RELEASED,it.v);
|
|
}
|
|
button(gRoot,"Wi-Fi",24,383,100,42,0x214D69,[](lv_event_t *){if(!gWifiEnabled)wifiEnable(true);wifiScreen(nullptr);});
|
|
button(gRoot,"TIME",132,383,100,42,0x214D69,[](lv_event_t *){timeScreen(nullptr);});
|
|
lv_obj_t *rot=lv_checkbox_create(gRoot);lv_checkbox_set_text(rot,"ROTATION CONTROL");lv_obj_set_pos(rot,32,437);
|
|
if(gRotation)lv_obj_add_state(rot,LV_STATE_CHECKED);
|
|
lv_obj_add_event_cb(rot,[](lv_event_t *e){gRotation=lv_obj_has_state(lv_event_get_target(e),LV_STATE_CHECKED);gRotationArmed=false;gOrientation=-1;gScreenEdgeOrientation=-1;gScreenEdgeCandidate=-1;saveSettings();appendEvent(10,UINT64_MAX,0,0,0,0,gRotation);},LV_EVENT_VALUE_CHANGED,nullptr);
|
|
button(gRoot,"ONLINE",240,383,100,42,0x214D69,[](lv_event_t *){onlineScreen(nullptr);});
|
|
button(gRoot,"ACCOUNT",348,383,108,42,0x214D69,[](lv_event_t *){accountScreen(nullptr);});
|
|
button(gRoot,"FIRMWARE",24,431,120,40,0x214D69,[](lv_event_t *){firmwareScreen(nullptr);});
|
|
button(gRoot,"BACK",320,431,136,40,0x214D69,[](lv_event_t *){if(gPaused)togglePause();enterMonitor(nullptr);});
|
|
}
|
|
// PMU power key can blank the AMOLED independently of our timeout flag.
|
|
// Explicitly wake the panel for any accepted KEY1 action.
|
|
static void wakeDisplayFromKey1() {
|
|
gLastActivity=millis();
|
|
gKey1WakeUntil=gLastActivity+1500;
|
|
gScreenOn=true;
|
|
gfx->setBrightness(220);
|
|
}
|
|
static void keyShort(){
|
|
wakeDisplayFromKey1();
|
|
if(gScreen==Screen::WifiPassword||gScreen==Screen::Wifi||gScreen==Screen::Time||gScreen==Screen::ManualTime||gScreen==Screen::Online||gScreen==Screen::Account||gScreen==Screen::Firmware||gScreen==Screen::FirmwareConfirm){
|
|
if(!gWorkerActive && (gScreen==Screen::Wifi ||
|
|
(gScreen==Screen::WifiPassword && gInputTarget==InputTarget::WifiPass)))networkFinish("Wi-Fi off");
|
|
settings(nullptr);
|
|
}
|
|
else if(gScreen==Screen::Settings){if(gPaused)togglePause();enterMonitor(nullptr);}
|
|
else settings(nullptr);
|
|
}
|
|
static void keyLong(){
|
|
wakeDisplayFromKey1();
|
|
if(gWifiEnabled&&!gWorkerActive)networkFinish("Wi-Fi off");
|
|
if(!gPaused)togglePause();
|
|
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(){
|
|
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);}
|
|
const char *state=gBreath==BreathState::Waiting?"WAITING":gBreath==BreathState::Inhale?"INHALE":"EXHALE";
|
|
if(gTopPhase){lv_label_set_text(gTopPhase,state);lv_obj_set_style_text_color(gTopPhase,color(gBreath==BreathState::Inhale?0x38B26D:0x4FB3FF),0);}
|
|
if(gTopPhaseTime){if(gBreath==BreathState::Waiting)lv_label_set_text(gTopPhaseTime,"");else{fmt(t,sizeof(t),now-gPhaseStarted);lv_label_set_text(gTopPhaseTime,t);}}
|
|
if(gPauseButton){lv_obj_t *txt=lv_obj_get_child(gPauseButton,0);if(txt)lv_label_set_text(txt,gPaused?"RESUME":"PAUSE");}
|
|
if(gScreen!=Screen::Monitor)return;
|
|
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)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=false;
|
|
WiFi.mode(WIFI_OFF);WiFi.setAutoReconnect(false);WiFi.persistent(false);
|
|
}
|
|
static void wifiEnable(bool enabled){
|
|
gWifiEnabled=enabled;gWifiScanActive=false;gWifiConnecting=false;gWifiManual=false;
|
|
if(!enabled){WiFi.scanDelete();WiFi.disconnect(true,false);WiFi.mode(WIFI_OFF);}
|
|
else{WiFi.mode(WIFI_STA);WiFi.setAutoReconnect(false);gAttemptMask=0;gWifiNextScan=millis()+100;}
|
|
}
|
|
static void networkFinish(const String &message){
|
|
NetOperation op=gNetOperation;
|
|
gNetOperation=NetOperation::None;gNtpPending=false;
|
|
wifiEnable(false);gWifiNotice=message;
|
|
if(op==NetOperation::Time){timeScreen(nullptr);}
|
|
else if(op==NetOperation::Upload||op==NetOperation::Pair||op==NetOperation::ChangeAccount){if(op==NetOperation::ChangeAccount)accountScreen(nullptr);else onlineScreen(nullptr);}
|
|
else if(gScreen==Screen::Wifi){wifiScreen(nullptr);}
|
|
else if(op==NetOperation::Firmware){firmwareScreen(nullptr);}
|
|
}
|
|
static void networkStart(NetOperation op){
|
|
if(gWorkerActive||gNetOperation!=NetOperation::None)return;
|
|
gNetOperation=op;gOperationReturn=gScreen;gNetStarted=millis();gAttemptMask=0;gWifiNotice="Finding saved Wi-Fi...";
|
|
wifiEnable(true);gWifiNextScan=millis();
|
|
}
|
|
static int wifiKnown(const String &ssid){for(int i=0;i<8;i++)if(gSavedSsid[i]==ssid)return i;return -1;}
|
|
static void wifiRemember(const String &ssid,const String &pass){
|
|
int i=wifiKnown(ssid);
|
|
if(i<0){for(i=0;i<8 && gSavedSsid[i].length();i++);if(i>=8){
|
|
for(int j=0;j<7;j++){gSavedSsid[j]=gSavedSsid[j+1];gSavedPass[j]=gSavedPass[j+1];}i=7;
|
|
}}
|
|
gSavedSsid[i]=ssid;gSavedPass[i]=pass;
|
|
String k=String("wifi_ssid_")+i,p=String("wifi_pass_")+i;
|
|
gWifiPrefs.putString(k.c_str(),ssid);gWifiPrefs.putString(p.c_str(),pass);
|
|
}
|
|
static void wifiConnect(const String &ssid,const String &password,bool manual){
|
|
if(!gWifiEnabled)return;
|
|
if(ssid.isEmpty())return;
|
|
gWifiManual=manual;gWifiConnecting=true;gWifiStarted=millis();
|
|
gWifiNotice=String("Connecting: ")+ssid;
|
|
WiFi.mode(WIFI_STA);
|
|
WiFi.begin(ssid.c_str(),password.c_str()); // asynchronous: WiFi.status() polled in loop()
|
|
}
|
|
static void wifiScan(bool manual){
|
|
if(!gWifiEnabled)return;
|
|
if(gWifiScanActive||gWifiConnecting)return;
|
|
gWifiManual=manual;gWifiNotice="Scanning...";
|
|
gScannedCount=0;
|
|
int result=WiFi.scanNetworks(true,false); // asynchronous scanning
|
|
gWifiScanActive=(result==WIFI_SCAN_RUNNING || result==-1);
|
|
if(!gWifiScanActive)gWifiNextScan=millis()+15000;
|
|
}
|
|
static void wifiTryAvailable(){
|
|
int best=-1,bestRssi=-9999;
|
|
for(int j=0;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{
|
|
gWifiNotice="Select a Wi-Fi network";
|
|
// Never silently retry in background. Offer SSID selection for current operation.
|
|
if(gScreen!=Screen::Wifi){wifiScreen(nullptr);}
|
|
wifiScan(true);
|
|
}
|
|
}
|
|
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);gPendingPassword="";}
|
|
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();
|
|
else wifiScreen(nullptr);
|
|
}
|
|
return;
|
|
}
|
|
if(gWifiScanActive){
|
|
int result=WiFi.scanComplete();
|
|
if(result==WIFI_SCAN_RUNNING||result==-1)return;
|
|
gWifiScanActive=false;
|
|
if(result>0){
|
|
for(int i=0;i<result&&gScannedCount<20;i++){
|
|
String ssid=WiFi.SSID(i);if(ssid.isEmpty())continue;
|
|
bool repeat=false;for(int j=0;j<gScannedCount;j++)if(gScannedSsid[j]==ssid){repeat=true;break;}
|
|
if(repeat)continue;gScannedSsid[gScannedCount]=ssid;gScannedRssi[gScannedCount]=WiFi.RSSI(i);gScannedCount++;
|
|
}
|
|
}
|
|
WiFi.scanDelete();
|
|
if(gWifiManual)wifiScreen(nullptr);else wifiTryAvailable();
|
|
return;
|
|
}
|
|
if(WiFi.status()==WL_CONNECTED){
|
|
if(gNetOperation==NetOperation::Test){networkFinish("Wi-Fi test OK");return;}
|
|
if(gNetOperation==NetOperation::Time){if(!gNtpPending)requestNtp();return;}
|
|
if(gNetOperation==NetOperation::Firmware){networkTick();return;}
|
|
if(gNetOperation==NetOperation::Upload||gNetOperation==NetOperation::Pair||gNetOperation==NetOperation::ChangeAccount){
|
|
if(!gTimeValid){if(!gNtpPending)requestNtp();return;}
|
|
networkTick();return;
|
|
}
|
|
return;
|
|
}
|
|
if(gNetOperation!=NetOperation::None&&now-gNetStarted>90000){
|
|
networkFinish("Wi-Fi timeout");return;
|
|
}
|
|
if((int32_t)(now-gWifiNextScan)>=0 && gNetOperation!=NetOperation::None){gWifiNextScan=now+60000;wifiScan(false);}
|
|
}
|
|
static void wifiSelect(lv_event_t *e){
|
|
uint32_t i=(uintptr_t)lv_event_get_user_data(e);if(i>=gScannedCount)return;
|
|
gSelectedSsid=gScannedSsid[i];int old=wifiKnown(gSelectedSsid);
|
|
if(gNetOperation==NetOperation::None)gNetOperation=NetOperation::Test;
|
|
if(old>=0){gPendingPassword=gSavedPass[old];wifiConnect(gSelectedSsid,gSavedPass[old],true);wifiScreen(nullptr);}
|
|
else {gInputTarget=InputTarget::WifiPass;gKbValue="";gKbPage=false;gKbSymbols=false;gKbShift=false;gKbShowPassword=false;wifiPasswordScreen();}
|
|
}
|
|
static void wifiStartScan(lv_event_t *){
|
|
if(gWifiConnecting||gWifiScanActive)return;
|
|
if(!gWifiEnabled)wifiEnable(true);
|
|
wifiScan(true);wifiScreen(nullptr);
|
|
}
|
|
static void wifiForget(lv_event_t *){
|
|
for(int i=0;i<8;i++){
|
|
gSavedSsid[i]="";gSavedPass[i]="";
|
|
String a=String("wifi_ssid_")+i,b=String("wifi_pass_")+i;
|
|
gWifiPrefs.remove(a.c_str());gWifiPrefs.remove(b.c_str());
|
|
}
|
|
WiFi.disconnect(false,false);gWifiConnecting=false;gWifiNextScan=millis()+1500;
|
|
gWifiNotice="Saved networks cleared";wifiScreen(nullptr);
|
|
}
|
|
static void wifiScreen(lv_event_t *){
|
|
gScreen=Screen::Wifi;clearUi();legend();topBar("Wi-Fi");
|
|
String connected=WiFi.status()==WL_CONNECTED?String("Connected: ")+WiFi.SSID():
|
|
(gWifiConnecting?gWifiNotice:String("Not connected"));
|
|
lv_obj_t *status=label(gRoot,connected.c_str(),&lv_font_montserrat_16,0xC9D3DE);
|
|
lv_obj_set_pos(status,24,88);lv_obj_set_width(status,432);lv_label_set_long_mode(status,LV_LABEL_LONG_DOT);
|
|
lv_obj_t *note=label(gRoot,"Wi-Fi turns off after each operation",&lv_font_montserrat_14,0x9EB4C2);
|
|
lv_obj_set_pos(note,24,123);
|
|
button(gRoot,"SCAN",24,167,132,43,0x214D69,wifiStartScan);
|
|
button(gRoot,"TEST",164,167,132,43,0x214D69,[](lv_event_t *){networkStart(NetOperation::Test);wifiScreen(nullptr);});
|
|
button(gRoot,"FORGET",304,167,152,43,0x553442,wifiForget);
|
|
gWifiList=lv_obj_create(gRoot);lv_obj_set_pos(gWifiList,24,222);lv_obj_set_size(gWifiList,432,191);card(gWifiList);
|
|
lv_obj_set_style_pad_all(gWifiList,8,0);
|
|
lv_obj_set_flex_flow(gWifiList,LV_FLEX_FLOW_COLUMN);
|
|
lv_obj_set_style_pad_row(gWifiList,7,0);
|
|
lv_obj_add_flag(gWifiList,LV_OBJ_FLAG_SCROLLABLE);
|
|
if(!gScannedCount){label(gWifiList,!gWifiEnabled?"Enable Wi-Fi first":(gWifiScanActive?"Scanning networks...":"Tap SCAN to find networks"),&lv_font_montserrat_16,0xC9D3DE);}
|
|
for(int i=0;i<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 *){if(!gWorkerActive)networkFinish("Wi-Fi off");onlineSettings(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>")){
|
|
if(gInputTarget==InputTarget::AccountLogin){
|
|
String v=gKbValue;v.toLowerCase();
|
|
bool valid=v.length()>=3 && v.length()<=24;
|
|
for(size_t i=0;i<v.length();i++)if(!((v[i]>='a'&&v[i]<='z')||(v[i]>='0'&&v[i]<='9')||v[i]=='_'||v[i]=='-'))valid=false;
|
|
if(!valid){gWifiNotice="Login: 3-24 letters/digits/_/-";accountScreen(nullptr);return;}
|
|
gPendingAccountLogin=v;gInputTarget=InputTarget::AccountPass;gKbValue="";gKbShowPassword=false;wifiPasswordScreen();return;
|
|
}
|
|
if(gInputTarget==InputTarget::AccountPass){gPendingAccountPassword=gKbValue;networkStart(NetOperation::ChangeAccount);accountScreen(nullptr);return;}
|
|
String ssid=gSelectedSsid,pass=gKbValue;gPendingPassword=pass;
|
|
wifiConnect(ssid,pass,true);gWifiNotice="Connecting...";wifiScreen(nullptr);return;
|
|
}
|
|
if(!strcmp(key,"<CANCEL>")){if(gInputTarget==InputTarget::WifiPass)wifiScreen(nullptr);else accountScreen(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()>=(gInputTarget==InputTarget::AccountLogin?24: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(gInputTarget==InputTarget::WifiPass?"Wi-Fi password":(gInputTarget==InputTarget::AccountLogin?"Account login":"Account password"));
|
|
lv_obj_t *name=label(gRoot,gInputTarget==InputTarget::WifiPass?gSelectedSsid.c_str():"breathmonitor.shineup.me",&lv_font_montserrat_20,0xFFFFFF);
|
|
lv_obj_set_pos(name,18,73);lv_obj_set_width(name,444);lv_label_set_long_mode(name,LV_LABEL_LONG_DOT);
|
|
gPasswordField=lv_textarea_create(gRoot);
|
|
lv_obj_set_pos(gPasswordField,18,109);lv_obj_set_size(gPasswordField,444,51);
|
|
lv_textarea_set_one_line(gPasswordField,true);
|
|
lv_textarea_set_password_mode(gPasswordField,gInputTarget!=InputTarget::AccountLogin&&!gKbShowPassword);
|
|
lv_textarea_set_max_length(gPasswordField,63);
|
|
lv_obj_set_style_text_font(gPasswordField,&lv_font_montserrat_20,0);
|
|
kbRefreshField();
|
|
// Same split-page layout as shine_homeserver_main.ino, rescaled for 480x480.
|
|
static const char *alphaA[3][5]={{"q","w","e","r","t"},{"a","s","d","f","g"},{"z","x","c","v","b"}};
|
|
static const char *alphaB[3][5]={{"y","u","i","o","p"},{"h","j","k","l","."},{"n","m","-","_","@"}};
|
|
static const char *symA[3][5]={{"1","2","3","4","5"},{"/",":","_","@","."},{"!","?","#","+","="}};
|
|
static const char *symB[3][5]={{"6","7","8","9","0"},{"$","%","&","*","-"},{"(",")","[","]","~"}};
|
|
const char *(*rows)[5]=gKbSymbols?(gKbPage?symB:symA):(gKbPage?alphaB:alphaA);
|
|
for(int row=0;row<3;row++)for(int col=0;col<5;col++){
|
|
const char *token=rows[row][col];String cap=token;
|
|
if(!gKbSymbols&&gKbShift)cap.toUpperCase();
|
|
kbButton(cap.c_str(),token,18+col*91,169+row*58,84,51,0x2A6F97);
|
|
}
|
|
kbButton(gKbSymbols?"ABC":"123","<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(gInputTarget==InputTarget::WifiPass?"CONNECT":"SAVE","<SAVE>",330,406,132,54,0x2A9D8F,14);
|
|
}
|
|
|
|
static void timeScreen(lv_event_t *){
|
|
gScreen=Screen::Time;clearUi();legend();topBar("TIME SETTINGS");
|
|
gTimeCurrent=label(gRoot,"--.--.---- --:--:--",&lv_font_montserrat_24,0xFFFFFF);
|
|
lv_obj_align(gTimeCurrent,LV_ALIGN_TOP_MID,0,80);
|
|
gTimeStatus=label(gRoot,"Clock not synchronized",&lv_font_montserrat_14,0x9EB4C2);
|
|
lv_obj_align(gTimeStatus,LV_ALIGN_TOP_MID,0,123);
|
|
lv_obj_t *note=label(gRoot,"Wi-Fi is off except during sync",&lv_font_montserrat_16,0x9EB4C2);
|
|
lv_obj_set_pos(note,26,160);
|
|
lv_obj_t *tzTitle=label(gRoot,"Time zone (fixed UTC offset)",&lv_font_montserrat_16,0xC9D3DE);lv_obj_set_pos(tzTitle,26,205);
|
|
// Fixed selection avoids LVGL dropdown invalidation on screen changes.
|
|
gTzDraft=gTimezoneMinutes;
|
|
lv_obj_t *tz=label(gRoot,"",&lv_font_montserrat_20,0xFFFFFF);lv_obj_set_pos(tz,175,246);gTzDropdown=tz;
|
|
auto tzUpdate=[](){char txt[20];int m=abs(gTzDraft);snprintf(txt,sizeof(txt),"UTC%c%02d:%02d",gTzDraft<0?'-':'+',m/60,m%60);if(gTzDropdown)lv_label_set_text(gTzDropdown,txt);};
|
|
tzUpdate();
|
|
button(gRoot,"-",25,235,60,49,0x214D69,[](lv_event_t *){gTzDraft=max(-720,gTzDraft-15);char b[20];int m=abs(gTzDraft);snprintf(b,sizeof(b),"UTC%c%02d:%02d",gTzDraft<0?'-':'+',m/60,m%60);lv_label_set_text(gTzDropdown,b);});
|
|
button(gRoot,"+",95,235,60,49,0x214D69,[](lv_event_t *){gTzDraft=min(840,gTzDraft+15);char b[20];int m=abs(gTzDraft);snprintf(b,sizeof(b),"UTC%c%02d:%02d",gTzDraft<0?'-':'+',m/60,m%60);lv_label_set_text(gTzDropdown,b);});
|
|
button(gRoot,"SET",330,235,122,49,0x214D69,[](lv_event_t *){gTimezoneMinutes=gTzDraft;saveSettings();timeUiTick();});
|
|
button(gRoot,"SYNC NOW",23,316,210,54,0x214D69,[](lv_event_t *){networkStart(NetOperation::Time);timeUiTick();});
|
|
button(gRoot,"SET MANUALLY",245,316,209,54,0x214D69,[](lv_event_t *){
|
|
time_t e=time(nullptr);if(!gTimeValid||e<1700000000)e=1760000000;
|
|
e+=(int32_t)gTimezoneMinutes*60;tm t={};gmtime_r(&e,&t);
|
|
gManualParts[0]=t.tm_year+1900;gManualParts[1]=t.tm_mon+1;gManualParts[2]=t.tm_mday;gManualParts[3]=t.tm_hour;gManualParts[4]=t.tm_min;
|
|
gManualField=0;gManualDigits="";manualTimeScreen();
|
|
});
|
|
button(gRoot,"BACK",140,399,200,52,0x214D69,[](lv_event_t *){onlineSettings(nullptr);});
|
|
}
|
|
static bool manualValid(){
|
|
int y=gManualParts[0],m=gManualParts[1],d=gManualParts[2],h=gManualParts[3],n=gManualParts[4];
|
|
if(y<2024||y>2099||m<1||m>12||h<0||h>23||n<0||n>59)return false;
|
|
int nd[]={31,28,31,30,31,30,31,31,30,31,30,31};
|
|
if((y%4==0&&y%100!=0)||y%400==0)nd[1]=29;
|
|
return d>=1&&d<=nd[m-1];
|
|
}
|
|
static int64_t utcFromParts(int y,int m,int d,int h,int minute){
|
|
y-=m<=2;int era=(y>=0?y:y-399)/400;unsigned yoe=y-era*400;
|
|
unsigned mp=m+(m>2?-3:9);unsigned doy=(153*mp+2)/5+d-1;
|
|
unsigned doe=yoe*365+yoe/4-yoe/100+doy;
|
|
return ((int64_t)era*146097+doe-719468)*86400+h*3600+minute*60;
|
|
}
|
|
static void manualRefresh(){
|
|
if(!gManualPreview)return;char b[96];
|
|
static const char *fieldNames[]={"YEAR","MONTH","DAY","HOUR","MINUTE"};
|
|
snprintf(b,sizeof(b),"%04d.%02d.%02d %02d:%02d:00\nEditing: %s %s",gManualParts[0],gManualParts[1],gManualParts[2],gManualParts[3],gManualParts[4],
|
|
fieldNames[gManualField],gManualDigits.c_str());
|
|
lv_label_set_text(gManualPreview,b);
|
|
}
|
|
static void manualKey(lv_event_t *e){
|
|
const char *key=(const char*)lv_event_get_user_data(e);if(!key)return;
|
|
if(strcmp(key,"CANCEL")==0){timeScreen(nullptr);return;}
|
|
if(strcmp(key,"BACK")==0){if(!gManualDigits.isEmpty())gManualDigits.remove(gManualDigits.length()-1);manualRefresh();return;}
|
|
if(strcmp(key,"OK")==0){
|
|
if(!gManualDigits.isEmpty())gManualParts[gManualField]=gManualDigits.toInt();
|
|
gManualDigits="";
|
|
if(gManualField<4){gManualField++;manualRefresh();return;}
|
|
if(!manualValid()){lv_label_set_text(gManualPreview,"Invalid date or time!\nEdit fields again.");gManualField=0;return;}
|
|
time_t utc=(time_t)(utcFromParts(gManualParts[0],gManualParts[1],gManualParts[2],gManualParts[3],gManualParts[4])-(int64_t)gTimezoneMinutes*60);
|
|
timeval tv={};tv.tv_sec=utc;tv.tv_usec=0;settimeofday(&tv,nullptr);rtcWrite(utc);gTimeValid=true;gNtpPending=false;
|
|
appendEvent(9);timeScreen(nullptr);return;
|
|
}
|
|
if(gManualDigits.length()<4){gManualDigits+=key;manualRefresh();}
|
|
}
|
|
static void manualTimeScreen(){
|
|
gScreen=Screen::ManualTime;clearUi();legend();topBar("SET DATE AND TIME");
|
|
gManualPreview=label(gRoot,"",&lv_font_montserrat_20,0xFFFFFF);lv_obj_set_pos(gManualPreview,44,86);manualRefresh();
|
|
const char *keys[]={"1","2","3","4","5","6","7","8","9","BACK","0","OK"};
|
|
for(int i=0;i<12;i++){
|
|
int col=i%3,row=i/3;
|
|
button(gRoot,keys[i],30+col*147,173+row*61,126,53,0x214D69,manualKey,(void*)keys[i]);
|
|
}
|
|
button(gRoot,"CANCEL",133,424,214,45,0x553442,manualKey,(void*)"CANCEL");
|
|
}
|
|
static void timeUiTick(){
|
|
if(gScreen!=Screen::Time||!gTimeCurrent)return;
|
|
time_t now=time(nullptr);char buf[48];
|
|
if(gTimeValid&&now>1700000000){now+=(int32_t)gTimezoneMinutes*60;tm t={};gmtime_r(&now,&t);snprintf(buf,sizeof(buf),"%02d.%02d.%04d %02d:%02d:%02d",t.tm_mday,t.tm_mon+1,t.tm_year+1900,t.tm_hour,t.tm_min,t.tm_sec);}
|
|
else snprintf(buf,sizeof(buf),"--.--.---- --:--:--");
|
|
lv_label_set_text(gTimeCurrent,buf);
|
|
String st=gNetOperation==NetOperation::Time?(gNtpPending?"Synchronizing via NTP...":gWifiNotice):(gTimeValid?"Clock available (RTC / NTP)":"Clock not synchronized");
|
|
if(gNetOperation==NetOperation::None&&gWifiNotice=="Time synchronized")st=gWifiNotice;
|
|
lv_label_set_text(gTimeStatus,st.c_str());
|
|
}
|
|
static void onlineScreen(lv_event_t *){
|
|
gScreen=Screen::Online;clearUi();legend();topBar("ONLINE SYNC");
|
|
String account="Account: "+(gAccountLogin.length()?gAccountLogin:String("not set"));
|
|
lv_obj_t *a=label(gRoot,account.c_str(),&lv_font_montserrat_20,0xFFFFFF);lv_obj_set_pos(a,26,105);
|
|
lv_obj_t *url=label(gRoot,"breathmonitor.shineup.me",&lv_font_montserrat_16,0x9EB4C2);lv_obj_set_pos(url,26,154);
|
|
gOnlineStatus=label(gRoot,"Ready",&lv_font_montserrat_16,0xFFD34D);lv_obj_set_pos(gOnlineStatus,26,210);
|
|
lv_obj_set_width(gOnlineStatus,430);lv_label_set_long_mode(gOnlineStatus,LV_LABEL_LONG_WRAP);
|
|
button(gRoot,"UPLOAD",24,300,208,55,0x2A9D8F,[](lv_event_t *){
|
|
if(gDeviceToken.isEmpty()&&(gAccountLogin.isEmpty()||gAccountPassword.isEmpty())){gWifiNotice="Set login + password in ACCOUNT";return;}
|
|
networkStart(NetOperation::Upload);
|
|
});
|
|
button(gRoot,"SETTINGS",248,300,208,55,0x214D69,[](lv_event_t *){onlineSettings(nullptr);});
|
|
button(gRoot,"BACK",248,377,208,50,0x214D69,[](lv_event_t *){settings(nullptr);});
|
|
}
|
|
static void accountScreen(lv_event_t *){
|
|
gScreen=Screen::Account;clearUi();legend();topBar("ACCOUNT");
|
|
String title="Login: "+(gAccountLogin.length()?gAccountLogin:String("not set"));
|
|
lv_obj_t *a=label(gRoot,title.c_str(),&lv_font_montserrat_20,0xFFFFFF);lv_obj_set_pos(a,26,105);
|
|
lv_obj_t *paired=label(gRoot,gDeviceToken.length()?"Paired with server":"Not paired",&lv_font_montserrat_20,gDeviceToken.length()?0x38B26D:0xFFD34D);lv_obj_set_pos(paired,26,156);
|
|
lv_obj_t *explain=label(gRoot,"Password is kept in RAM only until pairing.\nToken is saved for subsequent uploads.",&lv_font_montserrat_14,0x9EB4C2);
|
|
lv_obj_set_pos(explain,26,205);lv_obj_set_width(explain,420);
|
|
button(gRoot,"CHANGE ACCOUNT",24,292,432,58,0xA56A36,[](lv_event_t *){accountConfirmScreen(nullptr);});
|
|
button(gRoot,"BACK",140,375,200,52,0x214D69,[](lv_event_t *){onlineSettings(nullptr);});
|
|
}
|
|
static void accountConfirmScreen(lv_event_t *){
|
|
gScreen=Screen::Account;clearUi();legend();topBar("CHANGE ACCOUNT");
|
|
lv_obj_t *warning=label(gRoot,"All local results and saved account data\nwill be deleted after successful login\nwith the new account.",&lv_font_montserrat_18,0xFFD34D);lv_obj_set_pos(warning,24,112);
|
|
button(gRoot,"CANCEL",24,320,200,55,0x553442,[](lv_event_t *){accountScreen(nullptr);});
|
|
button(gRoot,"CONTINUE",256,320,200,55,0x2A9D8F,[](lv_event_t *){gChangingAccount=true;gPendingAccountLogin="";gPendingAccountPassword="";gInputTarget=InputTarget::AccountLogin;gKbValue="";gKbShowPassword=false;gKbSymbols=gKbPage=gKbShift=false;wifiPasswordScreen();});
|
|
}
|
|
static bool doFirmwareUpdate(WiFiClientSecure &secure){
|
|
String url=String(SERVER_URL)+"/firmware/breathmonitor-v"+gFirmwareTarget+".bin";HTTPClient http;
|
|
workerSet(String("Downloading firmware ")+gFirmwareTarget+"...");if(!http.begin(secure,url)){workerSet("OTA HTTPS initialization failed");return false;}
|
|
http.setTimeout(30000);int status=http.GET();int total=http.getSize();if(status!=200||total<=0){http.end();workerSet(String("OTA download failed: HTTP ")+status);return false;}
|
|
if(!Update.begin((size_t)total)){http.end();workerSet("OTA storage unavailable");return false;}
|
|
WiFiClient *stream=http.getStreamPtr();uint8_t buffer[1024];size_t written=0;while(http.connected()&&(total<0||written<(size_t)total)){size_t available=stream->available();if(!available){delay(1);continue;}size_t n=stream->readBytes(buffer,min(available,sizeof(buffer)));if(!Update.write(buffer,n)){Update.abort();http.end();workerSet("OTA write failed");return false;}written+=n;}
|
|
http.end();if(!Update.end()||!Update.isFinished()){workerSet("OTA finalize failed");return false;}workerSet("Firmware updated; restarting");delay(500);ESP.restart();return true;
|
|
}
|
|
static void firmwareConfirmScreen(lv_event_t *){
|
|
gScreen=Screen::FirmwareConfirm;clearUi();legend();topBar("FIRMWARE UPDATE");String text="Update device to firmware "+gFirmwareTarget+"?";lv_obj_t *t=label(gRoot,text.c_str(),&lv_font_montserrat_20,0xFFFFFF);lv_obj_set_pos(t,24,130);
|
|
button(gRoot,"CANCEL",24,300,200,55,0x553442,[](lv_event_t *){firmwareScreen(nullptr);});
|
|
button(gRoot,"UPDATE",256,300,200,55,0x2A9D8F,[](lv_event_t *){networkStart(NetOperation::Firmware);firmwareScreen(nullptr);});
|
|
}
|
|
static void firmwareScreen(lv_event_t *){
|
|
gScreen=Screen::Firmware;clearUi();legend();topBar("FIRMWARE");char line[96];snprintf(line,sizeof(line),"Installed: %s\nStable: 1.1\nTest: 1.2",FIRMWARE_VERSION);lv_obj_t *t=label(gRoot,line,&lv_font_montserrat_20,0xFFFFFF);lv_obj_set_pos(t,28,100);
|
|
if(gNetOperation==NetOperation::Firmware||gWorkerActive){lv_obj_t *s=label(gRoot,workerMessage().c_str(),&lv_font_montserrat_16,0xFFD34D);lv_obj_set_pos(s,28,220);}
|
|
button(gRoot,"UPDATE STABLE",24,285,208,55,0x2A9D8F,[](lv_event_t *){gFirmwareTarget="1.1";firmwareConfirmScreen(nullptr);});
|
|
button(gRoot,"UPDATE TEST",248,285,208,55,0xA56A36,[](lv_event_t *){gFirmwareTarget="1.2";firmwareConfirmScreen(nullptr);});
|
|
button(gRoot,"BACK",140,375,200,52,0x214D69,[](lv_event_t *){onlineSettings(nullptr);});
|
|
}
|
|
static void networkUiTick(){
|
|
if(gScreen!=Screen::Online||!gOnlineStatus)return;
|
|
String msg=gWorkerActive?workerMessage():gWifiNotice;
|
|
if(msg.length()==0)msg=gDeviceToken.length()?"Paired. Ready to upload":"Set account login/password";
|
|
lv_label_set_text(gOnlineStatus,msg.c_str());
|
|
}
|
|
static int64_t lastSyncedBytes(const String &day){
|
|
File f=FFat.open("/sync.state","r");if(!f)return -1;
|
|
int64_t result=-1;while(f.available()){
|
|
String line=f.readStringUntil('\n');int x=line.indexOf(' ');
|
|
if(x>0 && line.substring(0,x)==day)result=strtoll(line.c_str()+x+1,nullptr,10);
|
|
}
|
|
f.close();return result;
|
|
}
|
|
static bool markSynced(const String &day,size_t sz){
|
|
File f=FFat.open("/sync.state","a");if(!f)return false;
|
|
size_t n=f.printf("%s %u\n",day.c_str(),(unsigned)sz);f.flush();f.close();return n>0;
|
|
}
|
|
static bool requestToken(WiFiClientSecure &secure,const String &login,const String &password,String &token){
|
|
if(login.isEmpty()||password.isEmpty()){workerSet("Enter login and password");return false;}
|
|
workerSet("Authorizing device...");
|
|
HTTPClient http;String url=String(SERVER_URL)+"/api/device/login";
|
|
if(!http.begin(secure,url)){workerSet("HTTPS initialization failed");return false;}
|
|
http.setTimeout(15000);http.addHeader("Content-Type","text/plain; charset=utf-8");
|
|
String body=login+"\n"+password+"\n"+gDeviceId;
|
|
int status=http.POST(body);String response=http.getString();http.end();
|
|
if(status!=200||response.length()!=64){workerSet(String("Login failed: HTTP ")+status);return false;}
|
|
for(size_t i=0;i<response.length();i++)if(!isxdigit((unsigned char)response[i])){workerSet("Invalid token from server");return false;}
|
|
token=response;return true;
|
|
}
|
|
static bool doPair(WiFiClientSecure &secure){
|
|
String token;String login=gPendingAccountLogin.length()?gPendingAccountLogin:gAccountLogin;String password=gPendingAccountPassword.length()?gPendingAccountPassword:gAccountPassword;
|
|
if(!requestToken(secure,login,password,token))return false;
|
|
gAccountLogin=login;gDeviceToken=token;gAccountPassword="";gAccountPrefs.putString("login",gAccountLogin);gAccountPrefs.putString("token",gDeviceToken);gPendingAccountLogin="";gPendingAccountPassword="";gChangingAccount=false;workerSet("Device paired");return true;
|
|
}
|
|
static bool clearLocalAccountData(){
|
|
if(!gFileReady)return false;
|
|
FFat.remove("/events.bin");FFat.remove("/migration.done");FFat.remove("/sync.state");
|
|
File dir=FFat.open("/logs");if(dir){File f=dir.openNextFile();while(f){String path=f.name();f.close();if(!FFat.remove(path))return false;f=dir.openNextFile();}dir.close();}
|
|
if(!FFat.exists("/logs")&&!FFat.mkdir("/logs"))return false;gEventSeq=0;gCycleCount=0;gCompletedMs=0;return true;
|
|
}
|
|
static bool changeAccount(WiFiClientSecure &secure){
|
|
String token;if(!requestToken(secure,gPendingAccountLogin,gPendingAccountPassword,token))return false;
|
|
if(!clearLocalAccountData()){workerSet("New account authorized, local reset failed");return false;}
|
|
gAccountLogin=gPendingAccountLogin;gDeviceToken=token;gAccountPassword="";gAccountPrefs.putString("login",gAccountLogin);gAccountPrefs.putString("token",gDeviceToken);gPendingAccountLogin="";gPendingAccountPassword="";gChangingAccount=false;workerSet("Account changed; local data cleared");return true;
|
|
}
|
|
static bool uploadFiles(WiFiClientSecure &secure){
|
|
if(gDeviceToken.isEmpty()&&!doPair(secure))return false;
|
|
if(!gFileReady){workerSet("FFat unavailable");return false;}
|
|
File dir=FFat.open("/logs");if(!dir){workerSet("No /logs directory");return false;}
|
|
String today=dayFor(unixMs(),gTimeValid?1:0);File f=dir.openNextFile();unsigned sent=0,skipped=0;bool ok=true;
|
|
while(f){
|
|
String fileName=String(f.name());int slash=fileName.lastIndexOf('/');if(slash>=0)fileName=fileName.substring(slash+1);
|
|
if(!f.isDirectory()&&fileName.endsWith(".bin")){
|
|
String day=fileName.substring(0,fileName.length()-4);
|
|
if((day.length()==8||day=="undated")&&day==today){
|
|
size_t snapshot=f.size();
|
|
if(snapshot%sizeof(EventRecord)!=0){workerSet(String("Incomplete journal: ")+day);ok=false;}
|
|
else if(snapshot==0 || lastSyncedBytes(day)==(int64_t)snapshot){skipped++;}
|
|
else{
|
|
workerSet(String("Uploading ")+day+" ...");
|
|
// Keep a second read-only handle bounded to the file length at start.
|
|
HTTPClient http;String url=String(SERVER_URL)+"/api/device/upload?date="+day;
|
|
if(!http.begin(secure,url)){workerSet("HTTPS initialization failed");ok=false;}
|
|
else{
|
|
http.setTimeout(30000);
|
|
http.addHeader("Content-Type","application/octet-stream");
|
|
http.addHeader("Authorization",String("Bearer ")+gDeviceToken);
|
|
http.addHeader("X-Device-ID",gDeviceId);
|
|
f.seek(0);
|
|
int status=http.sendRequest("PUT",&f,snapshot);
|
|
http.end();
|
|
if(status!=200){workerSet(String("Upload ")+day+" HTTP "+status);ok=false;}
|
|
else if(!markSynced(day,snapshot)){workerSet("Upload OK but cannot save sync state");ok=false;}
|
|
else sent++;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
f.close();if(!ok)break;f=dir.openNextFile();
|
|
}
|
|
dir.close();if(ok)workerSet(String("Done: ")+sent+" uploaded, "+skipped+" unchanged");
|
|
return ok;
|
|
}
|
|
static void networkWorker(void *){
|
|
// HTTPS streaming runs on a separate FreeRTOS task, never on the LVGL/input task.
|
|
// ESP-IDF/WiFiClientSecure uses one TLS stream at a time.
|
|
WiFiClientSecure secure;secure.setCACert(ROOT_CA);secure.setTimeout(30);
|
|
NetOperation op=gNetOperation;
|
|
bool ok=op==NetOperation::Pair?doPair(secure):(op==NetOperation::ChangeAccount?changeAccount(secure):(op==NetOperation::Firmware?doFirmwareUpdate(secure):uploadFiles(secure)));
|
|
workerSet(workerMessage(),true,ok);gWorkerActive=false;
|
|
vTaskDelete(nullptr);
|
|
}
|
|
static void networkTick(){
|
|
if(gWorkerActive||gWorkerDone)return;
|
|
if(gNetOperation!=NetOperation::Upload&&gNetOperation!=NetOperation::Pair&&gNetOperation!=NetOperation::ChangeAccount&&gNetOperation!=NetOperation::Firmware)return;
|
|
gWorkerActive=true;workerSet("Starting secure connection...");
|
|
BaseType_t started=xTaskCreatePinnedToCore(networkWorker,"breath-sync",16384,nullptr,1,nullptr,0);
|
|
if(started!=pdPASS){gWorkerActive=false;networkFinish("Cannot start upload task");}
|
|
}
|
|
static void networkFinishTick(){
|
|
if(!gWorkerDone)return;
|
|
bool ok=gWorkerSuccess;gWorkerDone=false;
|
|
String result=workerMessage();
|
|
networkFinish(result.length()?result:(ok?"Completed":"Upload failed"));
|
|
}
|
|
static void applyRotationScreenPolicy(){
|
|
if(!gRotation || !gImuOk || gPaused || gScreen!=Screen::Monitor)return;
|
|
// Keep on for the top edge; keep off for the other three edges.
|
|
// For flat orientations retain the ordinary configured screen timeout.
|
|
if(gScreenEdgeOrientation==2){
|
|
if(!gScreenOn){gfx->setBrightness(220);gScreenOn=true;}
|
|
}else if(gScreenEdgeOrientation==3){
|
|
if(gScreenOn){gfx->setBrightness(0);gScreenOn=false;}
|
|
}
|
|
}
|
|
static void pollOrientation(){
|
|
if(!gRotation||!gImuOk||gPaused||gScreen!=Screen::Monitor)return;
|
|
uint32_t now=millis();if(now-gOrientationSample<70)return;gOrientationSample=now;
|
|
uint8_t data[6];if(!imuRead(0x35,data,6))return;
|
|
int16_t x=(int16_t)(data[0]|data[1]<<8),y=(int16_t)(data[2]|data[3]<<8),z=(int16_t)(data[4]|data[5]<<8);
|
|
float horiz=sqrtf((float)x*x+(float)y*y),az=fabsf((float)z);
|
|
if(horiz<100&&az<100)return;
|
|
// 0 = face up/down (EXHALE); 1 = any edge up (INHALE).
|
|
int8_t detected=(az>horiz*1.428f)?0:((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 commands: LOG LIST, LOG INFO, LOG DOWNLOAD YYYYMMDD (or undated), LOG DOWNLOAD LEGACY.
|
|
static String gUsbCommand="";
|
|
static void usbDownload(File f){
|
|
size_t sz=f?f.size():0;Serial.printf("LOG BEGIN %u\n",(unsigned)sz);
|
|
if(f){const char hex[]="0123456789ABCDEF";char line[129];size_t n=0;
|
|
while(f.available()){int x=f.read();if(x<0)break;line[2*n]=hex[((uint8_t)x)>>4];line[2*n+1]=hex[((uint8_t)x)&15];n++;
|
|
if(n==64){line[128]=0;Serial.println(line);n=0;delay(1);}}
|
|
if(n){line[2*n]=0;Serial.println(line);}f.close();}
|
|
Serial.println("LOG END");
|
|
}
|
|
static void usbCommands(){
|
|
while(Serial.available()){
|
|
char ch=(char)Serial.read();if(ch=='\r')continue;
|
|
if(ch!='\n'){if(gUsbCommand.length()<64)gUsbCommand+=ch;continue;}
|
|
gUsbCommand.trim();
|
|
if(!gFileReady){Serial.println("LOG ERROR FS");}
|
|
else if(gUsbCommand=="LOG LIST"||gUsbCommand=="LOG INFO"){
|
|
File d=FFat.open("/logs");File f=d?d.openNextFile():File();size_t bytes=0;unsigned count=0;
|
|
while(f){if(!f.isDirectory()){bytes+=f.size();count++;if(gUsbCommand=="LOG LIST")Serial.printf("LOG FILE %s %u\n",f.name(),(unsigned)f.size());}f.close();f=d.openNextFile();}
|
|
if(d)d.close();Serial.printf("LOG INFO %u %u %u\n",(unsigned)bytes,(unsigned)gEventSeq,count);
|
|
}else if(gUsbCommand.startsWith("LOG DOWNLOAD ")){
|
|
String date=gUsbCommand.substring(13);String path;
|
|
if(date=="LEGACY")path="/events.bin";
|
|
else if(date=="undated"||date.length()==8)path=journalPath(date);
|
|
else{Serial.println("LOG ERROR DATE");gUsbCommand="";continue;}
|
|
File f=FFat.open(path.c_str(),"r");if(!f)Serial.println("LOG ERROR NOT FOUND");else usbDownload(f);
|
|
}else if(gUsbCommand.length()){Serial.println("LOG ERROR COMMAND");}
|
|
gUsbCommand="";
|
|
}
|
|
}
|
|
static void formatPromptScreen(){
|
|
gScreen=Screen::Settings;clearUi();topBar("STORAGE ERROR");
|
|
lv_obj_t *title=label(gRoot,"FFat storage is unavailable",&lv_font_montserrat_20,0xFFB86B);lv_obj_align(title,LV_ALIGN_TOP_MID,0,112);
|
|
lv_obj_t *text=label(gRoot,"The device cannot read its local logs.\nFormat storage to continue?\nFormatting deletes local logs.",&lv_font_montserrat_16,0xFFFFFF);lv_obj_align(text,LV_ALIGN_TOP_MID,0,160);
|
|
button(gRoot,"FORMAT FFat",28,318,196,62,0xA94747,[](lv_event_t *){
|
|
if(!FFat.begin(true)){formatPromptScreen();return;}
|
|
if(!FFat.exists("/logs")&&!FFat.mkdir("/logs")){gFileReady=false;formatPromptScreen();return;}
|
|
gFileReady=true;gFileMountFailed=false;gEventSeq=0;enterMonitor(nullptr);
|
|
},nullptr);
|
|
button(gRoot,"CONTINUE",260,318,196,62,0x214D69,[](lv_event_t *){enterMonitor(nullptr);},nullptr);
|
|
}
|
|
void setup(){Serial.begin(115200);Wire.begin(PIN_I2C_SDA,PIN_I2C_SCL);initPower();pinMode(PIN_INHALE,INPUT_PULLUP);pinMode(PIN_EXHALE,INPUT_PULLUP);initAudio();gfx->begin();gBus->writeC8D8(0x36,0xA0);gfx->setBrightness(220);gTouch.setPins(PIN_TP_INT,-1);gTouch.begin(Wire,0x5A,PIN_I2C_SDA,PIN_I2C_SCL);gTouch.setMaxCoordinates(DISP_W,DISP_H);gTouch.setSwapXY(true);gTouch.setMirrorXY(true,false);loadSettings();initClock();initImu();initEvents();appendEvent(2);wifiLoad();
|
|
gAccountPrefs.begin("breath-account",false);
|
|
gAccountLogin=gAccountPrefs.getString("login","");gDeviceToken=gAccountPrefs.getString("token","");
|
|
uint64_t chip=ESP.getEfuseMac();char ident[20];snprintf(ident,sizeof(ident),"%012llX",(unsigned long long)chip);gDeviceId=ident;
|
|
lv_init();gBuf1=(lv_color_t *)heap_caps_malloc(DISP_W*40*sizeof(lv_color_t),MALLOC_CAP_DMA);gBuf2=(lv_color_t *)heap_caps_malloc(DISP_W*40*sizeof(lv_color_t),MALLOC_CAP_DMA);lv_disp_draw_buf_init(&gDrawBuf,gBuf1,gBuf2,DISP_W*40);static lv_disp_drv_t dd;lv_disp_drv_init(&dd);dd.hor_res=DISP_W;dd.ver_res=DISP_H;dd.flush_cb=flush;dd.rounder_cb=rounder;dd.draw_buf=&gDrawBuf;lv_disp_drv_register(&dd);static lv_indev_drv_t id;lv_indev_drv_init(&id);id.type=LV_INDEV_TYPE_POINTER;id.read_cb=touchRead;lv_indev_drv_register(&id);const esp_timer_create_args_t ta={.callback=&tick,.name="lvgl_tick"};esp_timer_handle_t timer;esp_timer_create(&ta,&timer);esp_timer_start_periodic(timer,LVGL_TICK_MS*1000);gLastActivity=millis();if(gFileMountFailed)formatPromptScreen();else enterMonitor(nullptr);}
|
|
void loop(){uint32_t now=millis();poll(gInhale,true);poll(gExhale,false);pollPowerKey();pollOrientation();usbCommands();wifiTick();ntpTick();networkFinishTick();reminders();if(now-gLastUi>=UI_MS){gLastUi=now;refresh();timeUiTick();networkUiTick();}if(now-gLastBatt>=BATT_MS){gLastBatt=now;batteryUi();}uint32_t timeout=SCREEN_TIMEOUTS[gScreenTimeout];if(gScreenOn&&!(gRotation && gImuOk && gScreenEdgeOrientation==2)&&gScreen!=Screen::Settings&&gScreen!=Screen::Wifi&&gScreen!=Screen::WifiPassword&&gScreen!=Screen::Time&&gScreen!=Screen::ManualTime&&gScreen!=Screen::Online&&gScreen!=Screen::Account&&(int32_t)(now-gKey1WakeUntil)>=0&&timeout&&now-gLastActivity>=timeout){gScreenOn=false;gfx->setBrightness(0);}lv_timer_handler();applyRotationScreenPolicy();if((int32_t)(millis()-gKey1WakeUntil)<0){gScreenOn=true;gfx->setBrightness(220);}delay(5);}
|