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>
390 lines
14 KiB
Dart
390 lines
14 KiB
Dart
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);
|
|
}
|
|
}
|