From 1ec485701a00cc4623f905d5eb8e846f1d5acc04 Mon Sep 17 00:00:00 2001 From: suffian Date: Wed, 14 Oct 2026 07:12:24 +0800 Subject: [PATCH] All fixes before Bluetooth --- TuneBoss.Core/BLE/SimBleService.cs | 1 + TuneBoss.Core/Models/EcuInfo.cs | 20 +++ TuneBoss.Core/Models/EcuStatusResult.cs | 153 ++++++++++++++++++ TuneBoss.Core/Models/MemoryLayout.cs | 31 +++- TuneBossPC/App.xaml.cs | 1 + TuneBossPC/Services/EcuStatusService.cs | 123 ++++++++++++++ TuneBossPC/Services/IEcuStatusService.cs | 19 +++ TuneBossPC/Services/MapTableCodec.cs | 10 ++ TuneBossPC/ViewModels/ConnectViewModel.cs | 45 +++++- .../ViewModels/DiagnosticsStripViewModel.cs | 54 ++++++- .../ViewModels/OneDimTablesViewModel.cs | 18 +++ .../Tables/TuningTablesViewModel.cs | 31 ++++ TuneBossPC/ViewModels/TpsCalViewModel.cs | 15 +- 13 files changed, 504 insertions(+), 17 deletions(-) create mode 100644 TuneBoss.Core/Models/EcuStatusResult.cs create mode 100644 TuneBossPC/Services/EcuStatusService.cs create mode 100644 TuneBossPC/Services/IEcuStatusService.cs diff --git a/TuneBoss.Core/BLE/SimBleService.cs b/TuneBoss.Core/BLE/SimBleService.cs index a13c4e1..5b3aff7 100644 --- a/TuneBoss.Core/BLE/SimBleService.cs +++ b/TuneBoss.Core/BLE/SimBleService.cs @@ -83,6 +83,7 @@ public sealed class SimBleService : IBleService BikeManufacturer = 1, // Yamaha UpgradeLogImmo = 0x0F, // dual-injector unlocked FirstUseInfo0 = SimTpsCalibrated ? TpsCalibration.CalDoneFlag : (byte)0, + Reg1Reg2 = 1, // activated — so the post-unlock status gate passes offline }); // ── Auth ────────────────────────────────────────────────────────────────── diff --git a/TuneBoss.Core/Models/EcuInfo.cs b/TuneBoss.Core/Models/EcuInfo.cs index fcb3ca6..a1767c0 100644 --- a/TuneBoss.Core/Models/EcuInfo.cs +++ b/TuneBoss.Core/Models/EcuInfo.cs @@ -42,6 +42,18 @@ public sealed class EcuInfo public byte UpgradeFuture12 { get; init; } public byte UpgradeFuture2 { get; init; } // only if buffer > 68 + // ── Registration / activation ───────────────────────────────────────────── + /// + /// ECU activation nibble (legacy Reg1_Reg2 = buf[offset+53] & 0x0F, + /// present only on longer info buffers / newer firmware). > 0 means the unit has + /// been activated. Used by the post-unlock status gate as the offline / server-error + /// fallback and to rescue "not registered" verdicts (see EcuStatusInterpreter). + /// + public byte Reg1Reg2 { get; init; } + + /// True when the ECU reports itself activated ( > 0). + public bool IsActivated => Reg1Reg2 > 0; + // ── Derived ────────────────────────────────────────────────────────────── public int RpmLimit => UpgradeRpmMax * 100; /// @@ -153,6 +165,13 @@ public sealed class EcuInfo hwComp = buf[o + 12]; } + // Registration/activation nibble — legacy Reg1_Reg2 = buf[offset+53] & 0x0F. + // The legacy parser maps offset+37 → FW_Version, which is this parser's o, so + // Reg1_Reg2 lands at o+16. Only present on longer buffers (legacy gate: len >= 84); + // absent on older units → 0 (treated as "not activated", but those are FW < 150 + // which the status gate passes anyway). + byte reg1Reg2 = buf.Length > o + 16 ? (byte)(buf[o + 16] & 0x0F) : (byte)0; + var appInfoVersion = buf[^1]; // last byte var pwdRstCount = buf[^5]; // 4 bytes from end @@ -182,6 +201,7 @@ public sealed class EcuInfo UpgradeLogImmo = upgradeLogImmo, UpgradeFuture12 = upgradeFuture12, UpgradeFuture2 = upgradeFuture2, + Reg1Reg2 = reg1Reg2, }; } diff --git a/TuneBoss.Core/Models/EcuStatusResult.cs b/TuneBoss.Core/Models/EcuStatusResult.cs new file mode 100644 index 0000000..1fbc157 --- /dev/null +++ b/TuneBoss.Core/Models/EcuStatusResult.cs @@ -0,0 +1,153 @@ +namespace TuneBoss.Core.Models; + +/// +/// What the app should do after the post-unlock server status check. +/// Mirrors the Flutter checkEmailStatus gate (doneAfterConnect): +/// Pass → continue into the app, +/// Warn → continue, but show a warning first, +/// Block → show the message, disconnect, do NOT load tables. +/// +public enum EcuStatusOutcome +{ + Pass, + Warn, + Block, +} + +/// +/// Result of the post-unlock ECU status check against the TracBoss account server. +/// +public sealed record EcuStatusResult( + EcuStatusOutcome Outcome, + string Message, + int? SuccessCode, + bool ServerReachable) +{ + public bool IsBlocked => Outcome == EcuStatusOutcome.Block; +} + +/// +/// Pure interpretation of the server's success code into an app outcome. +/// No HTTP or UI here so it can be unit-tested and reused. +/// +/// Ported from the Flutter app's checkEmailStatus (lib/services/tb_interactor.dart), +/// MINUS the ECU activation-bit (reg1Reg2) second chance and the global payment/systemSync +/// side effects — those are a later phase. Where the Flutter code relied on reg1Reg2 to +/// rescue a "not activated" verdict, this build hard-blocks instead. +/// +public static class EcuStatusInterpreter +{ + /// FW below this is a legacy unit that predates activation — always allowed. + public const int LegacyFwCeiling = 150; + + /// + /// Interpret a definitive server response. Mirrors the legacy Android app's + /// CheckEmailStatus success-code handling, including the ECU activation-bit + /// () rescue on the "not registered" verdicts (5 and 0). + /// + /// The server's success status code. + /// This unit's firmware version (for the legacy-ECU branch). + /// ECU self-reported activation (Reg1_Reg2 > 0). + /// Optional human message echoed from the server. + public static EcuStatusResult Interpret(int success, byte fwVersion, bool isActivated, + string? serverMessage = null) + { + string msg = string.IsNullOrWhiteSpace(serverMessage) ? "" : serverMessage!.Trim(); + + switch (success) + { + // Registered / global / dealer-bypass — full access. + case 1: + case 2: + case 3: + case 8: + return new EcuStatusResult( + EcuStatusOutcome.Pass, + success == 8 ? "Dealer-bypassed ECU — access granted." + : "ECU registered — access granted.", + success, ServerReachable: true); + + // Activated but not warranty-registered — allowed, with a warning. + case 6: + case 7: + return new EcuStatusResult( + EcuStatusOutcome.Warn, + "This ECU is activated but not registered for warranty.", + success, ServerReachable: true); + + // Phone not registered. Legacy: FW < 150 → pass; else if activated → pass with a + // "password change disabled" warning; else block. + case 5: + if (fwVersion < LegacyFwCeiling) + return new EcuStatusResult(EcuStatusOutcome.Pass, + "Legacy ECU — access granted.", success, ServerReachable: true); + return isActivated + ? new EcuStatusResult(EcuStatusOutcome.Warn, + "This ECU is activated but not registered for warranty. " + + "Password change is disabled.", + success, ServerReachable: true) + : NotActivated(success); + + // Unregistered. Legacy: FW < 150 → pass; else if activated → pass; else block. + case 0: + if (fwVersion < LegacyFwCeiling) + return new EcuStatusResult(EcuStatusOutcome.Pass, + "Legacy ECU — access granted.", success, ServerReachable: true); + return isActivated + ? new EcuStatusResult(EcuStatusOutcome.Pass, + "ECU activated — access granted.", success, ServerReachable: true) + : NotActivated(success); + + // Account removed — warranty void, but access is allowed. + case 9: + return new EcuStatusResult( + EcuStatusOutcome.Warn, + "The account for this ECU has been removed — warranty is void.", + success, ServerReachable: true); + + // App out of date (server rejected the request shape). + case 98: + return new EcuStatusResult( + EcuStatusOutcome.Block, + "Missing parameter. Please update TuneBoss PC to the latest version.", + success, ServerReachable: true); + + default: + return new EcuStatusResult( + EcuStatusOutcome.Block, + $"Unrecognised ECU status from server (code {success})" + + (msg.Length > 0 ? $": {msg}" : "."), + success, ServerReachable: true); + } + } + + /// + /// Outcome when the server can't be reached (offline, timeout, or a transport/parse error). + /// Mirrors the legacy Android offline / server-error fallback exactly: FW < 150 passes, + /// an activated ECU () passes, and only a genuinely + /// unactivated modern unit is blocked. This is why an activated unit still works offline. + /// + public static EcuStatusResult Unreachable(byte fwVersion, bool isActivated, string? reason = null) + { + if (fwVersion < LegacyFwCeiling) + return new EcuStatusResult(EcuStatusOutcome.Pass, + "Legacy ECU — access granted (server not contacted).", SuccessCode: null, + ServerReachable: false); + + if (isActivated) + return new EcuStatusResult(EcuStatusOutcome.Pass, + "ECU activated — access granted (server not contacted).", SuccessCode: null, + ServerReachable: false); + + string why = string.IsNullOrWhiteSpace(reason) ? "" : $" ({reason})"; + return new EcuStatusResult(EcuStatusOutcome.Block, + "This ECU has not been activated, and the activation server could not be reached " + + "to verify it. Please activate the ECU with your dealer." + why, + SuccessCode: null, ServerReachable: false); + } + + private static EcuStatusResult NotActivated(int success) => new( + EcuStatusOutcome.Block, + "This ECU has not been activated. Please activate it with your dealer.", + success, ServerReachable: true); +} diff --git a/TuneBoss.Core/Models/MemoryLayout.cs b/TuneBoss.Core/Models/MemoryLayout.cs index 1e16f13..50c9baa 100644 --- a/TuneBoss.Core/Models/MemoryLayout.cs +++ b/TuneBoss.Core/Models/MemoryLayout.cs @@ -49,6 +49,15 @@ public sealed record MemoryLayout public MemoryRegion Fuel_Angle2D { get; init; } = MemoryRegion.Unavailable; public MemoryRegion Secondary_Load_Conversion { get; init; } = MemoryRegion.Unavailable; + // ── Acceleration-compensation 2D tables (FW_Version >= 197) ─────────────── + // 228-byte tables in the MAIN 2D address space (base 2D opcodes — NOT user tables), + // at slots 9/10/11 (index × 228): 0x0804 / 0x08E8 / 0x09CC. The firmware allocates + // the cyl2 base tables (slots 5-8) on every unit, so accel comp sits at a fixed + // 9-11 regardless of cylinder count. + public MemoryRegion Accel_Fuel_Comp { get; init; } = MemoryRegion.Unavailable; // 0x0804 (9×228) + public MemoryRegion Accel_Spark_Comp { get; init; } = MemoryRegion.Unavailable; // 0x08E8 (10×228) + public MemoryRegion Accel_FuelAngle_Comp { get; init; } = MemoryRegion.Unavailable; // 0x09CC (11×228) + // ── 2D user-adjustable tables (cyl1) ───────────────────────────────────── public MemoryRegion Fuel_PulseWidth_Adjust1 { get; init; } = MemoryRegion.Unavailable; public MemoryRegion Spark_Angle_Adjust1 { get; init; } = MemoryRegion.Unavailable; @@ -179,11 +188,14 @@ public sealed record MemoryLayout Fuel_PulseWidth_Adjust1_SubTable = R(0x0018, LenSubTable), Spark_Angle_Adjust1_SubTable = R(0x0030, LenSubTable), - // Cyl2 2D (zero/unavailable for single cylinder) - Fuel_PulseWidth2 = isTwoCyl ? R(0x063C, Len2DTable) : MemoryRegion.Unavailable, - AFR_Target2 = isTwoCyl ? R(0x0720, LenAFRTable) : MemoryRegion.Unavailable, - Fuel_Angle2D_2 = isTwoCyl ? R(0x0804, Len2DTable) : MemoryRegion.Unavailable, - Spark_Angle2 = isTwoCyl ? R(0x08E8, Len2DTable) : MemoryRegion.Unavailable, + // Cyl2 2D — MAIN space slots 5/6/7/8, matching the firmware's contiguous 2D + // declaration (0x0474/0x0558/0x063C/0x0720). The memory is allocated on EVERY + // unit; single-cylinder just doesn't access it (gated isTwoCyl for the nav). + // (Previously mis-mapped to slots 7-10, which then clashed with accel at 9-11.) + Fuel_PulseWidth2 = isTwoCyl ? R(0x0474, Len2DTable) : MemoryRegion.Unavailable, // idx 5 + AFR_Target2 = isTwoCyl ? R(0x0558, LenAFRTable) : MemoryRegion.Unavailable, // idx 6 + Fuel_Angle2D_2 = isTwoCyl ? R(0x063C, Len2DTable) : MemoryRegion.Unavailable, // idx 7 + Spark_Angle2 = isTwoCyl ? R(0x0720, Len2DTable) : MemoryRegion.Unavailable, // idx 8 Fuel_PulseWidth_Adjust2 = isTwoCyl ? R(0x09CC, Len2DTable) : MemoryRegion.Unavailable, Spark_Angle_Adjust2 = isTwoCyl ? R(0x0AB0, Len2DTable) : MemoryRegion.Unavailable, @@ -191,6 +203,13 @@ public sealed record MemoryLayout AFR_Target2_SubTable = isTwoCyl ? R(0x0048, LenSubTable) : MemoryRegion.Unavailable, Fuel_PulseWidth_Adjust2_SubTable = isTwoCyl ? R(0x0060, LenSubTable) : MemoryRegion.Unavailable, Spark_Angle_Adjust2_SubTable = isTwoCyl ? R(0x0078, LenSubTable) : MemoryRegion.Unavailable, + // Acceleration-compensation tables — FW >= 197, MAIN 2D space, slots 9/10/11 + // (index × 228): 0x0804 / 0x08E8 / 0x09CC, right after cyl2 Spark_Angle2 (idx 8). + // Present on EVERY unit regardless of cylinder count — the cyl2 slots 5-8 are + // always allocated in firmware, so accel sits at a fixed 9-11 (fw-gate only). + Accel_Fuel_Comp = fw >= 197 ? R(0x0804, Len2DTable) : MemoryRegion.Unavailable, + Accel_Spark_Comp = fw >= 197 ? R(0x08E8, Len2DTable) : MemoryRegion.Unavailable, + Accel_FuelAngle_Comp = fw >= 197 ? R(0x09CC, Len2DTable) : MemoryRegion.Unavailable, // Misc core MiscCore = R(0x0000, LenMiscCore), @@ -228,6 +247,8 @@ public sealed record MemoryLayout Spark_Angle_Adjust1 = R(0x00E4, Len2DTable), Fuel_PulseWidth_Adjust2 = isTwoCyl ? R(0x01C8, Len2DTable) : MemoryRegion.Unavailable, Spark_Angle_Adjust2 = isTwoCyl ? R(0x02AC, Len2DTable) : MemoryRegion.Unavailable, + // Acceleration-compensation tables are inherited from BuildGen2 (MAIN 2D space, + // slots 9/10/11, single-cylinder only) — no GEN3 override needed. }; } diff --git a/TuneBossPC/App.xaml.cs b/TuneBossPC/App.xaml.cs index b2eb7f8..88685db 100644 --- a/TuneBossPC/App.xaml.cs +++ b/TuneBossPC/App.xaml.cs @@ -31,6 +31,7 @@ public partial class App : Application services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/TuneBossPC/Services/EcuStatusService.cs b/TuneBossPC/Services/EcuStatusService.cs new file mode 100644 index 0000000..825f21c --- /dev/null +++ b/TuneBossPC/Services/EcuStatusService.cs @@ -0,0 +1,123 @@ +using System.Net.Http; +using System.Text; +using System.Text.Json; +using TuneBoss.Core.Models; + +namespace TuneBossPC.Services; + +/// +/// Talks to the TracBoss account server to check an ECU's registration/activation status +/// after unlock, then maps the reply to an app outcome via . +/// +/// Endpoint + request shape mirror the Flutter app's checkEmailStatus: +/// POST https://apiv3.tracboss.com/account/task +/// header Auth-Key: asdwqe123asd.dv2lr14 +/// body { task:"status", tbid, serialNum, firmware_version, model, make } +/// +public sealed class EcuStatusService : IEcuStatusService +{ + private const string Endpoint = "https://apiv3.tracboss.com/account/task"; + private const string AuthKey = "asdwqe123asd.dv2lr14"; + private static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(5); + + // One reusable client. Per-call timeout is enforced with a linked CTS so a caller's + // token still cancels early. + private static readonly HttpClient Http = new(); + + public async Task CheckAsync(EcuInfo info, string serialNumber, CancellationToken ct = default) + { + var payload = new Dictionary + { + ["task"] = "status", + ["tbid"] = info.UniqueId, + ["serialNum"] = serialNumber, + ["firmware_version"] = info.FwVersion, + ["model"] = info.BikeModel, + ["make"] = info.BikeManufacturer, + }; + + string json = JsonSerializer.Serialize(payload); + + using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct); + linked.CancelAfter(RequestTimeout); + + try + { + using var req = new HttpRequestMessage(HttpMethod.Post, Endpoint) + { + Content = new StringContent(json, Encoding.UTF8, "application/json"), + }; + req.Headers.TryAddWithoutValidation("Auth-Key", AuthKey); + + using var resp = await Http.SendAsync(req, linked.Token); + string body = await resp.Content.ReadAsStringAsync(linked.Token); + + if (!resp.IsSuccessStatusCode) + return EcuStatusInterpreter.Unreachable( + info.FwVersion, info.IsActivated, $"HTTP {(int)resp.StatusCode}"); + + if (!TryParse(body, out int success, out string message)) + return EcuStatusInterpreter.Unreachable( + info.FwVersion, info.IsActivated, "bad server response"); + + return EcuStatusInterpreter.Interpret(success, info.FwVersion, info.IsActivated, message); + } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + // The caller cancelled (e.g. disconnect) — not a server problem; surface as unreachable. + return EcuStatusInterpreter.Unreachable(info.FwVersion, info.IsActivated, "cancelled"); + } + catch (OperationCanceledException) + { + return EcuStatusInterpreter.Unreachable(info.FwVersion, info.IsActivated, "timed out"); + } + catch (HttpRequestException ex) + { + return EcuStatusInterpreter.Unreachable(info.FwVersion, info.IsActivated, ex.Message); + } + catch (Exception ex) + { + return EcuStatusInterpreter.Unreachable(info.FwVersion, info.IsActivated, ex.Message); + } + } + + /// + /// Pull the integer success code and optional message out of the JSON body. + /// Tolerant of success arriving as a number or a numeric string. + /// + private static bool TryParse(string body, out int success, out string message) + { + success = -1; + message = ""; + if (string.IsNullOrWhiteSpace(body)) return false; + + try + { + using var doc = JsonDocument.Parse(body); + var root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) return false; + + if (!root.TryGetProperty("success", out var s)) return false; + switch (s.ValueKind) + { + case JsonValueKind.Number when s.TryGetInt32(out int n): + success = n; + break; + case JsonValueKind.String when int.TryParse(s.GetString(), out int sn): + success = sn; + break; + default: + return false; + } + + if (root.TryGetProperty("message", out var m) && m.ValueKind == JsonValueKind.String) + message = m.GetString() ?? ""; + + return true; + } + catch (JsonException) + { + return false; + } + } +} diff --git a/TuneBossPC/Services/IEcuStatusService.cs b/TuneBossPC/Services/IEcuStatusService.cs new file mode 100644 index 0000000..baa53ff --- /dev/null +++ b/TuneBossPC/Services/IEcuStatusService.cs @@ -0,0 +1,19 @@ +using TuneBoss.Core.Models; + +namespace TuneBossPC.Services; + +/// +/// Post-unlock ECU status/registration check against the TracBoss account server. +/// Called once, right after a successful password unlock, before the app loads tables. +/// +public interface IEcuStatusService +{ + /// + /// Ask the server whether this ECU is registered/activated and return the app outcome. + /// Never throws for network problems — a timeout / offline / transport error comes back + /// as an via . + /// + /// The connected unit's parsed info (tbid, firmware, bike ids). + /// Unit serial — the advertised BLE name with the "B_" prefix stripped. + Task CheckAsync(EcuInfo info, string serialNumber, CancellationToken ct = default); +} diff --git a/TuneBossPC/Services/MapTableCodec.cs b/TuneBossPC/Services/MapTableCodec.cs index e91b888..3c2de09 100644 --- a/TuneBossPC/Services/MapTableCodec.cs +++ b/TuneBossPC/Services/MapTableCodec.cs @@ -79,6 +79,13 @@ public sealed class MapTableCodec : IMapTableCodec yield return new("Spark_Angle_Adjust2", "User Spark Angle 2", K.TwoD); } + // Acceleration compensation — FW >= 197. Not cylinder-split (single set). On older + // firmware the entries are absent from the nav, so Prepare/Serialize/Write all skip + // them by the (e == null) guards — no explicit FW check needed here. + yield return new("Accel_Fuel_Comp_Table_2D", "Acceleration Fuel Compensation", K.TwoD); + yield return new("Accel_Spark_Comp_Table_2D", "Acceleration Spark Compensation", K.TwoD); + yield return new("Accel_FuelAngle_Comp_Table_2D", "Acceleration Fuel Angle Compensation", K.TwoD); + yield return new("Fuel_PulseWidth_Adjust1_SubTable", "User Fuel Pulse Width 1", K.Sub); yield return new("Spark_Angle_Adjust1_SubTable", "User Spark Angle 1", K.Sub); if (cyl >= 2) @@ -515,6 +522,9 @@ public sealed class MapTableCodec : IMapTableCodec "Base Fuel Injection Angle 1" => "Fuel_Angle2D", "Base Fuel Injection Angle 2" => "Fuel_Angle2D_2", "Base MAP Compensation" => "Secondary_Load_Conversion", + "Acceleration Fuel Compensation" => "Accel_Fuel_Comp_Table_2D", + "Acceleration Spark Compensation" => "Accel_Spark_Comp_Table_2D", + "Acceleration Fuel Angle Compensation" => "Accel_FuelAngle_Comp_Table_2D", "User Fuel Pulse Width 1" => "Fuel_PulseWidth_Adjust1", "User Fuel Pulse Width 2" => "Fuel_PulseWidth_Adjust2", "User Spark Angle 1" => "Spark_Angle_Adjust1", diff --git a/TuneBossPC/ViewModels/ConnectViewModel.cs b/TuneBossPC/ViewModels/ConnectViewModel.cs index 4454f68..9a3a52c 100644 --- a/TuneBossPC/ViewModels/ConnectViewModel.cs +++ b/TuneBossPC/ViewModels/ConnectViewModel.cs @@ -14,6 +14,7 @@ public partial class ConnectViewModel : ObservableObject, IDisposable private readonly IBleService _ble; private readonly MainWindowViewModel _mainVm; private readonly IAuthService _auth; + private readonly IEcuStatusService _ecuStatus; private readonly ISessionService _session; private readonly TuneBossPC.ViewModels.Tables.TuningTablesViewModel _tablesVm; private readonly TuneBossPC.ViewModels.Tables.OneDimTablesViewModel _oneDimVm; @@ -50,16 +51,18 @@ public partial class ConnectViewModel : ObservableObject, IDisposable IBleService ble, MainWindowViewModel mainVm, IAuthService auth, + IEcuStatusService ecuStatus, ISessionService session, TuneBossPC.ViewModels.Tables.TuningTablesViewModel tablesVm, TuneBossPC.ViewModels.Tables.OneDimTablesViewModel oneDimVm, TuneBossPC.ViewModels.Tables.MiscValuesViewModel miscVm, ISnackbarService snackbar) { - _ble = ble; - _mainVm = mainVm; - _auth = auth; - _session = session; + _ble = ble; + _mainVm = mainVm; + _auth = auth; + _ecuStatus = ecuStatus; + _session = session; _tablesVm = tablesVm; _oneDimVm = oneDimVm; _miscVm = miscVm; @@ -151,6 +154,28 @@ public partial class ConnectViewModel : ObservableObject, IDisposable return; } + // Step 3b — Post-unlock ECU status check (server registration / activation gate). + // Mirrors the Flutter app's initAfterUnlock → checkEmailStatus gate: a definitive + // "not activated" (or an unreachable server, per policy) blocks entry and + // disconnects; "activated but not registered" is allowed with a warning. + SetStatus("Checking ECU status…"); + var status = await _ecuStatus.CheckAsync(_ecuInfo, SerialFromAdvertisedName(SelectedDevice.Name)); + + if (status.IsBlocked) + { + MessageBox.Show(status.Message, "ECU Status", + MessageBoxButton.OK, MessageBoxImage.Warning); + SetStatus($"Blocked: {status.Message}"); + await _ble.DisconnectAsync(); + return; + } + + if (status.Outcome == TuneBoss.Core.Models.EcuStatusOutcome.Warn) + { + MessageBox.Show(status.Message, "ECU Status", + MessageBoxButton.OK, MessageBoxImage.Warning); + } + // Step 4 — Populate UI EcuUsername = _ecuInfo.Username; EcuFwVersion = $"v{_ecuInfo.FwVersion} FW2: {_ecuInfo.FwVersion2}.{_ecuInfo.FwSubVersion2}"; @@ -243,6 +268,18 @@ public partial class ConnectViewModel : ObservableObject, IDisposable SetStatus("Disconnected"); } + /// + /// The unit serial the status server expects: the advertised BLE name with the + /// leading "B_" prefix stripped (e.g. "B_TBYA028A0498" → "TBYA028A0498"). + /// + private static string SerialFromAdvertisedName(string advertisedName) + { + if (string.IsNullOrEmpty(advertisedName)) return string.Empty; + return advertisedName.StartsWith("B_", StringComparison.OrdinalIgnoreCase) + ? advertisedName[2..] + : advertisedName; + } + private void SetStatus(string msg) { StatusMessage = msg; diff --git a/TuneBossPC/ViewModels/DiagnosticsStripViewModel.cs b/TuneBossPC/ViewModels/DiagnosticsStripViewModel.cs index f65a3bd..127b660 100644 --- a/TuneBossPC/ViewModels/DiagnosticsStripViewModel.cs +++ b/TuneBossPC/ViewModels/DiagnosticsStripViewModel.cs @@ -138,9 +138,17 @@ public partial class DiagnosticsStripViewModel : ObservableObject, IDisposable { private readonly IBleService _ble; private IDisposable? _diagSub; + private IDisposable? _connSub; [ObservableProperty] private bool _isRunning; + /// True only while a device is connected. The START/STOP toggle is gated on + /// this so it can't be pressed with no device (which previously crashed the app). + [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(ToggleCommand))] + [NotifyCanExecuteChangedFor(nameof(StartCommand))] + private bool _isConnected; + // The 6 configurable gauge slots public ObservableCollection Slots { get; } = new() { @@ -159,18 +167,48 @@ public partial class DiagnosticsStripViewModel : ObservableObject, IDisposable public DiagnosticsStripViewModel(IBleService ble) { _ble = ble; + _connSub = ble.ConnectionStateChanged.Subscribe(OnConnectionStateChanged); + } + + private void OnConnectionStateChanged(BleConnectionState state) + { + System.Windows.Application.Current.Dispatcher.Invoke(() => + { + IsConnected = state == BleConnectionState.Connected; + + // Link dropped while streaming — reflect the stopped state so the strip + // doesn't keep showing stale values or think it's still running. + if (!IsConnected && IsRunning) + { + _diagSub?.Dispose(); + _diagSub = null; + IsRunning = false; + foreach (var slot in Slots) slot.Value = "—"; + } + }); } // ── Start / Stop ────────────────────────────────────────────────────────── - [RelayCommand] + /// Start/Stop can only run with a connected device. + public bool CanToggle => IsConnected; + + [RelayCommand(CanExecute = nameof(CanToggle))] public async Task StartAsync() { - if (IsRunning) return; - await _ble.StartDiagnosticsAsync(); - IsRunning = true; - - _diagSub = _ble.DiagnosticsFrames.Subscribe(OnFrame); + if (IsRunning || !IsConnected) return; + try + { + await _ble.StartDiagnosticsAsync(); + IsRunning = true; + _diagSub = _ble.DiagnosticsFrames.Subscribe(OnFrame); + } + catch (Exception ex) + { + // Never let a start failure (e.g. no device) take down the app. + IsRunning = false; + System.Diagnostics.Debug.WriteLine($"[STRIP] Start failed: {ex.Message}"); + } } [RelayCommand] @@ -210,11 +248,13 @@ public partial class DiagnosticsStripViewModel : ObservableObject, IDisposable public void Dispose() { _diagSub?.Dispose(); + _connSub?.Dispose(); } - [RelayCommand] + [RelayCommand(CanExecute = nameof(CanToggle))] public async Task ToggleAsync() { + if (!IsConnected) return; if (IsRunning) await StopAsync(); else diff --git a/TuneBossPC/ViewModels/OneDimTablesViewModel.cs b/TuneBossPC/ViewModels/OneDimTablesViewModel.cs index 2de8433..e326daf 100644 --- a/TuneBossPC/ViewModels/OneDimTablesViewModel.cs +++ b/TuneBossPC/ViewModels/OneDimTablesViewModel.cs @@ -370,6 +370,24 @@ public partial class OneDimTablesViewModel : ObservableObject, IDisposable finally { IsReading = false; await ResumeDiagnosticsIfLiveAsync(); } } + /// + /// Forces a fresh BLE re-read of one 1D table by slot (1-based), refreshing the cached + /// model and the on-screen grid if that table is selected. Used after TPS calibration, + /// which writes the Throttle Position table (slot 6) directly on the device — without + /// this, the 1D page would keep showing the copy cached at connect. + /// + public async Task RefreshSlotAsync(int slot) + { + var entry = Groups.SelectMany(g => g.Entries).FirstOrDefault(e => e.Slot == slot); + if (entry == null) return; + try + { + if (await ReadEntryAsync(entry) && entry.Table != null && SelectedEntry == entry) + Application.Current.Dispatcher.Invoke(() => PopulateGrid(entry.Table)); + } + catch { /* best-effort refresh */ } + } + /// Reads all available 1D tables so they're cached for instant viewing. Mirrors the 2D init. public async Task InitializeAllAsync(IProgress? progress = null) { diff --git a/TuneBossPC/ViewModels/Tables/TuningTablesViewModel.cs b/TuneBossPC/ViewModels/Tables/TuningTablesViewModel.cs index 29980ed..17ea572 100644 --- a/TuneBossPC/ViewModels/Tables/TuningTablesViewModel.cs +++ b/TuneBossPC/ViewModels/Tables/TuningTablesViewModel.cs @@ -320,6 +320,27 @@ public partial class TuningTablesViewModel : ObservableObject, IDisposable }); Groups.Add(stage3); + // ── Acceleration compensation (FW >= 197) ── + // Firmware-gated, not stage-gated: the regions are Unavailable below FW 197, + // so the entries (and the whole group) only appear when the unit exposes them. + // RequiredStage = 1 keeps the group unlocked on any connected stage. + var accel = new TableGroupViewModel { Label = "ACCELERATION COMP", RequiredStage = 1 }; + // MAIN 2D tables (base read/write opcodes) at slots 9/10/11 — not user tables. + if (layout?.Accel_Fuel_Comp?.IsAvailable == true) + accel.Entries.Add(MakeEntry("Acceleration Fuel Compensation", + layout.Accel_Fuel_Comp, TableEntryType.TuningTable, + displayName: "Accel Fuel Comp", icon: TableIconKind.Fuel)); + if (layout?.Accel_Spark_Comp?.IsAvailable == true) + accel.Entries.Add(MakeEntry("Acceleration Spark Compensation", + layout.Accel_Spark_Comp, TableEntryType.TuningTable, + displayName: "Accel Spark Comp", icon: TableIconKind.Spark)); + if (layout?.Accel_FuelAngle_Comp?.IsAvailable == true) + accel.Entries.Add(MakeEntry("Acceleration Fuel Angle Compensation", + layout.Accel_FuelAngle_Comp, TableEntryType.TuningTable, + displayName: "Accel Angle Comp", icon: TableIconKind.Angle)); + if (accel.Entries.Count > 0) + Groups.Add(accel); + // Read-only gate: a group is stage-unlocked if the ECU is at/above its stage. // Offline (connectedStage == null) leaves everything unlocked. Entries mirror // their group so per-entry comms gating is a simple bind. @@ -422,9 +443,19 @@ public partial class TuningTablesViewModel : ObservableObject, IDisposable } } else + { + // Not loaded — clear the grid so it shows EMPTY, not the previously + // selected table's data (that stale carry-over looked like the old + // table "reappearing" under the new one). READ will populate it. + RpmHeaders.Clear(); + LoadHeaders.Clear(); + Rows.Clear(); + SubRows.Clear(); + SurfaceChanged?.Invoke(); StatusMessage = entry.IsStandaloneSub ? "Click READ to load this subtable." : "Click READ to load this table."; + } } // ── Read ────────────────────────────────────────────────────────────────── diff --git a/TuneBossPC/ViewModels/TpsCalViewModel.cs b/TuneBossPC/ViewModels/TpsCalViewModel.cs index c424658..729b5ac 100644 --- a/TuneBossPC/ViewModels/TpsCalViewModel.cs +++ b/TuneBossPC/ViewModels/TpsCalViewModel.cs @@ -25,6 +25,11 @@ public partial class TpsCalViewModel : ObservableObject, IDisposable { private readonly IBleService _ble; private readonly ISessionService _session; + private readonly TuneBossPC.ViewModels.Tables.OneDimTablesViewModel _oneDim; + + /// 1D slot of the Throttle Position (TPS conversion) table — the one the + /// calibration write at 0x0078 lands in, refreshed after a successful cal. + private const int ThrottlePositionSlot = 6; private IDisposable? _diagSub; private TpsCalibration.Addresses _addr; @@ -61,10 +66,12 @@ public partial class TpsCalViewModel : ObservableObject, IDisposable public bool IsIdle => !IsCalibrating && !IsBusy; - public TpsCalViewModel(IBleService ble, ISessionService session) + public TpsCalViewModel(IBleService ble, ISessionService session, + TuneBossPC.ViewModels.Tables.OneDimTablesViewModel oneDim) { _ble = ble; _session = session; + _oneDim = oneDim; } // ── Activation ───────────────────────────────────────────────────────────── @@ -229,6 +236,12 @@ public partial class TpsCalViewModel : ObservableObject, IDisposable StatusMessage = fr.Success ? "TPS calibration successful and saved to ECU." : $"Flash write failed: {fr.ErrorMessage}"; + + // 4) Refresh the cached Throttle Position 1D table (slot 6, addr 0x0078) that + // this calibration just rewrote, so the 1D page reflects the new raw-axis + // values instead of the copy cached at connect. + if (fr.Success) + await _oneDim.RefreshSlotAsync(ThrottlePositionSlot); } catch (Exception ex) { StatusMessage = $"Error during write: {ex.Message}"; } finally