diff --git a/docs/dev/is31fl3193_led_test/is31fl3193_led_test.ino b/docs/dev/is31fl3193_led_test/is31fl3193_led_test.ino new file mode 100644 index 0000000..42b12ff --- /dev/null +++ b/docs/dev/is31fl3193_led_test/is31fl3193_led_test.ino @@ -0,0 +1,138 @@ +/* + * ═══════════════════════════════════════════════════════════════════════════════ + * is31fl3193_led_test.ino — Bring-up test for IS31FL3193 3-channel LED driver + * ═══════════════════════════════════════════════════════════════════════════════ + * + * TEMPORARY TEST SKETCH — not part of the Vesper firmware build. + * Open directly in Arduino IDE and flash it on its own (does NOT go through + * PlatformIO / src/main.cpp). Delete once the chip/board is verified. + * + * Hardware: + * - Board: Kincony KC868-A6 (ESP32-D0WD-V3) + * - I2C bus: SDA = GPIO4, SCL = GPIO15 (see src/main.cpp Wire.begin(4, 15)) + * - Chip: IS31FL3193-DLS2-TR, address 0x6B (AD pin tied to VCC) + * - OUT1/OUT2/OUT3 are CURRENT SOURCE outputs, LED anodes on OUT1~OUT3, + * cathodes to GND. + * + * Register map — read directly from the official Lumissil datasheet + * (IS31FL3193_DS.pdf, Rev. D, 2024-03-28): + * 0x00 Shutdown Register D5=EN (1=channels enabled), D0=SSD (1=shutdown!) + * Must write EN=1, SSD=0 -> 0x20 to enable. + * 0x02 LED Mode Register D5=RGB (0=PWM control mode, 1=one-shot mode) + * 0x03 Current Setting D4:D2=CS + * 0x04 PWM Register OUT1 0-255 duty cycle + * 0x05 PWM Register OUT2 0-255 duty cycle + * 0x06 PWM Register OUT3 0-255 duty cycle + * 0x07 Update Register write 0x00 to latch PWM/LED-control changes + * + * NOTE: this board is missing the datasheet-recommended VCC decoupling caps + * (1uF + 0.1uF) and the LED-side 1uF cap. Suspected cause of no output: the + * current-source stage's switching transient (up to 3 channels x 42mA) isn't + * being absorbed locally, so the bias/reference circuit glitches every time + * an output tries to turn on, while the low-current digital I2C block keeps + * working fine regardless. This variant minimizes that transient as a test: + * only ONE channel active at a time, lowest current setting (5mA instead of + * 42mA), and a slow software ramp instead of an instant full-brightness step. + * If this makes the LED light where full-brightness/all-channels didn't, + * that's strong confirmation the missing caps are the real fix needed. + * + * Behavior: OUT1 -> OUT2 -> OUT3, one at a time, each ramping 0->dim->0. + * ═══════════════════════════════════════════════════════════════════════════════ + */ + +#include + +#define I2C_SDA_PIN 4 +#define I2C_SCL_PIN 15 +#define IS31FL3193_ADDR 0x6B + +#define REG_SHUTDOWN 0x00 +#define REG_LED_MODE 0x02 +#define REG_CURRENT 0x03 +#define REG_PWM_OUT1 0x04 +#define REG_PWM_OUT2 0x05 +#define REG_PWM_OUT3 0x06 +#define REG_UPDATE 0x07 +#define REG_LED_CONTROL 0x1D +#define REG_RESET 0x2F + +#define SHUTDOWN_NORMAL 0x20 // EN=1, SSD=0 — channels enabled, not in shutdown +#define MODE_PWM 0x00 +#define LED_CONTROL_ALL_ON 0x07 +#define CURRENT_5MA (0x2 << 2) // lowest available current step + +#define MAX_DIM_PWM 40 // cap brightness low — small fraction of 255 +#define RAMP_STEP 2 +#define RAMP_DELAY_MS 30 // slow ramp -> gentler current transient +#define HOLD_MS 500 +#define GAP_MS 300 // pause between channels, all outputs off + +void writeReg(uint8_t reg, uint8_t value) { + Wire.beginTransmission(IS31FL3193_ADDR); + Wire.write(reg); + Wire.write(value); + Wire.endTransmission(); +} + +void update() { + writeReg(REG_UPDATE, 0x00); +} + +void setAll(uint8_t out1, uint8_t out2, uint8_t out3) { + writeReg(REG_PWM_OUT1, out1); + writeReg(REG_PWM_OUT2, out2); + writeReg(REG_PWM_OUT3, out3); + update(); +} + +void rampChannel(int channel) { + // channel: 0=OUT1, 1=OUT2, 2=OUT3 + const char* names[3] = {"OUT1", "OUT2", "OUT3"}; + Serial.printf("%s -> ramping up (low brightness, low current)\n", names[channel]); + + for (int v = 0; v <= MAX_DIM_PWM; v += RAMP_STEP) { + uint8_t out1 = (channel == 0) ? v : 0; + uint8_t out2 = (channel == 1) ? v : 0; + uint8_t out3 = (channel == 2) ? v : 0; + setAll(out1, out2, out3); + delay(RAMP_DELAY_MS); + } + + delay(HOLD_MS); + + for (int v = MAX_DIM_PWM; v >= 0; v -= RAMP_STEP) { + uint8_t out1 = (channel == 0) ? v : 0; + uint8_t out2 = (channel == 1) ? v : 0; + uint8_t out3 = (channel == 2) ? v : 0; + setAll(out1, out2, out3); + delay(RAMP_DELAY_MS); + } + + setAll(0, 0, 0); + delay(GAP_MS); +} + +void setup() { + Serial.begin(115200); + delay(1000); + Serial.println("=== IS31FL3193 LED Test — one channel at a time, low brightness ==="); + + Wire.begin(I2C_SDA_PIN, I2C_SCL_PIN); + + writeReg(REG_RESET, 0x00); + delay(10); + writeReg(REG_SHUTDOWN, SHUTDOWN_NORMAL); + delay(10); + writeReg(REG_LED_MODE, MODE_PWM); + writeReg(REG_CURRENT, CURRENT_5MA); + writeReg(REG_LED_CONTROL, LED_CONTROL_ALL_ON); + update(); + setAll(0, 0, 0); +} + +void loop() { + rampChannel(0); + rampChannel(1); + rampChannel(2); + Serial.println("=== cycle complete, restarting ===\n"); +} diff --git a/docs/dev/pcf8575_external_diagnostic/pcf8575_external_diagnostic.ino b/docs/dev/pcf8575_external_diagnostic/pcf8575_external_diagnostic.ino new file mode 100644 index 0000000..5bbabb6 --- /dev/null +++ b/docs/dev/pcf8575_external_diagnostic/pcf8575_external_diagnostic.ino @@ -0,0 +1,115 @@ +/* + * ═══════════════════════════════════════════════════════════════════════════════ + * pcf8575_external_diagnostic.ino — Per-pin write + readback test, external PCF8575 + * ═══════════════════════════════════════════════════════════════════════════════ + * + * TEMPORARY TEST SKETCH — not part of the Vesper firmware build. + * Open directly in Arduino IDE and flash it on its own (does NOT go through + * PlatformIO / src/main.cpp). Delete once the chip is verified. + * + * Purpose: isolate whether P00-P02 (indices 0-2) failing to fire is a software + * problem (write never reaching the chip / shadow register not flushing) or a + * hardware problem (chip accepts the write but can't sink the pin). + * + * For each pin 0-15: + * 1. Write LOW. + * 2. Immediately read back via digitalRead() — this tells us what the + * library's shadow register / the chip itself reports. + * 3. Hold LOW for HOLD_MS so you can probe the physical pin with a meter. + * 4. Write HIGH, read back again, hold OFF_MS. + * + * How to interpret: + * - Readback says LOW, meter says ~3.3V -> chip accepted the write but + * can't sink the pin -> hardware fault (bad driver transistor on that pin). + * - Readback says HIGH (write didn't take) -> library/addressing issue, + * not chip damage. Check pin index mapping / I2C bus health on retry. + * - Readback says LOW, meter says ~0V -> pin is fine. + * + * Hardware: + * - Board: Kincony KC868-A6 (ESP32-D0WD-V3) + * - I2C bus: SDA = GPIO4, SCL = GPIO15 (see src/main.cpp Wire.begin(4, 15)) + * - Chip: PCF8575, address 0x20 (external expansion board) + * + * Library: Adafruit PCF8575 (same library the firmware uses in + * src/OutputManager/OutputManager.cpp) + * + * Convention: ACTIVE-LOW outputs, matching OutputManager::firePhysicalOutput() + * — LOW = relay energized/fired, HIGH = relay off. + * ═══════════════════════════════════════════════════════════════════════════════ + */ + +#include +#include + +// ── Config ─────────────────────────────────────────────────────────────────── +#define I2C_SDA_PIN 4 +#define I2C_SCL_PIN 15 +#define PCF8575_ADDR 0x20 +#define NUM_OUTPUTS 16 + +#define HOLD_MS 3000 // time held LOW — probe the pin during this window +#define OFF_MS 500 + +#define FIRED LOW // active-low: LOW = relay on +#define OFF HIGH // active-low: HIGH = relay off + +Adafruit_PCF8575 pcf; + +// P00-P02 (indices 0-2) are the pins reported as not firing on the board. +bool isSuspect(uint8_t i) { return i <= 2; } + +void allOff() { + for (uint8_t i = 0; i < NUM_OUTPUTS; i++) pcf.digitalWrite(i, OFF); +} + +void setup() { + Serial.begin(115200); + delay(1000); + Serial.println(); + Serial.println("=== External PCF8575 — per-pin write/readback diagnostic ==="); + + Wire.begin(I2C_SDA_PIN, I2C_SCL_PIN); + + if (!pcf.begin(PCF8575_ADDR, &Wire)) { + Serial.printf("FAILED to initialize PCF8575 at 0x%02X — check wiring/address.\n", PCF8575_ADDR); + while (true) { delay(1000); } + } + Serial.printf("PCF8575 initialized at 0x%02X\n", PCF8575_ADDR); + + for (uint8_t i = 0; i < NUM_OUTPUTS; i++) pcf.pinMode(i, OUTPUT); + allOff(); + + Serial.println("Each pin holds LOW for 3s — probe the physical pin with a"); + Serial.println("multimeter during that window. Compare against the printed"); + Serial.println("readback value."); + Serial.println(); +} + +void loop() { + for (uint8_t i = 0; i < NUM_OUTPUTS; i++) { + const char* tag = isSuspect(i) ? " <-- SUSPECT PIN (P0x reported dead)" : ""; + + bool writeOk = pcf.digitalWrite(i, FIRED); + delay(10); + bool readLow = (pcf.digitalRead(i) == LOW); + + Serial.print("Pin "); + Serial.print(i); + Serial.print(" (P"); + Serial.print((i < 8) ? 0 : 1); + Serial.print(i % 8); + Serial.print(") -> write_ok="); + Serial.print(writeOk); + Serial.print(" readback="); + Serial.print(readLow ? "LOW" : "HIGH"); + Serial.println(tag); + + delay(HOLD_MS); + + pcf.digitalWrite(i, OFF); + delay(OFF_MS); + } + + Serial.println("=== cycle complete, restarting ===\n"); + delay(200); +} diff --git a/docs/dev/pcf_22_relay_sequence_test/pcf_22_relay_sequence_test.ino b/docs/dev/pcf_22_relay_sequence_test/pcf_22_relay_sequence_test.ino new file mode 100644 index 0000000..e2b82fb --- /dev/null +++ b/docs/dev/pcf_22_relay_sequence_test/pcf_22_relay_sequence_test.ino @@ -0,0 +1,135 @@ +/* + * ═══════════════════════════════════════════════════════════════════════════════ + * pcf_22_relay_sequence_test.ino — Combined bring-up test: onboard 6 + external 16 + * ═══════════════════════════════════════════════════════════════════════════════ + * + * TEMPORARY TEST SKETCH — not part of the Vesper firmware build. + * Open directly in Arduino IDE and flash it on its own (does NOT go through + * PlatformIO / src/main.cpp). Delete once both chips are verified. + * + * Purpose: treat the board as one 22-relay unit — + * - Outputs 0-5 = onboard PCF8574 (KC868-A6 relays, 6ch) + * - Outputs 6-21 = external PCF8575 (your 16ch expansion board) + * + * Sequence: + * 1. Fire all 22 relays in order, one at a time (onboard 1-6, then external 1-16). + * 2. Flash all 22 relays together ALL_FLASH_COUNT times (on/off/on/off...). + * 3. Repeat forever. + * + * Hardware: + * - Board: Kincony KC868-A6 (ESP32-D0WD-V3) + * - I2C bus: SDA = GPIO4, SCL = GPIO15 (see src/main.cpp Wire.begin(4, 15)) + * - Chip 1: PCF8574, address 0x24 (onboard relay outputs) + * - Chip 2: PCF8575, address 0x20 (external expansion board) + * - Both chips share the same I2C bus/address space as the firmware — + * do NOT run this at the same time as the main Vesper firmware. + * + * Library: Adafruit PCF8574 + Adafruit PCF8575 (same libraries the firmware + * uses in src/OutputManager/OutputManager.cpp) + * + * Convention: ACTIVE-LOW outputs, matching OutputManager::firePhysicalOutput() + * — LOW = relay energized/fired, HIGH = relay off. + * ═══════════════════════════════════════════════════════════════════════════════ + */ + +#include +#include +#include + +// ── Config ─────────────────────────────────────────────────────────────────── +#define I2C_SDA_PIN 4 +#define I2C_SCL_PIN 15 + +#define ONBOARD_ADDR 0x24 // KC868-A6 relay PCF8574 +#define EXTERNAL_ADDR 0x20 // External PCF8575 + +#define ONBOARD_COUNT 6 +#define EXTERNAL_COUNT 16 +#define TOTAL_COUNT (ONBOARD_COUNT + EXTERNAL_COUNT) // 22 + +#define STEP_ON_MS 150 +#define STEP_OFF_MS 30 + +#define ALL_FLASH_COUNT 5 // how many times to flash all 22 together +#define ALL_ON_MS 300 +#define ALL_OFF_MS 300 + +#define CYCLE_PAUSE_MS 1500 + +#define FIRED LOW // active-low: LOW = relay on +#define OFF HIGH // active-low: HIGH = relay off + +Adafruit_PCF8574 onboard; +Adafruit_PCF8575 external; + +void allOff() { + for (uint8_t i = 0; i < ONBOARD_COUNT; i++) onboard.digitalWrite(i, OFF); + for (uint8_t i = 0; i < EXTERNAL_COUNT; i++) external.digitalWrite(i, OFF); +} + +void allOn() { + for (uint8_t i = 0; i < ONBOARD_COUNT; i++) onboard.digitalWrite(i, FIRED); + for (uint8_t i = 0; i < EXTERNAL_COUNT; i++) external.digitalWrite(i, FIRED); +} + +void setup() { + Serial.begin(115200); + delay(1000); + Serial.println(); + Serial.println("=== 22-Relay Sequence + Flash Test (onboard 6 + external 16) ==="); + + Wire.begin(I2C_SDA_PIN, I2C_SCL_PIN); + + if (!onboard.begin(ONBOARD_ADDR, &Wire)) { + Serial.printf("FAILED to init onboard PCF8574 at 0x%02X\n", ONBOARD_ADDR); + while (true) { delay(1000); } + } + Serial.printf("Onboard PCF8574 OK at 0x%02X\n", ONBOARD_ADDR); + + if (!external.begin(EXTERNAL_ADDR, &Wire)) { + Serial.printf("FAILED to init external PCF8575 at 0x%02X\n", EXTERNAL_ADDR); + while (true) { delay(1000); } + } + Serial.printf("External PCF8575 OK at 0x%02X\n", EXTERNAL_ADDR); + + for (uint8_t i = 0; i < ONBOARD_COUNT; i++) onboard.pinMode(i, OUTPUT); + for (uint8_t i = 0; i < EXTERNAL_COUNT; i++) external.pinMode(i, OUTPUT); + allOff(); + + Serial.printf("Ready. %d onboard + %d external = %d total relays.\n", + ONBOARD_COUNT, EXTERNAL_COUNT, TOTAL_COUNT); +} + +void loop() { + // ── Step 1: fire all 22 relays in sequence, one at a time ────────────── + Serial.println("--- Sequence: onboard 1-6, then external 1-16 ---"); + for (uint8_t i = 0; i < ONBOARD_COUNT; i++) { + Serial.printf("Onboard relay %d -> ON\n", i + 1); + onboard.digitalWrite(i, FIRED); + delay(STEP_ON_MS); + onboard.digitalWrite(i, OFF); + delay(STEP_OFF_MS); + } + for (uint8_t i = 0; i < EXTERNAL_COUNT; i++) { + Serial.printf("External relay %d -> ON\n", i + 1); + external.digitalWrite(i, FIRED); + delay(STEP_ON_MS); + external.digitalWrite(i, OFF); + delay(STEP_OFF_MS); + } + + // ── Step 2: flash all 22 together, several times ─────────────────────── + Serial.printf("--- Flashing all %d relays together x%d ---\n", TOTAL_COUNT, ALL_FLASH_COUNT); + for (uint8_t flash = 0; flash < ALL_FLASH_COUNT; flash++) { + Serial.printf("Flash %d: ALL ON\n", flash + 1); + allOn(); + delay(ALL_ON_MS); + + Serial.printf("Flash %d: ALL OFF\n", flash + 1); + allOff(); + delay(ALL_OFF_MS); + } + + Serial.println("=== cycle complete, restarting ===\n"); + delay(CYCLE_PAUSE_MS); +} diff --git a/docs/features/problems-fixes.md b/docs/features/problems-fixes.md new file mode 100644 index 0000000..6ad63a7 --- /dev/null +++ b/docs/features/problems-fixes.md @@ -0,0 +1 @@ +- Uptime on the hearbeat maxes out at 299 days. \ No newline at end of file diff --git a/docs/reference/dart-command-handler.dart b/docs/reference/dart-command-handler.dart new file mode 100644 index 0000000..aee17a1 --- /dev/null +++ b/docs/reference/dart-command-handler.dart @@ -0,0 +1,1261 @@ +import '/backend/schema/enums/enums.dart'; +import '/flutter_flow/flutter_flow_util.dart'; +import 'package:flutter/foundation.dart'; +import '/backend/schema/structs/index.dart'; +import '/custom_code/actions/index.dart'; +import '/flutter_flow/custom_functions.dart'; +import '/custom_code/webSocketService.dart'; + +/// ============================================================================ +/// PROJECT VESPER - GROUPED COMMAND HANDLER v3.0 +/// ============================================================================ +/// +/// This class contains all command functions to communicate with the Vesper ESP32 device +/// using the new grouped command architecture with batch support. +/// Each function returns a Future indicating success/failure. + +class RelaySetup { + // ============================================================================ + // RELAY CONFIGURATION - Single and Batch Commands available + // ============================================================================ + + /// Set Bell Output pin assignment (single bell) + static Future setRelayOutput( + int bell, + int outputRelay, + ) async { + final contents = { + 'action': 'set_outputs', + 'b${bell + 1}': outputRelay, + }; + + return Messenger._sendCommand('relay_setup', contents); + } + + /// Set Bell Timing (hammer activation time) in milliseconds (single bell) + static Future setRelayTiming( + int bell, + int timing, + ) async { + final contents = { + 'action': 'set_timings', + 'b${bell + 1}': timing, + }; + + return Messenger._sendCommand('relay_setup', contents); + } + + /// Set multiple Bell Output pin assignments at once (batch) + static Future setBatchRelayOutputs( + List bellOutputs, + ) async { + final contents = { + 'action': 'set_outputs', + }; + + for (int i = 0; i < bellOutputs.length; i++) { + contents['b${i + 1}'] = bellOutputs[i]; + } + + return Messenger._sendCommand('relay_setup', contents); + } + + /// Set multiple Bell Timings at once (batch) using List + static Future setBatchRelayTimings( + List bellTimings, + ) async { + final contents = { + 'action': 'set_timings', + }; + + for (int i = 0; i < bellTimings.length; i++) { + contents['b${i + 1}'] = bellTimings[i]; + } + return Messenger._sendCommand('relay_setup', contents); + } +} + +class FileManager { + static final WebSocketService _ws = WebSocketService(); + + // ============================================================================ + // FILE HANDLING - List, Download and Delete files. + // ============================================================================ + + /// Download a melody to the ESP32 device + static Future downloadMelody( + String downloadURL, + String melodysUID, + String? name, + ) async { + final contents = { + 'action': 'download_melody', + 'download_url': downloadURL, + 'melodys_uid': melodysUID, + }; + + if (name != null) { + contents['name'] = name; + } + return Messenger._sendCommand('file_manager', contents); + } + + /// Delete a melody from the ESP32 device + static Future deleteMelody(String melodyName) async { + final contents = { + 'action': 'delete_melody', + 'name': melodyName, + }; + return Messenger._sendCommand('file_manager', contents); + } + + /// List available melodies on the ESP32 device + static Future> listMelodies() async { + try { + final response = await _ws.sendAndWaitForResponse( + data: { + 'cmd': 'file_manager', + 'contents': {'action': 'list_melodies'} + }, + matcher: (msg) => + msg['status'] == 'SUCCESS' && msg['type'] == 'list_melodies', + timeout: const Duration(seconds: 5), + ); + + final payload = response['payload']; + if (payload is List) { + return payload.map((e) => e.toString()).toList(); + } else { + return []; + } + } catch (e) { + debugPrint('Error listing melodies: $e'); + return []; + } + } +} + +class ClockSetup { + // ============================================================================ + // CLOCK AND ALERTS CONFIGURATION - Single & Batch commands available + // ============================================================================ + + /// Enable or Disable Clock Functionality + static Future setClockEnabled(bool enabled) async { + return Messenger._sendCommand('clock_setup', { + 'action': 'set_enabled', + 'enabled': enabled, + }); + } + + /// Set Odd Clock Output + static Future setOddClockOutput(int output) async { + return Messenger._sendCommand('clock_setup', { + 'action': 'set_outputs', + 'c1': output, + }); + } + + /// Set Even Clock Output + static Future setEvenClockOutput(int output) async { + return Messenger._sendCommand('clock_setup', { + 'action': 'set_outputs', + 'c2': output, + }); + } + + /// Set both clock outputs at once + static Future setBothClockOutputs(int oddOutput, int evenOutput) async { + return Messenger._sendCommand('clock_setup', { + 'action': 'set_outputs', + 'c1': oddOutput, + 'c2': evenOutput, + }); + } + + /// Set Pulse Duration of the Clock Motor + static Future setPulseDuration(int pulseDuration) async { + return Messenger._sendCommand('clock_setup', { + 'action': 'set_timings', + 'pulseDuration': pulseDuration, + }); + } + + /// Set Pause Duration of the Clock Motor + static Future setPauseDuration(int pauseDuration) async { + return Messenger._sendCommand('clock_setup', { + 'action': 'set_timings', + 'pauseDuration': pauseDuration, + }); + } + + /// Set both clock timing parameters at once + static Future setClockTimings( + int pulseDuration, int pauseDuration) async { + return Messenger._sendCommand('clock_setup', { + 'action': 'set_timings', + 'pulseDuration': pulseDuration, + 'pauseDuration': pauseDuration, + }); + } + + /// Set Alert Type (SINGLE, HOURS, OFF) + static Future setAlertType(String alertType) async { + return Messenger._sendCommand('clock_setup', { + 'action': 'set_alerts', + 'alertType': alertType, + }); + } + + /// Set Alert Ring Interval (pause between rings in milliseconds) + static Future setAlertRingInterval(int ringInterval) async { + return Messenger._sendCommand('clock_setup', { + 'action': 'set_alerts', + 'alertRingInterval': ringInterval, + }); + } + + /// Set the Hour Bell Selection (1-6, or 0 to disable) + static Future setHourBell(int hourBell) async { + return Messenger._sendCommand('clock_setup', { + 'action': 'set_alerts', + 'hourBell': hourBell, + }); + } + + /// Set the Half-Hour Bell Selection (1-6, or 0 to disable) + static Future setHalfBell(int halfBell) async { + return Messenger._sendCommand('clock_setup', { + 'action': 'set_alerts', + 'halfBell': halfBell, + }); + } + + /// Set the Quarter Bell Selection (1-6, or 0 to disable) + static Future setQuarterBell(int quarterBell) async { + return Messenger._sendCommand('clock_setup', { + 'action': 'set_alerts', + 'quarterBell': quarterBell, + }); + } + + /// Set all alert configuration at once + static Future setAllAlerts({ + String? alertType, + int? alertRingInterval, + int? hourBell, + int? halfBell, + int? quarterBell, + }) async { + final contents = { + 'action': 'set_alerts', + }; + + if (alertType != null) contents['alertType'] = alertType; + if (alertRingInterval != null) + contents['alertRingInterval'] = alertRingInterval; + if (hourBell != null) contents['hourBell'] = hourBell; + if (halfBell != null) contents['halfBell'] = halfBell; + if (quarterBell != null) contents['quarterBell'] = quarterBell; + + return Messenger._sendCommand('clock_setup', contents); + } + + /// Set Backlight Automation Master Switch + static Future setBacklightAutomation(bool enabled) async { + return Messenger._sendCommand('clock_setup', { + 'action': 'set_backlight', + 'enabled': enabled, + }); + } + + /// Set the Backlight's Output Pin + static Future setBacklightOutput(int output) async { + return Messenger._sendCommand('clock_setup', { + 'action': 'set_backlight', + 'output': output, + }); + } + + /// Set the Backlight's Automation ON Time + static Future setBacklightOnTime(String onTime) async { + return Messenger._sendCommand('clock_setup', { + 'action': 'set_backlight', + 'onTime': onTime, + }); + } + + /// Set the Backlight's Automation OFF Time + static Future setBacklightOffTime(String offTime) async { + return Messenger._sendCommand('clock_setup', { + 'action': 'set_backlight', + 'offTime': offTime, + }); + } + + /// Set all backlight configuration at once + static Future setAllBacklight({ + bool? enabled, + int? output, + String? onTime, + String? offTime, + }) async { + final contents = { + 'action': 'set_backlight', + }; + + if (enabled != null) contents['enabled'] = enabled; + if (output != null) contents['output'] = output; + if (onTime != null) contents['onTime'] = onTime; + if (offTime != null) contents['offTime'] = offTime; + + return Messenger._sendCommand('clock_setup', contents); + } + + /// Enable/disable daytime silence period + static Future setDaytimeSilenceEnabled(bool enabled) async { + final contents = { + 'action': 'set_silence', + 'daytime': { + 'enabled': enabled, + } + }; + return Messenger._sendCommand('clock_setup', contents); + } + + /// Set daytime silence start time + static Future setDaytimeSilenceOnTime(String onTime) async { + final contents = { + 'action': 'set_silence', + 'daytime': { + 'onTime': onTime, + } + }; + return Messenger._sendCommand('clock_setup', contents); + } + + /// Set daytime silence end time + static Future setDaytimeSilenceOffTime(String offTime) async { + final contents = { + 'action': 'set_silence', + 'daytime': { + 'offTime': offTime, + } + }; + return Messenger._sendCommand('clock_setup', contents); + } + + /// Enable/disable nighttime silence period + static Future setNighttimeSilenceEnabled(bool enabled) async { + final contents = { + 'action': 'set_silence', + 'nighttime': { + 'enabled': enabled, + } + }; + return Messenger._sendCommand('clock_setup', contents); + } + + /// Set nighttime silence start time + static Future setNighttimeSilenceOnTime(String onTime) async { + final contents = { + 'action': 'set_silence', + 'nighttime': { + 'onTime': onTime, + } + }; + return Messenger._sendCommand('clock_setup', contents); + } + + /// Set nighttime silence end time + static Future setNighttimeSilenceOffTime(String offTime) async { + final contents = { + 'action': 'set_silence', + 'nighttime': { + 'offTime': offTime, + } + }; + return Messenger._sendCommand('clock_setup', contents); + } + + /// Pause Clock Updates (to fix time) + static Future pauseClockUpdates() async { + final contents = { + 'action': 'pause_clock_updates', + }; + return Messenger._sendCommand('clock_setup', contents); + } + + /// Resume Clock Updates (to fix time) + static Future resumeClockUpdates() async { + final contents = { + 'action': 'resume_clock_updates', + }; + return Messenger._sendCommand('clock_setup', contents); + } + + /// Set complete silence configuration at once + static Future setAllSilencePeriods({ + bool? daytimeEnabled, + String? daytimeOnTime, + String? daytimeOffTime, + bool? nighttimeEnabled, + String? nighttimeOnTime, + String? nighttimeOffTime, + }) async { + final contents = { + 'action': 'set_silence', + }; + + if (daytimeEnabled != null || + daytimeOnTime != null || + daytimeOffTime != null) { + contents['daytime'] = {}; + if (daytimeEnabled != null) + contents['daytime']['enabled'] = daytimeEnabled; + if (daytimeOnTime != null) contents['daytime']['onTime'] = daytimeOnTime; + if (daytimeOffTime != null) + contents['daytime']['offTime'] = daytimeOffTime; + } + + if (nighttimeEnabled != null || + nighttimeOnTime != null || + nighttimeOffTime != null) { + contents['nighttime'] = {}; + if (nighttimeEnabled != null) + contents['nighttime']['enabled'] = nighttimeEnabled; + if (nighttimeOnTime != null) + contents['nighttime']['onTime'] = nighttimeOnTime; + if (nighttimeOffTime != null) + contents['nighttime']['offTime'] = nighttimeOffTime; + } + + return Messenger._sendCommand('clock_setup', contents); + } + + /// Batch setup: Configure multiple clock settings at once + static Future batchClockSetup({ + // Outputs + int? c1Output, + int? c2Output, + // Timings + int? pulseDuration, + int? pauseDuration, + // Alerts + String? alertType, + int? alertRingInterval, + int? hourBell, + int? halfBell, + int? quarterBell, + // Backlight + bool? backlightEnabled, + int? backlightOutput, + String? backlightOnTime, + String? backlightOffTime, + // Silence periods + bool? daytimeSilenceEnabled, + String? daytimeSilenceOnTime, + String? daytimeSilenceOffTime, + bool? nighttimeSilenceEnabled, + String? nighttimeSilenceOnTime, + String? nighttimeSilenceOffTime, + }) async { + final contents = { + 'action': 'batch_setup', + }; + + // Add outputs section if any output is specified + if (c1Output != null || c2Output != null) { + contents['outputs'] = {}; + if (c1Output != null) contents['outputs']['c1'] = c1Output; + if (c2Output != null) contents['outputs']['c2'] = c2Output; + } + + // Add timings section if any timing is specified + if (pulseDuration != null || pauseDuration != null) { + contents['timings'] = {}; + if (pulseDuration != null) + contents['timings']['pulseDuration'] = pulseDuration; + if (pauseDuration != null) + contents['timings']['pauseDuration'] = pauseDuration; + } + + // Add alerts section if any alert setting is specified + if (alertType != null || + alertRingInterval != null || + hourBell != null || + halfBell != null || + quarterBell != null) { + contents['alerts'] = {}; + if (alertType != null) contents['alerts']['alertType'] = alertType; + if (alertRingInterval != null) + contents['alerts']['alertRingInterval'] = alertRingInterval; + if (hourBell != null) contents['alerts']['hourBell'] = hourBell; + if (halfBell != null) contents['alerts']['halfBell'] = halfBell; + if (quarterBell != null) contents['alerts']['quarterBell'] = quarterBell; + } + + // Add backlight section if any backlight setting is specified + if (backlightEnabled != null || + backlightOutput != null || + backlightOnTime != null || + backlightOffTime != null) { + contents['backlight'] = {}; + if (backlightEnabled != null) + contents['backlight']['enabled'] = backlightEnabled; + if (backlightOutput != null) + contents['backlight']['output'] = backlightOutput; + if (backlightOnTime != null) + contents['backlight']['onTime'] = backlightOnTime; + if (backlightOffTime != null) + contents['backlight']['offTime'] = backlightOffTime; + } + + // Add silence section if any silence setting is specified + if (daytimeSilenceEnabled != null || + daytimeSilenceOnTime != null || + daytimeSilenceOffTime != null || + nighttimeSilenceEnabled != null || + nighttimeSilenceOnTime != null || + nighttimeSilenceOffTime != null) { + contents['silence'] = {}; + + if (daytimeSilenceEnabled != null || + daytimeSilenceOnTime != null || + daytimeSilenceOffTime != null) { + contents['silence']['daytime'] = {}; + if (daytimeSilenceEnabled != null) + contents['silence']['daytime']['enabled'] = daytimeSilenceEnabled; + if (daytimeSilenceOnTime != null) + contents['silence']['daytime']['onTime'] = daytimeSilenceOnTime; + if (daytimeSilenceOffTime != null) + contents['silence']['daytime']['offTime'] = daytimeSilenceOffTime; + } + + if (nighttimeSilenceEnabled != null || + nighttimeSilenceOnTime != null || + nighttimeSilenceOffTime != null) { + contents['silence']['nighttime'] = {}; + if (nighttimeSilenceEnabled != null) + contents['silence']['nighttime']['enabled'] = nighttimeSilenceEnabled; + if (nighttimeSilenceOnTime != null) + contents['silence']['nighttime']['onTime'] = nighttimeSilenceOnTime; + if (nighttimeSilenceOffTime != null) + contents['silence']['nighttime']['offTime'] = nighttimeSilenceOffTime; + } + } + + return Messenger._sendCommand('clock_setup', contents); + } + + /// Set RTC Time (Real Time Clock) with timezone + static Future setRtcTime([DateTime? dateTime]) async { + final timestamp = + (dateTime ?? DateTime.now()).millisecondsSinceEpoch ~/ 1000; + + // Get current timezone offset in seconds + final now = dateTime ?? DateTime.now(); + final offsetMinutes = now.timeZoneOffset.inMinutes; + final offsetSeconds = offsetMinutes * 60; + + // Detect if DST is likely active (simple heuristic) + final isDST = _isDaylightSavingTime(now); + final dstOffsetSeconds = isDST ? 3600 : 0; // 1 hour DST + + return Messenger._sendCommand('clock_setup', { + 'action': 'set_rtc_time', + 'timestamp': timestamp, + 'timezone_offset': offsetSeconds, + 'dst_offset': dstOffsetSeconds, + 'timezone_name': now.timeZoneName, // e.g., "EET", "EEST" + }); + } + + /// Simple DST detection heuristic + static bool _isDaylightSavingTime(DateTime dateTime) { + // For Europe: DST typically last Sunday in March to last Sunday in October + final year = dateTime.year; + final month = dateTime.month; + + // Rough DST period (March-October) + if (month >= 4 && month <= 9) return true; // Definitely DST + if (month <= 2 || month >= 11) return false; // Definitely standard time + + // March/October need more precise calculation, but this is good enough + return month == 3 ? dateTime.day > 25 : dateTime.day < 25; + } + + /// Set Physical Clock Time (Tower Clock) + static Future setPhysicalClockTime(DateTime dateTime) async { + return Messenger._sendCommand('clock_setup', { + 'action': 'set_physical_clock_time', + 'hour': dateTime.hour, + 'minute': dateTime.minute, + }); + } +} + +class SystemInfo { + static final WebSocketService _ws = WebSocketService(); + + // ============================================================================ + // SYSTEM INFORMATION - Device Status, Time, and Information Requests + // ============================================================================ + + /// Get ESP32 device status and update app state + static Future getDeviceStatus() async { + try { + final response = await _ws.sendAndWaitForResponse( + data: { + 'cmd': 'system_info', + 'contents': {'action': 'report_status'} + }, + matcher: (msg) => + msg['status'] == 'SUCCESS' && msg['type'] == 'current_status', + timeout: const Duration(seconds: 5), + ); + + // Extract payload from the response + final payload = response['payload']; + if (payload == null || payload is! Map) { + debugPrint('Error: Invalid payload in ESP32 status response'); + return null; + } + + // Extract player_status and time_elapsed + final String playerStatus = payload['player_status'] ?? 'idle'; + final dynamic timeElapsedDynamic = payload['time_elapsed']; + final dynamic projectedRunDurationDynamic = payload['projected_run_time']; + final dynamic strikeCountersRaw = payload['strike_counters']; + + // Convert time_elapsed to int, handle potential type mismatches + int timeElapsed = 0; + if (timeElapsedDynamic is int) { + timeElapsed = timeElapsedDynamic; + } else if (timeElapsedDynamic is double) { + timeElapsed = timeElapsedDynamic.toInt(); + } else if (timeElapsedDynamic is String) { + timeElapsed = int.tryParse(timeElapsedDynamic) ?? 0; + } + + // Convert projected_run_time to int, handle potential type mismatches + int projectedRunDuration = 0; + if (projectedRunDurationDynamic is int) { + projectedRunDuration = projectedRunDurationDynamic; + } else if (projectedRunDurationDynamic is double) { + projectedRunDuration = projectedRunDurationDynamic.toInt(); + } else if (projectedRunDurationDynamic is String) { + projectedRunDuration = int.tryParse(projectedRunDurationDynamic) ?? 0; + } + + // Extract and convert strike_counters array + List strikeCounters = []; + if (strikeCountersRaw != null && strikeCountersRaw is List) { + strikeCounters = strikeCountersRaw.map((e) { + if (e is int) return e; + if (e is double) return e.toInt(); + if (e is String) return int.tryParse(e) ?? 0; + return 0; + }).toList(); + } + + // Map ESP32 PlayerStatus to FlutterFlow playback status enum + PlaybackStatus playbackStatus; + switch (playerStatus.toLowerCase()) { + case 'playing': + playbackStatus = PlaybackStatus.playing; + break; + case 'paused': + playbackStatus = PlaybackStatus.paused; + break; + case 'stopping': + playbackStatus = PlaybackStatus.stopping; + break; + case 'idle': + default: + playbackStatus = PlaybackStatus.idle; + break; + } + + // Calculate playbackStartTime (currentTime - time_elapsed) + DateTime? playbackStartTime; + if (playbackStatus == PlaybackStatus.playing && timeElapsed > 0) { + final now = getCurrentTimestamp; + playbackStartTime = DateTime.fromMillisecondsSinceEpoch( + now.millisecondsSinceEpoch - + timeElapsed); // timeElapsed is already in milliseconds + } + + // Calculate projectedEndTime only if we have a start time and projected duration + DateTime? projectedEndTime; + if (playbackStartTime != null && projectedRunDuration > 0) { + projectedEndTime = + playbackStartTime.add(Duration(milliseconds: projectedRunDuration)); + } + + // Update the DeviceStatus app state + FFAppState().update(() { + FFAppState().activeDeviceStatus = DeviceStatusStruct( + playbackStatus: playbackStatus, + playbackStartTime: playbackStartTime, + projectedEndTime: projectedEndTime); + + // Update nested strike counters in activeDeviceSettings > stats > perBellStrikes + // FlutterFlow structs: we need to update the perBellStrikes field + FFAppState().activeDeviceSettings.stats.perBellStrikes = strikeCounters; + }); + + debugPrint( + 'ESP32 Status updated: $playerStatus, elapsed: ${timeElapsed}ms, projectedDuration: ${projectedRunDuration}ms'); + + // Return time_elapsed as before for backward compatibility + return timeElapsed; + } catch (e) { + debugPrint('Error getting ESP32 status: $e'); + + // On error, set device status to unavailable + FFAppState().update(() { + FFAppState().activeDeviceStatus = DeviceStatusStruct( + playbackStatus: PlaybackStatus.unavailable, + playbackStartTime: null, + projectedEndTime: null, + ); + }); + + return null; // Return null on error to distinguish from "not playing" (0) + } + } + + /// Get device time from RTC + static Future getDeviceTime() async { + try { + final response = await _ws.sendAndWaitForResponse( + data: { + 'cmd': 'system_info', + 'contents': {'action': 'get_device_time'} + }, + matcher: (msg) => + msg['status'] == 'SUCCESS' && msg['type'] == 'device_time', + timeout: const Duration(seconds: 5), + ); + + if (response['status'] == 'SUCCESS') { + final payload = response['payload']; + final timestamp = payload['timestamp'] as int?; + if (timestamp != null) { + return DateTime.fromMillisecondsSinceEpoch(timestamp * 1000); + } + + // Alternative: construct from individual components + final year = payload['year'] as int?; + final month = payload['month'] as int?; + final day = payload['day'] as int?; + final hour = payload['hour'] as int?; + final minute = payload['minute'] as int?; + final second = payload['second'] as int?; + + if (year != null && + month != null && + day != null && + hour != null && + minute != null && + second != null) { + return DateTime(year, month, day, hour, minute, second); + } + } + return null; + } catch (e) { + debugPrint('Error getting device time: $e'); + return null; + } + } + + /// Get physical clocktower time + static Future getClocktowerTime() async { + try { + final response = await _ws.sendAndWaitForResponse( + data: { + 'cmd': 'system_info', + 'contents': {'action': 'get_clock_time'} + }, + matcher: (msg) => + msg['status'] == 'SUCCESS' && msg['type'] == 'clock_time', + timeout: const Duration(seconds: 5), + ); + + if (response['status'] == 'SUCCESS') { + final payload = response['payload']; + final hour = payload['clock_hour'] as int?; + final minute = payload['clock_minute'] as int?; + final available = payload['clock_available'] as bool? ?? false; + + if (hour != null && minute != null && available) { + // Create DateTime with today's date but the physical clock's time + final now = DateTime.now(); + return DateTime(now.year, now.month, now.day, hour, minute); + } + } + return null; + } catch (e) { + debugPrint('Error getting clocktower time: $e'); + return null; + } + } + + static Future?> cmdGetNetworkInfo() async { + try { + final response = await WebSocketService().sendAndWaitForResponse( + data: { + "cmd": "system_info", + "contents": {"action": "network_info"} + }, + matcher: (msg) => + msg['status'] == 'SUCCESS' && msg['type'] == 'network_info', + timeout: const Duration(seconds: 5), + ); + + final payload = response['payload']; + if (payload == null || payload is! Map) { + print('Error: Invalid payload in network info response'); + return null; + } + + return [ + payload['ip'] ?? 'unknown', + payload['gateway'] ?? 'unknown', + payload['dns'] ?? 'unknown', + ]; + } catch (e) { + print('Error getting network info: $e'); + return null; + } + } + + /// Get full device settings from ESP32 and update app state + static Future getFullSettings() async { + try { + final response = await _ws.sendAndWaitForResponse( + data: { + 'cmd': 'system_info', + 'contents': {'action': 'get_full_settings'} + }, + matcher: (msg) => + msg['status'] == 'SUCCESS' && msg['type'] == 'full_settings', + timeout: const Duration(seconds: 5), + ); + + final payload = response['payload']; + if (payload == null || payload is! Map) { + print('Error: Invalid payload in full settings response'); + return false; + } + + // Helper function to convert Map to List + List mapToList(Map? map, int size) { + if (map == null) return List.filled(size, 0); + List result = []; + for (int i = 1; i <= size; i++) { + final key = 'b$i'; + final value = map[key]; + if (value is int) { + result.add(value); + } else if (value is double) { + result.add(value.toInt()); + } else if (value is String) { + result.add(int.tryParse(value) ?? 0); + } else { + result.add(0); + } + } + return result; + } + + // Helper function to parse time string to DateTime + DateTime? parseTime(String? timeStr) { + if (timeStr == null || timeStr.isEmpty) return null; + try { + final parts = timeStr.split(':'); + if (parts.length == 2) { + final now = DateTime.now(); + return DateTime( + now.year, + now.month, + now.day, + int.parse(parts[0]), + int.parse(parts[1]), + ); + } + } catch (e) { + print('Error parsing time: $timeStr - $e'); + } + return null; + } + + // Extract bell data + final bellDurationsMap = + payload['bellDurations'] as Map?; + final bellOutputsMap = payload['bellOutputs'] as Map?; + + List hammerTimings = mapToList(bellDurationsMap, 16); + List bellOutputs = mapToList(bellOutputsMap, 16); + + // Extract clock configuration + final clockData = payload['clock'] as Map?; + final alertsData = payload['alerts'] as Map?; + final backlightData = payload['backlight'] as Map?; + final silenceData = payload['silence'] as Map?; + + // Build clock outputs list (c1 and c2) + List clockOutputs = [ + clockData?['c1output'] ?? 255, + clockData?['c2output'] ?? 255, + ]; + + // Build clock timings list (pulse and pause) + List clockTimings = [ + clockData?['pulseDuration'] ?? 5000, + clockData?['pauseDuration'] ?? 2000, + ]; + + // Extract silence period data + final daytimeSilence = silenceData?['daytime'] as Map?; + final nighttimeSilence = + silenceData?['nighttime'] as Map?; + + // Parse alert type - convert ESP32 format to FlutterFlow enum + final alertTypeStr = + (alertsData?['alertType'] ?? 'OFF').toString().toUpperCase(); + + // Get current ringAlerts value to preserve it (will be updated after enum export) + final currentRingAlerts = + FFAppState().activeDeviceSettings.settings.clockSettings.ringAlerts; + + // Build a new DeviceClockSettings struct + // TODO: Once HelperRingAlerts enum is exported from FlutterFlow, replace currentRingAlerts with: + // alertTypeStr == 'SINGLE' ? HelperRingAlerts.single : + // (alertTypeStr == 'HOURS' || alertTypeStr == 'MULTI') ? HelperRingAlerts.multi : + // HelperRingAlerts.disabled + final newClockSettings = DeviceClockSettingsStruct( + clockOutputs: clockOutputs, + clockTimings: clockTimings, + ringAlertsMasterOn: alertTypeStr != 'OFF', + ringAlerts: alertTypeStr == 'SINGLE' + ? HelperRingAlerts.single + : (alertTypeStr == 'HOURS' || alertTypeStr == 'MULTI') + ? HelperRingAlerts.multi + : HelperRingAlerts.disabled, + ringIntervals: alertsData?['alertRingInterval'] ?? 1200, + hourAlertsBell: alertsData?['hourBell'] ?? 255, + halfhourAlertsBell: alertsData?['halfBell'] ?? 255, + quarterAlertsBell: alertsData?['quarterBell'] ?? 255, + isDaySilenceOn: daytimeSilence?['enabled'] ?? false, + isNightSilenceOn: nighttimeSilence?['enabled'] ?? false, + daySilenceFrom: parseTime(daytimeSilence?['onTime']), + daySilenceTo: parseTime(daytimeSilence?['offTime']), + nightSilenceFrom: parseTime(nighttimeSilence?['onTime']), + nightSilenceTo: parseTime(nighttimeSilence?['offTime']), + backlightTurnOnTime: parseTime(backlightData?['onTime']), + backlightTurnOffTime: parseTime(backlightData?['offTime']), + isBacklightAutomationOn: backlightData?['enabled'] ?? false, + backlightOutput: backlightData?['output'] ?? 255, + ); + + // Update FFAppState with the new settings + FFAppState().update(() { + // Update DeviceAttributes fields + FFAppState().activeDeviceSettings.settings.bellOutputs = bellOutputs; + FFAppState().activeDeviceSettings.settings.hammerTimings = + hammerTimings; + FFAppState().activeDeviceSettings.settings.clockSettings = + newClockSettings; + FFAppState().activeDeviceSettings.settings.serialLogLevel = + payload['generalConfig']?['serialLogLevel'] ?? 3; + FFAppState().activeDeviceSettings.settings.sdLogLevel = + payload['generalConfig']?['sdLogLevel'] ?? 0; + }); + + print('Full settings updated successfully'); + return true; + } catch (e) { + print('Error getting full settings: $e'); + return false; + } + } +} + +class Playback { + // ============================================================================ + // PLAYBACK CONTROL - Play and Stop commands (play as batch) + // ============================================================================ + + /// Start playback with full configuration + static Future startPlayback({ + required String name, + required String uid, + String? url, + int? speed, + List? noteAssignments, + int? segmentDuration, + int? pauseDuration, + int? totalDuration, + bool? continuousLoop, + }) async { + if (url == null || speed == null) return null; + + final contents = { + 'action': 'play', + 'uid': uid, + 'speed': speed, + 'segment_duration': segmentDuration ?? 0, + 'pause_duration': pauseDuration ?? 0, + 'total_duration': totalDuration ?? 0, + 'continuous_loop': continuousLoop ?? false, + }; + + contents['url'] = url; + + if (noteAssignments != null) { + final assignments = List.filled(16, 0); + for (int i = 0; i < noteAssignments.length && i < 16; i++) { + assignments[i] = noteAssignments[i]; + } + contents['note_assignments'] = assignments; + } + + return Messenger._sendCommand('playback', contents); + } + + /// Stop current playback + static Future stopPlayback() async { + return Messenger._sendCommand('playback', {'action': 'stop'}); + } +} + +class GeneralCommands { + static final WebSocketService _ws = WebSocketService(); + + /// Send ping to device + static Future ping() async { + try { + final response = await _ws.sendAndWaitForResponse( + data: { + 'cmd': 'system', + 'contents': {'action': 'ping'} + }, + matcher: (msg) => msg['status'] == 'SUCCESS' && msg['type'] == 'pong', + timeout: const Duration(seconds: 3), + ); + + return response['status'] == 'SUCCESS'; + } catch (e) { + debugPrint('Ping failed: $e'); + return false; + } + } + + /// Reset All Settings to Factory Defaults + static Future cmdResetDefaults() async { + try { + final response = await WebSocketService().sendAndWaitForResponse( + data: { + "cmd": "system", + "contents": {"action": "reset_defaults"} + }, + matcher: (msg) => + msg['status'] == 'SUCCESS' && msg['type'] == 'reset_defaults', + timeout: const Duration(seconds: 10), + ); + + print('Reset defaults successful'); + return true; + } catch (e) { + print('Error resetting to defaults: $e'); + return false; + } + } + + /// Identify device type (WebSocket only) + static Future identify(String deviceType) async { + try { + final response = await _ws.sendAndWaitForResponse( + data: { + 'cmd': 'system', + 'contents': { + 'action': 'identify', + 'device_type': deviceType, + } + }, + matcher: (msg) => msg['status'] == 'SUCCESS', + timeout: const Duration(seconds: 5), + ); + + return response['status'] == 'SUCCESS'; + } catch (e) { + debugPrint('Identify failed: $e'); + return false; + } + } +} + +class System { + // ============================================================================ + // SYSTEM CONFIGURATION - Log levels and system settings + // ============================================================================ + + /// Set serial log level (0-5) + /// 0=NONE, 1=ERROR, 2=WARNING, 3=INFO, 4=DEBUG, 5=VERBOSE + static Future setSerialLogLevel(int level) async { + if (level < 0 || level > 5) { + debugPrint('Invalid log level: $level (must be 0-5)'); + return false; + } + + final contents = { + 'action': 'set_serial_log_level', + 'level': level, + }; + + return Messenger._sendCommand('system', contents); + } + + /// Set SD card log level (0-5) - for future use + /// 0=NONE, 1=ERROR, 2=WARNING, 3=INFO, 4=DEBUG, 5=VERBOSE + static Future setSdLogLevel(int level) async { + if (level < 0 || level > 5) { + debugPrint('Invalid log level: $level (must be 0-5)'); + return false; + } + + final contents = { + 'action': 'set_sd_log_level', + 'level': level, + }; + + return Messenger._sendCommand('system', contents); + } +} + +class Network { + static final WebSocketService _ws = WebSocketService(); + + // ============================================================================ + // NETWORK CONFIGURATION - Set network settings + // ============================================================================ + + /// Set network configuration (hostname and/or static IP) + /// All IP addresses should be passed as Strings (e.g., "192.168.1.100") + static Future setNetworkConfig({ + String? hostname, + bool? useStaticIP, + String? ip, + String? gateway, + String? subnet, + String? dns1, + String? dns2, + }) async { + final contents = { + 'action': 'set_network_config', + }; + + // Add hostname if provided + if (hostname != null && hostname.isNotEmpty) { + contents['hostname'] = hostname; + } + + // Add static IP configuration if provided + if (useStaticIP != null) { + contents['useStaticIP'] = useStaticIP; + + // If enabling static IP, include IP configuration + if (useStaticIP) { + if (ip != null && ip.isNotEmpty) contents['ip'] = ip; + if (gateway != null && gateway.isNotEmpty) + contents['gateway'] = gateway; + if (subnet != null && subnet.isNotEmpty) contents['subnet'] = subnet; + if (dns1 != null && dns1.isNotEmpty) contents['dns1'] = dns1; + if (dns2 != null && dns2.isNotEmpty) contents['dns2'] = dns2; + } + } + + return Messenger._sendCommand('system', contents); + } + + /// Set network configuration (hostname and/or static IP) + /// All IP addresses should be passed as String Lists (e.g., ['192','168','1','100']) + static Future setNetworkConfigIPasLists({ + String? hostname, + bool? useStaticIP, + List? ipParts, + List? gatewayParts, + List? subnetParts, + List? dns1Parts, + List? dns2Parts, + }) async { + bool _isValidIp(List? parts) { + if (parts == null || parts.length != 4) return false; + for (final p in parts) { + final num = int.tryParse(p.trim()); + if (num == null || num < 0 || num > 255) return false; + } + return true; + } + + String _joinIp(List parts) => parts.map((e) => e.trim()).join('.'); + + final contents = {'action': 'set_network_config'}; + + if (hostname != null && hostname.isNotEmpty) { + contents['hostname'] = hostname; + } + + if (useStaticIP != null) { + contents['useStaticIP'] = useStaticIP; + + if (useStaticIP) { + // Validate all required IP fields + if (!_isValidIp(ipParts) || + !_isValidIp(gatewayParts) || + !_isValidIp(subnetParts) || + !_isValidIp(dns1Parts)) { + return false; // Missing or invalid field + } + + contents['ip'] = _joinIp(ipParts!); + contents['gateway'] = _joinIp(gatewayParts!); + contents['subnet'] = _joinIp(subnetParts!); + contents['dns1'] = _joinIp(dns1Parts!); + + // Optional DNS2 + if (_isValidIp(dns2Parts)) { + contents['dns2'] = _joinIp(dns2Parts!); + } + } + } + + return Messenger._sendCommand('system', contents); + } +} + +class Messenger { + static final WebSocketService _ws = WebSocketService(); + + static Future _sendCommand( + String command, Map contents) async { + try { + final response = await _ws.sendAndWaitForResponse( + data: {'cmd': command, 'contents': contents}, + matcher: (msg) => msg['status'] == 'SUCCESS', + timeout: const Duration(seconds: 5), + ); + + final success = response['status'] == 'SUCCESS'; + if (!success) { + debugPrint('Command $command failed: ${response['payload']}'); + } + return success; + } catch (e) { + debugPrint('Error sending command $command: $e'); + return false; + } + } +} diff --git a/docs/reference/dart-message-handler.dart b/docs/reference/dart-message-handler.dart new file mode 100644 index 0000000..5b575f5 --- /dev/null +++ b/docs/reference/dart-message-handler.dart @@ -0,0 +1,389 @@ +import 'dart:convert'; +import 'package:flutter/foundation.dart'; +import '/flutter_flow/flutter_flow_util.dart'; +import '/backend/backend.dart'; +import '/backend/schema/structs/index.dart'; +import '/backend/schema/enums/enums.dart'; +import '/custom_code/actions/index.dart'; +import 'dart:async'; +import '/auth/firebase_auth/auth_util.dart' as auth_util; + +class OverloadHandler { + /// Handle Overload - WARNING + static Future handleBellOverloadWarning( + List bellNumbers, List loadPercentages) async { + // Create notification message + String message = 'Bell Overload Warning!\n\n'; + for (int i = 0; i < bellNumbers.length; i++) { + message += 'Bell ${bellNumbers[i]}: ${loadPercentages[i]}% load\n'; + } + message += '\nHey, you are driving the hammers too hard. Calm down.'; + + // Create a notification in user's sub-collection + try { + final currentUser = auth_util.currentUserReference; + final deviceRef = FFAppState().activeDeviceSettings.deviceReference; + + if (currentUser != null && deviceRef != null) { + await currentUser.collection('user_notifications').add({ + 'title': 'Bell Overload Warning', + 'body': message, + 'timestamp': getCurrentTimestamp, + 'type': HelperNotificationTypes.warning, // Using your enum + 'is_read': false, + 'device_ref': deviceRef, + }); + print('Bell overload warning notification created: $message'); + } + } catch (e) { + print('Failed to create bell overload warning notification: $e'); + } + } + + static Future handleBellOverloadCritical( + List bellNumbers, List loadPercentages) async { + // Create critical alert message + String message = 'CRITICAL: Bell Protection Activated!\n\n'; + for (int i = 0; i < bellNumbers.length; i++) { + message += 'Bell ${bellNumbers[i]}: ${loadPercentages[i]}% load\n'; + } + message += + '\nWe noticed overloading so we kicked in the protection for you.'; + + // Create notification in user's sub-collection + try { + final currentUser = auth_util.currentUserReference; + final deviceRef = FFAppState().activeDeviceSettings.deviceReference; + + if (currentUser != null && deviceRef != null) { + await currentUser.collection('user_notifications').add({ + 'title': 'CRITICAL: Bell Protection Activated', + 'body': message, + 'timestamp': getCurrentTimestamp, + 'type': HelperNotificationTypes + .warning, // Using your enum - could also be GENERAL depending on your preference + 'is_read': false, + 'device_ref': deviceRef, + }); + } + } catch (e) { + print('Failed to create critical bell overload notification: $e'); + } + + // Also trigger a popup/dialog by setting app state variables + FFAppState().update(() { + FFAppState().alerts = AlertsStruct( + criticalAlertMessage: message, + showCriticalAlert: true, + errorAlertMessage: + FFAppState().alerts.errorAlertMessage, // Keep existing + showErrorAlert: FFAppState().alerts.showErrorAlert, // Keep existing + alertIsActive: FFAppState().alerts.alertIsActive, + ); + }); + + print('Critical bell overload alert triggered: $message'); + } +} + +class InfoMessageHandler { + static InfoMessageHandler? _instance; + Timer? _clearFiredBellsTimer; + + InfoMessageHandler._internal(); + + factory InfoMessageHandler() { + _instance ??= InfoMessageHandler._internal(); + return _instance!; + } + + Future handleMessage(dynamic data) async { + // Only handle if it's a proper Map and has INFO status + if (data is! Map) { + debugPrint('InfoMessageHandler: Data is not a Map, skipping'); + return; + } + + final Map message = data; + + if (message['status'] != 'INFO') { + debugPrint('InfoMessageHandler: Not an INFO message, skipping'); + return; + } + + final String type = message['type'] ?? ''; + final dynamic payload = message['payload']; + + debugPrint( + 'InfoMessageHandler: Handling INFO message - type: $type, payload: $payload'); + + try { + switch (type) { + case 'playback': + await _handlePlaybackMessage(payload); + break; + + case 'bell_overload': + await _handleBellOverloadMessage(payload); + break; + + case 'general': + case 'error': + case 'warning': + await _handleGeneralInfoMessage(type, payload); + break; + case 'ding': + await _handleDingMessage(payload); + break; + default: + debugPrint('InfoMessageHandler: Unhandled message type: $type'); + } + } catch (e) { + debugPrint('InfoMessageHandler: Error handling message: $e'); + } + } + + Future _handleDingMessage(dynamic payload) async { + debugPrint( + 'InfoMessageHandler: Handling Ding Message with payload: $payload'); + + try { + List firedBells = []; + + if (payload is List) { + // Handle array of bell numbers [1, 3, 5] + for (dynamic bellItem in payload) { + if (bellItem is int) { + firedBells.add(bellItem); + } else if (bellItem is double) { + firedBells.add(bellItem.toInt()); + } else if (bellItem is String) { + final parsed = int.tryParse(bellItem); + if (parsed != null) { + firedBells.add(parsed); + } + } + } + } else if (payload is int) { + firedBells.add(payload); + } else if (payload is double) { + firedBells.add(payload.toInt()); + } else if (payload is String) { + final parsed = int.tryParse(payload); + if (parsed != null) { + firedBells.add(parsed); + } + } + + // Merge with existing fired bells (don't overwrite, combine) + Set combinedBells = + Set.from(FFAppState().activeDeviceStatus.firedBells ?? []); + combinedBells.addAll(firedBells); + + // Update app state with combined bells + FFAppState().update(() { + FFAppState().activeDeviceStatus.firedBells = combinedBells.toList(); + }); + + debugPrint( + 'InfoMessageHandler: Updated firedBells with bells: ${combinedBells.toList()}'); + + // CANCEL any existing timer + _clearFiredBellsTimer?.cancel(); + + // Start NEW timer - this ensures 150ms after the LAST message + _clearFiredBellsTimer = Timer(Duration(milliseconds: 60), () { + FFAppState().update(() { + FFAppState().activeDeviceStatus.firedBells = []; + }); + debugPrint('InfoMessageHandler: Cleared firedBells after 60'); + _clearFiredBellsTimer = null; + }); + } catch (e) { + debugPrint('InfoMessageHandler: Error processing ding message: $e'); + + // On error, clear immediately + _clearFiredBellsTimer?.cancel(); + FFAppState().update(() { + FFAppState().activeDeviceStatus.firedBells = []; + }); + } + } + + Future _handlePlaybackMessage(dynamic payload) async { + debugPrint( + 'InfoMessageHandler: Handling playback message with payload: $payload'); + PlaybackStatus playbackStatus; + + if (payload is String) { + // Simple string payload like "playing", "paused", "stopping", "idle" + switch (payload.toLowerCase()) { + case 'playing': + playbackStatus = PlaybackStatus.playing; + debugPrint('Playback started (via INFO message)'); + break; + case 'paused': + playbackStatus = PlaybackStatus.paused; + debugPrint('Playback is paused (via INFO message)'); + break; + case 'stopping': + playbackStatus = PlaybackStatus.stopping; + debugPrint('Playback is stopping (via INFO message)'); + break; + case 'idle': + playbackStatus = PlaybackStatus.idle; + debugPrint('Playback is idle (via INFO message)'); + break; + default: + playbackStatus = PlaybackStatus.unavailable; + debugPrint('InfoMessageHandler: Unknown playback payload: $payload'); + } + + // For simple string payloads, we don't have timing info + FFAppState().update(() { + FFAppState().activeDeviceStatus = DeviceStatusStruct( + playbackStatus: playbackStatus, + playbackStartTime: playbackStatus == PlaybackStatus.playing + ? getCurrentTimestamp + : null, + projectedEndTime: + null, // No timing info available for simple payloads + ); + }); + } else if (payload is Map) { + // Complex payload with additional data + final String action = payload['action'] ?? ''; + final dynamic timeElapsedDynamic = payload['time_elapsed'] ?? 0; + final dynamic projectedRunTimeDynamic = + payload['projected_run_time'] ?? 0; + + // Convert time_elapsed to int (could be in seconds or milliseconds from ESP32) + int timeElapsed = 0; + if (timeElapsedDynamic is int) { + timeElapsed = timeElapsedDynamic; + } else if (timeElapsedDynamic is double) { + timeElapsed = timeElapsedDynamic.toInt(); + } else if (timeElapsedDynamic is String) { + timeElapsed = int.tryParse(timeElapsedDynamic) ?? 0; + } + + // Convert projected_run_time to int + int projectedRunTime = 0; + if (projectedRunTimeDynamic is int) { + projectedRunTime = projectedRunTimeDynamic; + } else if (projectedRunTimeDynamic is double) { + projectedRunTime = projectedRunTimeDynamic.toInt(); + } else if (projectedRunTimeDynamic is String) { + projectedRunTime = int.tryParse(projectedRunTimeDynamic) ?? 0; + } + + switch (action.toLowerCase()) { + case 'playing': + playbackStatus = PlaybackStatus.playing; + debugPrint( + 'Playback started (via INFO message) with elapsed time: ${timeElapsed}ms, projected duration: ${projectedRunTime}ms'); + break; + case 'paused': + playbackStatus = PlaybackStatus.paused; + debugPrint( + 'Playback paused (via INFO message) with elapsed time: ${timeElapsed}ms'); + break; + case 'stopping': + playbackStatus = PlaybackStatus.stopping; + debugPrint( + 'Playback stopping (via INFO message) with elapsed time: ${timeElapsed}ms'); + break; + case 'idle': + playbackStatus = PlaybackStatus.idle; + debugPrint('Playback is idle (via INFO message)'); + break; + default: + playbackStatus = PlaybackStatus.unavailable; + debugPrint('InfoMessageHandler: Unknown playback action: $action'); + } + + // Calculate playbackStartTime (currentTime - time_elapsed) + // timeElapsed from ESP32 is in seconds, but we need milliseconds + DateTime? playbackStartTime; + if ((playbackStatus == PlaybackStatus.playing || + playbackStatus == PlaybackStatus.paused || + playbackStatus == PlaybackStatus.stopping) && + timeElapsed > 0) { + final now = getCurrentTimestamp; + // timeElapsed is in seconds from ESP32, convert to milliseconds + playbackStartTime = DateTime.fromMillisecondsSinceEpoch( + now.millisecondsSinceEpoch - (timeElapsed * 1000)); + } else if (playbackStatus == PlaybackStatus.playing) { + // If just started playing, use current time + playbackStartTime = getCurrentTimestamp; + } + + // Calculate projectedEndTime only if we have valid data + DateTime? projectedEndTime; + if (playbackStartTime != null && projectedRunTime > 0) { + projectedEndTime = + playbackStartTime.add(Duration(milliseconds: projectedRunTime)); + } + + // Update the DeviceStatus app state + FFAppState().update(() { + FFAppState().activeDeviceStatus = DeviceStatusStruct( + playbackStatus: playbackStatus, + playbackStartTime: playbackStartTime, + projectedEndTime: projectedEndTime, + ); + }); + + debugPrint( + 'InfoMessageHandler: Updated device status - status: $playbackStatus, ' + 'startTime: $playbackStartTime, endTime: $projectedEndTime'); + } + } + + Future _handleBellOverloadMessage(dynamic payload) async { + debugPrint('InfoMessageHandler: Handling bell overload message'); + + if (payload is Map) { + final List? bells = payload['bells']; + final List? loads = payload['loads']; + final String severity = + payload['severity'] ?? 'warning'; // 'warning' or 'critical' + + if (bells != null && loads != null && bells.length == loads.length) { + // Convert to proper types + final List bellNumbers = bells.cast(); + final List loadPercentages = loads.cast(); + + if (severity == 'critical') { + await OverloadHandler.handleBellOverloadCritical( + bellNumbers, loadPercentages); + } else { + await OverloadHandler.handleBellOverloadWarning( + bellNumbers, loadPercentages); + } + } else { + debugPrint( + 'InfoMessageHandler: Invalid bell overload payload structure'); + } + } + } + + Future _handleGeneralInfoMessage(String type, dynamic payload) async { + debugPrint( + 'InfoMessageHandler: Handling general info message - type: $type'); + + String message = ''; + String severity = type; // 'general', 'error', 'warning' + + if (payload is String) { + message = payload; + } else if (payload is Map) { + message = payload['message'] ?? payload.toString(); + severity = payload['severity'] ?? type; + } else { + message = payload.toString(); + } + + await handleGeneralNotification(message, severity); + } +}