docs: add hardware bring-up sketches, known-issues note, and tablet reference

Standalone Arduino test sketches for IS31FL3193 LED driver and PCF8575/PCF8574
relay bring-up (not part of the PlatformIO build), a known-issues note, and
two Dart files from the tablet app kept as reference for the comms protocol.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-09-18 08:36:31 +03:00
co-authored by Claude Sonnet 5
parent 230c1edfed
commit 2748cd5cce
6 changed files with 2039 additions and 0 deletions
@@ -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 <Wire.h>
#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");
}
@@ -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 <Wire.h>
#include <Adafruit_PCF8575.h>
// ── 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);
}
@@ -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 <Wire.h>
#include <Adafruit_PCF8574.h>
#include <Adafruit_PCF8575.h>
// ── 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);
}
+1
View File
@@ -0,0 +1 @@
- Uptime on the hearbeat maxes out at 299 days.
File diff suppressed because it is too large Load Diff
+389
View File
@@ -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<void> handleBellOverloadWarning(
List<int> bellNumbers, List<int> 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<void> handleBellOverloadCritical(
List<int> bellNumbers, List<int> 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<void> handleMessage(dynamic data) async {
// Only handle if it's a proper Map and has INFO status
if (data is! Map<String, dynamic>) {
debugPrint('InfoMessageHandler: Data is not a Map, skipping');
return;
}
final Map<String, dynamic> 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<void> _handleDingMessage(dynamic payload) async {
debugPrint(
'InfoMessageHandler: Handling Ding Message with payload: $payload');
try {
List<int> 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<int> combinedBells =
Set<int>.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<void> _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<String, dynamic>) {
// 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<void> _handleBellOverloadMessage(dynamic payload) async {
debugPrint('InfoMessageHandler: Handling bell overload message');
if (payload is Map<String, dynamic>) {
final List<dynamic>? bells = payload['bells'];
final List<dynamic>? 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<int> bellNumbers = bells.cast<int>();
final List<int> loadPercentages = loads.cast<int>();
if (severity == 'critical') {
await OverloadHandler.handleBellOverloadCritical(
bellNumbers, loadPercentages);
} else {
await OverloadHandler.handleBellOverloadWarning(
bellNumbers, loadPercentages);
}
} else {
debugPrint(
'InfoMessageHandler: Invalid bell overload payload structure');
}
}
}
Future<void> _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<String, dynamic>) {
message = payload['message'] ?? payload.toString();
severity = payload['severity'] ?? type;
} else {
message = payload.toString();
}
await handleGeneralNotification(message, severity);
}
}