diff --git a/.gitmodules b/.gitmodules index 38d0f71..36dad3b 100644 --- a/.gitmodules +++ b/.gitmodules @@ -4,3 +4,6 @@ [submodule "src/VRCFaceTracking"] path = src/VRCFaceTracking url = https://github.com/Project-Babble/VRCFaceTracking.git +[submodule "src/espflash"] + path = src/espflash + url = https://github.com/esp-rs/espflash.git diff --git a/Baballonia.sln b/Baballonia.sln index e8458d4..9cd68f5 100644 --- a/Baballonia.sln +++ b/Baballonia.sln @@ -27,7 +27,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VRCFaceTracking.Core", "src EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VRCFaceTracking.SDK", "src\VRCFaceTracking\VRCFaceTracking.SDK\VRCFaceTracking.SDK.csproj", "{1DD9FEF8-E0D2-48C1-894F-325A2DBE2979}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Baballonia.Tests", "Baballonia.Tests\Baballonia.Tests.csproj", "{2607F8F1-1E25-4C61-9D2A-8387412CA036}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Baballonia.Tests", "src\Baballonia.Tests\Baballonia.Tests.csproj", "{10F4B957-D0DA-4B65-8EA6-20491B031C60}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -68,10 +68,10 @@ Global {1DD9FEF8-E0D2-48C1-894F-325A2DBE2979}.Debug|Any CPU.Build.0 = Debug|Any CPU {1DD9FEF8-E0D2-48C1-894F-325A2DBE2979}.Release|Any CPU.ActiveCfg = Release|Any CPU {1DD9FEF8-E0D2-48C1-894F-325A2DBE2979}.Release|Any CPU.Build.0 = Release|Any CPU - {2607F8F1-1E25-4C61-9D2A-8387412CA036}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2607F8F1-1E25-4C61-9D2A-8387412CA036}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2607F8F1-1E25-4C61-9D2A-8387412CA036}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2607F8F1-1E25-4C61-9D2A-8387412CA036}.Release|Any CPU.Build.0 = Release|Any CPU + {10F4B957-D0DA-4B65-8EA6-20491B031C60}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {10F4B957-D0DA-4B65-8EA6-20491B031C60}.Debug|Any CPU.Build.0 = Debug|Any CPU + {10F4B957-D0DA-4B65-8EA6-20491B031C60}.Release|Any CPU.ActiveCfg = Release|Any CPU + {10F4B957-D0DA-4B65-8EA6-20491B031C60}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Baballonia.Tests/Baballonia.Tests.csproj b/src/Baballonia.Tests/Baballonia.Tests.csproj similarity index 100% rename from Baballonia.Tests/Baballonia.Tests.csproj rename to src/Baballonia.Tests/Baballonia.Tests.csproj diff --git a/Baballonia.Tests/Program.cs b/src/Baballonia.Tests/Program.cs similarity index 98% rename from Baballonia.Tests/Program.cs rename to src/Baballonia.Tests/Program.cs index bbafa6b..e158c1a 100644 --- a/Baballonia.Tests/Program.cs +++ b/src/Baballonia.Tests/Program.cs @@ -52,14 +52,14 @@ class Program // Create payload Payload payload = new Payload { - commands = new Command[] - { + commands = + [ new Command { command = "set_wifi", data = new WifiData { ssid = ssid, password = password } } - } + ] }; // Add mDNS command if hostname is provided diff --git a/src/Baballonia/Baballonia.csproj b/src/Baballonia/Baballonia.csproj index f650ada..7f9f5d4 100644 --- a/src/Baballonia/Baballonia.csproj +++ b/src/Baballonia/Baballonia.csproj @@ -58,6 +58,9 @@ PreserveNewest + + PreserveNewest + @@ -141,5 +144,10 @@ PreserveNewest + + + + + diff --git a/src/Baballonia/Firmware/Windows/espflash.exe b/src/Baballonia/Firmware/Windows/espflash.exe new file mode 100644 index 0000000..bc94c8a Binary files /dev/null and b/src/Baballonia/Firmware/Windows/espflash.exe differ diff --git a/src/Baballonia/Services/Firmware/WirelessFirmware.cs b/src/Baballonia/Services/Firmware/WirelessFirmware.cs index da70717..6a8e79c 100644 --- a/src/Baballonia/Services/Firmware/WirelessFirmware.cs +++ b/src/Baballonia/Services/Firmware/WirelessFirmware.cs @@ -9,7 +9,7 @@ public class WifiData public class MdnsData { - public const string DefaultHostName = "openiris.local"; + public const string DefaultHostName = "openiristracker"; public string hostname { get; set; } } diff --git a/src/Baballonia/Services/FirmwareService.cs b/src/Baballonia/Services/FirmwareService.cs index f48365c..3de70a2 100644 --- a/src/Baballonia/Services/FirmwareService.cs +++ b/src/Baballonia/Services/FirmwareService.cs @@ -16,57 +16,45 @@ public class FirmwareService public event Action OnFirmwareUpdateComplete; public event Action OnFirmwareUpdateError; - private const string PYTHON_COMMAND = "python3"; - private const string ESPTOOL_COMMAND = "esptool"; - private const int DEFAULT_BAUD_RATE = 921600; + private static readonly string EsptoolCommand; + private const int DefaultBaudRate = 921600; // esptool-rs: Setting baud rate higher than 115,200 can cause issues + + static FirmwareService() + { + EsptoolCommand = OperatingSystem.IsWindows() ? "espflash.exe" : "espflash"; + } /// - /// Uploads firmware to an ESP32-S3 device using esptool.py via Python subprocess + /// Uploads firmware to an ESP32-S3 device using an subprocess esptool-rs /// /// COM port where the device is connected /// Path to the firmware file to upload - /// - /// /// Cancellation token - /// /// A task representing the asynchronous operation - public void UploadFirmwareAsync(string port, string pathToFirmware, bool isWireless, string ssid = "", string password = "", CancellationToken token = default) + public void UploadFirmware(string port, string pathToFirmware) { try { - // Check if Python is installed - var hasPython = RunPythonScript(arguments: "--version"); - if (!hasPython) - { - OnFirmwareUpdateError?.Invoke("Python is not installed or not in PATH. Please install Python to continue."); - return; - } - // Check if firmware file exists if (!File.Exists(pathToFirmware)) { - OnFirmwareUpdateError?.Invoke($"Firmware file not found: {pathToFirmware}"); + OnFirmwareUpdateError($"Firmware file not found: {pathToFirmware}"); return; } - // Check for updates to the esptool - RunPythonScript(arguments: $"-m pip install {ESPTOOL_COMMAND}"); - // Notify start of firmware update - OnFirmwareUpdateStart?.Invoke(); + OnFirmwareUpdateStart(); // Create process to run esptool.py - RunPythonScript( - arguments: - $"-m {ESPTOOL_COMMAND} --chip esp32-s3 --port {port} --baud {DEFAULT_BAUD_RATE} write_flash 0x0 \"{pathToFirmware}\""); - - if (isWireless) + if (!RunEspSubprocess( + arguments: + $"write-bin 0x00 \"{pathToFirmware}\" --port {port} --baud {DefaultBaudRate}")) { - SendWirelessCredentials(port, ssid, password); + OnFirmwareUpdateError($"Firmware update failed!"); } - // Firmware update completed successfully - OnFirmwareUpdateComplete?.Invoke(); + // Wired firmware update completed successfully + OnFirmwareUpdateComplete(); } catch (Exception ex) { @@ -74,7 +62,7 @@ public class FirmwareService } } - private void SendWirelessCredentials(string port, string ssid, string password, string hostname = MdnsData.DefaultHostName) + public void SendWirelessCredentials(string port, string ssid, string password, string hostname = MdnsData.DefaultHostName) { // Create payload Payload payload = new Payload @@ -100,13 +88,13 @@ public class FirmwareService string jsonPayload = JsonSerializer.Serialize(payload, new JsonSerializerOptions { - WriteIndented = true + WriteIndented = false }); try { // Create a new SerialPort object with the specified port name and baud rate - using SerialPort serialPort = new SerialPort(port, DEFAULT_BAUD_RATE); + using SerialPort serialPort = new SerialPort(port, DefaultBaudRate); // Set serial port parameters serialPort.DataBits = 8; @@ -115,31 +103,32 @@ public class FirmwareService serialPort.Handshake = Handshake.None; // Set read/write timeouts - serialPort.ReadTimeout = 2000; - serialPort.WriteTimeout = 2000; + serialPort.ReadTimeout = 5000; + serialPort.WriteTimeout = 5000; try { // Open the port serialPort.Open(); + serialPort.DiscardInBuffer(); + serialPort.DiscardOutBuffer(); // Convert the payload to bytes byte[] payloadBytes = Encoding.UTF8.GetBytes(jsonPayload); // Write the payload to the serial port - serialPort.Write(payloadBytes, 0, payloadBytes.Length); + const int chunkSize = 64; + for (int i = 0; i < payloadBytes.Length; i += chunkSize) + { + int length = Math.Min(chunkSize, payloadBytes.Length - i); + serialPort.Write(payloadBytes, i, length); + Thread.Sleep(50); // Small pause between chunks + } // Add a newline to indicate end of message serialPort.Write("\n"); - // Allow time for the device to process - Thread.Sleep(500); - - // Check for response - if (!(serialPort.BytesToRead > 0)) - { - OnFirmwareUpdateError?.Invoke($"Firmware update failed: No response from serial port"); - } + Thread.Sleep(1000); } finally { @@ -152,16 +141,16 @@ public class FirmwareService } catch (Exception ex) { - OnFirmwareUpdateError?.Invoke($"Firmware update failed: {ex.Message}"); + OnFirmwareUpdateError($"Firmware update failed: {ex.Message}"); } } - private bool RunPythonScript(string arguments) + private bool RunEspSubprocess(string arguments) { try { using var process = new Process(); - process.StartInfo.FileName = PYTHON_COMMAND; + process.StartInfo.FileName = EsptoolCommand; process.StartInfo.Arguments = arguments; process.StartInfo.UseShellExecute = true; process.StartInfo.CreateNoWindow = true; @@ -172,7 +161,7 @@ public class FirmwareService } catch (Exception ex) { - OnFirmwareUpdateError?.Invoke($"Firmware update failed: {ex.Message}"); + OnFirmwareUpdateError($"Firmware update failed: {ex.Message}"); return false; } } diff --git a/src/Baballonia/Services/Inference/Captures/VFTCapture.cs b/src/Baballonia/Services/Inference/Captures/VFTCapture.cs index 4533249..481d392 100644 --- a/src/Baballonia/Services/Inference/Captures/VFTCapture.cs +++ b/src/Baballonia/Services/Inference/Captures/VFTCapture.cs @@ -88,22 +88,29 @@ public class VftCapture : Capture private Task VideoCapture_UpdateLoop() { + Mat lut = new Mat(new Size(1,256), MatType.CV_8U); + for (var i = 0; i <= 255; i++) + { + lut.Set(i, (byte)(Math.Pow(i / 2048.0, (1 / 2.5)) * 255.0)); + } while (_loop) { try { - // Grab VideoCapture frame and provide proper cropping/transformations/etc - // Also map YUV color space to RGB IsReady = _videoCapture?.Read(_orignalMat) == true; - Mat yuvConvert = Mat.FromPixelData(400, 400, MatType.CV_8UC2, _orignalMat.Data); - yuvConvert = yuvConvert.CvtColor(ColorConversionCodes.YUV2GRAY_Y422, 0); - yuvConvert = yuvConvert.ColRange(new OpenCvSharp.Range(0, 200)); - yuvConvert = yuvConvert.Resize(new Size(400, 400)); - _mat = yuvConvert; - if (!IsReady) continue; - FrameCount++; - _dimensions.width = _mat.Width; - _dimensions.height = _mat.Height; + if (IsReady) + { + Mat yuvConvert = Mat.FromPixelData(400, 400, MatType.CV_8UC2, _orignalMat.Data); + yuvConvert = yuvConvert.CvtColor(ColorConversionCodes.YUV2GRAY_Y422, 0); + yuvConvert = yuvConvert.ColRange(new OpenCvSharp.Range(0, 200)); + yuvConvert = yuvConvert.Resize(new Size(400, 400)); + yuvConvert = yuvConvert.GaussianBlur(new Size(15, 15), 0); + + _mat = yuvConvert.LUT(lut); + FrameCount++; + _dimensions.width = _mat.Width; + _dimensions.height = _mat.Height; + } } catch (Exception) { diff --git a/src/Baballonia/ViewModels/SplitViewPane/FirmwareViewModel.cs b/src/Baballonia/ViewModels/SplitViewPane/FirmwareViewModel.cs index f797946..8534a4b 100644 --- a/src/Baballonia/ViewModels/SplitViewPane/FirmwareViewModel.cs +++ b/src/Baballonia/ViewModels/SplitViewPane/FirmwareViewModel.cs @@ -1,15 +1,13 @@ -using System.Collections.ObjectModel; +using System; +using System.Collections.ObjectModel; +using System.Diagnostics; using System.IO; using System.IO.Ports; using System.Linq; +using System.Threading; using System.Threading.Tasks; -using System.Windows.Input; -using Avalonia.Controls; -using Avalonia.Controls.Shapes; -using Avalonia.Media; using Avalonia.Threading; using Baballonia.Contracts; -using Baballonia.Models; using Baballonia.Services; using Baballonia.Views; using CommunityToolkit.Mvvm.ComponentModel; @@ -20,24 +18,25 @@ namespace Baballonia.ViewModels.SplitViewPane; public partial class FirmwareViewModel : ViewModelBase { + #region Services and Dependencies + private readonly HomePageView _homePageView; private readonly GithubService _githubService; private readonly FirmwareService _firmwareService; - private ILocalSettingsService _settingsService { get; } - private GithubRelease _githubRelease; + private readonly ILocalSettingsService _settingsService; - public bool IsDeviceSelected { get; private set; } - public bool IsWirelessFirmware { get; private set; } + #endregion + + #region Properties [ObservableProperty] - [property: SavedSetting("LicensedAcknowledged", false)] - private bool _licensedAcknowledged; - - [ObservableProperty] private string _licenseUrl = - "https://github.com/espressif/esptool"; + private bool _isDeviceSelected; [ObservableProperty] - private bool _isReadyToFlashFirmware; + private bool _isWirelessFirmware; + + [ObservableProperty] + private bool _wirelessWarningVisible; [ObservableProperty] private bool _isFlashing; @@ -46,141 +45,284 @@ public partial class FirmwareViewModel : ViewModelBase private bool _isFinished; [ObservableProperty] - [NotifyPropertyChangedFor(nameof(IsReadyToFlashFirmware))] private string _wifiSsid = string.Empty; [ObservableProperty] - [NotifyPropertyChangedFor(nameof(IsReadyToFlashFirmware))] private string _wifiPassword = string.Empty; [ObservableProperty] private ObservableCollection _availableFirmwareTypes = new(); [ObservableProperty] - [NotifyPropertyChangedFor(nameof(IsWirelessFirmware))] - [NotifyPropertyChangedFor(nameof(IsReadyToFlashFirmware))] private string? _selectedFirmwareType; [ObservableProperty] private ObservableCollection _availableSerialPorts = new(); [ObservableProperty] - [NotifyPropertyChangedFor(nameof(IsDeviceSelected))] - [NotifyPropertyChangedFor(nameof(IsReadyToFlashFirmware))] - private string? _selectedSerialPort = string.Empty; + private string? _selectedSerialPort; - public ICommand ProgramCommand { get; } - public ICommand FlashFirmware { get; } - public ICommand AcceptLicense { get; } + public bool IsReadyToFlashFirmware => + !string.IsNullOrEmpty(SelectedSerialPort) && + !string.IsNullOrEmpty(SelectedFirmwareType) && + (!IsWirelessFirmware || + (!string.IsNullOrEmpty(WifiSsid) && !string.IsNullOrEmpty(WifiPassword))); + + #endregion + + #region Commands + + public IRelayCommand RefreshSerialPortsCommand { get; } + public IRelayCommand FlashFirmwareCommand { get; } + public IRelayCommand DismissWirelessWarningCommand { get; } + + #endregion public FirmwareViewModel() { + // Initialize services _homePageView = Ioc.Default.GetService()!; _githubService = Ioc.Default.GetRequiredService(); _firmwareService = Ioc.Default.GetRequiredService(); _settingsService = Ioc.Default.GetService()!; _settingsService.Load(this); - ProgramCommand = new RelayCommand(RefreshSerialPorts); - FlashFirmware = new RelayCommand(FlashDeviceFirmware); - AcceptLicense = new RelayCommand(AcceptedLicense); + // Initialize commands + RefreshSerialPortsCommand = new RelayCommand(RefreshSerialPorts); + FlashFirmwareCommand = new RelayCommand(FlashDeviceFirmware, () => IsReadyToFlashFirmware && !IsFlashing); + DismissWirelessWarningCommand = new RelayCommand(OnDismissWirelessWarning); + + // Initialize events + _firmwareService.OnFirmwareUpdateStart += HandleFirmwareUpdateStart; + _firmwareService.OnFirmwareUpdateError += msg => Debug.WriteLine(msg); + _firmwareService.OnFirmwareUpdateComplete += HandleFirmwareUpdateComplete; + + // Initial state setup RefreshSerialPorts(); + LoadAvailableFirmwareTypesAsync(); - IsFinished = false; - IsFlashing = false; - _firmwareService.OnFirmwareUpdateStart += async () => - { - IsFlashing = true; - IsFinished = false; - - }; - _firmwareService.OnFirmwareUpdateComplete += async () => - { - IsFlashing = false; - IsFinished = true; - }; - - Task.Run(async () => - { - _githubRelease = await _githubService.GetReleases("EyeTrackVR", "OpenIris"); - foreach (var asset in _githubRelease.assets) - { - if (asset.name.ToLower().Contains("babble")) - { - AvailableFirmwareTypes.Add(asset.name); - } - } - }); + // Setup property changed handlers + SetupPropertyChangeHandlers(); + } + private void SetupPropertyChangeHandlers() + { PropertyChanged += (_, args) => { switch (args.PropertyName) { - case nameof(SelectedSerialPort) when string.IsNullOrEmpty(SelectedSerialPort): - IsDeviceSelected = false; - return; case nameof(SelectedSerialPort): - IsDeviceSelected = true; + IsDeviceSelected = !string.IsNullOrEmpty(SelectedSerialPort); + OnPropertyChanged(nameof(IsReadyToFlashFirmware)); break; - case nameof(SelectedFirmwareType) when string.IsNullOrEmpty(SelectedFirmwareType): - return; + case nameof(SelectedFirmwareType): - IsWirelessFirmware = !SelectedFirmwareType!.Contains("Babble_USB"); + if (!string.IsNullOrEmpty(SelectedFirmwareType)) + { + IsWirelessFirmware = !SelectedFirmwareType.Contains("Babble_USB"); + OnPropertyChanged(nameof(IsReadyToFlashFirmware)); + } + break; + + case nameof(WifiSsid): + case nameof(WifiPassword): + if (IsWirelessFirmware) + { + OnPropertyChanged(nameof(IsReadyToFlashFirmware)); + } break; } - if (IsWirelessFirmware) - { - _isReadyToFlashFirmware = - !string.IsNullOrEmpty(SelectedSerialPort) && - !string.IsNullOrEmpty(SelectedFirmwareType) && - !string.IsNullOrEmpty(WifiSsid) && - !string.IsNullOrEmpty(WifiPassword); - } - else - { - _isReadyToFlashFirmware = - !string.IsNullOrEmpty(SelectedSerialPort) && - !string.IsNullOrEmpty(SelectedFirmwareType); - } + // Re-evaluate command's CanExecute status + FlashFirmwareCommand.NotifyCanExecuteChanged(); }; } - private async void AcceptedLicense() + #region UI Event Handlers + + private void OnDismissWirelessWarning() { - await _settingsService.SaveSettingAsync("LicensedAcknowledged", true); - LicensedAcknowledged = true; + WirelessWarningVisible = false; } + private void HandleFirmwareUpdateStart() + { + Dispatcher.UIThread.Post(() => + { + IsFlashing = true; + IsFinished = false; + FlashFirmwareCommand.NotifyCanExecuteChanged(); + }); + } + + private void HandleFirmwareUpdateComplete() + { + Dispatcher.UIThread.Post(() => + { + IsFlashing = false; + + if (IsWirelessFirmware) + { + WirelessWarningVisible = true; + } + else + { + IsFinished = true; + } + + FlashFirmwareCommand.NotifyCanExecuteChanged(); + }); + } + + #endregion + + #region Operations + public void RefreshSerialPorts() { AvailableSerialPorts.Clear(); - foreach (var name in SerialPort.GetPortNames()) + + foreach (var port in SerialPort.GetPortNames()) { - AvailableSerialPorts.Add(name); + AvailableSerialPorts.Add(port); + } + } + + private async void LoadAvailableFirmwareTypesAsync() + { + try + { + var githubRelease = await _githubService.GetReleases("EyeTrackVR", "OpenIris"); + + await Dispatcher.UIThread.InvokeAsync(() => + { + AvailableFirmwareTypes.Clear(); + foreach (var asset in githubRelease.assets) + { + if (asset.name.ToLower().Contains("babble")) + { + AvailableFirmwareTypes.Add(asset.name); + } + } + }); + } + catch (Exception ex) + { + // Log or handle the exception + System.Diagnostics.Debug.WriteLine($"Error loading firmware types: {ex.Message}"); } } private async void FlashDeviceFirmware() { - await Task.Run(async () => + if (string.IsNullOrEmpty(SelectedFirmwareType) || string.IsNullOrEmpty(SelectedSerialPort)) { - var releases = await _githubService.GetReleases("EyeTrackVR", "OpenIris"); - var asset = releases.assets.Where(asset => asset.name == SelectedFirmwareType)!.First(); - var tempDir = Directory.CreateTempSubdirectory().FullName; - var pathToBinary = await _githubService.DownloadAndExtractOpenIrisRelease(tempDir, asset.browser_download_url, asset.name); + return; + } - _homePageView.StopLeftCamera(null, null!); - _homePageView.StopRightCamera(null, null!); - _homePageView.StopFaceCamera(null, null!); + string? tempDir = null; + CancellationTokenSource cts = new CancellationTokenSource(); - _firmwareService.UploadFirmwareAsync(_selectedSerialPort!, pathToBinary.firmwarePath, IsWirelessFirmware, WifiSsid, WifiPassword); - Directory.Delete(tempDir, true); - }); + try + { + await Task.Run(async () => + { + var releases = await _githubService.GetReleases("EyeTrackVR", "OpenIris"); + var asset = releases.assets.FirstOrDefault(a => a.name == SelectedFirmwareType); + + if (asset == null) + { + throw new Exception($"Selected firmware {SelectedFirmwareType} not found"); + } + + tempDir = Directory.CreateTempSubdirectory().FullName; + var pathToBinary = await _githubService.DownloadAndExtractOpenIrisRelease( + tempDir, + asset.browser_download_url, + asset.name); + + // Stop all cameras before firmware update + await Dispatcher.UIThread.InvokeAsync(() => + { + _homePageView.StopLeftCamera(null, null!); + _homePageView.StopRightCamera(null, null!); + _homePageView.StopFaceCamera(null, null!); + }); + + _firmwareService.UploadFirmware(SelectedSerialPort!, pathToBinary.firmwarePath); + + if (IsWirelessFirmware) + { + // Wait for user to acknowledge reconnection + var wirelessReconnectionEvent = new TaskCompletionSource(); + + // Set up a one-time event handler to catch when warning is dismissed + void WirelessWarningHandler(object? sender, System.ComponentModel.PropertyChangedEventArgs e) + { + if (e.PropertyName == nameof(WirelessWarningVisible) && !WirelessWarningVisible) + { + wirelessReconnectionEvent.SetResult(true); + PropertyChanged -= WirelessWarningHandler; + } + } + + PropertyChanged += WirelessWarningHandler; + + // Wait for user to dismiss the warning or for timeout + var timeoutTask = Task.Delay(Timeout.InfiniteTimeSpan, cts.Token); + var completedTask = await Task.WhenAny(wirelessReconnectionEvent.Task, timeoutTask); + + // Only send credentials if not timed out and not canceled + if (completedTask == wirelessReconnectionEvent.Task && !cts.Token.IsCancellationRequested) + { + Dispatcher.UIThread.Post(() => IsFlashing = true); + _firmwareService.SendWirelessCredentials(SelectedSerialPort!, WifiSsid, WifiPassword); + Dispatcher.UIThread.Post(() => IsFlashing = false); + Dispatcher.UIThread.Post(() => IsFinished = true); + } + } + }, cts.Token); + } + catch (TaskCanceledException) + { + // Operation was canceled, no need for additional handling + } + catch (Exception ex) + { + // Log or display error to user + Debug.WriteLine($"Error during firmware update: {ex.Message}"); + IsFlashing = false; + IsFinished = false; + } + finally + { + cts.Dispose(); + + // Clean up temp directory + if (tempDir != null && Directory.Exists(tempDir)) + { + try + { + Directory.Delete(tempDir, true); + } + catch + { + // Ignore cleanup errors + } + } + } } - public void OpenLicenseUrl() + #endregion + + #region Cleanup + + // Called when the ViewModel is no longer needed + public void Cleanup() { - Utils.OpenUrl(LicenseUrl); + _firmwareService.OnFirmwareUpdateStart -= HandleFirmwareUpdateStart; + _firmwareService.OnFirmwareUpdateComplete -= HandleFirmwareUpdateComplete; } + + #endregion } diff --git a/src/Baballonia/Views/FirmwareView.axaml b/src/Baballonia/Views/FirmwareView.axaml index 4c30c5d..86c9a94 100644 --- a/src/Baballonia/Views/FirmwareView.axaml +++ b/src/Baballonia/Views/FirmwareView.axaml @@ -89,14 +89,13 @@