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; } } }