using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using TuneBoss.Core.Models;
using TuneBoss.Core.Protocol;
namespace TuneBoss.Core.BLE;
///
/// A fully in-memory 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).
///
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 _state = new(BleConnectionState.Disconnected);
private readonly Subject _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 ConnectionStateChanged => _state.AsObservable();
// ── Scan ──────────────────────────────────────────────────────────────────
public IObservable StartScan() => Observable.Create(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 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 ReadEcuInfoAsync(CancellationToken ct = default) =>
Task.FromResult(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 UnlockAsync(string password, CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(Array.Empty()));
public Task UnlockTunerAsync(string password, CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(Array.Empty()));
// ── 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 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 WriteTable2DAsync(ushort address, byte[] data,
bool userTable = false, CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(data));
// ── 1D tables ─────────────────────────────────────────────────────────────
public Task 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);
}
/// 8-byte TPS abs-bounds block: [absMax, absMin, store2, store3, ...].
private static byte[] TpsAbsBounds()
=> new byte[] { 195, 5, 197, 199, 201, 203, 205, 207 };
public Task WriteTable1DAsync(ushort address, byte[] data,
CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(data));
// ── Subtables ─────────────────────────────────────────────────────────────
public Task ReadSubTableAsync(ushort address, CancellationToken ct = default)
=> OkFramed(CanonicalSub(), Commands.APP_MEMRD_SUBT);
public Task WriteSubTableAsync(ushort address, byte[] data,
CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(data));
// ── Misc ──────────────────────────────────────────────────────────────────
public Task ReadMiscAsync(ushort address, byte lengthBytes,
CancellationToken ct = default)
=> OkFramed(CanonicalMisc(lengthBytes), Commands.APP_MEMRD_MISC);
public Task WriteMiscAsync(ushort address, byte[] data,
CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(data));
// ── Flash ─────────────────────────────────────────────────────────────────
public Task FlashWriteAsync(CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(Array.Empty()));
// ── First-use settings ──────────────────────────────────────────────────────
public Task WriteFirstUseAsync(byte[] fourBytes, CancellationToken ct = default)
{
if (fourBytes is { Length: >= 1 })
SimTpsCalibrated = fourBytes[0] == TpsCalibration.CalDoneFlag;
return Task.FromResult(CommandResult.Ok(Array.Empty()));
}
// ── Diagnostics (the moving part) ─────────────────────────────────────────
public IObservable 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 ────────────────────────────────────────────────────
/// 228-byte 2D combined payload: smooth fuel surface, realistic axes.
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
}
/// 24-byte 1D table: monotonic axis + ramp values, unscaled.
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
}
/// 40-byte subtable body (4×6) with a monotonic RPM/load axis so it parses cleanly.
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;
}
///
/// 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.
///
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;
}
/// Wraps a data block in the 4-byte response header (51 cmd len 00).
private static Task 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();
}
}