using System.Collections.Concurrent; using System.Reactive.Linq; using System.Reactive.Subjects; using Windows.Devices.Bluetooth; using Windows.Devices.Bluetooth.Advertisement; using Windows.Devices.Bluetooth.GenericAttributeProfile; using Windows.Storage.Streams; using TuneBoss.Core.Models; using TuneBoss.Core.Protocol; using System.Runtime.InteropServices.WindowsRuntime; namespace TuneBoss.Core.BLE; /// /// Windows WinRT BLE implementation of IBleService. /// Uses Nordic UART Service (NUS) over a single bidirectional characteristic. /// public sealed class BleManager : IBleService { // ── NUS UUIDs ──────────────────────────────────────────────────────────── private static readonly Guid NusServiceUuid = new("0000f0f0-0000-1000-8000-00805f9b34fb"); private static readonly Guid NusCharUuid = new("0000f0f1-0000-1000-8000-00805f9b34fb"); // ── Config ─────────────────────────────────────────────────────────────── private const int CommandTimeoutMs = 3000; // 3s default timeout private const int SilenceWindowMs = 300; // diag silence detection window private const int MaxSilenceWaitMs = 5000; // max wait for diagnostics drain private const int KeepaliveIdleMs = 15000; // send keepalive after 15s idle // ── GATT resources ─────────────────────────────────────────────────────── private BluetoothLEDevice? _device; private GattDeviceService? _nusService; private GattCharacteristic? _nusChar; // ── State ──────────────────────────────────────────────────────────────── private BleConnectionState _connectionState = BleConnectionState.Disconnected; private GenerationConfig? _genConfig; private byte _seqNum = 1; // ── Rx processing ──────────────────────────────────────────────────────── private readonly ConcurrentQueue _bleQueue = new(); private readonly SemaphoreSlim _bleSignal = new(0); private CancellationTokenSource? _loopCts; // ── Packet parser state ────────────────────────────────────────────────── private readonly PacketParser _parser; // ── Response rendezvous ────────────────────────────────────────────────── // The BLE receive loop sets this when a non-streaming packet arrives. private readonly SemaphoreSlim _responseReady = new(0); private volatile byte[]? _responsePayload; private readonly object _responseLock = new(); // ── Diagnostics ────────────────────────────────────────────────────────── private readonly Subject _diagSubject = new(); private volatile bool _diagnosticsRunning; private long _lastDiagTickUtc; // ── Observables ────────────────────────────────────────────────────────── private readonly BehaviorSubject _connSubject = new(BleConnectionState.Disconnected); private readonly Subject _scanSubject = new(); private BluetoothLEAdvertisementWatcher? _watcher; // ── Keepalive ──────────────────────────────────────────────────────────── private long _lastCommandTickUtc; // ──────────────────────────────────────────────────────────────────────── // Constructor // ──────────────────────────────────────────────────────────────────────── public BleManager() { _parser = new PacketParser(OnFullPacketReceived); } // ── IBleService: State ─────────────────────────────────────────────────── public BleConnectionState ConnectionState => _connectionState; public bool IsConnected => _connectionState == BleConnectionState.Connected; public IObservable ConnectionStateChanged => _connSubject.AsObservable(); public IObservable DiagnosticsFrames => _diagSubject.AsObservable(); public bool DiagnosticsRunning => _diagnosticsRunning; // ──────────────────────────────────────────────────────────────────────── // SCANNING // ──────────────────────────────────────────────────────────────────────── /// Checks that a Bluetooth adapter exists, supports LE, and its radio is on. /// Never throws — any failure comes back as IsReady=false with a reason. public async Task CheckBluetoothAsync() { try { var adapter = await BluetoothAdapter.GetDefaultAsync(); if (adapter == null) return new BluetoothAvailability(false, "No Bluetooth adapter found on this PC."); if (!adapter.IsLowEnergySupported) return new BluetoothAvailability(false, "This PC's Bluetooth does not support Bluetooth LE."); var radio = await adapter.GetRadioAsync(); if (radio == null) return new BluetoothAvailability(false, "Could not access the Bluetooth radio."); if (radio.State != Windows.Devices.Radios.RadioState.On) return new BluetoothAvailability(false, "Bluetooth is turned off. Please turn it on, then press Scan."); return new BluetoothAvailability(true, string.Empty); } catch (Exception ex) { return new BluetoothAvailability(false, $"Bluetooth is unavailable: {ex.Message}"); } } public IObservable StartScan() { var seen = new Dictionary(); _watcher = new BluetoothLEAdvertisementWatcher { ScanningMode = BluetoothLEScanningMode.Active }; _watcher.SignalStrengthFilter.InRangeThresholdInDBm = -127; _watcher.SignalStrengthFilter.OutOfRangeThresholdInDBm = -127; _watcher.SignalStrengthFilter.OutOfRangeTimeout = null; _watcher.Received += (_, args) => { ulong addr = args.BluetoothAddress; string name = args.Advertisement.LocalName?.Trim() ?? string.Empty; bool hasName = !string.IsNullOrWhiteSpace(name); lock (seen) { if (!seen.ContainsKey(addr)) { seen[addr] = hasName ? name : $"Unknown [{new BleDeviceInfo(addr, "", 0).MacAddress}]"; _scanSubject.OnNext(new BleDeviceInfo(addr, seen[addr], args.RawSignalStrengthInDBm)); } else if (hasName && seen[addr].StartsWith("Unknown")) { seen[addr] = name; _scanSubject.OnNext(new BleDeviceInfo(addr, name, args.RawSignalStrengthInDBm)); } } }; // Guard the radio-off / adapter-missing case so a scan start can never crash the // app. Callers should CheckBluetoothAsync() first, but this is the safety net. try { _watcher.Start(); } catch (Exception) { _watcher = null; } return _scanSubject.AsObservable(); } public void StopScan() { _watcher?.Stop(); _watcher = null; } // ──────────────────────────────────────────────────────────────────────── // CONNECTION // ──────────────────────────────────────────────────────────────────────── public async Task ConnectAsync(BleDeviceInfo device, CancellationToken ct = default) { SetState(BleConnectionState.Connecting); try { // Step 1: Resolve device _device = await BluetoothLEDevice.FromBluetoothAddressAsync(device.Address); if (_device == null) return Fail("Could not resolve device from address."); _device.ConnectionStatusChanged += OnDeviceConnectionStatusChanged; // Step 2: Open GATT channel with retry if (!await OpenGattChannelAsync(ct)) return Fail("Could not open GATT channel."); // Step 3: Stabilize await Task.Delay(1500, ct); // Step 4: Get NUS service _nusService = await GetServiceAsync(NusServiceUuid, ct); if (_nusService == null) return Fail("NUS service not found."); // Step 5: Get characteristic _nusChar = await GetCharacteristicAsync(_nusService, NusCharUuid, ct); if (_nusChar == null) return Fail("NUS characteristic not found."); // Step 6: Enable notifications _nusChar.ValueChanged += OnCharValueChanged; await _nusChar.WriteClientCharacteristicConfigurationDescriptorAsync( GattClientCharacteristicConfigurationDescriptorValue.Notify); // Step 7: Start BLE processing loop StartProcessingLoop(); SetState(BleConnectionState.Connected); return true; } catch (OperationCanceledException) { return Fail("Connection cancelled."); } catch (Exception ex) { return Fail($"Connection error: {ex.Message}"); } } public async Task DisconnectAsync() { SetState(BleConnectionState.Disconnecting); if (_diagnosticsRunning) await StopDiagnosticsAsync(); StopProcessingLoop(); if (_nusChar != null) { _nusChar.ValueChanged -= OnCharValueChanged; try { await _nusChar.WriteClientCharacteristicConfigurationDescriptorAsync( GattClientCharacteristicConfigurationDescriptorValue.None); } catch { } } _nusChar = null; _nusService?.Dispose(); _nusService = null; if (_device != null) { _device.ConnectionStatusChanged -= OnDeviceConnectionStatusChanged; _device.Dispose(); _device = null; } SetState(BleConnectionState.Disconnected); } // ──────────────────────────────────────────────────────────────────────── // DEVICE INFO // ──────────────────────────────────────────────────────────────────────── public async Task ReadEcuInfoAsync(CancellationToken ct = default) { var frame = PacketBuilder.BuildReadInfo(NextSeq()); var result = await SendAndWaitAsync(frame, ct); if (!result.Success) return null; var info = EcuInfo.Parse(result.Payload); // Store generation config for subsequent table operations var gen = GenerationConfig.ResolveGeneration(info.AppInfoVersion); _genConfig = GenerationConfig.For(gen); return info; } // ──────────────────────────────────────────────────────────────────────── // AUTH // ──────────────────────────────────────────────────────────────────────── public async Task UnlockAsync(string password, CancellationToken ct = default) { var payload = BuildUnlockPayload(_genConfig?.UnlockCmd ?? Commands.APP_UNLOCK, password, isReset: false); var frame = PacketBuilder.Build(Commands.TL_NONPOSTED, NextSeq(), payload); return await SendAndWaitAsync(frame, ct); } public async Task UnlockTunerAsync(string password, CancellationToken ct = default) { var payload = BuildUnlockPayload(Commands.APP_UNLOCK_TUNER, password, isReset: false); var frame = PacketBuilder.Build(Commands.TL_NONPOSTED, NextSeq(), payload); return await SendAndWaitAsync(frame, ct); } // ──────────────────────────────────────────────────────────────────────── // TABLE OPERATIONS // ──────────────────────────────────────────────────────────────────────── public Task ReadTable2DAsync(ushort address, byte lengthBytes, bool userTable = false, CancellationToken ct = default) => ReadTableAsync( userTable ? (_genConfig?.ReadCmd2DUser ?? Commands.APP_MEMRD_2D_USER) : (_genConfig?.ReadCmd2D ?? Commands.APP_MEMRD_2D), address, lengthBytes, ct); public Task WriteTable2DAsync(ushort address, byte[] data, bool userTable = false, CancellationToken ct = default) => WriteTableAsync( userTable ? (_genConfig?.WriteCmd2DUser ?? Commands.APP_MEMWR_2D_USER) : (_genConfig?.WriteCmd2D ?? Commands.APP_MEMWR_2D), address, data, ct); public Task ReadTable1DAsync(ushort address, byte lengthBytes, CancellationToken ct = default) => ReadTableAsync(_genConfig?.ReadCmd1D ?? Commands.APP_MEMRD_1D, address, lengthBytes, ct); public Task WriteTable1DAsync(ushort address, byte[] data, CancellationToken ct = default) => WriteTableAsync(_genConfig?.WriteCmd1D ?? Commands.APP_MEMWR_1D, address, data, ct); public Task ReadSubTableAsync(ushort address, CancellationToken ct = default) => ReadTableAsync(_genConfig?.ReadCmdSubT ?? Commands.APP_MEMRD_SUBT, address, (byte)TuneBoss.Core.Models.SubTable.TotalBytes, ct); public Task WriteSubTableAsync(ushort address, byte[] data, CancellationToken ct = default) => WriteTableAsync(_genConfig?.WriteCmdSubT ?? Commands.APP_MEMWR_SUBT, address, data, ct); public Task ReadMiscAsync(ushort address, byte lengthBytes, CancellationToken ct = default) => ReadTableAsync(_genConfig?.ReadCmdMisc ?? Commands.APP_MEMRD_MISC, address, lengthBytes, ct); public Task WriteMiscAsync(ushort address, byte[] data, CancellationToken ct = default) => WriteTableAsync(_genConfig?.WriteCmdMisc ?? Commands.APP_MEMWR_MISC, address, data, ct); // ──────────────────────────────────────────────────────────────────────── // FLASH WRITE // ──────────────────────────────────────────────────────────────────────── public async Task FlashWriteAsync(CancellationToken ct = default) { await StopDiagnosticsIfRunningAsync(ct); var now = DateTime.Now; var payload = new byte[] { Commands.APP_FLASH_WR, (byte)'F', (byte)'S', (byte)'R', (byte)now.Day, (byte)now.Month, (byte)(now.Year % 100), 0x00 }; var frame = PacketBuilder.Build(Commands.TL_NONPOSTED, NextSeq(), payload); var result = await SendAndWaitAsync(frame, ct); await RestartDiagnosticsIfStoppedAsync(ct); return result; } // ──────────────────────────────────────────────────────────────────────── // FIRST-USE SETTINGS (APP_FIRSTUSE) // ──────────────────────────────────────────────────────────────────────── public async Task WriteFirstUseAsync(byte[] fourBytes, CancellationToken ct = default) { if (fourBytes is null || fourBytes.Length < 4) return CommandResult.Fail(0x00, "First-use payload must be 4 bytes."); // Legacy updateFirstUseSettings layout: [APP_FIRSTUSE, 0x00, 0x00, 0x00, b0, b1, b2, b3] var payload = new byte[] { Commands.APP_FIRSTUSE, 0x00, 0x00, 0x00, fourBytes[0], fourBytes[1], fourBytes[2], fourBytes[3], }; var frame = PacketBuilder.Build(Commands.TL_NONPOSTED, NextSeq(), payload); return await SendAndWaitAsync(frame, ct); } // ──────────────────────────────────────────────────────────────────────── // DIAGNOSTICS // ──────────────────────────────────────────────────────────────────────── public async Task StartDiagnosticsAsync(CancellationToken ct = default) { if (_diagnosticsRunning) return; _diagnosticsRunning = true; Interlocked.Exchange(ref _lastDiagTickUtc, DateTime.UtcNow.Ticks); await SendRawAsync(PacketBuilder.BuildMonStart()); } public async Task StopDiagnosticsAsync(CancellationToken ct = default) { if (!_diagnosticsRunning) return; _diagnosticsRunning = false; await SendRawAsync(PacketBuilder.BuildMonStop()); // Wait for silence — device keeps sending 0x70s for a while after STOP Interlocked.Exchange(ref _lastDiagTickUtc, DateTime.UtcNow.Ticks); int waited = 0; while (waited < MaxSilenceWaitMs) { await Task.Delay(100, ct); waited += 100; long elapsed = (DateTime.UtcNow.Ticks - Interlocked.Read(ref _lastDiagTickUtc)) / TimeSpan.TicksPerMillisecond; if (elapsed >= SilenceWindowMs) break; } // Flush residual 0x70 packets _parser.Reset(); while (_bleQueue.TryDequeue(out byte[]? _)) { } } // ──────────────────────────────────────────────────────────────────────── // KEEPALIVE // ──────────────────────────────────────────────────────────────────────── public void OnKeepaliveTimer() { if (!IsConnected) return; long idleMs = (DateTime.UtcNow.Ticks - Interlocked.Read(ref _lastCommandTickUtc)) / TimeSpan.TicksPerMillisecond; if (idleMs >= KeepaliveIdleMs) _ = SendRawAsync(PacketBuilder.BuildReadInfo(NextSeq())); } // ──────────────────────────────────────────────────────────────────────── // PRIVATE: Table helpers // ──────────────────────────────────────────────────────────────────────── private async Task ReadTableAsync( byte cmd, ushort address, byte lengthBytes, CancellationToken ct) { await StopDiagnosticsIfRunningAsync(ct); var addrBytes = BitConverter.GetBytes(address); // little-endian var payload = new byte[] { cmd, lengthBytes, addrBytes[0], addrBytes[1] }; var frame = PacketBuilder.Build(Commands.TL_NONPOSTED, NextSeq(), payload); // Flush residual diagnostic packets before sending _parser.Reset(); while (_bleQueue.TryDequeue(out byte[]? _)) { } var result = await SendAndWaitAsync(frame, ct); await RestartDiagnosticsIfStoppedAsync(ct); return result; } private async Task WriteTableAsync( byte cmd, ushort address, byte[] data, CancellationToken ct) { await StopDiagnosticsIfRunningAsync(ct); var addrBytes = BitConverter.GetBytes(address); var payload = new byte[4 + data.Length]; payload[0] = cmd; // The length byte is the LAST inclusive offset the device writes (offset 0..N), // exactly like the read commands — so N = data.Length - 1. Sending the raw count // wrote one byte past the region and returned 0x54 (APP_MEMADDR_INV) — seen on the // tightly-packed 1D tables and on 2D part-2 writes (100-byte tail region). payload[1] = (byte)(data.Length - 1); payload[2] = addrBytes[0]; payload[3] = addrBytes[1]; data.CopyTo(payload, 4); var frame = PacketBuilder.Build(Commands.TL_NONPOSTED, NextSeq(), payload); var result = await SendAndWaitAsync(frame, ct); await RestartDiagnosticsIfStoppedAsync(ct); return result; } private async Task StopDiagnosticsIfRunningAsync(CancellationToken ct) { if (_diagnosticsRunning) await StopDiagnosticsAsync(ct); } private async Task RestartDiagnosticsIfStoppedAsync(CancellationToken ct) { // Intentionally does NOT auto-restart here. Resume is driven by the ViewModel // layer (ResumeDiagnosticsIfLiveAsync) which knows whether the strip should be // live. Restarting here as well caused a double MON_START and a frame storm that // disrupted the next command's response matching (froze edits / writes). } // ──────────────────────────────────────────────────────────────────────── // PRIVATE: Send and wait for response // ──────────────────────────────────────────────────────────────────────── private async Task SendAndWaitAsync(byte[] frame, CancellationToken ct) { lock (_responseLock) { _responsePayload = null; // drain any stale ready signal while (_responseReady.CurrentCount > 0) _responseReady.Wait(0); } await SendRawAsync(frame); Interlocked.Exchange(ref _lastCommandTickUtc, DateTime.UtcNow.Ticks); using var timeout = new CancellationTokenSource(CommandTimeoutMs); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeout.Token); try { await _responseReady.WaitAsync(linked.Token); } catch (OperationCanceledException) { return timeout.IsCancellationRequested ? CommandResult.Timeout() : CommandResult.Fail(0x00, "Cancelled"); } var payload = _responsePayload; if (payload == null || payload.Length == 0) return CommandResult.Fail(0x00, "Empty response"); return payload[0] == 0x51 ? CommandResult.Ok(payload) : CommandResult.Fail(payload[0], $"Device returned 0x{payload[0]:X2}"); } private async Task SendRawAsync(byte[] frame) { if (_nusChar == null) return; var writer = new DataWriter(); writer.WriteBytes(frame); var writeOption = _nusChar.CharacteristicProperties .HasFlag(GattCharacteristicProperties.WriteWithoutResponse) ? GattWriteOption.WriteWithoutResponse : GattWriteOption.WriteWithResponse; await _nusChar.WriteValueAsync(writer.DetachBuffer(), writeOption); } // ──────────────────────────────────────────────────────────────────────── // PRIVATE: BLE receive path // ──────────────────────────────────────────────────────────────────────── private void OnCharValueChanged(GattCharacteristic _, GattValueChangedEventArgs args) { try { var chunk = args.CharacteristicValue.ToArray(); if (chunk.Length == 0) return; _bleQueue.Enqueue(chunk); _bleSignal.Release(); } catch { /* non-critical */ } } private void StartProcessingLoop() { _loopCts = new CancellationTokenSource(); var token = _loopCts.Token; Task.Run(async () => { while (!token.IsCancellationRequested) { await _bleSignal.WaitAsync(token); while (_bleQueue.TryDequeue(out byte[]? chunk)) { foreach (byte b in chunk) _parser.ProcessByte(b); } } }, token); } private void StopProcessingLoop() { _loopCts?.Cancel(); _loopCts?.Dispose(); _loopCts = null; } // ──────────────────────────────────────────────────────────────────────── // PRIVATE: Packet dispatch // ──────────────────────────────────────────────────────────────────────── private void OnFullPacketReceived(PacketParser.ParsedPacket packet) { // ── Diagnostics frame ──────────────────────────────────────────────── if (packet.TlResponse == Commands.APP_MONITORING) { Interlocked.Exchange(ref _lastDiagTickUtc, DateTime.UtcNow.Ticks); if (_diagnosticsRunning) { try { var frame = DiagnosticsFrame.Parse(packet.Payload, packet.SeqNum, DateTime.UtcNow); _diagSubject.OnNext(frame); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"[DIAG] Parse error: {ex.Message}"); } } return; } // ── Non-posted response ────────────────────────────────────────────── lock (_responseLock) { _responsePayload = packet.Payload; } _responseReady.Release(); } // ──────────────────────────────────────────────────────────────────────── // PRIVATE: GATT helpers // ──────────────────────────────────────────────────────────────────────── private async Task OpenGattChannelAsync(CancellationToken ct, int maxAttempts = 6) { for (int i = 1; i <= maxAttempts; i++) { try { var result = await _device!.GetGattServicesAsync(BluetoothCacheMode.Uncached); if (result.Status == GattCommunicationStatus.Success) return true; if (result.Status == GattCommunicationStatus.AccessDenied) await TrySilentPairAsync(); } catch { } if (i < maxAttempts) await Task.Delay(2000, ct); } return false; } private async Task GetServiceAsync(Guid uuid, CancellationToken ct, int maxAttempts = 4) { for (int i = 1; i <= maxAttempts; i++) { var result = await _device!.GetGattServicesAsync(BluetoothCacheMode.Uncached); if (result.Status == GattCommunicationStatus.Success) { var svc = result.Services.FirstOrDefault(s => s.Uuid == uuid); if (svc != null) return svc; } if (i < maxAttempts) await Task.Delay(1500, ct); } return null; } private async Task GetCharacteristicAsync( GattDeviceService service, Guid uuid, CancellationToken ct, int maxAttempts = 3) { for (int i = 1; i <= maxAttempts; i++) { var result = await service.GetCharacteristicsForUuidAsync(uuid, BluetoothCacheMode.Uncached); if (result.Status == GattCommunicationStatus.Success && result.Characteristics.Count > 0) return result.Characteristics[0]; if (i < maxAttempts) await Task.Delay(1000, ct); } return null; } private async Task TrySilentPairAsync() { var pairing = _device!.DeviceInformation.Pairing; if (pairing.IsPaired || !pairing.CanPair) return; await pairing.PairAsync(Windows.Devices.Enumeration.DevicePairingProtectionLevel.None); await Task.Delay(800); } private void OnDeviceConnectionStatusChanged(BluetoothLEDevice sender, object _) { if (sender.ConnectionStatus == BluetoothConnectionStatus.Disconnected && IsConnected) { _diagnosticsRunning = false; _parser.Reset(); while (_bleQueue.TryDequeue(out byte[]? _)) { } SetState(BleConnectionState.Disconnected); } } // ──────────────────────────────────────────────────────────────────────── // PRIVATE: Misc helpers // ──────────────────────────────────────────────────────────────────────── private void SetState(BleConnectionState state) { _connectionState = state; _connSubject.OnNext(state); } private bool Fail(string _) { SetState(BleConnectionState.Disconnected); return false; } private byte NextSeq() => _seqNum == 0xFF ? (_seqNum = 1) : _seqNum++; private static byte[] BuildUnlockPayload(byte unlockCmd, string password, bool isReset) { var now = DateTime.Now; var pwd = System.Text.Encoding.ASCII.GetBytes(password.Trim()); var data = new List { unlockCmd, 0x00, 0x00, 0x00 }; // 16-byte password field (null-padded) for (int i = 0; i < 16; i++) data.Add(i < pwd.Length ? pwd[i] : (byte)0x00); data.Add((byte)now.Day); data.Add((byte)now.Month); data.Add((byte)(now.Year % 100)); data.Add(0x00); // reserved // Sentinel bytes matching original data.AddRange(new byte[] { 0xF3, 0xF3, 0xF3, 0xF3 }); return data.ToArray(); } public void Dispose() { StopProcessingLoop(); _nusService?.Dispose(); _device?.Dispose(); _diagSubject.Dispose(); _connSubject.Dispose(); _responseReady.Dispose(); _bleSignal.Dispose(); } }