feat: multi-board HAL guards, RFRemote subsystem, Player/OTA improvements

Multi-board variant support:
- variants/vesper.hpp: enable HAS_RF=1, define RF_RX_PIN=22
- variants/agnus.hpp: enable HAS_RF=1, RF_RX_PIN=22, correct HAS_RTC=0
- main.cpp, Player, HealthMonitor, OTAManager, ConfigManager: wrap all
  RTC/SD/RF-dependent code in #if HAS_RTC / HAS_SD_CARD / HAS_RF guards
  so Agnus builds cleanly without those peripherals

RFRemote subsystem (new):
- src/RFRemote/: RF receiver driver (GPIO RF_RX_PIN) + command handler
- Registered with HealthMonitor and CommunicationRouter when HAS_RF=1

Player improvements:
- uid -> pid rename throughout (Player, BuiltInMelodies, api-reference)
- loadMelodyInRAM() now returns bool
- playerControlTaskFn task added — defers stop/pause/resume out of
  timer callback (Tmr Svc) to avoid stack overflows
- setDependencies() accepts nullptr FileManager for SD-less boards

OTAManager:
- Consume download_url from server metadata response instead of
  constructing firmware path locally
- HTTP redirect following enabled (setFollowRedirects)
- HAS_RTC guards on TimeKeeper references

platformio.ini:
- Add rc-switch library for RF remote support
- Remove BOARD_TYPE/BOARD_NAME/BOARD_VERSION flags (moved to variant headers)
- MQTT_SECRET placeholders only — no secrets in source

