Initial Commit
This commit is contained in:
@@ -0,0 +1,668 @@
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// Windows WinRT BLE implementation of IBleService.
|
||||
/// Uses Nordic UART Service (NUS) over a single bidirectional characteristic.
|
||||
/// </summary>
|
||||
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<byte[]> _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<DiagnosticsFrame> _diagSubject = new();
|
||||
private volatile bool _diagnosticsRunning;
|
||||
private long _lastDiagTickUtc;
|
||||
|
||||
// ── Observables ──────────────────────────────────────────────────────────
|
||||
private readonly BehaviorSubject<BleConnectionState> _connSubject =
|
||||
new(BleConnectionState.Disconnected);
|
||||
|
||||
private readonly Subject<BleDeviceInfo> _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<BleConnectionState> ConnectionStateChanged => _connSubject.AsObservable();
|
||||
public IObservable<DiagnosticsFrame> DiagnosticsFrames => _diagSubject.AsObservable();
|
||||
public bool DiagnosticsRunning => _diagnosticsRunning;
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────────
|
||||
// SCANNING
|
||||
// ────────────────────────────────────────────────────────────────────────
|
||||
public IObservable<BleDeviceInfo> StartScan()
|
||||
{
|
||||
var seen = new Dictionary<ulong, string>();
|
||||
|
||||
_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));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
_watcher.Start();
|
||||
return _scanSubject.AsObservable();
|
||||
}
|
||||
|
||||
public void StopScan()
|
||||
{
|
||||
_watcher?.Stop();
|
||||
_watcher = null;
|
||||
}
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────────
|
||||
// CONNECTION
|
||||
// ────────────────────────────────────────────────────────────────────────
|
||||
public async Task<bool> 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<EcuInfo?> 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<CommandResult> 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<CommandResult> 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<CommandResult> 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<CommandResult> 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<CommandResult> ReadTable1DAsync(ushort address, byte lengthBytes, CancellationToken ct = default)
|
||||
=> ReadTableAsync(_genConfig?.ReadCmd1D ?? Commands.APP_MEMRD_1D, address, lengthBytes, ct);
|
||||
|
||||
public Task<CommandResult> WriteTable1DAsync(ushort address, byte[] data, CancellationToken ct = default)
|
||||
=> WriteTableAsync(_genConfig?.WriteCmd1D ?? Commands.APP_MEMWR_1D, address, data, ct);
|
||||
|
||||
public Task<CommandResult> ReadSubTableAsync(ushort address, CancellationToken ct = default)
|
||||
=> ReadTableAsync(_genConfig?.ReadCmdSubT ?? Commands.APP_MEMRD_SUBT, address,
|
||||
(byte)TuneBoss.Core.Models.SubTable.TotalBytes, ct);
|
||||
|
||||
public Task<CommandResult> WriteSubTableAsync(ushort address, byte[] data, CancellationToken ct = default)
|
||||
=> WriteTableAsync(_genConfig?.WriteCmdSubT ?? Commands.APP_MEMWR_SUBT, address, data, ct);
|
||||
|
||||
public Task<CommandResult> ReadMiscAsync(ushort address, byte lengthBytes, CancellationToken ct = default)
|
||||
=> ReadTableAsync(_genConfig?.ReadCmdMisc ?? Commands.APP_MEMRD_MISC, address, lengthBytes, ct);
|
||||
|
||||
public Task<CommandResult> WriteMiscAsync(ushort address, byte[] data, CancellationToken ct = default)
|
||||
=> WriteTableAsync(_genConfig?.WriteCmdMisc ?? Commands.APP_MEMWR_MISC, address, data, ct);
|
||||
|
||||
// ────────────────────────────────────────────────────────────────────────
|
||||
// FLASH WRITE
|
||||
// ────────────────────────────────────────────────────────────────────────
|
||||
public async Task<CommandResult> 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<CommandResult> 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<CommandResult> 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<CommandResult> 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<CommandResult> 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<bool> 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<GattDeviceService?> 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<GattCharacteristic?> 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<byte>
|
||||
{
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
using TuneBoss.Core.Models;
|
||||
using TuneBoss.Core.Protocol;
|
||||
|
||||
namespace TuneBoss.Core.BLE;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a discovered BLE device before connection.
|
||||
/// </summary>
|
||||
public sealed record BleDeviceInfo(
|
||||
ulong Address,
|
||||
string Name,
|
||||
short Rssi)
|
||||
{
|
||||
public string MacAddress => FormatMac(Address);
|
||||
|
||||
private static string FormatMac(ulong a)
|
||||
{
|
||||
var b = BitConverter.GetBytes(a);
|
||||
return $"{b[5]:X2}:{b[4]:X2}:{b[3]:X2}:{b[2]:X2}:{b[1]:X2}:{b[0]:X2}";
|
||||
}
|
||||
|
||||
public override string ToString() => $"{Name} | {MacAddress} | {Rssi} dBm";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Connection state published to observers.
|
||||
/// </summary>
|
||||
public enum BleConnectionState
|
||||
{
|
||||
Disconnected,
|
||||
Connecting,
|
||||
Connected,
|
||||
Disconnecting,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Result of a command sent to the device.
|
||||
/// </summary>
|
||||
public sealed record CommandResult(
|
||||
bool Success,
|
||||
byte ResponseCode, // 0x51 = success, 0x52 = fail, etc.
|
||||
byte[] Payload,
|
||||
string? ErrorMessage = null)
|
||||
{
|
||||
public static CommandResult Ok(byte[] payload) =>
|
||||
new(true, 0x51, payload);
|
||||
|
||||
public static CommandResult Fail(byte responseCode, string message) =>
|
||||
new(false, responseCode, Array.Empty<byte>(), message);
|
||||
|
||||
public static CommandResult Timeout() =>
|
||||
new(false, 0x00, Array.Empty<byte>(), "Command timed out");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The primary BLE service contract.
|
||||
/// All table and device operations go through this interface.
|
||||
/// The UI layer never touches BLE APIs directly.
|
||||
/// </summary>
|
||||
public interface IBleService : IDisposable
|
||||
{
|
||||
// ── State ────────────────────────────────────────────────────────────────
|
||||
|
||||
BleConnectionState ConnectionState { get; }
|
||||
bool IsConnected { get; }
|
||||
|
||||
/// <summary>Observable connection state changes.</summary>
|
||||
IObservable<BleConnectionState> ConnectionStateChanged { get; }
|
||||
|
||||
// ── Scanning ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Starts BLE advertisement scanning. Emits discovered devices.</summary>
|
||||
IObservable<BleDeviceInfo> StartScan();
|
||||
|
||||
/// <summary>Stops active scan.</summary>
|
||||
void StopScan();
|
||||
|
||||
// ── Connection ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Connects to a device. Handles GATT channel opening, NUS service
|
||||
/// discovery, notification subscription, and the post-connect APP_READ_INFO.
|
||||
/// </summary>
|
||||
Task<bool> ConnectAsync(BleDeviceInfo device, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Gracefully disconnects, stops diagnostics, cleans up GATT resources.</summary>
|
||||
Task DisconnectAsync();
|
||||
|
||||
// ── Device info ──────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Reads ECU info (APP_READ_INFO). Returns null on timeout or failure.
|
||||
/// Also sets the active GenerationConfig internally.
|
||||
/// </summary>
|
||||
Task<EcuInfo?> ReadEcuInfoAsync(CancellationToken ct = default);
|
||||
|
||||
// ── Auth ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Sends unlock command with password and current date.</summary>
|
||||
Task<CommandResult> UnlockAsync(string password, CancellationToken ct = default);
|
||||
|
||||
/// <summary>Sends tuner unlock command.</summary>
|
||||
Task<CommandResult> UnlockTunerAsync(string password, CancellationToken ct = default);
|
||||
|
||||
// ── Table operations ─────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Reads a 2D table (split read: two halves, with diagnostics pause/resume).
|
||||
/// Returns the raw combined payload.
|
||||
/// </summary>
|
||||
Task<CommandResult> ReadTable2DAsync(
|
||||
ushort address,
|
||||
byte lengthBytes,
|
||||
bool userTable = false,
|
||||
CancellationToken ct = default);
|
||||
|
||||
/// <summary>Writes a 2D table (split write).</summary>
|
||||
Task<CommandResult> WriteTable2DAsync(
|
||||
ushort address,
|
||||
byte[] data,
|
||||
bool userTable = false,
|
||||
CancellationToken ct = default);
|
||||
|
||||
/// <summary>Reads a 1D table.</summary>
|
||||
Task<CommandResult> ReadTable1DAsync(
|
||||
ushort address,
|
||||
byte lengthBytes,
|
||||
CancellationToken ct = default);
|
||||
|
||||
/// <summary>Writes a 1D table.</summary>
|
||||
Task<CommandResult> WriteTable1DAsync(
|
||||
ushort address,
|
||||
byte[] data,
|
||||
CancellationToken ct = default);
|
||||
|
||||
/// <summary>Reads a subtable.</summary>
|
||||
Task<CommandResult> ReadSubTableAsync(
|
||||
ushort address,
|
||||
CancellationToken ct = default);
|
||||
|
||||
/// <summary>Writes a subtable.</summary>
|
||||
Task<CommandResult> WriteSubTableAsync(
|
||||
ushort address,
|
||||
byte[] data,
|
||||
CancellationToken ct = default);
|
||||
|
||||
/// <summary>Reads misc values block.</summary>
|
||||
Task<CommandResult> ReadMiscAsync(
|
||||
ushort address,
|
||||
byte lengthBytes,
|
||||
CancellationToken ct = default);
|
||||
|
||||
/// <summary>Writes misc values block.</summary>
|
||||
Task<CommandResult> WriteMiscAsync(
|
||||
ushort address,
|
||||
byte[] data,
|
||||
CancellationToken ct = default);
|
||||
|
||||
// ── Flash ────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Sends APP_FLASH_WR to persist all writes to ECU flash.</summary>
|
||||
Task<CommandResult> FlashWriteAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Writes the 4-byte first-use settings block via APP_FIRSTUSE (0x35).
|
||||
/// Byte[0] (DD slot) carries the TPS-calibration-done flag.
|
||||
/// </summary>
|
||||
Task<CommandResult> WriteFirstUseAsync(byte[] fourBytes, CancellationToken ct = default);
|
||||
|
||||
// ── Diagnostics streaming ────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Observable stream of diagnostics frames (APP_MONITORING 0x70).
|
||||
/// Emits continuously while diagnostics are running.
|
||||
/// </summary>
|
||||
IObservable<DiagnosticsFrame> DiagnosticsFrames { get; }
|
||||
|
||||
bool DiagnosticsRunning { get; }
|
||||
|
||||
/// <summary>Sends APP_MON_START and begins emitting DiagnosticsFrames.</summary>
|
||||
Task StartDiagnosticsAsync(CancellationToken ct = default);
|
||||
|
||||
/// <summary>
|
||||
/// Sends APP_MON_STOP and waits for silence before returning.
|
||||
/// Safe to call even if diagnostics aren't running.
|
||||
/// </summary>
|
||||
Task StopDiagnosticsAsync(CancellationToken ct = default);
|
||||
|
||||
// ── Keepalive ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Called by the keepalive timer. Sends APP_READ_INFO if idle for > 15s.
|
||||
/// Internally managed — exposed for test visibility only.
|
||||
/// </summary>
|
||||
void OnKeepaliveTimer();
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
namespace TuneBoss.Core.BLE;
|
||||
|
||||
/// <summary>
|
||||
/// Stateful byte-stream parser for TuneBoss BLE packets.
|
||||
/// Extracted from Form1_BLEhelper.cs ProcessByte() / OnFullPacketReceived().
|
||||
/// Thread-safe only when all calls are serialized (BLE processing loop does this).
|
||||
/// </summary>
|
||||
public sealed class PacketParser
|
||||
{
|
||||
public sealed record ParsedPacket(
|
||||
byte DlCommand,
|
||||
byte SeqNum,
|
||||
byte DwCount,
|
||||
byte TlResponse,
|
||||
byte TlCommand,
|
||||
byte TlLength,
|
||||
byte[] Payload);
|
||||
|
||||
private readonly Action<ParsedPacket> _onPacketReceived;
|
||||
|
||||
// ── Parser state ─────────────────────────────────────────────────────────
|
||||
private int _byteCycle;
|
||||
private int _startSeqCycle;
|
||||
private int _packetHeaderCycle;
|
||||
private int _dWordByteTrack;
|
||||
private int _dWordCheckSumTrack;
|
||||
|
||||
private readonly byte[] _startSeq = new byte[4];
|
||||
private readonly byte[] _packetHeader = new byte[4];
|
||||
private readonly List<byte> _dataBuffer = new();
|
||||
private readonly List<byte> _csBuffer = new();
|
||||
|
||||
private byte _currDlCommand;
|
||||
private byte _currDlSeqCount;
|
||||
private byte _currDlDWordCount;
|
||||
private byte _currTlResp;
|
||||
private byte _currTlCommand;
|
||||
private byte _currTlLength;
|
||||
|
||||
public PacketParser(Action<ParsedPacket> onPacketReceived)
|
||||
{
|
||||
_onPacketReceived = onPacketReceived;
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
_byteCycle = 0;
|
||||
_startSeqCycle = 0;
|
||||
_packetHeaderCycle = 0;
|
||||
_dWordByteTrack = 0;
|
||||
_dWordCheckSumTrack = 0;
|
||||
_dataBuffer.Clear();
|
||||
_csBuffer.Clear();
|
||||
_currDlCommand = 0;
|
||||
_currDlSeqCount = 0;
|
||||
_currDlDWordCount = 0;
|
||||
_currTlResp = 0;
|
||||
_currTlCommand = 0;
|
||||
_currTlLength = 0;
|
||||
}
|
||||
|
||||
public void ProcessByte(byte b)
|
||||
{
|
||||
// ── Zone 1: bytes 0–3 — preamble FF 00 FF 00 ─────────────────────
|
||||
if (_byteCycle <= 3)
|
||||
{
|
||||
_startSeq[_startSeqCycle] = b;
|
||||
|
||||
if (_startSeqCycle == 3)
|
||||
{
|
||||
bool valid = _startSeq[0] == 0xFF && _startSeq[1] == 0x00
|
||||
&& _startSeq[2] == 0xFF && _startSeq[3] == 0x00;
|
||||
if (!valid) { Reset(); return; }
|
||||
}
|
||||
|
||||
_startSeqCycle++;
|
||||
_byteCycle++;
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Zone 2: bytes 4–7 — packet header ────────────────────────────
|
||||
if (_byteCycle <= 7)
|
||||
{
|
||||
_packetHeader[_packetHeaderCycle] = b;
|
||||
|
||||
if (_packetHeaderCycle == 3)
|
||||
{
|
||||
if (!HeaderIntegrityOk(_packetHeader)) { Reset(); return; }
|
||||
|
||||
_currDlCommand = _packetHeader[0];
|
||||
_currDlSeqCount = _packetHeader[1];
|
||||
_currDlDWordCount = _packetHeader[2];
|
||||
}
|
||||
|
||||
_packetHeaderCycle++;
|
||||
_byteCycle++;
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Zone 3: no payload ────────────────────────────────────────────
|
||||
if (_currDlDWordCount == 0) { Reset(); return; }
|
||||
|
||||
// ── Zone 4: bytes 8–11 — TL header (first DWord of payload) ──────
|
||||
if (_byteCycle <= 11)
|
||||
{
|
||||
switch (_byteCycle)
|
||||
{
|
||||
case 8: _currTlResp = b; break;
|
||||
case 9: _currTlCommand = b; break;
|
||||
case 10: _currTlLength = b; break;
|
||||
}
|
||||
|
||||
_dataBuffer.Add(b);
|
||||
_byteCycle++;
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Zone 5: bytes 12+ — payload bytes + checksum ─────────────────
|
||||
_byteCycle++;
|
||||
|
||||
int payloadBytes = 4 * (_currDlDWordCount - 1); // DWords after the TL header
|
||||
|
||||
if (_dWordByteTrack < payloadBytes)
|
||||
{
|
||||
_dataBuffer.Add(b);
|
||||
_dWordByteTrack++;
|
||||
}
|
||||
else if (_dWordCheckSumTrack < 4)
|
||||
{
|
||||
_csBuffer.Add(b);
|
||||
_dWordCheckSumTrack++;
|
||||
|
||||
if (_dWordCheckSumTrack == 4)
|
||||
OnFullPacketReceived();
|
||||
}
|
||||
}
|
||||
|
||||
private void OnFullPacketReceived()
|
||||
{
|
||||
byte[] data = _dataBuffer.ToArray();
|
||||
byte[] cs = _csBuffer.ToArray();
|
||||
|
||||
// Verify checksum
|
||||
var expected = Protocol.ChecksumHelper.GenChecksumDW(data);
|
||||
var receivedCs = (uint)(cs[0] | (cs[1] << 8) | (cs[2] << 16) | (cs[3] << 24));
|
||||
|
||||
if (expected != receivedCs) { Reset(); return; }
|
||||
|
||||
var packet = new ParsedPacket(
|
||||
DlCommand: _currDlCommand,
|
||||
SeqNum: _currDlSeqCount,
|
||||
DwCount: _currDlDWordCount,
|
||||
TlResponse: _currTlResp,
|
||||
TlCommand: _currTlCommand,
|
||||
TlLength: _currTlLength,
|
||||
Payload: data);
|
||||
|
||||
Reset();
|
||||
_onPacketReceived(packet);
|
||||
}
|
||||
|
||||
private static bool HeaderIntegrityOk(byte[] h)
|
||||
{
|
||||
byte sum = unchecked((byte)(h[0] + h[1] + h[2]));
|
||||
byte invSum = unchecked((byte)~sum);
|
||||
return invSum == h[3];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
using System.Reactive.Disposables;
|
||||
using System.Reactive.Linq;
|
||||
using System.Reactive.Subjects;
|
||||
using TuneBoss.Core.Models;
|
||||
using TuneBoss.Core.Protocol;
|
||||
|
||||
namespace TuneBoss.Core.BLE;
|
||||
|
||||
/// <summary>
|
||||
/// A fully in-memory <see cref="IBleService"/> for hardware-free testing.
|
||||
///
|
||||
/// • Scan/connect/unlock succeed instantly.
|
||||
/// • Reads synthesize correctly-framed wire payloads (4-byte header, data at offset 4,
|
||||
/// the device len+1 convention, and the 2D split-read halves) so every table,
|
||||
/// misc block and 1D table populates in the real UI.
|
||||
/// • Diagnostics stream a LIVE, moving RPM + load (sine sweep, ~20 Hz) so the 2D
|
||||
/// tuning-table tracker visibly walks across the grid. The six gauge channels
|
||||
/// move with it (MAP follows load, ETemp warms up, AFR wobbles, spark advances).
|
||||
///
|
||||
/// Swap it in via DI (see the App.xaml.cs snippet in SimBleService_DI_README).
|
||||
/// </summary>
|
||||
public sealed class SimBleService : IBleService
|
||||
{
|
||||
// ── Tunables (change before connecting to exercise different cases) ────────
|
||||
public byte SimAppInfoVersion { get; set; } = 2; // 2=Gen3, 1=Gen2, 245=Gen1
|
||||
public byte SimFwVersion { get; set; } = 193; // try 70 / 100 / 150 to see FW gating
|
||||
public bool SimTpsCalibrated { get; set; } = false; // false => connect warns + jumps to TPS cal
|
||||
public byte SimRpmMax { get; set; } = 130; // ×100 = 13000 rpm limit
|
||||
public double SweepSeconds { get; set; } = 6.0; // one full idle→redline→idle cycle
|
||||
public int EmitHz { get; set; } = 20; // diagnostics frames per second
|
||||
|
||||
// ── Plumbing ──────────────────────────────────────────────────────────────
|
||||
private readonly BehaviorSubject<BleConnectionState> _state = new(BleConnectionState.Disconnected);
|
||||
private readonly Subject<DiagnosticsFrame> _diag = new();
|
||||
private CancellationTokenSource? _diagCts;
|
||||
private byte _seq;
|
||||
private readonly Random _rng = new(1234);
|
||||
|
||||
public BleConnectionState ConnectionState => _state.Value;
|
||||
public bool IsConnected => _state.Value == BleConnectionState.Connected;
|
||||
public IObservable<BleConnectionState> ConnectionStateChanged => _state.AsObservable();
|
||||
|
||||
// ── Scan ──────────────────────────────────────────────────────────────────
|
||||
public IObservable<BleDeviceInfo> StartScan() => Observable.Create<BleDeviceInfo>(o =>
|
||||
{
|
||||
o.OnNext(new BleDeviceInfo(0xAABBCCDDEEFF, "B_SIM-PG1", -42));
|
||||
o.OnNext(new BleDeviceInfo(0x0011223344556, "B_SIM-R15", -57));
|
||||
return Disposable.Empty; // stay "scanning" (no completion)
|
||||
});
|
||||
|
||||
public void StopScan() { }
|
||||
|
||||
// ── Connect ───────────────────────────────────────────────────────────────
|
||||
public async Task<bool> ConnectAsync(BleDeviceInfo device, CancellationToken ct = default)
|
||||
{
|
||||
_state.OnNext(BleConnectionState.Connecting);
|
||||
await Task.Delay(120, ct);
|
||||
_state.OnNext(BleConnectionState.Connected);
|
||||
|
||||
// Auto-start the live stream so the persistent gauge strip + table tracker
|
||||
// come alive immediately. Idempotent — a later StartDiagnosticsAsync() is a no-op.
|
||||
await StartDiagnosticsAsync(ct);
|
||||
return true;
|
||||
}
|
||||
|
||||
public async Task DisconnectAsync()
|
||||
{
|
||||
await StopDiagnosticsAsync();
|
||||
_state.OnNext(BleConnectionState.Disconnecting);
|
||||
_state.OnNext(BleConnectionState.Disconnected);
|
||||
}
|
||||
|
||||
// ── Device info ───────────────────────────────────────────────────────────
|
||||
public Task<EcuInfo?> ReadEcuInfoAsync(CancellationToken ct = default) =>
|
||||
Task.FromResult<EcuInfo?>(new EcuInfo
|
||||
{
|
||||
Username = "SIM-RIDER",
|
||||
UniqueId = "51A0-0000-0000-0001",
|
||||
AppInfoVersion = SimAppInfoVersion,
|
||||
FwVersion = SimFwVersion,
|
||||
HwVersion = 10,
|
||||
UpgradeRpmMax = SimRpmMax,
|
||||
BikeManufacturer = 1, // Yamaha
|
||||
UpgradeLogImmo = 0x0F, // dual-injector unlocked
|
||||
FirstUseInfo0 = SimTpsCalibrated ? TpsCalibration.CalDoneFlag : (byte)0,
|
||||
});
|
||||
|
||||
// ── Auth ──────────────────────────────────────────────────────────────────
|
||||
public Task<CommandResult> UnlockAsync(string password, CancellationToken ct = default)
|
||||
=> Task.FromResult(CommandResult.Ok(Array.Empty<byte>()));
|
||||
|
||||
public Task<CommandResult> UnlockTunerAsync(string password, CancellationToken ct = default)
|
||||
=> Task.FromResult(CommandResult.Ok(Array.Empty<byte>()));
|
||||
|
||||
// ── 2D tables (split read) ────────────────────────────────────────────────
|
||||
// The VM reads part 1 with len = SplitFirstLength (0x7F) at the base address,
|
||||
// then part 2 (len = 100) at base+128. FromSplitResponses copies from offset 4
|
||||
// of each. We branch on the requested length. Tuning + AFR share this layout.
|
||||
public Task<CommandResult> ReadTable2DAsync(ushort address, byte lengthBytes,
|
||||
bool userTable = false, CancellationToken ct = default)
|
||||
{
|
||||
var combined = Canonical2D(); // 228 bytes
|
||||
const int firstCount = TuningTable.SplitFirstLength + 1; // 128
|
||||
|
||||
if (lengthBytes == TuningTable.SplitFirstLength)
|
||||
return OkFramed(Slice(combined, 0, firstCount), Commands.APP_MEMRD_2D);
|
||||
|
||||
int secondCount = TuningTable.TotalPayloadBytes - firstCount; // 100
|
||||
return OkFramed(Slice(combined, firstCount, secondCount), Commands.APP_MEMRD_2D);
|
||||
}
|
||||
|
||||
public Task<CommandResult> WriteTable2DAsync(ushort address, byte[] data,
|
||||
bool userTable = false, CancellationToken ct = default)
|
||||
=> Task.FromResult(CommandResult.Ok(data));
|
||||
|
||||
// ── 1D tables ─────────────────────────────────────────────────────────────
|
||||
public Task<CommandResult> ReadTable1DAsync(ushort address, byte lengthBytes,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
// TPS absolute bounds live at a fixed address; return [max, min, ...] so the
|
||||
// calibration page validates a full sweep successfully.
|
||||
var addr = TpsCalibration.For((GenerationType)SimAppInfoVersion, SimFwVersion);
|
||||
if (address == addr.AbsBounds)
|
||||
return OkFramed(TpsAbsBounds(), Commands.APP_MEMRD_1D);
|
||||
|
||||
return OkFramed(Canonical1D(), Commands.APP_MEMRD_1D);
|
||||
}
|
||||
|
||||
/// <summary>8-byte TPS abs-bounds block: [absMax, absMin, store2, store3, ...].</summary>
|
||||
private static byte[] TpsAbsBounds()
|
||||
=> new byte[] { 195, 5, 197, 199, 201, 203, 205, 207 };
|
||||
|
||||
public Task<CommandResult> WriteTable1DAsync(ushort address, byte[] data,
|
||||
CancellationToken ct = default)
|
||||
=> Task.FromResult(CommandResult.Ok(data));
|
||||
|
||||
// ── Subtables ─────────────────────────────────────────────────────────────
|
||||
public Task<CommandResult> ReadSubTableAsync(ushort address, CancellationToken ct = default)
|
||||
=> OkFramed(CanonicalSub(), Commands.APP_MEMRD_SUBT);
|
||||
|
||||
public Task<CommandResult> WriteSubTableAsync(ushort address, byte[] data,
|
||||
CancellationToken ct = default)
|
||||
=> Task.FromResult(CommandResult.Ok(data));
|
||||
|
||||
// ── Misc ──────────────────────────────────────────────────────────────────
|
||||
public Task<CommandResult> ReadMiscAsync(ushort address, byte lengthBytes,
|
||||
CancellationToken ct = default)
|
||||
=> OkFramed(CanonicalMisc(lengthBytes), Commands.APP_MEMRD_MISC);
|
||||
|
||||
public Task<CommandResult> WriteMiscAsync(ushort address, byte[] data,
|
||||
CancellationToken ct = default)
|
||||
=> Task.FromResult(CommandResult.Ok(data));
|
||||
|
||||
// ── Flash ─────────────────────────────────────────────────────────────────
|
||||
public Task<CommandResult> FlashWriteAsync(CancellationToken ct = default)
|
||||
=> Task.FromResult(CommandResult.Ok(Array.Empty<byte>()));
|
||||
|
||||
// ── First-use settings ──────────────────────────────────────────────────────
|
||||
public Task<CommandResult> WriteFirstUseAsync(byte[] fourBytes, CancellationToken ct = default)
|
||||
{
|
||||
if (fourBytes is { Length: >= 1 })
|
||||
SimTpsCalibrated = fourBytes[0] == TpsCalibration.CalDoneFlag;
|
||||
return Task.FromResult(CommandResult.Ok(Array.Empty<byte>()));
|
||||
}
|
||||
|
||||
// ── Diagnostics (the moving part) ─────────────────────────────────────────
|
||||
public IObservable<DiagnosticsFrame> DiagnosticsFrames => _diag.AsObservable();
|
||||
public bool DiagnosticsRunning => _diagCts is not null;
|
||||
|
||||
public Task StartDiagnosticsAsync(CancellationToken ct = default)
|
||||
{
|
||||
if (_diagCts is not null) return Task.CompletedTask;
|
||||
_diagCts = new CancellationTokenSource();
|
||||
_ = RunDiagnosticsLoop(_diagCts.Token);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task StopDiagnosticsAsync(CancellationToken ct = default)
|
||||
{
|
||||
_diagCts?.Cancel();
|
||||
_diagCts?.Dispose();
|
||||
_diagCts = null;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public void OnKeepaliveTimer() { /* no-op in sim */ }
|
||||
|
||||
private async Task RunDiagnosticsLoop(CancellationToken ct)
|
||||
{
|
||||
var period = TimeSpan.FromMilliseconds(1000.0 / Math.Max(1, EmitHz));
|
||||
using var timer = new PeriodicTimer(period);
|
||||
var start = DateTime.UtcNow;
|
||||
|
||||
// RPM raw sweep range — must sit inside the canonical RpmAxis (10..217)
|
||||
const double rpmIdle = 12, rpmRedline = 205;
|
||||
const double loadLo = 22, loadHi = 95;
|
||||
|
||||
try
|
||||
{
|
||||
while (await timer.WaitForNextTickAsync(ct))
|
||||
{
|
||||
double tSec = (DateTime.UtcNow - start).TotalSeconds;
|
||||
double phase = tSec / Math.Max(0.5, SweepSeconds) * 2 * Math.PI;
|
||||
double s = (Math.Sin(phase) + 1) / 2; // 0..1
|
||||
bool rising = Math.Cos(phase) >= 0;
|
||||
|
||||
byte rpmRaw = (byte)Math.Round(rpmIdle + s * (rpmRedline - rpmIdle));
|
||||
byte load = (byte)Math.Round(loadLo + s * (loadHi - loadLo) + Noise(2));
|
||||
byte tps = (byte)Math.Clamp(Math.Round(s * 100 + Noise(2)), 0, 100);
|
||||
byte map = (byte)Math.Clamp(load + Noise(2), 0, 255);
|
||||
byte etemp = (byte)Math.Clamp(40 + tSec * 3, 40, 92); // warm-up ramp
|
||||
byte afrx10 = (byte)Math.Clamp(Math.Round(145 + Noise(8)), 120, 170);
|
||||
|
||||
_diag.OnNext(new DiagnosticsFrame
|
||||
{
|
||||
SeqNum = _seq++,
|
||||
ReceivedAt = DateTime.UtcNow,
|
||||
|
||||
// tracker channels
|
||||
Load = load,
|
||||
RPM_Raw = rpmRaw,
|
||||
TPS_Percent = tps,
|
||||
TPS_Raw = (byte)Math.Clamp(Math.Round(10 + s * 178), 0, 255),
|
||||
|
||||
// gauges
|
||||
Baro_kPa = 101,
|
||||
Baro_Dynamic = 101,
|
||||
VBAT_deciV = (byte)(138 - (int)(s * 6)), // sags under load
|
||||
ETEMP_DegC = etemp,
|
||||
IAT_DegC = 32,
|
||||
MAP_kPa = map,
|
||||
MAP_Lo_Avg = (byte)Math.Max(0, map - 4),
|
||||
MAP_Hi_Avg_Raw = (byte)Math.Clamp(s * 120, 0, 255), // doubles as meter speed
|
||||
O2_AFR_x10 = afrx10,
|
||||
FuelStartAngle1_Raw = (byte)Math.Clamp(20 + s * 30, 0, 255),
|
||||
FuelStartAngle2_Raw = (byte)Math.Clamp(20 + s * 30, 0, 255),
|
||||
FuelPulseWidth1 = (int)(1500 + s * 6000),
|
||||
FuelEndAngle = (int)(s * 360),
|
||||
SparkAngle1 = (sbyte)Math.Clamp(5 + s * 30, -30, 60),
|
||||
SparkAngle2 = (sbyte)Math.Clamp(5 + s * 30, -30, 60),
|
||||
SparkPulseWidth = 25,
|
||||
CrankSyncLostCounter = 0,
|
||||
|
||||
// packed state bytes
|
||||
CrankState_Raw = 0x06, // 6 = RUNNING (low nibble), TC_Mode 0 (high)
|
||||
UMState_Packed = 0x33, // UMState 3 = RUN, gear 3 (high nibble)
|
||||
ThrottleState_Packed = (byte)(rising ? 0x01 : 0x02), // Accel / Decel
|
||||
RPMState_Packed = (byte)((rising ? 0x02 : 0x01) | 0x80), // Accel/Decel + StayTuned
|
||||
|
||||
// no faults
|
||||
ErrorsFatal = 0,
|
||||
AnalogError_Current = 0, AnalogError_Persistent = 0,
|
||||
OutputError_Current = 0, OutputError_Persistent = 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { /* normal stop */ }
|
||||
}
|
||||
|
||||
private double Noise(double amp) => (_rng.NextDouble() - 0.5) * 2 * amp;
|
||||
|
||||
// ── Canonical payloads ────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>228-byte 2D combined payload: smooth fuel surface, realistic axes.</summary>
|
||||
private static byte[] Canonical2D()
|
||||
{
|
||||
var data = new byte[TuningTable.DataBytes]; // 24 cols × 8 rows
|
||||
for (int r = 0; r < TuningTable.Rows; r++)
|
||||
for (int c = 0; c < TuningTable.Cols; c++)
|
||||
data[r * TuningTable.Cols + c] = (byte)Math.Clamp(30 + c * 8 + r * 3, 0, 255);
|
||||
|
||||
var loadAxis = new byte[TuningTable.Rows];
|
||||
for (int r = 0; r < TuningTable.Rows; r++) loadAxis[r] = (byte)(20 + r * 10); // 20..90
|
||||
|
||||
var rpmAxis = new byte[TuningTable.Cols];
|
||||
for (int c = 0; c < TuningTable.Cols; c++) rpmAxis[c] = (byte)(10 + c * 9); // 10..217 (×100)
|
||||
|
||||
var t = new TuningTable
|
||||
{
|
||||
Data = data, LoadAxis = loadAxis, RpmAxis = rpmAxis,
|
||||
MaxRaw = 255, MinRaw = 0, Mult = 1, Sign = 0,
|
||||
};
|
||||
return t.ToWirePayload(); // 228 bytes
|
||||
}
|
||||
|
||||
/// <summary>24-byte 1D table: monotonic axis + ramp values, unscaled.</summary>
|
||||
private static byte[] Canonical1D()
|
||||
{
|
||||
var t = new OneDimTable
|
||||
{
|
||||
MaxRaw = 255, MinRaw = 0,
|
||||
RawSignedFlag = 0, ConvSignedFlag = 0,
|
||||
RawMultiplier = 1, ConvMultiplier = 1, RawRounding = 0, ConvOffset = 0,
|
||||
};
|
||||
for (int i = 0; i < OneDimTable.PointCount; i++)
|
||||
{
|
||||
t.RawAxis[i] = i * 10; // 0,10,...,70
|
||||
t.ConvValues[i] = 20 + i * 6; // gentle ramp
|
||||
}
|
||||
return t.ToWirePayload(); // 24 bytes
|
||||
}
|
||||
|
||||
/// <summary>40-byte subtable body (4×6) with a monotonic RPM/load axis so it parses cleanly.</summary>
|
||||
private static byte[] CanonicalSub()
|
||||
{
|
||||
var buf = new byte[SubTable.TotalBytes]; // 40
|
||||
for (int i = 0; i < SubTable.DataBytes; i++) buf[i] = (byte)(40 + i);
|
||||
// load axis (4)
|
||||
var lo = SubTable.DefaultLoadAxis;
|
||||
for (int i = 0; i < SubTable.LoadBytes; i++) buf[SubTable.DataBytes + i] = lo[i];
|
||||
// rpm axis (12 = 6 lo/hi pairs)
|
||||
for (int c = 0; c < SubTable.Cols; c++)
|
||||
{
|
||||
buf[SubTable.DataBytes + SubTable.LoadBytes + c * 2] = (byte)(15 + c * 20);
|
||||
buf[SubTable.DataBytes + SubTable.LoadBytes + c * 2 + 1] = (byte)(20 + c * 20);
|
||||
}
|
||||
return buf;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Misc block sized for the request (returns len+1 bytes, mimicking the device
|
||||
/// off-by-one). The 136-byte core block gets a few representative settings bytes
|
||||
/// set so the bit-editors show real state.
|
||||
/// </summary>
|
||||
private byte[] CanonicalMisc(byte lengthBytes)
|
||||
{
|
||||
var data = new byte[lengthBytes + 1]; // device returns len+1
|
||||
|
||||
if (lengthBytes >= MemoryLayout.LenMiscCore) // core block (0x88 = 136)
|
||||
{
|
||||
data[8] = 131; // Crank_CamSync_Config
|
||||
data[25] = 0x05; // Fuel_Settings2 (a couple of flags)
|
||||
data[31] = 0x12; // Spark_Settings
|
||||
data[33] = 0x01; // O2_Autotune_Enable
|
||||
data[84] = 0x0F; // ShiftBoss_Enable = enable + both DIN bits
|
||||
data[88] = 35; // ShiftBoss_Spark_Retard_deg
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
// ── Framing helpers ───────────────────────────────────────────────────────
|
||||
private static byte[] Slice(byte[] src, int start, int count)
|
||||
{
|
||||
var b = new byte[count];
|
||||
Buffer.BlockCopy(src, start, b, 0, count);
|
||||
return b;
|
||||
}
|
||||
|
||||
/// <summary>Wraps a data block in the 4-byte response header (51 cmd len 00).</summary>
|
||||
private static Task<CommandResult> OkFramed(byte[] data, byte cmd)
|
||||
{
|
||||
var buf = new byte[4 + data.Length];
|
||||
buf[0] = 0x51;
|
||||
buf[1] = cmd;
|
||||
buf[2] = (byte)data.Length;
|
||||
buf[3] = 0x00;
|
||||
Buffer.BlockCopy(data, 0, buf, 4, data.Length);
|
||||
return Task.FromResult(CommandResult.Ok(buf));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_diagCts?.Cancel();
|
||||
_diagCts?.Dispose();
|
||||
_diag.Dispose();
|
||||
_state.Dispose();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user