Docs:
- docs/architecture/codebase-refactor-plan.md: new migration strategy doc
- docs/reference/api-reference.md: updated for pid, note_assignments, download_url
- Remove stale docs: ota-telemetry-api.md, platformio-commands.md, firmware-variants.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-17 17:02:01 +02:00
co-authored by Claude Sonnet 4.6
parent 37b65cc15a
commit a4d071d5d5
31 changed files with 2431 additions and 891 deletions
+366 -389
View File
@@ -44,7 +44,7 @@ namespace BuiltInMelodies {
struct MelodyInfo {
const char* name; // Display name
const char* uid; // Unique identifier
const char* pid; // Playback ID
const uint16_t* data; // Pointer to melody data in PROGMEM
uint16_t stepCount; // Number of steps
};
@@ -54,270 +54,14 @@ struct MelodyInfo {
// ═════════════════════════════════════════════════════════════════════════════════
// 1 Bell Test Melody
const uint16_t PROGMEM builtin_1bell_test[] = {
const uint16_t PROGMEM one_bell_test[] = {
0x0001, 0x0000, 0x0001, 0x0000
};
// Doxology Traditional
const uint16_t PROGMEM builtin_doxology_traditional[] = {
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0000, 0x0000,
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0008, 0x0000, 0x0000,
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0008, 0x0000, 0x0000
};
// Generated: 2026-03-16 08:57:17
// Doxology Alternative
const uint16_t PROGMEM builtin_doxology_alternative[] = {
0x0001, 0x0000, 0x0002, 0x0004, 0x0000, 0x0018, 0x0000, 0x0001,
0x0000, 0x0002, 0x0004, 0x0000, 0x0018, 0x0000, 0x0001, 0x0000,
0x0002, 0x0004, 0x0000, 0x0018, 0x0000, 0x0001, 0x0002, 0x0001,
0x0002, 0x0004, 0x0000, 0x0018, 0x0000
};
// Doxology Festive
const uint16_t PROGMEM builtin_doxology_festive[] = {
0x0002, 0x0004, 0x0009, 0x0004, 0x0002, 0x0004, 0x0011, 0x0004,
0x0002, 0x0004, 0x0021, 0x0004, 0x0002, 0x0004, 0x0011, 0x0004
};
// Vesper Traditional
const uint16_t PROGMEM builtin_vesper_traditional[] = {
0x0001, 0x0002, 0x0004, 0x0000, 0x0001, 0x0002, 0x0004, 0x0000,
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0004, 0x0000
};
// Vesper Alternative
const uint16_t PROGMEM builtin_vesper_alternative[] = {
0x0001, 0x0002, 0x0000, 0x0000, 0x0001, 0x0002, 0x0000, 0x0000,
0x0001, 0x0004, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0001, 0x0002, 0x0000, 0x0000, 0x0001, 0x0002, 0x0000, 0x0000,
0x0001, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0001, 0x0002, 0x0000, 0x0000, 0x0001, 0x0002, 0x0000, 0x0000,
0x0001, 0x0002, 0x0000, 0x0000, 0x0001, 0x0002, 0x0000, 0x0000,
0x0001, 0x0002, 0x0000, 0x0000, 0x0001, 0x0004, 0x0000, 0x0000,
0x0001, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000
};
// Catehetical
const uint16_t PROGMEM builtin_catehetical[] = {
0x0001, 0x0002, 0x0004, 0x0008, 0x0010
};
// Orthros Traditional
const uint16_t PROGMEM builtin_orthros_traditional[] = {
0x0001, 0x0000, 0x0002, 0x0000, 0x0004, 0x0008, 0x0000, 0x0010,
0x0000, 0x0020, 0x0000, 0x0040, 0x0080, 0x0000
};
// Orthros Alternative
const uint16_t PROGMEM builtin_orthros_alternative[] = {
0x0001, 0x0000, 0x0002, 0x0001, 0x0000, 0x0002, 0x0000, 0x0001,
0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0004, 0x0000
};
// Mournfull Toll
const uint16_t PROGMEM builtin_mournfull_toll[] = {
0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0002, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0002, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000
};
// Mournfull Toll Alternative
const uint16_t PROGMEM builtin_mournfull_toll_alternative[] = {
0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001,
0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0004,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0002, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0002, 0x0002, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0008, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0008, 0x0008, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000
};
// Mournfull Toll Meg Par
const uint16_t PROGMEM builtin_mournfull_toll_meg_par[] = {
0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0001,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0004, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0002, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0002, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0002, 0x0002, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0008, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000
};
// Sematron
const uint16_t PROGMEM builtin_sematron[] = {
0x0001, 0x0001, 0x0001, 0x0002, 0x0001, 0x0001, 0x0001, 0x0008,
0x0001, 0x0001, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0008
};
// Sematron Alternative
const uint16_t PROGMEM builtin_sematron_alternative[] = {
0x0001, 0x0001, 0x0001, 0x0002, 0x0001, 0x0001, 0x0001, 0x0008,
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0001, 0x0001, 0x0008
};
// Athonite 1 2 Voices
const uint16_t PROGMEM builtin_athonite_1_2_voices[] = {
0x0001, 0x0002, 0x0001, 0x0001, 0x0002, 0x0001, 0x0001, 0x0002,
0x0001, 0x0001, 0x0002, 0x0001, 0x0002
};
// Athonite 3 Voices
const uint16_t PROGMEM builtin_athonite_3_voices[] = {
0x0002, 0x0001, 0x0000, 0x0000, 0x0002, 0x0001, 0x0000, 0x0000,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004
};
// Athonite 3 4 Voices
const uint16_t PROGMEM builtin_athonite_3_4_voices[] = {
0x0002, 0x0001, 0x0000, 0x0000, 0x0002, 0x0001, 0x0000, 0x0000,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0000, 0x0005,
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0002, 0x0005,
0x0002, 0x0001, 0x0008, 0x0005, 0x0002, 0x0001, 0x0000, 0x0005,
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0002, 0x0005,
0x0002, 0x0001, 0x0009, 0x0002, 0x0001, 0x0005, 0x0002, 0x0001,
0x000A, 0x0002, 0x0001, 0x0006, 0x0002, 0x0001, 0x0009, 0x0002,
0x0001, 0x0005, 0x0002, 0x0001, 0x000A, 0x0002, 0x0001, 0x0006,
0x0002, 0x0001, 0x0009
};
// Athonite 4 8 Voices
const uint16_t PROGMEM builtin_athonite_4_8_voices[] = {
0x0002, 0x0001, 0x0000, 0x0000, 0x0002, 0x0001, 0x0000, 0x0000,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0000, 0x0005,
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0002, 0x0005,
0x0002, 0x0001, 0x0008, 0x0005, 0x0002, 0x0001, 0x0000, 0x0005,
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0002, 0x0005,
0x0002, 0x0001, 0x0009, 0x0002, 0x0001, 0x0011, 0x0002, 0x0001,
0x0022, 0x0002, 0x0001, 0x0081, 0x0002, 0x0001, 0x000A, 0x0002,
0x0001, 0x0041, 0x0002, 0x0001, 0x0012, 0x0002, 0x0001, 0x0021,
0x0002, 0x0001, 0x0082, 0x0002, 0x0001, 0x0009, 0x0002, 0x0001,
0x0042, 0x0002, 0x0001, 0x0011, 0x0002, 0x0001, 0x0022, 0x0002,
0x0001, 0x0081, 0x0002, 0x0001, 0x000A, 0x0002, 0x0001, 0x0041,
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0000, 0x0005,
0x0002, 0x0001, 0x0002, 0x0005, 0x0002, 0x0001, 0x0000, 0x0000,
0x0000
};
// Onebyone 2 3 Voices
const uint16_t PROGMEM builtin_onebyone_2_3_voices[] = {
0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000,
0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000,
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002
};
// Onebyone 4 8 Voices
const uint16_t PROGMEM builtin_onebyone_4_8_voices[] = {
0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000,
0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000,
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
0x0002, 0x0004, 0x0008, 0x0004, 0x0002, 0x0011, 0x0002, 0x0004,
0x0008, 0x0004, 0x0002, 0x0021, 0x0002, 0x0004, 0x0008, 0x0004,
0x0002, 0x0041, 0x0002, 0x0004, 0x0008, 0x0004, 0x0002, 0x0081,
0x0002, 0x0004, 0x0008, 0x0004, 0x0002, 0x0041, 0x0002, 0x0004,
0x0008, 0x0004, 0x0002, 0x0021, 0x0002, 0x0004, 0x0008, 0x0004,
0x0002, 0x0041, 0x0002, 0x0004, 0x0008, 0x0004, 0x0002, 0x0081,
0x0002, 0x0004, 0x0008, 0x0004, 0x0002, 0x0041, 0x0002, 0x0004,
0x0008, 0x0004, 0x0002, 0x0021, 0x0002, 0x0004, 0x0008, 0x0004,
0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001,
0x0004, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001,
0x0004, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001,
0x0002, 0x0001, 0x0000
};
// Festive 1Voice
const uint16_t PROGMEM builtin_festive_1voice[] = {
0x0001, 0x0001, 0x0001, 0x0000, 0x0001, 0x0001, 0x0001, 0x0001,
0x0000, 0x0001, 0x0000, 0x0001, 0x0001, 0x0001, 0x0000, 0x0001,
0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0000, 0x0001, 0x0000
};
// Festive 4Voices
const uint16_t PROGMEM builtin_festive_4voices[] = {
0x0001, 0x0002, 0x0004, 0x0009, 0x0002, 0x0001, 0x0004, 0x0009
};
// Festive 5Voices
const uint16_t PROGMEM builtin_festive_5voices[] = {
0x0001, 0x0002, 0x0004, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
0x0008, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0004, 0x0002,
0x0001, 0x0002, 0x0001, 0x0002, 0x0010, 0x0002, 0x0001, 0x0002
};
// Festive 5Voice Alternative
const uint16_t PROGMEM builtin_festive_5voice_alternative[] = {
0x0004, 0x0002, 0x0008, 0x0001, 0x0004, 0x0004, 0x0002, 0x0008,
0x0001, 0x0010, 0x0004, 0x0002, 0x0008, 0x0001, 0x0004, 0x0004,
0x0002, 0x0008, 0x0001, 0x0011, 0x0004, 0x0002, 0x0008, 0x0001,
0x0004, 0x0004, 0x0002, 0x0008, 0x0001, 0x0011, 0x0004, 0x0002,
0x0008, 0x0001, 0x0005, 0x0004, 0x0002, 0x0008, 0x0001, 0x0011,
0x0004, 0x0002, 0x0008, 0x0001, 0x0005, 0x0004, 0x0002, 0x0008,
0x0001, 0x0011, 0x0004, 0x0002, 0x0008, 0x0001, 0x0004, 0x0004,
0x0002, 0x0008, 0x0001, 0x0010, 0x0004, 0x0002, 0x0008, 0x0001,
0x0004, 0x0004, 0x0002, 0x0008, 0x0001, 0x0010
};
// Festive 6Voices
const uint16_t PROGMEM builtin_festive_6voices[] = {
0x0001, 0x0002, 0x0004, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
0x0008, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0004, 0x0002,
0x0001, 0x0002, 0x0001, 0x0002, 0x0010, 0x0002, 0x0001, 0x0002,
0x0001, 0x0002, 0x0009, 0x0002, 0x0001, 0x0002, 0x0011, 0x0002,
0x0001, 0x0002, 0x0005, 0x0002, 0x0001, 0x0002, 0x0021, 0x0002,
0x0001, 0x0002, 0x0009, 0x0002, 0x0001, 0x0002, 0x0011, 0x0002,
0x0001, 0x0002, 0x0005, 0x0002, 0x0001, 0x0002, 0x0021, 0x0002,
0x0001, 0x0002, 0x0009, 0x0002, 0x0001, 0x0002, 0x0011, 0x0002,
0x0001, 0x0002, 0x0005, 0x0002, 0x0001, 0x0002, 0x0021, 0x0002,
0x0001, 0x0002
};
// Festive 8Voices
const uint16_t PROGMEM builtin_festive_8voices[] = {
0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080
};
// Ormilia
const uint16_t PROGMEM builtin_ormilia[] = {
// Melody: Ormilia 1,2,3,4,5,6,7,8
const uint16_t PROGMEM ormilia_1_8[] = {
0x0002, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
@@ -339,6 +83,252 @@ const uint16_t PROGMEM builtin_ormilia[] = {
0x0002, 0x0001, 0x0000
};
// Melody: Festal 1,2,3,4,5
const uint16_t PROGMEM festive_1_8[] = {
0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080
};
// Melody: Festive Chord 1,2,3,4,5
const uint16_t PROGMEM festive_alt_5[] = {
0x0004, 0x0002, 0x0008, 0x0001, 0x0004, 0x0004, 0x0002, 0x0008,
0x0001, 0x0010, 0x0004, 0x0002, 0x0008, 0x0001, 0x0004, 0x0004,
0x0002, 0x0008, 0x0001, 0x0011, 0x0004, 0x0002, 0x0008, 0x0001,
0x0004, 0x0004, 0x0002, 0x0008, 0x0001, 0x0011, 0x0004, 0x0002,
0x0008, 0x0001, 0x0005, 0x0004, 0x0002, 0x0008, 0x0001, 0x0011,
0x0004, 0x0002, 0x0008, 0x0001, 0x0005, 0x0004, 0x0002, 0x0008,
0x0001, 0x0011, 0x0004, 0x0002, 0x0008, 0x0001, 0x0004, 0x0004,
0x0002, 0x0008, 0x0001, 0x0010, 0x0004, 0x0002, 0x0008, 0x0001,
0x0004, 0x0004, 0x0002, 0x0008, 0x0001, 0x0010
};
// Melody: Festive 1,2,3,4,5,6
const uint16_t PROGMEM festive_6[] = {
0x0001, 0x0002, 0x0004, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
0x0008, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0004, 0x0002,
0x0001, 0x0002, 0x0001, 0x0002, 0x0010, 0x0002, 0x0001, 0x0002,
0x0001, 0x0002, 0x0009, 0x0002, 0x0001, 0x0002, 0x0011, 0x0002,
0x0001, 0x0002, 0x0005, 0x0002, 0x0001, 0x0002, 0x0021, 0x0002,
0x0001, 0x0002, 0x0009, 0x0002, 0x0001, 0x0002, 0x0011, 0x0002,
0x0001, 0x0002, 0x0005, 0x0002, 0x0001, 0x0002, 0x0021, 0x0002,
0x0001, 0x0002, 0x0009, 0x0002, 0x0001, 0x0002, 0x0011, 0x0002,
0x0001, 0x0002, 0x0005, 0x0002, 0x0001, 0x0002, 0x0021, 0x0002,
0x0001, 0x0002
};
// Melody: Festive 1,2,3,4,5
const uint16_t PROGMEM festive_5[] = {
0x0001, 0x0002, 0x0004, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
0x0008, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0004, 0x0002,
0x0001, 0x0002, 0x0001, 0x0002, 0x0010, 0x0002, 0x0001, 0x0002
};
// Melody: Festive 1,2,3,4
const uint16_t PROGMEM festive_2_4[] = {
0x0001, 0x0002, 0x0004, 0x0009, 0x0002, 0x0001, 0x0004, 0x0009
};
// Melody: Festive 1
const uint16_t PROGMEM festive_1[] = {
0x0001, 0x0001, 0x0001, 0x0000, 0x0001, 0x0001, 0x0001, 0x0001,
0x0000, 0x0001, 0x0000, 0x0001, 0x0001, 0x0001, 0x0000, 0x0001,
0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0000, 0x0001, 0x0000
};
// Melody: One By One 1,2,3,4,5,6,7,8
const uint16_t PROGMEM onebyone_4_8[] = {
0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000,
0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000,
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
0x0002, 0x0004, 0x0008, 0x0004, 0x0002, 0x0011, 0x0002, 0x0004,
0x0008, 0x0004, 0x0002, 0x0021, 0x0002, 0x0004, 0x0008, 0x0004,
0x0002, 0x0041, 0x0002, 0x0004, 0x0008, 0x0004, 0x0002, 0x0081,
0x0002, 0x0004, 0x0008, 0x0004, 0x0002, 0x0041, 0x0002, 0x0004,
0x0008, 0x0004, 0x0002, 0x0021, 0x0002, 0x0004, 0x0008, 0x0004,
0x0002, 0x0041, 0x0002, 0x0004, 0x0008, 0x0004, 0x0002, 0x0081,
0x0002, 0x0004, 0x0008, 0x0004, 0x0002, 0x0041, 0x0002, 0x0004,
0x0008, 0x0004, 0x0002, 0x0021, 0x0002, 0x0004, 0x0008, 0x0004,
0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001,
0x0004, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001,
0x0004, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001,
0x0002, 0x0001, 0x0000
};
// Melody: One By One 1,2,3
const uint16_t PROGMEM onebyone_2_3[] = {
0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000,
0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000,
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002
};
// Melody: Athonite Extended 1,2,3,4,5,6,7,8
const uint16_t PROGMEM athonite_4_8[] = {
0x0002, 0x0001, 0x0000, 0x0000, 0x0002, 0x0001, 0x0000, 0x0000,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0000, 0x0005,
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0002, 0x0005,
0x0002, 0x0001, 0x0008, 0x0005, 0x0002, 0x0001, 0x0000, 0x0005,
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0002, 0x0005,
0x0002, 0x0001, 0x0009, 0x0002, 0x0001, 0x0011, 0x0002, 0x0001,
0x0022, 0x0002, 0x0001, 0x0081, 0x0002, 0x0001, 0x000A, 0x0002,
0x0001, 0x0041, 0x0002, 0x0001, 0x0012, 0x0002, 0x0001, 0x0021,
0x0002, 0x0001, 0x0082, 0x0002, 0x0001, 0x0009, 0x0002, 0x0001,
0x0042, 0x0002, 0x0001, 0x0011, 0x0002, 0x0001, 0x0022, 0x0002,
0x0001, 0x0081, 0x0002, 0x0001, 0x000A, 0x0002, 0x0001, 0x0041,
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0000, 0x0005,
0x0002, 0x0001, 0x0002, 0x0005, 0x0002, 0x0001, 0x0000, 0x0000,
0x0000
};
// Melody: Athonite Extended 1,2,3,4
const uint16_t PROGMEM athonite_3_4[] = {
0x0002, 0x0001, 0x0000, 0x0000, 0x0002, 0x0001, 0x0000, 0x0000,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0000, 0x0005,
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0002, 0x0005,
0x0002, 0x0001, 0x0008, 0x0005, 0x0002, 0x0001, 0x0000, 0x0005,
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0002, 0x0005,
0x0002, 0x0001, 0x0009, 0x0002, 0x0001, 0x0005, 0x0002, 0x0001,
0x000A, 0x0002, 0x0001, 0x0006, 0x0002, 0x0001, 0x0009, 0x0002,
0x0001, 0x0005, 0x0002, 0x0001, 0x000A, 0x0002, 0x0001, 0x0006,
0x0002, 0x0001, 0x0009
};
// Melody: Athonite 1,2,3
const uint16_t PROGMEM athonite_3[] = {
0x0002, 0x0001, 0x0000, 0x0000, 0x0002, 0x0001, 0x0000, 0x0000,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004
};
// Melody: Athonite 2
const uint16_t PROGMEM athonite_1_2[] = {
0x0001, 0x0002, 0x0001, 0x0001, 0x0002, 0x0001, 0x0001, 0x0002,
0x0001, 0x0001, 0x0002, 0x0001, 0x0002
};
// Melody: Talanto 1,2,3,4
const uint16_t PROGMEM talanto_1_4[] = {
0x0001, 0x0001, 0x0001, 0x0002, 0x0001, 0x0001, 0x0001, 0x0008,
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0001, 0x0001, 0x0008
};
// Melody: Semantron 1,2,3,4
const uint16_t PROGMEM semantron_1_4[] = {
0x0001, 0x0001, 0x0001, 0x0002, 0x0001, 0x0001, 0x0001, 0x0008,
0x0001, 0x0001, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0008
};
// Melody: Toll Great Friday 1,2,3,4
const uint16_t PROGMEM mournfull_gf_1_4[] = {
0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0001,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0004, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0002, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0002, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0002, 0x0002, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0008, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000
};
// Melody: Mournfull Toll 1,2,3,4
const uint16_t PROGMEM mournfull_1_4[] = {
0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0000, 0x0002, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0000, 0x0002, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0000, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0000, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000
};
// Melody: Orthros Festive 1,2,3
const uint16_t PROGMEM orthros_fst_1_3[] = {
0x0001, 0x0000, 0x0002, 0x0001, 0x0000, 0x0002, 0x0000, 0x0001,
0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0004, 0x0000
};
// Melody: Orthros 2,1
const uint16_t PROGMEM orthros_1_8[] = {
0x0001, 0x0000, 0x0002, 0x0000, 0x0004, 0x0008, 0x0000, 0x0010,
0x0000, 0x0020, 0x0000, 0x0040, 0x0080, 0x0000
};
// Melody: Catechetical 1,2,3
const uint16_t PROGMEM catechetical_1_5[] = {
0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0000
};
// Melody: Vesper Festive 1,2,3,4
const uint16_t PROGMEM vesper_fst_1_4[] = {
0x0001, 0x0002, 0x0000, 0x0000, 0x0001, 0x0002, 0x0000, 0x0000,
0x0001, 0x0004, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0001, 0x0002, 0x0000, 0x0000, 0x0001, 0x0002, 0x0000, 0x0000,
0x0001, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
0x0001, 0x0002, 0x0000, 0x0000, 0x0001, 0x0002, 0x0000, 0x0000,
0x0001, 0x0002, 0x0000, 0x0000, 0x0001, 0x0002, 0x0000, 0x0000,
0x0001, 0x0002, 0x0000, 0x0000, 0x0001, 0x0004, 0x0000, 0x0000,
0x0001, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000
};
// Melody: Vesper 1,2,3
const uint16_t PROGMEM vesper_1_3[] = {
0x0001, 0x0002, 0x0004, 0x0000, 0x0001, 0x0002, 0x0004, 0x0000,
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0004, 0x0000
};
// Melody: Doxology Festive 1,2,3,4,5,6
const uint16_t PROGMEM doxology_fst_1_6[] = {
0x0002, 0x0004, 0x0009, 0x0004, 0x0002, 0x0004, 0x0011, 0x0004,
0x0002, 0x0004, 0x0021, 0x0004, 0x0002, 0x0004, 0x0011, 0x0004
};
// Melody: Doxology Alternative 1,2,3,4,5
const uint16_t PROGMEM doxology_alt_1_5[] = {
0x0001, 0x0000, 0x0002, 0x0004, 0x0000, 0x0018, 0x0000, 0x0001,
0x0000, 0x0002, 0x0004, 0x0000, 0x0018, 0x0000, 0x0001, 0x0000,
0x0002, 0x0004, 0x0000, 0x0018, 0x0000, 0x0001, 0x0002, 0x0001,
0x0002, 0x0004, 0x0000, 0x0018, 0x0000
};
// Melody: Doxology 1,2,3,4
const uint16_t PROGMEM doxology_1_4[] = {
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0000, 0x0000,
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0008, 0x0000, 0x0000,
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0008, 0x0000, 0x0000
};
// ═════════════════════════════════════════════════════════════════════════════════
// MELODY LIBRARY - Array of all built-in melodies
@@ -347,168 +337,164 @@ const uint16_t PROGMEM builtin_ormilia[] = {
const MelodyInfo MELODY_LIBRARY[] = {
{
"1 Bell Test",
"builtin_1bell_test",
builtin_1bell_test,
sizeof(builtin_1bell_test) / sizeof(uint16_t)
"one_bell_test",
one_bell_test,
sizeof(one_bell_test) / sizeof(uint16_t)
},
{
"Doxology Traditional",
"builtin_doxology_traditional",
builtin_doxology_traditional,
sizeof(builtin_doxology_traditional) / sizeof(uint16_t)
"Ormilia 1,2,3,4,5,6,7,8",
"ormilia_1_8",
ormilia_1_8,
sizeof(ormilia_1_8) / sizeof(uint16_t)
},
{
"Doxology Alternative",
"builtin_doxology_alternative",
builtin_doxology_alternative,
sizeof(builtin_doxology_alternative) / sizeof(uint16_t)
"Festal 1,2,3,4,5",
"festive_1_8",
festive_1_8,
sizeof(festive_1_8) / sizeof(uint16_t)
},
{
"Doxology Festive",
"builtin_doxology_festive",
builtin_doxology_festive,
sizeof(builtin_doxology_festive) / sizeof(uint16_t)
"Festive Chord 1,2,3,4,5",
"festive_alt_5",
festive_alt_5,
sizeof(festive_alt_5) / sizeof(uint16_t)
},
{
"Vesper Traditional",
"builtin_vesper_traditional",
builtin_vesper_traditional,
sizeof(builtin_vesper_traditional) / sizeof(uint16_t)
"Festive 1,2,3,4,5,6",
"festive_6",
festive_6,
sizeof(festive_6) / sizeof(uint16_t)
},
{
"Vesper Alternative",
"builtin_vesper_alternative",
builtin_vesper_alternative,
sizeof(builtin_vesper_alternative) / sizeof(uint16_t)
"Festive 1,2,3,4,5",
"festive_5",
festive_5,
sizeof(festive_5) / sizeof(uint16_t)
},
{
"Catehetical",
"builtin_catehetical",
builtin_catehetical,
sizeof(builtin_catehetical) / sizeof(uint16_t)
"Festive 1,2,3,4",
"festive_2_4",
festive_2_4,
sizeof(festive_2_4) / sizeof(uint16_t)
},
{
"Orthros Traditional",
"builtin_orthros_traditional",
builtin_orthros_traditional,
sizeof(builtin_orthros_traditional) / sizeof(uint16_t)
"Festive 1",
"festive_1",
festive_1,
sizeof(festive_1) / sizeof(uint16_t)
},
{
"Orthros Alternative",
"builtin_orthros_alternative",
builtin_orthros_alternative,
sizeof(builtin_orthros_alternative) / sizeof(uint16_t)
"One By One 1,2,3,4,5,6,7,8",
"onebyone_4_8",
onebyone_4_8,
sizeof(onebyone_4_8) / sizeof(uint16_t)
},
{
"Mournfull Toll",
"builtin_mournfull_toll",
builtin_mournfull_toll,
sizeof(builtin_mournfull_toll) / sizeof(uint16_t)
"One By One 1,2,3",
"onebyone_2_3",
onebyone_2_3,
sizeof(onebyone_2_3) / sizeof(uint16_t)
},
{
"Mournfull Toll Alternative",
"builtin_mournfull_toll_alternative",
builtin_mournfull_toll_alternative,
sizeof(builtin_mournfull_toll_alternative) / sizeof(uint16_t)
"Athonite Extended 1,2,3,4,5,6,7,8",
"athonite_4_8",
athonite_4_8,
sizeof(athonite_4_8) / sizeof(uint16_t)
},
{
"Mournfull Toll Meg Par",
"builtin_mournfull_toll_meg_par",
builtin_mournfull_toll_meg_par,
sizeof(builtin_mournfull_toll_meg_par) / sizeof(uint16_t)
"Athonite Extended 1,2,3,4",
"athonite_3_4",
athonite_3_4,
sizeof(athonite_3_4) / sizeof(uint16_t)
},
{
"Sematron",
"builtin_sematron",
builtin_sematron,
sizeof(builtin_sematron) / sizeof(uint16_t)
"Athonite 1,2,3",
"athonite_3",
athonite_3,
sizeof(athonite_3) / sizeof(uint16_t)
},
{
"Sematron Alternative",
"builtin_sematron_alternative",
builtin_sematron_alternative,
sizeof(builtin_sematron_alternative) / sizeof(uint16_t)
"Athonite 1,2",
"athonite_1_2",
athonite_1_2,
sizeof(athonite_1_2) / sizeof(uint16_t)
},
{
"Athonite 1 2 Voices",
"builtin_athonite_1_2_voices",
builtin_athonite_1_2_voices,
sizeof(builtin_athonite_1_2_voices) / sizeof(uint16_t)
"Talanto 1,2,3,4",
"talanto_1_4",
talanto_1_4,
sizeof(talanto_1_4) / sizeof(uint16_t)
},
{
"Athonite 3 Voices",
"builtin_athonite_3_voices",
builtin_athonite_3_voices,
sizeof(builtin_athonite_3_voices) / sizeof(uint16_t)
"Semantron 1,2,3,4",
"semantron_1_4",
semantron_1_4,
sizeof(semantron_1_4) / sizeof(uint16_t)
},
{
"Athonite 3 4 Voices",
"builtin_athonite_3_4_voices",
builtin_athonite_3_4_voices,
sizeof(builtin_athonite_3_4_voices) / sizeof(uint16_t)
"Toll Great Friday 1,2,3,4",
"mournfull_gf_1_4",
mournfull_gf_1_4,
sizeof(mournfull_gf_1_4) / sizeof(uint16_t)
},
{
"Athonite 4 8 Voices",
"builtin_athonite_4_8_voices",
builtin_athonite_4_8_voices,
sizeof(builtin_athonite_4_8_voices) / sizeof(uint16_t)
"Mournfull Toll 1,2,3,4",
"mournfull_1_4",
mournfull_1_4,
sizeof(mournfull_1_4) / sizeof(uint16_t)
},
{
"Onebyone 2 3 Voices",
"builtin_onebyone_2_3_voices",
builtin_onebyone_2_3_voices,
sizeof(builtin_onebyone_2_3_voices) / sizeof(uint16_t)
"Orthros Festive 1,2,3",
"orthros_fst_1_3",
orthros_fst_1_3,
sizeof(orthros_fst_1_3) / sizeof(uint16_t)
},
{
"Onebyone 4 8 Voices",
"builtin_onebyone_4_8_voices",
builtin_onebyone_4_8_voices,
sizeof(builtin_onebyone_4_8_voices) / sizeof(uint16_t)
"Orthros 1,2,3,4,5,6,7,8",
"orthros_1_8",
orthros_1_8,
sizeof(orthros_1_8) / sizeof(uint16_t)
},
{
"Festive 1Voice",
"builtin_festive_1voice",
builtin_festive_1voice,
sizeof(builtin_festive_1voice) / sizeof(uint16_t)
"Catechetical 1,2,3,4,5",
"catechetical_1_5",
catechetical_1_5,
sizeof(catechetical_1_5) / sizeof(uint16_t)
},
{
"Festive 4Voices",
"builtin_festive_4voices",
builtin_festive_4voices,
sizeof(builtin_festive_4voices) / sizeof(uint16_t)
"Vesper Festive 1,2,3,4",
"vesper_fst_1_4",
vesper_fst_1_4,
sizeof(vesper_fst_1_4) / sizeof(uint16_t)
},
{
"Festive 5Voices",
"builtin_festive_5voices",
builtin_festive_5voices,
sizeof(builtin_festive_5voices) / sizeof(uint16_t)
"Vesper 1,2,3",
"vesper_1_3",
vesper_1_3,
sizeof(vesper_1_3) / sizeof(uint16_t)
},
{
"Festive 5Voice Alternative",
"builtin_festive_5voice_alternative",
builtin_festive_5voice_alternative,
sizeof(builtin_festive_5voice_alternative) / sizeof(uint16_t)
"Doxology Festive 1,2,3,4,5,6",
"doxology_fst_1_6",
doxology_fst_1_6,
sizeof(doxology_fst_1_6) / sizeof(uint16_t)
},
{
"Festive 6Voices",
"builtin_festive_6voices",
builtin_festive_6voices,
sizeof(builtin_festive_6voices) / sizeof(uint16_t)
"Doxology Alternative 1,2,3,4,5",
"doxology_alt_1_5",
doxology_alt_1_5,
sizeof(doxology_alt_1_5) / sizeof(uint16_t)
},
{
"Festive 8Voices",
"builtin_festive_8voices",
builtin_festive_8voices,
sizeof(builtin_festive_8voices) / sizeof(uint16_t)
},
{
"Ormilia",
"builtin_ormilia",
builtin_ormilia,
sizeof(builtin_ormilia) / sizeof(uint16_t)
"Doxology 1,2,3,4",
"doxology_1_4",
doxology_1_4,
sizeof(doxology_1_4) / sizeof(uint16_t)
}
};
const uint16_t MELODY_COUNT = sizeof(MELODY_LIBRARY) / sizeof(MelodyInfo);
// ═════════════════════════════════════════════════════════════════════════════════
@@ -516,22 +502,13 @@ const uint16_t MELODY_COUNT = sizeof(MELODY_LIBRARY) / sizeof(MelodyInfo);
// ═════════════════════════════════════════════════════════════════════════════════
/**
* @brief Check if a UID is a built-in melody
* @param uid The melody UID to check
* @return true if it's a built-in melody (starts with "builtin_")
*/
inline bool isBuiltInMelody(const String& uid) {
return uid.startsWith("builtin_");
}
/**
* @brief Find a built-in melody by UID
* @param uid The melody UID to find
* @brief Find a built-in melody by PID
* @param pid The melody playback ID to find
* @return Pointer to MelodyInfo if found, nullptr otherwise
*/
inline const MelodyInfo* findMelodyByUID(const String& uid) {
inline const MelodyInfo* findMelodyByPID(const String& pid) {
for (uint16_t i = 0; i < MELODY_COUNT; i++) {
if (uid == MELODY_LIBRARY[i].uid) {
if (pid == MELODY_LIBRARY[i].pid) {
return &MELODY_LIBRARY[i];
}
}
@@ -540,12 +517,12 @@ inline const MelodyInfo* findMelodyByUID(const String& uid) {
/**
* @brief Load a built-in melody into a vector
* @param uid The melody UID to load
* @param pid The melody playback ID to load
* @param melodySteps Vector to fill with melody data
* @return true if melody was found and loaded, false otherwise
*/
inline bool loadBuiltInMelody(const String& uid, std::vector<uint16_t>& melodySteps) {
const MelodyInfo* melody = findMelodyByUID(uid);
inline bool loadBuiltInMelody(const String& pid, std::vector<uint16_t>& melodySteps) {
const MelodyInfo* melody = findMelodyByPID(pid);
if (!melody) {
return false;
}
@@ -561,7 +538,7 @@ inline bool loadBuiltInMelody(const String& uid, std::vector<uint16_t>& melodySt
/**
* @brief Get list of all built-in melodies as JSON string
* @return JSON array string of melody names and UIDs
* @return JSON array string of melody names and PIDs
*/
inline String getBuiltInMelodiesJSON() {
String json = "[";
@@ -569,11 +546,11 @@ inline String getBuiltInMelodiesJSON() {
if (i > 0) json += ",";
json += "{";
json += "\"name\":\"" + String(MELODY_LIBRARY[i].name) + "\",";
json += "\"uid\":\"" + String(MELODY_LIBRARY[i].uid) + "\",";
json += "\"pid\":\"" + String(MELODY_LIBRARY[i].pid) + "\"";
json += "}";
}
json += "]";
return json;
}
}
}
@@ -15,7 +15,9 @@
#include "../../Logging/Logging.hpp"
#include "../../Player/Player.hpp"
#include "../../FileManager/FileManager.hpp"
#if HAS_RTC
#include "../../TimeKeeper/TimeKeeper.hpp"
#endif
#include "../../FirmwareValidator/FirmwareValidator.hpp"
#include "../../Telemetry/Telemetry.hpp"
#include "../../HealthMonitor/HealthMonitor.hpp"
@@ -24,14 +26,19 @@
// Domain handlers
#include "../Handlers/PlaybackHandler/PlaybackHandler.hpp"
#include "../Handlers/RelayHandler/RelayHandler.hpp"
#if HAS_RTC
#include "../Handlers/ClockHandler/ClockHandler.hpp"
#include "../Handlers/SystemHandler/SystemHandler.hpp"
#endif
#include "../Handlers/FirmwareHandler/FirmwareHandler.hpp"
#include "../Handlers/NetworkHandler/NetworkHandler.hpp"
#include "../Handlers/FileHandler/FileHandler.hpp"
#include "../Handlers/LoggingHandler/LoggingHandler.hpp"
#include "../Handlers/TelemetryHandler/TelemetryHandler.hpp"
#include "../Handlers/MQTTHandler/MQTTHandler.hpp"
#if HAS_RF
#include "../../RFRemote/RFRemoteHandler.hpp"
#endif
// ─────────────────────────────────────────────────────────────────────────────
// Constructor
@@ -169,9 +176,11 @@ void CommunicationRouter::setFileManagerReference(FileManager* fm) {
}
}
#if HAS_RTC
void CommunicationRouter::setTimeKeeperReference(Timekeeper* tk) {
_timeKeeper = tk;
}
#endif
void CommunicationRouter::setFirmwareValidatorReference(FirmwareValidator* fv) {
_firmwareValidator = fv;
@@ -189,6 +198,12 @@ void CommunicationRouter::setOutputManagerReference(OutputManager* om) {
_outputManager = om;
}
#if HAS_RF
void CommunicationRouter::setRFRemoteReference(RFRemote* rf) {
_rfRemote = rf;
}
#endif
// ─────────────────────────────────────────────────────────────────────────────
// registerHandlers()
// ─────────────────────────────────────────────────────────────────────────────
@@ -197,7 +212,9 @@ void CommunicationRouter::registerHandlers() {
// Log any missing optional dependencies so issues surface at boot, not later.
if (!_player) LOG_ERROR(TAG, "registerHandlers: _player is null — PlaybackHandler, RelayHandler, FirmwareHandler, SystemHandler skipped");
if (!_fileManager) LOG_ERROR(TAG, "registerHandlers: _fileManager is null — FileHandler skipped");
#if HAS_RTC
if (!_timeKeeper) LOG_ERROR(TAG, "registerHandlers: _timeKeeper is null — ClockHandler skipped");
#endif
if (!_firmwareValidator) LOG_ERROR(TAG, "registerHandlers: _firmwareValidator is null — FirmwareHandler skipped");
if (!_telemetry) LOG_ERROR(TAG, "registerHandlers: _telemetry is null — TelemetryHandler and SystemHandler skipped");
if (!_healthMonitor) LOG_WARNING(TAG, "registerHandlers: _healthMonitor is null — system.health unavailable");
@@ -213,17 +230,21 @@ void CommunicationRouter::registerHandlers() {
_bus.registerHandler(std::make_unique<RelayHandler>(_configManager, *_outputManager, *_player));
}
#if HAS_RTC
// Clock
if (_timeKeeper) {
_bus.registerHandler(std::make_unique<ClockHandler>(_configManager, *_timeKeeper));
}
#endif
// System — requires player, telemetry, healthMonitor, timeKeeper, clientManager
#if HAS_RTC
if (_player && _telemetry && _healthMonitor && _timeKeeper) {
_bus.registerHandler(std::make_unique<SystemHandler>(
_configManager, *_player, *_telemetry, *_healthMonitor,
*_timeKeeper, _clientManager));
}
#endif
// Firmware / OTA
if (_firmwareValidator && _player) {
@@ -250,6 +271,13 @@ void CommunicationRouter::registerHandlers() {
// MQTT control (enable / disable)
_bus.registerHandler(std::make_unique<MQTTHandler>(_configManager, _mqttClient));
#if HAS_RF
// RF remote control
if (_rfRemote) {
_bus.registerHandler(std::make_unique<RFRemoteHandler>(*_rfRemote));
}
#endif
LOG_INFO(TAG, "All domain handlers registered on CommandBus");
}
@@ -323,11 +351,19 @@ size_t CommunicationRouter::getWebSocketClientCount() const {
}
bool CommunicationRouter::isHealthy() const {
if (!_player || !_fileManager || !_timeKeeper) {
LOG_WARNING(TAG, "Unhealthy — missing subsystem references (player=%d fileManager=%d timeKeeper=%d)",
_player != nullptr, _fileManager != nullptr, _timeKeeper != nullptr);
#if HAS_RTC
if (!_player || !_timeKeeper) {
LOG_WARNING(TAG, "Unhealthy — missing subsystem references (player=%d timeKeeper=%d)",
_player != nullptr, _timeKeeper != nullptr);
return false;
}
#else
if (!_player) {
LOG_WARNING(TAG, "Unhealthy — missing subsystem references (player=%d)",
_player != nullptr);
return false;
}
#endif
if (!_networking.isConnected()) {
LOG_WARNING(TAG, "Unhealthy — no network connection");
return false;
@@ -37,12 +37,17 @@ class ConfigManager;
class OTAManager;
class Player;
class FileManager;
#if HAS_RTC
class Timekeeper;
#endif
class Networking;
class FirmwareValidator;
class Telemetry;
class HealthMonitor;
class OutputManager;
#if HAS_RF
class RFRemote;
#endif
class CommunicationRouter {
public:
@@ -64,11 +69,16 @@ public:
// setXxxReference() calls have been made.
void setPlayerReference(Player* player);
void setFileManagerReference(FileManager* fm);
#if HAS_RTC
void setTimeKeeperReference(Timekeeper* tk);
#endif
void setFirmwareValidatorReference(FirmwareValidator* fv);
void setTelemetryReference(Telemetry* telemetry);
void setHealthMonitorReference(HealthMonitor* hm);
void setOutputManagerReference(OutputManager* om);
#if HAS_RF
void setRFRemoteReference(RFRemote* rf);
#endif
// UDP discovery (called by main.cpp)
void setupUdpDiscovery();
@@ -133,11 +143,16 @@ private:
// Late-bound (set via setXxxReference after construction)
Player* _player = nullptr;
FileManager* _fileManager = nullptr;
#if HAS_RTC
Timekeeper* _timeKeeper = nullptr;
#endif
FirmwareValidator* _firmwareValidator = nullptr;
Telemetry* _telemetry = nullptr;
HealthMonitor* _healthMonitor = nullptr;
OutputManager* _outputManager = nullptr;
#if HAS_RF
RFRemote* _rfRemote = nullptr;
#endif
// ── Underlying protocol objects (owned) ─────────────────────────────────
MQTTDriver _mqttClient;
@@ -1,3 +1,4 @@
#if HAS_RTC
#include "ClockHandler.hpp"
#include "../../../ConfigManager/ConfigManager.hpp"
#include "../../../TimeKeeper/TimeKeeper.hpp"
@@ -245,3 +246,5 @@ CommandResult ClockHandler::handleGetConfig(const CommandEnvelope& e) {
doc["night_off"] = cc.nighttimeSilenceOffTime;
return CommandResult::ok("clock.get_config", doc);
}
#endif // HAS_RTC
@@ -1,5 +1,7 @@
#pragma once
#if HAS_RTC
#include <vector>
#include "../ICommandHandler.hpp"
@@ -34,3 +36,5 @@ private:
CommandResult handleGetFace(const CommandEnvelope& e);
CommandResult handleGetConfig(const CommandEnvelope& e);
};
#endif // HAS_RTC
@@ -1,3 +1,4 @@
#if HAS_RTC
#include "SystemHandler.hpp"
#include "../../../ConfigManager/ConfigManager.hpp"
#include "../../../Player/Player.hpp"
@@ -202,3 +203,5 @@ CommandResult SystemHandler::handleRestart(const CommandEnvelope& e) {
}, "restartTask", 1024, nullptr, 1, nullptr);
return CommandResult::ok("system.restart", "Device will restart in 2 seconds");
}
#endif // HAS_RTC
@@ -1,5 +1,7 @@
#pragma once
#if HAS_RTC
#include <vector>
#include "../ICommandHandler.hpp"
@@ -37,3 +39,5 @@ private:
CommandResult handleFactoryReset(const CommandEnvelope& e);
CommandResult handleRestart(const CommandEnvelope& e);
};
#endif // HAS_RTC
+226 -22
View File
@@ -63,61 +63,53 @@ void ConfigManager::createDefaultBellConfig() {
bool ConfigManager::begin() {
LOG_INFO(TAG, "ConfigManager - ✅ Initializing...");
// Step 1: Initialize NVS for device identity (factory-set, permanent)
// Step 1: NVS init — required on all variants (device identity + Agnus user config)
if (!initializeNVS()) {
LOG_ERROR(TAG, "ConfigManager - ❌ NVS initialization failed, using empty defaults");
} else {
// Load device identity from NVS (serial, hwFamily, hwRevision)
loadDeviceIdentityFromNVS();
}
// Step 2: Initialize clean defaults and auto-generate identifiers
// Step 2: Auto-generate hostname, AP SSID, MQTT credentials from serial
initializeCleanDefaults();
// Step 3: Initialize SD card for user-configurable settings
#if HAS_SD_CARD
// ── Vesper (SD card present) ─────────────────────────────────────────────
if (!ensureSDCard()) {
LOG_ERROR(TAG, "ConfigManager - ❌ SD Card initialization failed, using defaults");
return false;
}
// Step 5: Load update servers list
if (!loadUpdateServers()) {
LOG_WARNING(TAG, "ConfigManager - ⚠️ Could not load update servers - using fallback only");
}
// Load network config, save defaults if not found
if (!loadNetworkConfig()) {
LOG_WARNING(TAG, "ConfigManager - ⚠️ Creating default network config file");
saveNetworkConfig();
}
// Load time config, save defaults if not found
if (!loadTimeConfig()) {
LOG_WARNING(TAG, "ConfigManager - ⚠️ Creating default time config file (GMT+2)");
saveTimeConfig();
}
// Load bell durations, save defaults if not found
if (!loadBellDurations()) {
LOG_WARNING(TAG, "ConfigManager - ⚠️ Creating default bell durations file");
saveBellDurations();
}
// Load bell outputs, save defaults if not found
if (!loadBellOutputs()) {
LOG_WARNING(TAG, "ConfigManager - ⚠️ Creating default bell outputs file");
saveBellOutputs();
}
// Load clock config, save defaults if not found
if (!loadClockConfig()) {
LOG_WARNING(TAG, "ConfigManager - ⚠️ Creating default clock config file");
saveClockConfig();
}
// Load clock state, save defaults if not found
if (!loadClockState()) {
LOG_WARNING(TAG, "ConfigManager - ⚠️ Creating default clock state file");
saveClockState();
@@ -127,8 +119,18 @@ bool ConfigManager::begin() {
LOG_WARNING(TAG, "ConfigManager - ⚠️ Creating default general config file");
saveGeneralConfig();
}
LOG_INFO(TAG, "ConfigManager - ✅ Initialization Complete ! Serial: %s, Hostname: %s",
#else
// ── Agnus (no SD card — NVS only) ───────────────────────────────────────
LOG_INFO(TAG, "ConfigManager - No SD card variant — loading all user config from NVS");
loadNetworkConfigFromNVS();
loadBellConfigFromNVS();
loadGeneralConfigFromNVS();
// No time/clock/update-server config on Agnus.
#endif
LOG_INFO(TAG, "ConfigManager - ✅ Initialization Complete — Serial: %s, Hostname: %s",
deviceConfig.serial.c_str(), networkConfig.hostname.c_str());
return true;
}
@@ -231,6 +233,61 @@ String ConfigManager::readNVSString(const char* key, const String& defaultValue)
return result;
}
uint8_t ConfigManager::readNVSU8(const char* key, uint8_t defaultValue) {
if (nvsHandle == 0) return defaultValue;
uint8_t val = defaultValue;
esp_err_t err = nvs_get_u8(nvsHandle, key, &val);
if (err == ESP_ERR_NVS_NOT_FOUND) return defaultValue;
if (err != ESP_OK) { LOG_ERROR(TAG, "NVS read u8 '%s': %s", key, esp_err_to_name(err)); return defaultValue; }
return val;
}
uint16_t ConfigManager::readNVSU16(const char* key, uint16_t defaultValue) {
if (nvsHandle == 0) return defaultValue;
uint16_t val = defaultValue;
esp_err_t err = nvs_get_u16(nvsHandle, key, &val);
if (err == ESP_ERR_NVS_NOT_FOUND) return defaultValue;
if (err != ESP_OK) { LOG_ERROR(TAG, "NVS read u16 '%s': %s", key, esp_err_to_name(err)); return defaultValue; }
return val;
}
bool ConfigManager::readNVSBool(const char* key, bool defaultValue) {
uint8_t val = readNVSU8(key, defaultValue ? 1 : 0);
return val != 0;
}
bool ConfigManager::writeNVSString(const char* key, const String& value) {
if (nvsHandle == 0) return false;
esp_err_t err = nvs_set_str(nvsHandle, key, value.c_str());
if (err != ESP_OK) { LOG_ERROR(TAG, "NVS write str '%s': %s", key, esp_err_to_name(err)); return false; }
return true;
}
bool ConfigManager::writeNVSU8(const char* key, uint8_t value) {
if (nvsHandle == 0) return false;
esp_err_t err = nvs_set_u8(nvsHandle, key, value);
if (err != ESP_OK) { LOG_ERROR(TAG, "NVS write u8 '%s': %s", key, esp_err_to_name(err)); return false; }
return true;
}
bool ConfigManager::writeNVSU16(const char* key, uint16_t value) {
if (nvsHandle == 0) return false;
esp_err_t err = nvs_set_u16(nvsHandle, key, value);
if (err != ESP_OK) { LOG_ERROR(TAG, "NVS write u16 '%s': %s", key, esp_err_to_name(err)); return false; }
return true;
}
bool ConfigManager::writeNVSBool(const char* key, bool value) {
return writeNVSU8(key, value ? 1 : 0);
}
bool ConfigManager::commitNVS() {
if (nvsHandle == 0) return false;
esp_err_t err = nvs_commit(nvsHandle);
if (err != ESP_OK) { LOG_ERROR(TAG, "NVS commit failed: %s", esp_err_to_name(err)); return false; }
return true;
}
// ════════════════════════════════════════════════════════════════════════════
// STANDARD SD CARD FUNCTIONALITY
// ════════════════════════════════════════════════════════════════════════════
@@ -269,11 +326,13 @@ bool ConfigManager::loadDeviceConfig() {
}
bool ConfigManager::isHealthy() const {
#if HAS_SD_CARD
if (!sdInitialized) {
LOG_VERBOSE(TAG, "ConfigManager - ⚠️ Unhealthy - SD card not initialized");
return false;
}
#endif
if (deviceConfig.serial.isEmpty()) {
LOG_VERBOSE(TAG, "ConfigManager - ⚠️ Unhealthy - Serial not set (factory configuration required)");
return false;
@@ -327,6 +386,9 @@ bool ConfigManager::loadBellDurations() {
}
bool ConfigManager::saveBellDurations() {
#if !HAS_SD_CARD
return saveBellConfigToNVS();
#endif
if (!ensureSDCard()) return false;
StaticJsonDocument<512> doc;
@@ -380,6 +442,9 @@ bool ConfigManager::loadBellOutputs() {
}
bool ConfigManager::saveBellOutputs() {
#if !HAS_SD_CARD
return saveBellConfigToNVS();
#endif
if (!ensureSDCard()) return false;
StaticJsonDocument<512> doc;
@@ -401,6 +466,48 @@ bool ConfigManager::saveBellOutputs() {
return true;
}
// ════════════════════════════════════════════════════════════════════════════
// BELL CONFIG — NVS STORAGE (Agnus: no SD card)
// NVS key layout:
// bd0..bd15 — bell durations (u16)
// bo0..bo15 — bell outputs (u16)
// ════════════════════════════════════════════════════════════════════════════
#if !HAS_SD_CARD
bool ConfigManager::loadBellConfigFromNVS() {
bool anyFound = false;
for (uint8_t i = 0; i < 16; i++) {
char keyD[5], keyO[5];
snprintf(keyD, sizeof(keyD), "bd%d", i);
snprintf(keyO, sizeof(keyO), "bo%d", i);
uint16_t dur = readNVSU16(keyD, bellConfig.durations[i]);
uint16_t out = readNVSU16(keyO, bellConfig.outputs[i]);
// readNVSU16 returns the default when key is not found — detect a real
// stored value by trying a sentinel read with an unlikely default.
// Simpler: just always write what we got; if nothing was stored the
// defaults from createDefaultBellConfig() remain unchanged.
bellConfig.durations[i] = dur;
bellConfig.outputs[i] = out;
anyFound = true; // NVS open succeeded — consider it loaded
}
LOG_DEBUG(TAG, "ConfigManager - Bell config loaded from NVS");
return anyFound;
}
bool ConfigManager::saveBellConfigToNVS() {
bool ok = true;
for (uint8_t i = 0; i < 16; i++) {
char keyD[5], keyO[5];
snprintf(keyD, sizeof(keyD), "bd%d", i);
snprintf(keyO, sizeof(keyO), "bo%d", i);
ok &= writeNVSU16(keyD, bellConfig.durations[i]);
ok &= writeNVSU16(keyO, bellConfig.outputs[i]);
}
ok &= commitNVS();
LOG_DEBUG(TAG, "ConfigManager - Bell config saved to NVS (%s)", ok ? "ok" : "errors");
return ok;
}
#endif
void ConfigManager::updateBellDurations(JsonVariant doc) {
for (uint8_t i = 0; i < 16; i++) {
String key = String("b") + (i + 1);
@@ -867,6 +974,9 @@ bool ConfigManager::loadNetworkConfig() {
}
bool ConfigManager::saveNetworkConfig() {
#if !HAS_SD_CARD
return saveNetworkConfigToNVS();
#endif
if (!ensureSDCard()) return false;
StaticJsonDocument<512> doc;
@@ -898,6 +1008,63 @@ bool ConfigManager::saveNetworkConfig() {
return true;
}
// ════════════════════════════════════════════════════════════════════════════
// NETWORK CONFIG — NVS STORAGE (Agnus: no SD card)
// NVS key layout (all strings to keep it simple; IPs stored as dotted strings):
// nc_host — custom hostname (empty = use auto-generated)
// nc_static — useStaticIP (u8 bool)
// nc_ip — static IP string
// nc_gw — gateway string
// nc_sn — subnet string
// nc_dns1 — DNS1 string
// nc_dns2 — DNS2 string
// nc_apmode — permanentAPMode (u8 bool)
// ════════════════════════════════════════════════════════════════════════════
#if !HAS_SD_CARD
bool ConfigManager::loadNetworkConfigFromNVS() {
String customHostname = readNVSString("nc_host", "");
if (!customHostname.isEmpty()) {
networkConfig.hostname = customHostname;
}
networkConfig.useStaticIP = readNVSBool("nc_static", false);
networkConfig.permanentAPMode = readNVSBool("nc_apmode", false);
String ipStr = readNVSString("nc_ip", "");
if (!ipStr.isEmpty() && ipStr != "0.0.0.0") networkConfig.ip.fromString(ipStr);
String gwStr = readNVSString("nc_gw", "");
if (!gwStr.isEmpty() && gwStr != "0.0.0.0") networkConfig.gateway.fromString(gwStr);
String snStr = readNVSString("nc_sn", "");
if (!snStr.isEmpty() && snStr != "0.0.0.0") networkConfig.subnet.fromString(snStr);
String dns1Str = readNVSString("nc_dns1", "");
if (!dns1Str.isEmpty() && dns1Str != "0.0.0.0") networkConfig.dns1.fromString(dns1Str);
String dns2Str = readNVSString("nc_dns2", "");
if (!dns2Str.isEmpty() && dns2Str != "0.0.0.0") networkConfig.dns2.fromString(dns2Str);
LOG_DEBUG(TAG, "ConfigManager - Network config loaded from NVS — hostname: %s, staticIP: %s",
networkConfig.hostname.c_str(), networkConfig.useStaticIP ? "yes" : "no");
return true;
}
bool ConfigManager::saveNetworkConfigToNVS() {
bool ok = true;
ok &= writeNVSString("nc_host", networkConfig.hostname);
ok &= writeNVSBool ("nc_static", networkConfig.useStaticIP);
ok &= writeNVSBool ("nc_apmode", networkConfig.permanentAPMode);
ok &= writeNVSString("nc_ip", networkConfig.ip.toString());
ok &= writeNVSString("nc_gw", networkConfig.gateway.toString());
ok &= writeNVSString("nc_sn", networkConfig.subnet.toString());
ok &= writeNVSString("nc_dns1", networkConfig.dns1.toString());
ok &= writeNVSString("nc_dns2", networkConfig.dns2.toString());
ok &= commitNVS();
LOG_DEBUG(TAG, "ConfigManager - Network config saved to NVS (%s)", ok ? "ok" : "errors");
return ok;
}
#endif
// ════════════════════════════════════════════════════════════════════════════
// TIME CONFIGURATION PERSISTENCE
// ════════════════════════════════════════════════════════════════════════════
@@ -1259,6 +1426,9 @@ bool ConfigManager::loadGeneralConfig() {
}
bool ConfigManager::saveGeneralConfig() {
#if !HAS_SD_CARD
return saveGeneralConfigToNVS();
#endif
if (!ensureSDCard()) return false;
StaticJsonDocument<256> doc;
@@ -1281,6 +1451,40 @@ bool ConfigManager::saveGeneralConfig() {
return true;
}
// ════════════════════════════════════════════════════════════════════════════
// GENERAL CONFIG — NVS STORAGE (Agnus: no SD card)
// NVS key layout:
// gc_slog — serialLogLevel (u8)
// gc_mlog — mqttLogLevel (u8)
// gc_mqtt — mqttEnabled (u8 bool)
// gc_ota — otaChannel (str)
// Note: sdLogLevel omitted — no SD card on Agnus.
// ════════════════════════════════════════════════════════════════════════════
#if !HAS_SD_CARD
bool ConfigManager::loadGeneralConfigFromNVS() {
generalConfig.serialLogLevel = readNVSU8 ("gc_slog", generalConfig.serialLogLevel);
generalConfig.mqttLogLevel = readNVSU8 ("gc_mlog", generalConfig.mqttLogLevel);
generalConfig.mqttEnabled = readNVSBool ("gc_mqtt", generalConfig.mqttEnabled);
generalConfig.otaChannel = readNVSString("gc_ota", generalConfig.otaChannel);
mqttConfig.enabled = generalConfig.mqttEnabled;
LOG_DEBUG(TAG, "ConfigManager - General config loaded from NVS — serialLog: %d, mqttEnabled: %s, otaCh: %s",
generalConfig.serialLogLevel, generalConfig.mqttEnabled ? "true" : "false",
generalConfig.otaChannel.c_str());
return true;
}
bool ConfigManager::saveGeneralConfigToNVS() {
bool ok = true;
ok &= writeNVSU8 ("gc_slog", generalConfig.serialLogLevel);
ok &= writeNVSU8 ("gc_mlog", generalConfig.mqttLogLevel);
ok &= writeNVSBool ("gc_mqtt", generalConfig.mqttEnabled);
ok &= writeNVSString("gc_ota", generalConfig.otaChannel);
ok &= commitNVS();
LOG_DEBUG(TAG, "ConfigManager - General config saved to NVS (%s)", ok ? "ok" : "errors");
return ok;
}
#endif
// =============================================================================
// HMAC-SHA256 MQTT password derivation
// Password = HMAC-SHA256(MQTT_SECRET, deviceUID), first 16 bytes as hex (32 chars)
+26 -5
View File
@@ -134,8 +134,8 @@ public:
*/
struct UpdateConfig {
String fallbackServerUrls[2] = {
"http://firmware.bellsystems.net", // 🥇 Primary fallback
"http://firmware.bonamin.space" // 🥈 Secondary fallback
"https://firmware.bellsystems.net", // 🥇 Primary fallback
"https://firmware.bonamin.space" // 🥈 Secondary fallback
};
int timeout = 10000; // ⏱️ Universal timeout - OK as is
int retries = 3; // 🔄 Universal retries - OK as is
@@ -272,11 +272,20 @@ private:
bool ensureSDCard();
void createDefaultBellConfig();
// NVS management (READ-ONLY for factory-set device identity)
// NVS management
bool initializeNVS();
bool loadDeviceIdentityFromNVS();
String readNVSString(const char* key, const String& defaultValue);
// REMOVED: saveDeviceIdentityToNVS() and writeNVSString() - Production firmware is READ-ONLY
uint8_t readNVSU8(const char* key, uint8_t defaultValue);
uint16_t readNVSU16(const char* key, uint16_t defaultValue);
bool readNVSBool(const char* key, bool defaultValue);
// NVS write helpers — used by Agnus (no SD card) to persist user config
bool writeNVSString(const char* key, const String& value);
bool writeNVSU8(const char* key, uint8_t value);
bool writeNVSU16(const char* key, uint16_t value);
bool writeNVSBool(const char* key, bool value);
bool commitNVS();
String computeMqttPassword(const String& uid);
@@ -339,16 +348,24 @@ public:
// Network configuration persistence
bool loadNetworkConfig();
bool saveNetworkConfig();
#if !HAS_SD_CARD
bool loadNetworkConfigFromNVS();
bool saveNetworkConfigToNVS();
#endif
// Time configuration persistence
bool loadTimeConfig();
bool saveTimeConfig();
// Bell and clock configuration methods (unchanged)
// Bell and clock configuration methods
bool loadBellDurations();
bool saveBellDurations();
bool loadBellOutputs();
bool saveBellOutputs();
#if !HAS_SD_CARD
bool loadBellConfigFromNVS();
bool saveBellConfigToNVS();
#endif
void updateBellDurations(JsonVariant doc);
void updateBellOutputs(JsonVariant doc);
uint16_t getBellDuration(uint8_t bellIndex) const;
@@ -428,6 +445,10 @@ public:
void setOtaChannel(const String& channel) { generalConfig.otaChannel = channel; }
bool loadGeneralConfig();
bool saveGeneralConfig();
#if !HAS_SD_CARD
bool loadGeneralConfigFromNVS();
bool saveGeneralConfigToNVS();
#endif
// Other methods (unchanged)
void updateClockAlerts(JsonVariant doc);
+2 -2
View File
@@ -79,8 +79,8 @@ ConfigManager has **no dependency on any other application subsystem**. It is th
| Method | Description |
|---|---|
| `String getDeviceUID() const` | Factory-set device UID from NVS |
| `String getHwType() const` | Hardware type code (e.g., `VS` for Vesper) |
| `String getHwVersion() const` | Hardware revision string (e.g., `01`) |
| `String getHwType() const` | Hardware family from NVS (e.g., `vesper`) |
| `String getHwVersion() const` | Hardware revision from NVS (e.g., `01`) |
| `String getFwVersion() const` | Current firmware version string (integer format, e.g., `154`) |
| `void setFwVersion(const String&)` | Updates firmware version in RAM; persist with `saveDeviceConfig()` |
| `String getHardwareVariant() const` | Alias for `getHwType()` |
+4 -9
View File
@@ -28,15 +28,10 @@ bool FileManager::addMelody(JsonVariant doc) {
const char* url = doc["download_url"];
const char* melodyUid = doc["melodys_uid"];
// Check if this is a built-in melody - skip download if it exists
if (BuiltInMelodies::isBuiltInMelody(melodyUid)) {
const BuiltInMelodies::MelodyInfo* builtinMelody = BuiltInMelodies::findMelodyByUID(melodyUid);
if (builtinMelody != nullptr) {
LOG_INFO(TAG, "Melody '%s' is a built-in melody, skipping download", melodyUid);
return true; // Success - no download needed
}
// If starts with builtin_ but not found, log warning and try download anyway
LOG_WARNING(TAG, "Melody '%s' has builtin_ prefix but not found in library, attempting download", melodyUid);
// Check built-in library by PID — skip download if found
if (BuiltInMelodies::findMelodyByPID(melodyUid) != nullptr) {
LOG_INFO(TAG, "Melody '%s' is a built-in, skipping download", melodyUid);
return true;
}
// Download the melody file to /melodies directory
+28 -2
View File
@@ -11,12 +11,17 @@
#include "../OutputManager/OutputManager.hpp"
#include "../Communication/CommunicationRouter/CommunicationRouter.hpp"
#include "../Player/Player.hpp"
#if HAS_RTC
#include "../TimeKeeper/TimeKeeper.hpp"
#endif
#include "../Telemetry/Telemetry.hpp"
#include "../OTAManager/OTAManager.hpp"
#include "../Networking/Networking.hpp"
#include "../ConfigManager/ConfigManager.hpp"
#include "../FileManager/FileManager.hpp"
#if HAS_RF
#include "../RFRemote/RFRemote.hpp"
#endif
#include <ArduinoJson.h>
HealthMonitor::HealthMonitor() {
@@ -68,7 +73,9 @@ void HealthMonitor::initializeSubsystemHealth() {
_subsystemHealth["FileManager"] = SubsystemHealth("FileManager", true);
_subsystemHealth["Communication"] = SubsystemHealth("Communication", false); // Non-critical
_subsystemHealth["Player"] = SubsystemHealth("Player", true);
#if HAS_RTC
_subsystemHealth["TimeKeeper"] = SubsystemHealth("TimeKeeper", false); // Non-critical
#endif
_subsystemHealth["Telemetry"] = SubsystemHealth("Telemetry", false); // Non-critical
_subsystemHealth["OTAManager"] = SubsystemHealth("OTAManager", false); // Non-critical
_subsystemHealth["Networking"] = SubsystemHealth("Networking", false); // Non-critical
@@ -173,14 +180,16 @@ HealthStatus HealthMonitor::performFullHealthCheck() {
checkedSystems++;
}
#if HAS_RTC
// Check TimeKeeper
if (_timeKeeper) {
bool healthy = _timeKeeper->isHealthy();
updateSubsystemHealth("TimeKeeper",
updateSubsystemHealth("TimeKeeper",
healthy ? HealthStatus::HEALTHY : HealthStatus::WARNING,
healthy ? "" : "TimeKeeper health check failed");
checkedSystems++;
}
#endif
// Check Telemetry
if (_telemetry) {
@@ -226,7 +235,18 @@ HealthStatus HealthMonitor::performFullHealthCheck() {
healthy ? "" : "FileManager health check failed");
checkedSystems++;
}
#if HAS_RF
// Check RFRemote — non-critical (system functions without RF)
if (_rfRemote) {
bool healthy = _rfRemote->isHealthy();
updateSubsystemHealth("RFRemote",
healthy ? HealthStatus::HEALTHY : HealthStatus::WARNING,
healthy ? "" : "RFRemote not initialized");
checkedSystems++;
}
#endif
unsigned long elapsed = millis() - startTime;
LOG_VERBOSE(TAG, "🔍 Health check completed: %d systems in %lums", checkedSystems, elapsed);
@@ -252,8 +272,10 @@ HealthStatus HealthMonitor::checkSubsystemHealth(const String& subsystemName) {
healthy = _communication->isHealthy();
} else if (subsystemName == "Player" && _player) {
healthy = _player->isHealthy();
#if HAS_RTC
} else if (subsystemName == "TimeKeeper" && _timeKeeper) {
healthy = _timeKeeper->isHealthy();
#endif
} else if (subsystemName == "Telemetry" && _telemetry) {
healthy = _telemetry->isHealthy();
} else if (subsystemName == "OTAManager" && _otaManager) {
@@ -264,6 +286,10 @@ HealthStatus HealthMonitor::checkSubsystemHealth(const String& subsystemName) {
healthy = _configManager->isHealthy();
} else if (subsystemName == "FileManager" && _fileManager) {
healthy = _fileManager->isHealthy();
#if HAS_RF
} else if (subsystemName == "RFRemote" && _rfRemote) {
healthy = _rfRemote->isHealthy();
#endif
} else {
LOG_WARNING(TAG, "🔌 Subsystem %s not connected to health monitor", subsystemName.c_str());
return HealthStatus::FAILED;
+17
View File
@@ -60,12 +60,17 @@ class BellEngine;
class OutputManager;
class CommunicationRouter;
class Player;
#if HAS_RTC
class Timekeeper;
#endif
class Telemetry;
class OTAManager;
class Networking;
class ConfigManager;
class FileManager;
#if HAS_RF
class RFRemote;
#endif
/**
* @enum HealthStatus
@@ -143,8 +148,10 @@ public:
/** @brief Register Player for monitoring */
void setPlayer(Player* player) { _player = player; }
#if HAS_RTC
/** @brief Register TimeKeeper for monitoring */
void setTimeKeeper(Timekeeper* timeKeeper) { _timeKeeper = timeKeeper; }
#endif
/** @brief Register Telemetry for monitoring */
void setTelemetry(Telemetry* telemetry) { _telemetry = telemetry; }
@@ -160,6 +167,11 @@ public:
/** @brief Register FileManager for monitoring */
void setFileManager(FileManager* fileManager) { _fileManager = fileManager; }
#if HAS_RF
/** @brief Register RFRemote for monitoring */
void setRFRemote(RFRemote* rfRemote) { _rfRemote = rfRemote; }
#endif
// ═══════════════════════════════════════════════════════════════════════════════
// HEALTH CHECK METHODS
@@ -270,12 +282,17 @@ private:
OutputManager* _outputManager = nullptr;
CommunicationRouter* _communication = nullptr;
Player* _player = nullptr;
#if HAS_RTC
Timekeeper* _timeKeeper = nullptr;
#endif
Telemetry* _telemetry = nullptr;
OTAManager* _otaManager = nullptr;
Networking* _networking = nullptr;
ConfigManager* _configManager = nullptr;
FileManager* _fileManager = nullptr;
#if HAS_RF
RFRemote* _rfRemote = nullptr;
#endif
// ═══════════════════════════════════════════════════════════════════════════════
// HEALTH MONITORING STATE
+5 -1
View File
@@ -166,7 +166,11 @@ void Logging::log(LogLevel level, const char* levelStr, const char* tag, const c
// Serial output
if (serialEnabled) {
Serial.printf("[%s][%s] %s\n", levelStr, tag, buffer);
const char* icon = (level == ERROR) ? "🔴" :
(level == WARNING) ? "🟡" :
(level == INFO) ? "🟢" :
(level == DEBUG) ? "🔵" : "⚪";
Serial.printf("%s [%s][%s] %s\n", icon, levelStr, tag, buffer);
}
// MQTT output
+43 -8
View File
@@ -13,7 +13,9 @@ OTAManager::OTAManager(ConfigManager& configManager)
: _configManager(configManager)
, _fileManager(nullptr)
, _player(nullptr)
#if HAS_RTC
, _timeKeeper(nullptr)
#endif
, _telemetry(nullptr)
, _status(Status::IDLE)
, _lastError(ErrorCode::NONE)
@@ -130,9 +132,11 @@ void OTAManager::setPlayer(Player* player) {
_player = player;
}
#if HAS_RTC
void OTAManager::setTimeKeeper(Timekeeper* tk) {
_timeKeeper = tk;
}
#endif
void OTAManager::setTelemetry(Telemetry* telemetry) {
_telemetry = telemetry;
@@ -317,6 +321,7 @@ bool OTAManager::checkVersion(const String& channel) {
HTTPClient http;
http.setTimeout(updateConfig.timeout);
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
http.begin(metadataUrl.c_str());
int retryCount = 0;
@@ -353,8 +358,9 @@ bool OTAManager::checkVersion(const String& channel) {
const char* minVersionStr = doc["min_fw_version"] | "";
_minVersion = (strlen(minVersionStr) > 0) ? SemVer::parse(String(minVersionStr)) : SemVer{0, 0, 0};
_availableChecksum = doc["sha256"] | "";
_expectedFileSize = doc["size"] | (size_t)0;
_availableChecksum = doc["sha256"] | "";
_expectedFileSize = doc["size"] | (size_t)0;
_availableDownloadPath = doc["download_url"] | "";
// update_type: "optional" | "mandatory" | "emergency"
// This is the urgency of the release — completely separate from the channel.
@@ -418,8 +424,16 @@ bool OTAManager::downloadAndInstall(const String& channel) {
String toVersion = _availableVersion.toString();
for (size_t serverIndex = 0; serverIndex < servers.size(); serverIndex++) {
String baseUrl = servers[serverIndex];
String firmwareUrl = buildFirmwareUrl(baseUrl, hwType, channel, toVersion);
String baseUrl = servers[serverIndex];
// Prefer the download_url returned by the server (relative path prepended with baseUrl).
// Fall back to constructing the URL locally if the server didn't return one.
String firmwareUrl;
if (_availableDownloadPath.length() > 0) {
firmwareUrl = baseUrl + _availableDownloadPath;
} else {
firmwareUrl = buildFirmwareUrl(baseUrl, hwType, channel, toVersion);
}
LOG_INFO(TAG, "OTA: Trying firmware download from server %d/%d: %s",
serverIndex + 1, servers.size(), firmwareUrl.c_str());
@@ -442,6 +456,7 @@ bool OTAManager::downloadDirectToFlash(const String& url, size_t expectedSize, c
LOG_INFO(TAG, "OTA: Starting direct-to-flash download (bypassing SD card)");
HTTPClient http;
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
http.begin(url.c_str());
http.setTimeout(30000); // 30 seconds
@@ -479,9 +494,11 @@ bool OTAManager::downloadDirectToFlash(const String& url, size_t expectedSize, c
// ═══════════════════════════════════════════════════════════════════════════
LOG_INFO(TAG, "OTA: Entering freeze mode - pausing TimeKeeper and Telemetry");
#if HAS_RTC
if (_timeKeeper) {
_timeKeeper->pauseClockUpdates();
}
#endif
if (_telemetry) {
_telemetry->pause();
@@ -494,7 +511,9 @@ bool OTAManager::downloadDirectToFlash(const String& url, size_t expectedSize, c
http.end();
// Resume systems
#if HAS_RTC
if (_timeKeeper) _timeKeeper->resumeClockUpdates();
#endif
if (_telemetry) _telemetry->resume();
return false;
@@ -506,7 +525,7 @@ bool OTAManager::downloadDirectToFlash(const String& url, size_t expectedSize, c
// Stream directly to flash with periodic watchdog feeding
WiFiClient* stream = http.getStreamPtr();
uint8_t buffer[4096]; // 4KB buffer for efficient transfer
static uint8_t buffer[4096]; // 4KB buffer — static to avoid blowing the 8KB task stack
size_t written = 0;
size_t lastLoggedPercent = 0;
unsigned long lastWatchdogReset = millis();
@@ -527,7 +546,9 @@ bool OTAManager::downloadDirectToFlash(const String& url, size_t expectedSize, c
http.end();
// Resume systems
#if HAS_RTC
if (_timeKeeper) _timeKeeper->resumeClockUpdates();
#endif
if (_telemetry) _telemetry->resume();
setStatus(Status::FAILED, ErrorCode::WRITE_FAILED);
@@ -544,6 +565,11 @@ bool OTAManager::downloadDirectToFlash(const String& url, size_t expectedSize, c
lastLoggedPercent = currentPercent;
}
}
} else {
// No data available yet — block for 1ms so IDLE0 can run and reset its watchdog.
// yield()/vPortYield() is cooperative and doesn't release the CPU long enough;
// vTaskDelay(1) actually suspends this task for one tick (~1ms).
vTaskDelay(1);
}
// Feed watchdog every 500ms to prevent timeout
@@ -551,9 +577,6 @@ bool OTAManager::downloadDirectToFlash(const String& url, size_t expectedSize, c
esp_task_wdt_reset();
lastWatchdogReset = millis();
}
// Small yield to prevent tight loop
yield();
}
http.end();
@@ -563,9 +586,11 @@ bool OTAManager::downloadDirectToFlash(const String& url, size_t expectedSize, c
// ═══════════════════════════════════════════════════════════════════════════
LOG_INFO(TAG, "OTA: Exiting freeze mode - resuming TimeKeeper and Telemetry");
#if HAS_RTC
if (_timeKeeper) {
_timeKeeper->resumeClockUpdates();
}
#endif
if (_telemetry) {
_telemetry->resume();
@@ -667,9 +692,11 @@ bool OTAManager::downloadToSD(const String& url, const String& expectedChecksum,
// ═══════════════════════════════════════════════════════════════════════════
LOG_INFO(TAG, "OTA: Entering freeze mode - pausing TimeKeeper and Telemetry");
#if HAS_RTC
if (_timeKeeper) {
_timeKeeper->pauseClockUpdates();
}
#endif
if (_telemetry) {
_telemetry->pause();
@@ -679,7 +706,9 @@ bool OTAManager::downloadToSD(const String& url, const String& expectedChecksum,
LOG_INFO(TAG, "OTA: Acquiring SD card mutex for safe file operations");
if (!SDCardMutex::getInstance().lock(10000)) { // 10 second timeout
LOG_ERROR(TAG, "OTA: Failed to acquire SD card mutex!");
#if HAS_RTC
if (_timeKeeper) _timeKeeper->resumeClockUpdates();
#endif
if (_telemetry) _telemetry->resume();
setStatus(Status::FAILED, ErrorCode::DOWNLOAD_FAILED);
http.end();
@@ -702,7 +731,9 @@ bool OTAManager::downloadToSD(const String& url, const String& expectedChecksum,
// Release mutex and resume systems before returning
SDCardMutex::getInstance().unlock();
#if HAS_RTC
if (_timeKeeper) _timeKeeper->resumeClockUpdates();
#endif
if (_telemetry) _telemetry->resume();
setStatus(Status::FAILED, ErrorCode::DOWNLOAD_FAILED);
@@ -737,7 +768,9 @@ bool OTAManager::downloadToSD(const String& url, const String& expectedChecksum,
SDCardMutex::getInstance().unlock();
http.end();
#if HAS_RTC
if (_timeKeeper) _timeKeeper->resumeClockUpdates();
#endif
if (_telemetry) _telemetry->resume();
setStatus(Status::FAILED, ErrorCode::WRITE_FAILED);
@@ -790,9 +823,11 @@ bool OTAManager::downloadToSD(const String& url, const String& expectedChecksum,
// ═══════════════════════════════════════════════════════════════════════════
LOG_INFO(TAG, "OTA: Exiting freeze mode - resuming TimeKeeper and Telemetry");
#if HAS_RTC
if (_timeKeeper) {
_timeKeeper->resumeClockUpdates();
}
#endif
if (_telemetry) {
_telemetry->resume();
+9
View File
@@ -27,12 +27,16 @@
#include <time.h>
#include "../FileManager/FileManager.hpp"
#include "../Telemetry/Telemetry.hpp"
#if HAS_RTC
#include "../TimeKeeper/TimeKeeper.hpp"
#endif
#include "../Version.hpp"
class ConfigManager; // Forward declaration
class Player; // Forward declaration for idle check
#if HAS_RTC
class Timekeeper; // Forward declaration for freeze mode
#endif
class Telemetry; // Forward declaration for freeze mode
class OTAManager {
@@ -72,7 +76,9 @@ public:
void begin();
void setFileManager(FileManager* fm);
void setPlayer(Player* player); // Set player reference for idle check
#if HAS_RTC
void setTimeKeeper(Timekeeper* tk); // Set timekeeper reference for freeze mode
#endif
void setTelemetry(Telemetry* telemetry); // Set telemetry reference for freeze mode
void checkForUpdates();
@@ -112,7 +118,9 @@ private:
ConfigManager& _configManager;
FileManager* _fileManager;
Player* _player; // Player reference for idle check
#if HAS_RTC
Timekeeper* _timeKeeper; // TimeKeeper reference for freeze mode
#endif
Telemetry* _telemetry; // Telemetry reference for freeze mode
Status _status;
ErrorCode _lastError;
@@ -121,6 +129,7 @@ private:
size_t _expectedFileSize; // NEW: Expected firmware file size
bool _updateAvailable;
String _availableChecksum;
String _availableDownloadPath; // Relative path from backend (e.g. /api/firmware/.../firmware.bin)
String _updateChannel;
bool _isMandatory;
bool _isEmergency;
+148 -85
View File
@@ -4,7 +4,9 @@
#include "../Communication/CommunicationRouter/CommunicationRouter.hpp"
#include "../BellEngine/BellEngine.hpp"
#include "../Telemetry/Telemetry.hpp"
#if HAS_RTC
#include "../TimeKeeper/TimeKeeper.hpp" // 🔥 Include for Timekeeper class definition
#endif
#include "../BuiltInMelodies/BuiltInMelodies.hpp"
// Note: Removed global melody_steps dependency for cleaner architecture
@@ -13,7 +15,7 @@
Player::Player(CommunicationRouter* comm, FileManager* fm)
: id(0)
, name("melody1")
, uid("x")
, pid("")
, url("-")
, noteAssignments{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
, speed(500)
@@ -34,7 +36,9 @@ Player::Player(CommunicationRouter* comm, FileManager* fm)
, _fileManager(fm)
, _bellEngine(nullptr)
, _telemetry(nullptr)
#if HAS_RTC
, _timekeeper(nullptr)
#endif
, _durationTimerHandle(NULL) {
}
@@ -42,7 +46,7 @@ Player::Player(CommunicationRouter* comm, FileManager* fm)
Player::Player()
: id(0)
, name("melody1")
, uid("x")
, pid("")
, url("-")
, noteAssignments{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
, speed(500)
@@ -63,7 +67,9 @@ Player::Player()
, _fileManager(nullptr)
, _bellEngine(nullptr)
, _telemetry(nullptr)
#if HAS_RTC
, _timekeeper(nullptr)
#endif
, _durationTimerHandle(NULL) {
}
@@ -88,7 +94,7 @@ Player::~Player() {
void Player::begin() {
LOG_INFO(TAG, "Initializing Player with FreeRTOS Timer (saves 4KB RAM!)");
// Create a periodic timer that fires every 500ms
_durationTimerHandle = xTimerCreate(
"PlayerTimer", // Timer name
@@ -97,13 +103,17 @@ void Player::begin() {
this, // Timer ID (pass Player instance)
durationTimerCallback // Callback function
);
if (_durationTimerHandle != NULL) {
xTimerStart(_durationTimerHandle, 0);
LOG_INFO(TAG, "Player initialized successfully with timer");
} else {
LOG_ERROR(TAG, "Failed to create Player timer!");
}
// Dedicated task handles deferred stop/pause/resume triggered by the timer callback.
// Timer callbacks run on Tmr Svc (tiny stack) so we must not do MQTT/WS work there.
xTaskCreate(playerControlTaskFn, "PlayerCtrl", 4096, this, 2, NULL);
}
void Player::play() {
@@ -112,11 +122,13 @@ void Player::play() {
return;
}
#if HAS_RTC
// 🔥 CRITICAL: Interrupt any active clock alerts - user playback has priority!
if (_timekeeper) {
_timekeeper->interruptActiveAlert();
LOG_DEBUG(TAG, "Player: Interrupted any active clock alerts");
}
#endif
if (_bellEngine) {
_bellEngine->setMelodyData(_melodySteps);
@@ -187,31 +199,40 @@ void Player::unpause() {
}
bool Player::command(JsonVariant data) {
setMelodyAttributes(data);
loadMelodyInRAM(); // Removed parameter - use internal storage
String action = data["action"];
LOG_DEBUG(TAG, "Incoming Command: %s", action.c_str());
// Play or Stop Logic
if (action == "play") {
play();
return true;
} else if (action == "stop") {
forceStop();
return true;
} else {
LOG_WARNING(TAG, "Unknown playback action: %s", action.c_str());
// While playing or stopping, only a stop command is accepted
if (_status != PlayerStatus::STOPPED) {
if (action == "stop") {
forceStop();
return true;
}
LOG_WARNING(TAG, "Command '%s' rejected — playback in progress", action.c_str());
return false;
}
setMelodyAttributes(data);
if (action == "play") {
if (!loadMelodyInRAM()) {
LOG_WARNING(TAG, "Play command aborted — melody '%s' could not be loaded", pid.c_str());
return false;
}
play();
return true;
}
LOG_WARNING(TAG, "Unknown playback action: %s", action.c_str());
return false;
}
void Player::setMelodyAttributes(JsonVariant doc) {
if (doc.containsKey("name")) {
name = doc["name"].as<const char*>();
}
if (doc.containsKey("uid")) {
uid = doc["uid"].as<const char*>();
if (doc.containsKey("pid")) {
pid = doc["pid"].as<const char*>();
}
if (doc.containsKey("url")) {
url = doc["url"].as<const char*>();
@@ -235,65 +256,69 @@ void Player::setMelodyAttributes(JsonVariant doc) {
if (doc.containsKey("total_duration")) {
total_duration = doc["total_duration"].as<uint32_t>();
}
if (doc.containsKey("continuous_loop")) {
continuous_loop = doc["continuous_loop"].as<bool>();
}
// Default to false — missing key must not carry over a previous true value
continuous_loop = doc.containsKey("continuous_loop") && doc["continuous_loop"].as<bool>();
// Recalculate infinite_play based on current values (reset first!)
infinite_play = (continuous_loop && total_duration == 0);
if (!continuous_loop) {
// If total_duration was not explicitly sent, derive it from segment_duration.
// If total_duration WAS sent, it takes precedence regardless of continuous_loop.
bool hasTotalDuration = doc.containsKey("total_duration");
bool hasSegmentDuration = doc.containsKey("segment_duration");
if (!hasTotalDuration && hasSegmentDuration) {
total_duration = segment_duration;
}
// Recalculate infinite_play based on final values
infinite_play = (continuous_loop && total_duration == 0);
// Print Just for Debugging Purposes
LOG_DEBUG(TAG, "Set Melody Vars / Name: %s, UID: %s",
name.c_str(), uid.c_str());
LOG_DEBUG(TAG, "Set Melody Vars / Name: %s, PID: %s",
name.c_str(), pid.c_str());
LOG_DEBUG(TAG, "URL: %s", url.c_str());
LOG_DEBUG(TAG, "Speed: %d, Per Segment Duration: %lu, Pause Duration: %lu, Total Duration: %d, Continuous: %s, Infinite: %s",
speed, segment_duration, pause_duration, total_duration,
continuous_loop ? "true" : "false", infinite_play ? "true" : "false");
}
void Player::loadMelodyInRAM() {
String uidStr = String(uid.c_str());
bool Player::loadMelodyInRAM() {
_melodySteps.clear(); // Always start clean — never play stale data from a previous command
String pidStr = String(pid.c_str());
// 🎵 PRIORITY 1: Check if this is a built-in melody
if (BuiltInMelodies::isBuiltInMelody(uidStr)) {
LOG_INFO(TAG, "Loading built-in melody: %s", uidStr.c_str());
if (BuiltInMelodies::loadBuiltInMelody(uidStr, _melodySteps)) {
LOG_INFO(TAG, "✅ Built-in melody loaded successfully: %d steps", _melodySteps.size());
return;
} else {
LOG_ERROR(TAG, "Failed to load built-in melody: %s", uidStr.c_str());
return;
}
// 🎵 PRIORITY 1: Check built-in library by PID (exact match, no prefix required)
if (BuiltInMelodies::loadBuiltInMelody(pidStr, _melodySteps)) {
LOG_INFO(TAG, "Built-in melody loaded: %s (%d steps)", pidStr.c_str(), _melodySteps.size());
return true;
}
// 🎵 PRIORITY 2: Load from SD card
String filePath = "/melodies/" + uidStr;
String filePath = "/melodies/" + pidStr;
File bin_file = SD.open(filePath.c_str(), FILE_READ);
if (!bin_file) {
LOG_ERROR(TAG, "Failed to open file: %s", filePath.c_str());
LOG_ERROR(TAG, "Check Servers for the File...");
// Try to download the file using FileManager
if (!bin_file) {
// 🎵 PRIORITY 3: Try to download using the provided URL
if (url.empty() || url == "-") {
LOG_ERROR(TAG, "Melody '%s' not found in built-ins or SD, and no download URL provided", pidStr.c_str());
return false;
}
LOG_INFO(TAG, "Melody '%s' not on SD, attempting download", pidStr.c_str());
if (_fileManager) {
StaticJsonDocument<128> doc;
doc["download_url"] = url;
doc["melodys_uid"] = uid;
doc["download_url"] = url.c_str();
doc["melodys_uid"] = pidStr;
if (!_fileManager->addMelody(doc)) {
LOG_ERROR(TAG, "Failed to Download File. Check Internet Connection");
return;
} else {
bin_file = SD.open(filePath.c_str(), FILE_READ);
LOG_ERROR(TAG, "Download failed for '%s'", pidStr.c_str());
return false;
}
bin_file = SD.open(filePath.c_str(), FILE_READ);
if (!bin_file) {
LOG_ERROR(TAG, "File still not found after download: %s", filePath.c_str());
return false;
}
} else {
LOG_ERROR(TAG, "FileManager not available for download");
return;
LOG_ERROR(TAG, "FileManager not available, cannot download '%s'", pidStr.c_str());
return false;
}
}
@@ -301,49 +326,77 @@ void Player::loadMelodyInRAM() {
if (fileSize % 2 != 0) {
LOG_ERROR(TAG, "Invalid file size: %u (not a multiple of 2)", fileSize);
bin_file.close();
return;
return false;
}
// Load into Player's internal melody storage only
_melodySteps.resize(fileSize / 2);
for (size_t i = 0; i < _melodySteps.size(); i++) {
uint8_t high = bin_file.read();
uint8_t low = bin_file.read();
_melodySteps[i] = (high << 8) | low;
}
LOG_INFO(TAG, "Melody loaded successfully from SD: %d steps", _melodySteps.size());
LOG_INFO(TAG, "Melody loaded from SD: %s (%d steps)", pidStr.c_str(), _melodySteps.size());
bin_file.close();
return true;
}
// Static timer callback function for FreeRTOS
// Static timer callback — runs on Tmr Svc (tiny stack).
// Only set flags; the playerControlTask does the real work.
void Player::durationTimerCallback(TimerHandle_t xTimer) {
// Get Player instance from timer ID
Player* player = static_cast<Player*>(pvTimerGetTimerID(xTimer));
// Only run checks when actually playing
if (!player->isPlaying) {
return;
}
unsigned long now = millis();
if (player->timeToStop(now)) {
player->stop();
player->_pendingStop = true;
} else if (player->timeToPause(now)) {
player->pause();
player->_pendingPause = true;
} else if (player->timeToResume(now)) {
player->unpause();
player->_pendingResume = true;
}
}
// Deferred task — executes stop/pause/resume outside the timer service context.
void Player::playerControlTaskFn(void* pvParameters) {
Player* player = static_cast<Player*>(pvParameters);
for (;;) {
if (player->_pendingStop) {
player->_pendingStop = false;
if (player->_pendingStopReason) {
LOG_DEBUG(TAG, "%s", player->_pendingStopReason);
player->_pendingStopReason = nullptr;
}
player->stop();
} else if (player->_pendingPause) {
player->_pendingPause = false;
if (player->_pendingPauseReason) {
LOG_DEBUG(TAG, "%s", player->_pendingPauseReason);
player->_pendingPauseReason = nullptr;
}
player->pause();
} else if (player->_pendingResume) {
player->_pendingResume = false;
if (player->_pendingResumeReason) {
LOG_DEBUG(TAG, "%s", player->_pendingResumeReason);
player->_pendingResumeReason = nullptr;
}
player->unpause();
}
vTaskDelay(pdMS_TO_TICKS(50));
}
}
// Check if it's time to stop playback
bool Player::timeToStop(unsigned long now) {
if (isPlaying && !infinite_play) {
uint64_t stopTime = startTime + total_duration;
if (now >= stopTime) {
LOG_DEBUG(TAG, "(TimerFunction) Total Run Duration Reached. Soft Stopping.");
if (isPlaying && !infinite_play && total_duration > 0) {
uint64_t stopTime = startTime + (uint64_t)total_duration;
if ((uint64_t)now >= stopTime) {
_pendingStopReason = "Total run duration reached — soft stopping";
return true;
}
}
@@ -400,24 +453,32 @@ void Player::setStatus(PlayerStatus newStatus) {
}
void Player::onMelodyLoopCompleted() {
// This is called by BellEngine when a melody loop actually finishes
if (_status == PlayerStatus::STOPPING) {
// We were in soft stop mode, now actually stop
setStatus(PlayerStatus::STOPPED);
LOG_DEBUG(TAG, "Plbck: ACTUAL STOP (melody loop completed)");
}
// Mark segment completion time
segmentCmpltTime = millis();
if (_status == PlayerStatus::STOPPING) {
// Timer already decided to stop — finalize now that the loop is done
setStatus(PlayerStatus::STOPPED);
LOG_DEBUG(TAG, "Plbck: ACTUAL STOP (melody loop completed)");
return;
}
// Play-once mode: total_duration=0 with no continuous_loop → stop after first loop.
// We are already at the end of the loop, so go directly to STOPPED (not STOPPING).
if (isPlaying && !continuous_loop && total_duration == 0) {
LOG_DEBUG(TAG, "Plbck: Play-once complete — stopped");
if (_bellEngine) _bellEngine->stop();
isPlaying = false;
setStatus(PlayerStatus::STOPPED);
if (_telemetry) _telemetry->saveStrikeCounters();
}
}
// Check if it's time to pause playback
bool Player::timeToPause(unsigned long now) {
if (isPlaying && continuous_loop) {
uint64_t timeToPause = segmentStartTime + segment_duration;
LOG_DEBUG(TAG, "PTL: %llu // NOW: %lu", timeToPause, now);
if (now >= timeToPause && !isPaused) {
LOG_DEBUG(TAG, "(TimerFunction) Segment Duration Reached. Pausing.");
uint64_t timeToPause = segmentStartTime + (uint64_t)segment_duration;
if ((uint64_t)now >= timeToPause && !isPaused) {
_pendingPauseReason = "Segment duration reached — pausing";
pauseTime = now;
return true;
}
@@ -428,9 +489,9 @@ bool Player::timeToPause(unsigned long now) {
// Check if it's time to resume playback
bool Player::timeToResume(unsigned long now) {
if (isPaused) {
uint64_t timeToResume = segmentCmpltTime + pause_duration;
if (now >= timeToResume) {
LOG_DEBUG(TAG, "(TimerFunction) Pause Duration Reached. Resuming");
uint64_t timeToResume = segmentCmpltTime + (uint64_t)pause_duration;
if ((uint64_t)now >= timeToResume) {
_pendingResumeReason = "Pause duration reached — resuming";
segmentStartTime = now; // Reset segment start time for next cycle
return true;
}
@@ -472,10 +533,12 @@ bool Player::isHealthy() const {
return false;
}
#if HAS_SD_CARD
if (!_fileManager) {
LOG_DEBUG(TAG, "Player: Unhealthy - File manager not set");
return false;
}
#endif
if (!_bellEngine) {
LOG_DEBUG(TAG, "Player: Unhealthy - BellEngine not set");
+20 -3
View File
@@ -133,11 +133,13 @@ public:
*/
void setTelemetry(Telemetry* telemetry) { _telemetry = telemetry; }
#if HAS_RTC
/**
* @brief Set Timekeeper reference for alert coordination
* @param timekeeper Pointer to Timekeeper instance
*/
void setTimekeeper(class Timekeeper* timekeeper) { _timekeeper = timekeeper; }
#endif
// ═══════════════════════════════════════════════════════════════════════════════
// MELODY METADATA - Public access for compatibility
@@ -145,7 +147,7 @@ public:
uint16_t id; // 🏷️ Internal ID of the selected melody
std::string name; // 🏵️ Display name of the melody
std::string uid; // 🆔 Unique identifier from Firestore
std::string pid; // 🆔 Playback ID
std::string url; // 🌐 Download URL for melody binary
uint16_t noteAssignments[16]; // 🎹 Note-to-bell mapping configuration
@@ -209,11 +211,14 @@ public:
/** @brief Set melody attributes from JSON configuration */
void setMelodyAttributes(JsonVariant doc);
/** @brief Load melody data into RAM for playback */
void loadMelodyInRAM();
/** @brief Load melody data into RAM for playback. Returns false if melody could not be loaded. */
bool loadMelodyInRAM();
/** @brief Static timer callback for FreeRTOS duration control */
static void durationTimerCallback(TimerHandle_t xTimer);
/** @brief Static task function for deferred playback control */
static void playerControlTaskFn(void* pvParameters);
// ═════════════════════════════════════════════════════════════════════════════════
// STATUS QUERY METHODS
@@ -255,10 +260,22 @@ private:
FileManager* _fileManager; // 📁 File operations reference
BellEngine* _bellEngine; // 🔥 High-precision timing engine reference
Telemetry* _telemetry; // 📄 Telemetry system reference
#if HAS_RTC
class Timekeeper* _timekeeper; // ⏰ Timekeeper reference for alert coordination
#endif
std::vector<uint16_t> _melodySteps; // 🎵 Melody data owned by Player
TimerHandle_t _durationTimerHandle = NULL; // ⏱️ FreeRTOS timer (saves 4KB vs task!)
// Deferred action flags set by timer callback, executed by playerControlTask
volatile bool _pendingStop = false;
volatile bool _pendingPause = false;
volatile bool _pendingResume = false;
// Reason strings for deferred log messages (set in timer context, logged in task context)
const char* _pendingStopReason = nullptr;
const char* _pendingPauseReason = nullptr;
const char* _pendingResumeReason = nullptr;
// ═══════════════════════════════════════════════════════════════════════════════
// PRIVATE HELPER METHODS
+401
View File
@@ -0,0 +1,401 @@
#include "RFRemote.hpp"
#if HAS_RF
#include <ArduinoJson.h>
#include "../Player/Player.hpp"
#include "../Logging/Logging.hpp"
#define TAG "RFRemote"
RFRemote* RFRemote::_instance = nullptr;
// ─────────────────────────────────────────────────────────────────────────────
// Constructor / Destructor
// ─────────────────────────────────────────────────────────────────────────────
RFRemote::RFRemote() {
_instance = this;
// Slots start zeroed — all empty. loadConfig() fills them from NVS.
}
RFRemote::~RFRemote() {
end();
_instance = nullptr;
}
// ─────────────────────────────────────────────────────────────────────────────
// begin()
// ─────────────────────────────────────────────────────────────────────────────
bool RFRemote::begin(Player* player) {
_player = player;
loadConfig();
_switch.enableReceive(RF_RX_PIN);
LOG_INFO(TAG, "RF receiver attached to GPIO %d", RF_RX_PIN);
_cmdQueue = xQueueCreate(4, sizeof(PendingCommand));
if (!_cmdQueue) {
LOG_ERROR(TAG, "Failed to create RF command queue");
return false;
}
BaseType_t result = xTaskCreatePinnedToCore(
taskFunction,
"RFRemote",
TASK_STACK,
this,
TASK_PRIO,
&_taskHandle,
0
);
if (result != pdPASS) {
LOG_ERROR(TAG, "Failed to create RF polling task");
return false;
}
result = xTaskCreatePinnedToCore(
dispatchTaskFunction,
"RFDispatch",
DISPATCH_STACK,
this,
TASK_PRIO,
&_dispatchHandle,
0
);
if (result != pdPASS) {
LOG_ERROR(TAG, "Failed to create RF dispatch task");
return false;
}
_initialized = true;
LOG_INFO(TAG, "RFRemote initialized — %d slots loaded, enabled=%s",
SLOT_COUNT, _enabled ? "yes" : "no");
return true;
}
// ─────────────────────────────────────────────────────────────────────────────
// end()
// ─────────────────────────────────────────────────────────────────────────────
void RFRemote::end() {
if (_taskHandle) {
vTaskDelete(_taskHandle);
_taskHandle = nullptr;
}
if (_dispatchHandle) {
vTaskDelete(_dispatchHandle);
_dispatchHandle = nullptr;
}
if (_cmdQueue) {
vQueueDelete(_cmdQueue);
_cmdQueue = nullptr;
}
_switch.disableReceive();
_prefs.end();
_initialized = false;
}
// ─────────────────────────────────────────────────────────────────────────────
// enable()
// ─────────────────────────────────────────────────────────────────────────────
void RFRemote::enable(bool enabled) {
_enabled = enabled;
LOG_INFO(TAG, "RF remote %s", enabled ? "enabled" : "disabled");
}
// ─────────────────────────────────────────────────────────────────────────────
// Slot access
// ─────────────────────────────────────────────────────────────────────────────
const RFRemote::RFSlot& RFRemote::getSlot(uint8_t slot) const {
static const RFSlot empty;
if (slot >= SLOT_COUNT) return empty;
return _slots[slot];
}
void RFRemote::setSlot(uint8_t slot, const RFSlot& s) {
if (slot >= SLOT_COUNT) return;
_slots[slot] = s;
// Reset press state for this slot so a stale window doesn't carry over
_state[slot] = {};
saveSlot(slot);
}
void RFRemote::clearSlot(uint8_t slot) {
if (slot >= SLOT_COUNT) return;
_slots[slot] = RFSlot{};
_state[slot] = {};
eraseSlot(slot);
}
void RFRemote::clearAllSlots() {
for (uint8_t i = 0; i < SLOT_COUNT; i++) {
_slots[i] = RFSlot{};
_state[i] = {};
}
// Wipe the entire "rf" namespace
_prefs.begin(NVS_NAMESPACE, false);
_prefs.clear();
_prefs.end();
LOG_INFO(TAG, "All RF slots cleared");
}
// ─────────────────────────────────────────────────────────────────────────────
// Config persistence — NVS namespace "rf"
// Key format: rf_s<N>_code / uid / spd / dur / na / stop (N = 0–15)
// ─────────────────────────────────────────────────────────────────────────────
bool RFRemote::loadConfig() {
if (!_prefs.begin(NVS_NAMESPACE, true)) { // read-only
LOG_WARNING(TAG, "NVS namespace '%s' not found — all slots empty", NVS_NAMESPACE);
return false;
}
_enabled = _prefs.getBool("enabled", true);
uint8_t loaded = 0;
for (uint8_t i = 0; i < SLOT_COUNT; i++) {
char key[12];
snprintf(key, sizeof(key), "s%d_code", i);
uint32_t code = _prefs.getUInt(key, 0);
if (code == 0) continue; // slot is empty
_slots[i].rf_code = code;
snprintf(key, sizeof(key), "s%d_uid", i);
_slots[i].melody_uid = _prefs.getString(key, "");
snprintf(key, sizeof(key), "s%d_spd", i);
_slots[i].speed = (uint16_t)_prefs.getUInt(key, 500);
snprintf(key, sizeof(key), "s%d_dur", i);
_slots[i].duration = _prefs.getUInt(key, 30000);
snprintf(key, sizeof(key), "s%d_na", i);
String naStr = _prefs.getString(key, "");
unpackNoteAssignments(naStr, _slots[i].note_assignments);
snprintf(key, sizeof(key), "s%d_stop", i);
_slots[i].is_stop = _prefs.getBool(key, false);
loaded++;
}
_prefs.end();
LOG_INFO(TAG, "RF config loaded from NVS — %d slot(s) active, enabled=%s",
loaded, _enabled ? "yes" : "no");
return true;
}
bool RFRemote::saveSlot(uint8_t slot) {
if (slot >= SLOT_COUNT) return false;
const RFSlot& s = _slots[slot];
if (!_prefs.begin(NVS_NAMESPACE, false)) {
LOG_ERROR(TAG, "Cannot open NVS namespace '%s' for writing", NVS_NAMESPACE);
return false;
}
char key[12];
snprintf(key, sizeof(key), "s%d_code", slot);
_prefs.putUInt(key, s.rf_code);
snprintf(key, sizeof(key), "s%d_uid", slot);
_prefs.putString(key, s.melody_uid);
snprintf(key, sizeof(key), "s%d_spd", slot);
_prefs.putUInt(key, s.speed);
snprintf(key, sizeof(key), "s%d_dur", slot);
_prefs.putUInt(key, s.duration);
snprintf(key, sizeof(key), "s%d_na", slot);
_prefs.putString(key, packNoteAssignments(s.note_assignments));
snprintf(key, sizeof(key), "s%d_stop", slot);
_prefs.putBool(key, s.is_stop);
_prefs.end();
LOG_INFO(TAG, "Slot %d saved to NVS (code=%lu, uid='%s', stop=%s)",
slot, (unsigned long)s.rf_code, s.melody_uid.c_str(), s.is_stop ? "yes" : "no");
return true;
}
bool RFRemote::eraseSlot(uint8_t slot) {
if (slot >= SLOT_COUNT) return false;
if (!_prefs.begin(NVS_NAMESPACE, false)) {
LOG_ERROR(TAG, "Cannot open NVS namespace '%s' for writing", NVS_NAMESPACE);
return false;
}
char key[12];
const char* suffixes[] = { "code", "uid", "spd", "dur", "na", "stop" };
for (const char* sfx : suffixes) {
snprintf(key, sizeof(key), "s%d_%s", slot, sfx);
_prefs.remove(key);
}
_prefs.end();
LOG_INFO(TAG, "Slot %d erased from NVS", slot);
return true;
}
// ─────────────────────────────────────────────────────────────────────────────
// Note assignment pack / unpack
// Format: "1,2,3,4,5,6,0,0,0,0,0,0,0,0,0,0"
// ─────────────────────────────────────────────────────────────────────────────
String RFRemote::packNoteAssignments(const uint8_t* na) {
String s;
s.reserve(48);
for (uint8_t i = 0; i < NOTE_ASSIGNMENT_COUNT; i++) {
if (i > 0) s += ',';
s += String(na[i]);
}
return s;
}
void RFRemote::unpackNoteAssignments(const String& s, uint8_t* na) {
memset(na, 0, NOTE_ASSIGNMENT_COUNT);
if (s.length() == 0) return;
uint8_t idx = 0;
int start = 0;
for (int i = 0; i <= (int)s.length() && idx < NOTE_ASSIGNMENT_COUNT; i++) {
if (i == (int)s.length() || s.charAt(i) == ',') {
na[idx++] = (uint8_t)s.substring(start, i).toInt();
start = i + 1;
}
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Task entry points
// ─────────────────────────────────────────────────────────────────────────────
void RFRemote::taskFunction(void* parameter) {
static_cast<RFRemote*>(parameter)->pollLoop();
}
void RFRemote::dispatchTaskFunction(void* parameter) {
static_cast<RFRemote*>(parameter)->dispatchLoop();
}
// ─────────────────────────────────────────────────────────────────────────────
// Poll loop — lightweight, never calls Player
// ─────────────────────────────────────────────────────────────────────────────
void RFRemote::pollLoop() {
for (;;) {
vTaskDelay(pdMS_TO_TICKS(POLL_MS));
if (!_enabled) continue;
if (!_switch.available()) continue;
uint32_t code = (uint32_t)_switch.getReceivedValue();
_switch.resetAvailable();
if (code == 0) continue;
int8_t slot = codeToSlot(code);
if (slot < 0) {
LOG_VERBOSE(TAG, "Unknown RF code: %lu", (unsigned long)code);
continue;
}
LOG_VERBOSE(TAG, "RF code %lu -> slot %d (stop=%s)",
(unsigned long)code, slot, _slots[slot].is_stop ? "yes" : "no");
if (_slots[slot].is_stop) {
PendingCommand cmd{ PendingCommand::Type::STOP, (uint8_t)slot };
xQueueSend(_cmdQueue, &cmd, 0);
continue;
}
// Play slot: long-press detection via sliding window
uint32_t now = millis();
if (_state[slot].count == 0 || (now - _state[slot].firstSeen) > LONG_PRESS_WINDOW_MS) {
_state[slot].count = 1;
_state[slot].firstSeen = now;
} else {
_state[slot].count++;
}
if (_state[slot].count >= LONG_PRESS_COUNT) {
_state[slot].count = 0;
PendingCommand cmd{ PendingCommand::Type::PLAY, (uint8_t)slot };
xQueueSend(_cmdQueue, &cmd, 0);
}
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Dispatch loop — blocks on queue, executes Player calls
// ─────────────────────────────────────────────────────────────────────────────
void RFRemote::dispatchLoop() {
PendingCommand cmd;
for (;;) {
if (xQueueReceive(_cmdQueue, &cmd, portMAX_DELAY) == pdTRUE) {
if (cmd.type == PendingCommand::Type::STOP) {
triggerStop();
} else {
triggerPlay(cmd.slot);
}
}
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Trigger helpers
// ─────────────────────────────────────────────────────────────────────────────
int8_t RFRemote::codeToSlot(uint32_t code) const {
for (uint8_t i = 0; i < SLOT_COUNT; i++) {
if (_slots[i].rf_code != 0 && _slots[i].rf_code == code) return (int8_t)i;
}
return -1;
}
void RFRemote::triggerPlay(uint8_t slot) {
if (!_player) return;
const RFSlot& s = _slots[slot];
if (s.melody_uid.length() == 0) {
LOG_WARNING(TAG, "Slot %d: no melody UID — ignoring", slot);
return;
}
LOG_INFO(TAG, "RF slot %d -> play '%s' speed=%d dur=%lu",
slot, s.melody_uid.c_str(), s.speed, (unsigned long)s.duration);
JsonDocument doc;
doc["action"] = "play";
doc["pid"] = s.melody_uid;
doc["speed"] = s.speed;
doc["segment_duration"] = s.duration;
doc["continuous_loop"] = false;
// Pass note assignments as a 16-element array
JsonArray na = doc["note_assignments"].to<JsonArray>();
for (uint8_t i = 0; i < NOTE_ASSIGNMENT_COUNT; i++) {
na.add(s.note_assignments[i]);
}
_player->command(doc.as<JsonVariant>());
}
void RFRemote::triggerStop() {
if (!_player) return;
LOG_INFO(TAG, "RF stop slot triggered -> force stop");
_player->forceStop();
}
#endif // HAS_RF
+200
View File
@@ -0,0 +1,200 @@
/*
* ═══════════════════════════════════════════════════════════════════════════════════
* RFREMOTE.HPP - RF Remote Control Receiver
* ═══════════════════════════════════════════════════════════════════════════════════
*
* Manages a 433 MHz RF remote receiver via RCSwitch.
*
* SLOT MODEL:
* Up to 16 independent slots. Each slot stores one RF trigger code and a
* complete playback action (melody UID, speed, duration, note assignments).
* A slot with is_stop=true acts as a stop trigger instead of playing.
* Slots are empty (rf_code=0) by default — nothing is pre-seeded.
* This allows any remote layout: 2×8-button, 8×2-button, 1×16-button, etc.
*
* BUTTON BEHAVIOUR:
* Play slots — Long-press trigger: same code received ≥ LONG_PRESS_COUNT times
* within LONG_PRESS_WINDOW_MS → initiates melody playback.
* Stop slots — Single receipt of the stop code immediately calls Player::forceStop().
*
* CONFIG STORAGE:
* Always NVS, namespace "rf", regardless of HAS_SD_CARD.
* Keys: rf_s<N>_code, rf_s<N>_uid, rf_s<N>_spd, rf_s<N>_dur, rf_s<N>_na, rf_s<N>_stop
* (N = 0-indexed slot number, 0–15)
*
* TASK ARCHITECTURE:
* Two FreeRTOS tasks on Core 0:
* - RFRemote (poll): lightweight — reads RCSwitch, manages press windows.
* Never calls into Player. Enqueues PendingCommand to _cmdQueue on trigger.
* - RFDispatch: blocks on _cmdQueue and executes Player calls with a full stack.
* enable(false) suspends processing without killing either task.
* HAS_RF 0 strips the entire subsystem at compile time.
* ═══════════════════════════════════════════════════════════════════════════════════
*/
#pragma once
#if HAS_RF
#include <Arduino.h>
#include <RCSwitch.h>
#include <Preferences.h>
// Forward declarations
class Player;
class RFRemote {
public:
// ──────────────────────────────────────────────────────────────────────────
// Public types
// ──────────────────────────────────────────────────────────────────────────
static constexpr uint8_t SLOT_COUNT = 16;
static constexpr uint8_t NOTE_ASSIGNMENT_COUNT = 16;
static constexpr uint8_t LONG_PRESS_COUNT = 6;
static constexpr uint32_t LONG_PRESS_WINDOW_MS = 3000;
/**
* @brief One RF slot: a trigger code + a complete playback action.
*
* rf_code == 0 means the slot is empty/unused.
* is_stop == true: receiving rf_code calls Player::forceStop() (single press).
* is_stop == false: receiving rf_code triggers playback (long-press required).
*
* note_assignments mirrors Player::noteAssignments:
* Index = melody note slot (0-based), value = physical bell output (1-indexed, 0 = unused).
* e.g. [1,2,3,1,2,3,0,...] plays a 6-note melody on bells 1–3, doubled.
*/
struct RFSlot {
uint32_t rf_code = 0;
String melody_uid = "";
uint16_t speed = 500; // ms per beat
uint32_t duration = 30000; // total playback ms (0 = play to end)
uint8_t note_assignments[NOTE_ASSIGNMENT_COUNT] = {};
bool is_stop = false;
bool isEmpty() const { return rf_code == 0; }
};
// ──────────────────────────────────────────────────────────────────────────
// Constructor & lifecycle
// ──────────────────────────────────────────────────────────────────────────
RFRemote();
~RFRemote();
/**
* @brief Initialize receiver and start the polling task.
* @param player Player instance for playback control.
* @return true if initialization succeeded.
*/
bool begin(Player* player);
/** @brief Stop the polling task and release hardware. */
void end();
// ──────────────────────────────────────────────────────────────────────────
// Runtime control
// ──────────────────────────────────────────────────────────────────────────
void enable(bool enabled);
bool isEnabled() const { return _enabled; }
bool isHealthy() const { return _initialized; }
// ──────────────────────────────────────────────────────────────────────────
// Slot access
// ──────────────────────────────────────────────────────────────────────────
/** @brief Get a slot (0-indexed). Returns an empty slot if out of range. */
const RFSlot& getSlot(uint8_t slot) const;
/**
* @brief Set a slot (0-indexed) and persist to NVS immediately.
* Passing a slot with rf_code==0 is equivalent to clearSlot().
*/
void setSlot(uint8_t slot, const RFSlot& s);
/** @brief Clear a single slot (0-indexed) and remove from NVS. */
void clearSlot(uint8_t slot);
/** @brief Clear all 16 slots and remove all RF keys from NVS. */
void clearAllSlots();
// ──────────────────────────────────────────────────────────────────────────
// Config persistence
// ──────────────────────────────────────────────────────────────────────────
bool loadConfig();
bool saveSlot(uint8_t slot);
bool eraseSlot(uint8_t slot);
private:
// ──────────────────────────────────────────────────────────────────────────
// Per-slot press tracking (play slots only)
// ──────────────────────────────────────────────────────────────────────────
struct SlotState {
uint8_t count = 0;
uint32_t firstSeen = 0;
};
// ──────────────────────────────────────────────────────────────────────────
// Member variables
// ──────────────────────────────────────────────────────────────────────────
RCSwitch _switch;
Player* _player = nullptr;
Preferences _prefs;
bool _initialized = false;
bool _enabled = true;
RFSlot _slots[SLOT_COUNT] = {};
SlotState _state[SLOT_COUNT] = {};
// Command queued from poll task to dispatcher task
struct PendingCommand {
enum class Type : uint8_t { PLAY, STOP } type;
uint8_t slot; // 0-indexed; only meaningful for PLAY
};
// FreeRTOS tasks & queue
TaskHandle_t _taskHandle = nullptr;
TaskHandle_t _dispatchHandle = nullptr;
QueueHandle_t _cmdQueue = nullptr;
static constexpr uint32_t TASK_STACK = 3072;
static constexpr uint32_t DISPATCH_STACK = 5120;
static constexpr UBaseType_t TASK_PRIO = 2;
static constexpr uint32_t POLL_MS = 50;
static constexpr const char* NVS_NAMESPACE = "rf";
static RFRemote* _instance;
// ──────────────────────────────────────────────────────────────────────────
// Private helpers
// ──────────────────────────────────────────────────────────────────────────
/** @brief Map a received raw code to a 0-indexed slot number (-1 = unknown). */
int8_t codeToSlot(uint32_t code) const;
/** @brief Execute a confirmed long-press play — called from dispatcher task. */
void triggerPlay(uint8_t slot);
/** @brief Execute a stop — called from dispatcher task. */
void triggerStop();
/** @brief Pack note_assignments[16] to a compact comma-separated string. */
static String packNoteAssignments(const uint8_t* na);
/** @brief Unpack comma-separated string back into note_assignments[16]. */
static void unpackNoteAssignments(const String& s, uint8_t* na);
static void taskFunction(void* parameter);
static void dispatchTaskFunction(void* parameter);
void pollLoop();
void dispatchLoop();
};
#endif // HAS_RF
+271
View File
@@ -0,0 +1,271 @@
#include "RFRemoteHandler.hpp"
#if HAS_RF
#include "../Logging/Logging.hpp"
#define TAG "RFRemoteHandler"
RFRemoteHandler::RFRemoteHandler(RFRemote& rfRemote) : _rfRemote(rfRemote) {}
std::vector<String> RFRemoteHandler::commands() const {
return { "rf.set_slot", "rf.clear_slot", "rf.get_slots", "rf.enable" };
}
CommandResult RFRemoteHandler::execute(const CommandEnvelope& envelope) {
const String& cmd = envelope.command;
if (cmd == "rf.set_slot") return handleSetSlot(envelope);
if (cmd == "rf.clear_slot") return handleClearSlot(envelope);
if (cmd == "rf.get_slots") return handleGetSlots(envelope);
if (cmd == "rf.enable") return handleEnable(envelope);
return CommandResult::err(cmd, "Unknown RF command");
}
// ─────────────────────────────────────────────────────────────────────────────
// rf.set_slot
//
// Single slot:
// { "slot": 0, "rf_code": 9274392, "pid": "vesper_fst_1_4",
// "speed": 500, "duration": 60000, "note_assignments": [1,2,3,4,5,6,0,...],
// "is_stop": false }
//
// Multiple slots (array):
// { "slots": [ { "slot": 0, ... }, { "slot": 1, ... } ] }
// ─────────────────────────────────────────────────────────────────────────────
CommandResult RFRemoteHandler::handleSetSlot(const CommandEnvelope& e) {
const JsonDocument& doc = e.contents;
// Batch form: "slots" key holds an array
JsonArrayConst arr = doc["slots"].as<JsonArrayConst>();
if (arr) {
uint8_t count = 0;
for (JsonVariantConst entry : arr) {
uint8_t idx;
RFRemote::RFSlot slot;
String errMsg;
if (!parseSlotObject(entry, idx, slot, errMsg)) {
return CommandResult::err("rf.set_slot",
"Slot entry invalid — " + errMsg + ". No slots were saved.");
}
_rfRemote.setSlot(idx, slot);
count++;
}
LOG_INFO(TAG, "rf.set_slot: %d slot(s) programmed", count);
return CommandResult::ok("rf.set_slot",
String(count) + " slot(s) programmed");
}
// Single-slot form: slot fields are at the top level
uint8_t idx;
RFRemote::RFSlot slot;
String errMsg;
if (!parseSlotObject(doc.as<JsonVariantConst>(), idx, slot, errMsg)) {
return CommandResult::err("rf.set_slot", errMsg);
}
_rfRemote.setSlot(idx, slot);
LOG_INFO(TAG, "rf.set_slot: slot %d programmed (code=%lu)", idx, (unsigned long)slot.rf_code);
return CommandResult::ok("rf.set_slot", "Slot " + String(idx) + " programmed");
}
// ─────────────────────────────────────────────────────────────────────────────
// rf.clear_slot
//
// { "slot": 3 } — clear a single slot
// { "slot": "all" } — clear all slots
// ─────────────────────────────────────────────────────────────────────────────
CommandResult RFRemoteHandler::handleClearSlot(const CommandEnvelope& e) {
const JsonDocument& doc = e.contents;
// Check for "all" string
if (doc["slot"].is<const char*>()) {
String val = doc["slot"].as<String>();
if (val.equalsIgnoreCase("all")) {
_rfRemote.clearAllSlots();
return CommandResult::ok("rf.clear_slot", "All slots cleared");
}
return CommandResult::err("rf.clear_slot",
"Invalid value for 'slot' — use a slot index (0–15) or \"all\"");
}
if (!doc["slot"].is<int>()) {
return CommandResult::err("rf.clear_slot",
"Required: 'slot' — slot index (0–15) or \"all\"");
}
int slotRaw = doc["slot"].as<int>();
if (slotRaw < 0 || slotRaw >= (int)RFRemote::SLOT_COUNT) {
return CommandResult::err("rf.clear_slot",
"Invalid slot index — must be 0–" + String(RFRemote::SLOT_COUNT - 1));
}
_rfRemote.clearSlot((uint8_t)slotRaw);
return CommandResult::ok("rf.clear_slot", "Slot " + String(slotRaw) + " cleared");
}
// ─────────────────────────────────────────────────────────────────────────────
// rf.get_slots — returns all 16 slots
// ─────────────────────────────────────────────────────────────────────────────
CommandResult RFRemoteHandler::handleGetSlots(const CommandEnvelope& e) {
JsonDocument resp;
resp["enabled"] = _rfRemote.isEnabled();
JsonArray slots = resp["slots"].to<JsonArray>();
for (uint8_t i = 0; i < RFRemote::SLOT_COUNT; i++) {
JsonObject obj = slots.add<JsonObject>();
serializeSlot(i, _rfRemote.getSlot(i), obj);
}
return CommandResult::ok("rf.get_slots", resp);
}
// ─────────────────────────────────────────────────────────────────────────────
// rf.enable
// { "enabled": true } or { "enabled": false }
// ─────────────────────────────────────────────────────────────────────────────
CommandResult RFRemoteHandler::handleEnable(const CommandEnvelope& e) {
const JsonDocument& doc = e.contents;
if (!doc["enabled"].is<bool>()) {
return CommandResult::err("rf.enable", "Required: 'enabled' (bool)");
}
bool en = doc["enabled"].as<bool>();
_rfRemote.enable(en);
return CommandResult::ok("rf.enable", en ? "RF remote enabled" : "RF remote disabled");
}
// ─────────────────────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────────────────────
bool RFRemoteHandler::parseSlotObject(JsonVariantConst obj,
uint8_t& outSlotIndex,
RFRemote::RFSlot& outSlot,
String& outErr) {
// slot — always required
if (!obj["slot"].is<int>()) {
outErr = "missing 'slot'";
LOG_WARNING(TAG, "rf.set_slot rejected: missing 'slot'");
return false;
}
int slotRaw = obj["slot"].as<int>();
if (slotRaw < 0 || slotRaw >= (int)RFRemote::SLOT_COUNT) {
outErr = "'slot' out of range (got " + String(slotRaw) + ", must be 0–"
+ String(RFRemote::SLOT_COUNT - 1) + ")";
LOG_WARNING(TAG, "rf.set_slot rejected: %s", outErr.c_str());
return false;
}
// rf_code — always required
uint32_t code = obj["rf_code"] | (uint32_t)0;
if (code == 0) {
outErr = "slot " + String(slotRaw) + ": missing or zero 'rf_code'";
LOG_WARNING(TAG, "rf.set_slot rejected: %s", outErr.c_str());
return false;
}
// is_stop — optional, defaults to false
bool isStop = obj["is_stop"] | false;
String melodyUid = "";
uint16_t speed = 0;
uint32_t dur = 0;
memset(outSlot.note_assignments, 0, RFRemote::NOTE_ASSIGNMENT_COUNT);
if (!isStop) {
// pid
const char* pidRaw = obj["pid"] | "";
if (strlen(pidRaw) == 0) {
outErr = "slot " + String(slotRaw) + ": play slot missing 'pid'";
LOG_WARNING(TAG, "rf.set_slot rejected: %s", outErr.c_str());
return false;
}
melodyUid = pidRaw;
// speed
if (!obj["speed"].is<int>()) {
outErr = "slot " + String(slotRaw) + ": play slot missing 'speed'";
LOG_WARNING(TAG, "rf.set_slot rejected: %s", outErr.c_str());
return false;
}
speed = obj["speed"].as<uint16_t>();
if (speed == 0) {
outErr = "slot " + String(slotRaw) + ": 'speed' must be non-zero";
LOG_WARNING(TAG, "rf.set_slot rejected: %s", outErr.c_str());
return false;
}
// duration
if (!obj["duration"].is<int>() && !obj["duration"].is<unsigned int>()) {
outErr = "slot " + String(slotRaw) + ": play slot missing 'duration'";
LOG_WARNING(TAG, "rf.set_slot rejected: %s", outErr.c_str());
return false;
}
dur = obj["duration"].as<uint32_t>();
if (dur == 0) {
outErr = "slot " + String(slotRaw) + ": 'duration' must be non-zero";
LOG_WARNING(TAG, "rf.set_slot rejected: %s", outErr.c_str());
return false;
}
// note_assignments — required, exactly 16 elements, at least one non-zero
JsonArrayConst na = obj["note_assignments"].as<JsonArrayConst>();
if (!na) {
outErr = "slot " + String(slotRaw) + ": play slot missing 'note_assignments'";
LOG_WARNING(TAG, "rf.set_slot rejected: %s", outErr.c_str());
return false;
}
if (na.size() != RFRemote::NOTE_ASSIGNMENT_COUNT) {
outErr = "slot " + String(slotRaw) + ": 'note_assignments' must have exactly "
+ String(RFRemote::NOTE_ASSIGNMENT_COUNT) + " elements (got "
+ String(na.size()) + ")";
LOG_WARNING(TAG, "rf.set_slot rejected: %s", outErr.c_str());
return false;
}
bool anyNonZero = false;
uint8_t i = 0;
for (JsonVariantConst v : na) {
outSlot.note_assignments[i] = v.as<uint8_t>();
if (outSlot.note_assignments[i] != 0) anyNonZero = true;
i++;
}
if (!anyNonZero) {
outErr = "slot " + String(slotRaw) + ": 'note_assignments' are all zero — no bells would ring";
LOG_WARNING(TAG, "rf.set_slot rejected: %s", outErr.c_str());
return false;
}
}
outSlotIndex = (uint8_t)slotRaw;
outSlot.rf_code = code;
outSlot.is_stop = isStop;
outSlot.melody_uid = melodyUid;
outSlot.speed = speed;
outSlot.duration = dur;
return true;
}
void RFRemoteHandler::serializeSlot(uint8_t slotIndex,
const RFRemote::RFSlot& s,
JsonObject out) {
out["slot"] = slotIndex;
out["empty"] = s.isEmpty();
out["rf_code"] = s.rf_code;
out["pid"] = s.melody_uid;
out["speed"] = s.speed;
out["duration"] = s.duration;
out["is_stop"] = s.is_stop;
JsonArray na = out["note_assignments"].to<JsonArray>();
for (uint8_t i = 0; i < RFRemote::NOTE_ASSIGNMENT_COUNT; i++) {
na.add(s.note_assignments[i]);
}
}
#endif // HAS_RF
+43
View File
@@ -0,0 +1,43 @@
#pragma once
#if HAS_RF
#include <vector>
#include "../Communication/Handlers/ICommandHandler.hpp"
#include "RFRemote.hpp"
/**
* @brief Command handler for the RF remote subsystem.
*
* Namespace: "rf"
*
* Commands:
* rf.set_slot — Program one or more slots. Accepts a single slot object or
* an array of slot objects. See API reference for field details.
* rf.clear_slot — Clear slot N, or all slots ({ "slot": "all" }).
* rf.get_slots — Return the full slot table (all 16 slots, empty or not).
* rf.enable — { "enabled": true|false }
*/
class RFRemoteHandler : public ICommandHandler {
public:
explicit RFRemoteHandler(RFRemote& rfRemote);
std::vector<String> commands() const override;
CommandResult execute(const CommandEnvelope& envelope) override;
private:
RFRemote& _rfRemote;
CommandResult handleSetSlot(const CommandEnvelope& e);
CommandResult handleClearSlot(const CommandEnvelope& e);
CommandResult handleGetSlots(const CommandEnvelope& e);
CommandResult handleEnable(const CommandEnvelope& e);
/** @brief Parse and fully validate a single slot JSON object. Returns false and populates outErr on failure. */
static bool parseSlotObject(JsonVariantConst obj, uint8_t& outSlotIndex, RFRemote::RFSlot& outSlot, String& outErr);
/** @brief Serialize one RFSlot into a JsonObject. */
static void serializeSlot(uint8_t slotIndex, const RFRemote::RFSlot& s, JsonObject out);
};
#endif // HAS_RF
+56 -1
View File
@@ -95,15 +95,21 @@
// HARDWARE LIBRARIES - Peripheral device control
// ═══════════════════════════════════════════════════════════════════════════════════
#include <Adafruit_PCF8574.h> // I2C GPIO expander for relay control
#if HAS_RTC
#include <RTClib.h> // Real-time clock functionality
#endif
// ═══════════════════════════════════════════════════════════════════════════════════
// CUSTOM CLASSES - Include Custom Classes and Functions
// ═══════════════════════════════════════════════════════════════════════════════════
#include "SDCardMutex/SDCardMutex.hpp" // ⚠️ MUST be included before any SD-using classes
#include "ConfigManager/ConfigManager.hpp"
#if HAS_SD_CARD
#include "FileManager/FileManager.hpp"
#endif
#if HAS_RTC
#include "TimeKeeper/TimeKeeper.hpp"
#endif
#include "Logging/Logging.hpp"
#include "Telemetry/Telemetry.hpp"
#include "OTAManager/OTAManager.hpp"
@@ -119,13 +125,20 @@
#include "InputManager/InputManager.hpp"
#include "Version.hpp"
#include "NvsMigration/NvsMigration.hpp"
#if HAS_RF
#include "RFRemote/RFRemote.hpp"
#endif
#define TAG "Main"
// Class Constructors
ConfigManager configManager;
#if HAS_SD_CARD
FileManager fileManager(&configManager);
#endif
#if HAS_RTC
Timekeeper timekeeper;
#endif
Telemetry telemetry;
OTAManager otaManager(configManager);
Player player;
@@ -137,6 +150,9 @@ CommunicationRouter communication(configManager, otaManager, networking, server
HealthMonitor healthMonitor;
FirmwareValidator firmwareValidator;
InputManager inputManager;
#if HAS_RF
RFRemote rfRemote;
#endif
// 🔥 OUTPUT SYSTEM - PCF8574/PCF8575 I2C Expanders Configuration
@@ -165,8 +181,10 @@ PCF8574OutputManager outputManager(0x24, ChipType::PCF8574, 6);
BellEngine bellEngine(player, configManager, telemetry, outputManager); // 🔥 THE ULTIMATE BEAST!
TaskHandle_t bellEngineHandle = NULL; // Legacy - will be removed
#if HAS_RTC
TimerHandle_t schedulerTimer;
TimerHandle_t ntpSyncTimer; // Non-blocking delayed NTP sync timer
#endif
@@ -177,6 +195,7 @@ void handleFactoryReset() {
}
}
#if HAS_RTC
// One-shot task to perform NTP sync outside the Tmr Svc context
static void ntpSyncTask(void* param) {
LOG_DEBUG(TAG, "Network stabilization complete - starting NTP sync");
@@ -190,6 +209,7 @@ static void ntpSyncTask(void* param) {
void ntpSyncTimerCallback(TimerHandle_t xTimer) {
xTaskCreate(ntpSyncTask, "ntpSync", 3072, NULL, 5, NULL);
}
#endif
@@ -197,7 +217,7 @@ void setup()
{
// Initialize Serial Communications (for debugging) & I2C Bus (for Hardware Control)
Serial.begin(115200);
Serial.print("VESPER System Booting UP! - Version ");
Serial.print("BellSystems Firmware Booting - Version ");
Serial.println(FW_VERSION);
// ── NVS schema migration ─────────────────────────────────────────────────
@@ -256,7 +276,9 @@ void setup()
healthMonitor.begin();
// Register all subsystems with health monitor for continuous monitoring
healthMonitor.setConfigManager(&configManager);
#if HAS_SD_CARD
healthMonitor.setFileManager(&fileManager);
#endif
// Initialize Output Manager - 🔥 THE NEW WAY!
outputManager.setConfigManager(&configManager);
@@ -292,6 +314,7 @@ void setup()
// SD Card initialization is now handled by ConfigManager
#if HAS_RTC
// Initialize timekeeper with NO clock outputs
timekeeper.begin(); // No parameters needed
// Connect the timekeeper to dependencies (CLEAN!)
@@ -303,12 +326,15 @@ void setup()
// Register TimeKeeper with health monitor
healthMonitor.setTimeKeeper(&timekeeper);
#endif
// Initialize Telemetry
telemetry.setPlayerReference(&player.isPlaying);
// 🚑 CRITICAL: Connect force stop callback for overload protection!
telemetry.setForceStopCallback([]() { player.forceStop(); });
#if HAS_SD_CARD
telemetry.setFileManager(&fileManager);
#endif
telemetry.begin();
// Register Telemetry with health monitor
@@ -333,18 +359,31 @@ void setup()
// Set all dependency references BEFORE begin() so that registerHandlers()
// (called inside begin()) can construct every domain handler.
communication.setPlayerReference(&player);
#if HAS_SD_CARD
communication.setFileManagerReference(&fileManager);
#endif
#if HAS_RTC
communication.setTimeKeeperReference(&timekeeper);
#endif
communication.setFirmwareValidatorReference(&firmwareValidator);
communication.setTelemetryReference(&telemetry);
communication.setHealthMonitorReference(&healthMonitor);
communication.setOutputManagerReference(&outputManager);
#if HAS_RF
communication.setRFRemoteReference(&rfRemote);
#endif
communication.begin();
#if HAS_SD_CARD
player.setDependencies(&communication, &fileManager);
#else
player.setDependencies(&communication, nullptr);
#endif
player.setBellEngine(&bellEngine); // Connect the beast!
player.setTelemetry(&telemetry);
#if HAS_RTC
player.setTimekeeper(&timekeeper); // 🔥 Connect for alert coordination
#endif
// Register Communication with health monitor
healthMonitor.setCommunication(&communication);
@@ -355,6 +394,7 @@ void setup()
// Track if AsyncWebServer has been started to prevent duplicates
static bool webServerStarted = false;
#if HAS_RTC
// Create NTP sync timer (one-shot, 3 second delay for network stabilization)
ntpSyncTimer = xTimerCreate(
"NTPSync", // Timer name
@@ -363,18 +403,21 @@ void setup()
NULL, // Timer ID (not used)
ntpSyncTimerCallback // Callback function
);
#endif
// Set up network callbacks
networking.setNetworkCallbacks(
[&webServerStarted]() {
communication.onNetworkConnected();
#if HAS_RTC
// Schedule non-blocking NTP sync after 3s network stabilization (like MQTT)
// Skip NTP sync in AP mode (no internet connection)
if (!networking.isInAPMode() && ntpSyncTimer) {
LOG_DEBUG(TAG, "Network connected - scheduling NTP sync after 3s stabilization (non-blocking)");
xTimerStart(ntpSyncTimer, 0);
}
#endif
// Start AsyncWebServer when network becomes available (only once!)
if (!webServerStarted && networking.getState() != NetworkState::WIFI_PORTAL_MODE) {
@@ -392,12 +435,14 @@ void setup()
LOG_INFO(TAG, "Network already connected - initializing services");
communication.onNetworkConnected();
#if HAS_RTC
// Schedule non-blocking NTP sync after 3s network stabilization (like MQTT)
// Skip NTP sync in AP mode (no internet connection)
if (!networking.isInAPMode() && ntpSyncTimer) {
LOG_DEBUG(TAG, "Network already connected - scheduling NTP sync after 3s stabilization (non-blocking)");
xTimerStart(ntpSyncTimer, 0);
}
#endif
// 🔥 CRITICAL: Start AsyncWebServer ONLY when network is ready
// Do NOT start if WiFiManager portal is active (port 80 conflict!)
@@ -413,9 +458,13 @@ void setup()
// Initialize OTA Manager
otaManager.begin();
#if HAS_SD_CARD
otaManager.setFileManager(&fileManager);
#endif
otaManager.setPlayer(&player); // Set player reference for idle check
#if HAS_RTC
otaManager.setTimeKeeper(&timekeeper); // Set timekeeper reference for freeze mode
#endif
otaManager.setTelemetry(&telemetry); // Set telemetry reference for freeze mode
// 🔥 FIX: OTA check will happen asynchronously via scheduled timer (no blocking delay)
@@ -425,6 +474,12 @@ void setup()
// Register OTA Manager with health monitor
healthMonitor.setOTAManager(&otaManager);
#if HAS_RF
// Initialize RF remote receiver
rfRemote.begin(&player);
healthMonitor.setRFRemote(&rfRemote);
#endif
// Note: AsyncWebServer will be started by network callbacks when connection is ready
// This avoids port 80 conflicts with WiFiManager's captive portal