All fixes before Bluetooth

This commit is contained in:
2026-10-14 07:12:24 +08:00
parent fbc92d57ba
commit 1ec485701a
13 changed files with 504 additions and 17 deletions
+1
View File
@@ -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 ──────────────────────────────────────────────────────────────────
+20
View File
@@ -42,6 +42,18 @@ public sealed class EcuInfo
public byte UpgradeFuture12 { get; init; }
public byte UpgradeFuture2 { get; init; } // only if buffer > 68
// ── Registration / activation ─────────────────────────────────────────────
/// <summary>
/// ECU activation nibble (legacy <c>Reg1_Reg2</c> = <c>buf[offset+53] &amp; 0x0F</c>,
/// present only on longer info buffers / newer firmware). &gt; 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).
/// </summary>
public byte Reg1Reg2 { get; init; }
/// <summary>True when the ECU reports itself activated (<see cref="Reg1Reg2"/> &gt; 0).</summary>
public bool IsActivated => Reg1Reg2 > 0;
// ── Derived ──────────────────────────────────────────────────────────────
public int RpmLimit => UpgradeRpmMax * 100;
/// <summary>
@@ -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,
};
}
+153
View File
@@ -0,0 +1,153 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// What the app should do after the post-unlock server status check.
/// Mirrors the Flutter <c>checkEmailStatus</c> gate (doneAfterConnect):
/// Pass → continue into the app,
/// Warn → continue, but show a warning first,
/// Block → show the message, disconnect, do NOT load tables.
/// </summary>
public enum EcuStatusOutcome
{
Pass,
Warn,
Block,
}
/// <summary>
/// Result of the post-unlock ECU status check against the TracBoss account server.
/// </summary>
public sealed record EcuStatusResult(
EcuStatusOutcome Outcome,
string Message,
int? SuccessCode,
bool ServerReachable)
{
public bool IsBlocked => Outcome == EcuStatusOutcome.Block;
}
/// <summary>
/// Pure interpretation of the server's <c>success</c> code into an app outcome.
/// No HTTP or UI here so it can be unit-tested and reused.
///
/// Ported from the Flutter app's <c>checkEmailStatus</c> (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.
/// </summary>
public static class EcuStatusInterpreter
{
/// <summary>FW below this is a legacy unit that predates activation — always allowed.</summary>
public const int LegacyFwCeiling = 150;
/// <summary>
/// Interpret a definitive server response. Mirrors the legacy Android app's
/// <c>CheckEmailStatus</c> success-code handling, including the ECU activation-bit
/// (<paramref name="isActivated"/>) rescue on the "not registered" verdicts (5 and 0).
/// </summary>
/// <param name="success">The server's <c>success</c> status code.</param>
/// <param name="fwVersion">This unit's firmware version (for the legacy-ECU branch).</param>
/// <param name="isActivated">ECU self-reported activation (<c>Reg1_Reg2 &gt; 0</c>).</param>
/// <param name="serverMessage">Optional human message echoed from the server.</param>
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);
}
}
/// <summary>
/// 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 &lt; 150 passes,
/// an activated ECU (<paramref name="isActivated"/>) passes, and only a genuinely
/// unactivated modern unit is blocked. This is why an activated unit still works offline.
/// </summary>
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);
}
+26 -5
View File
@@ -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.
};
}
+1
View File
@@ -31,6 +31,7 @@ public partial class App : Application
services.AddSingleton<IBleService, BleManager>();
services.AddSingleton<IAuthService, AuthService>();
services.AddSingleton<IEcuStatusService, EcuStatusService>();
services.AddSingleton<ISettingsService, SettingsService>();
services.AddSingleton<ISessionService, SessionService>();
services.AddSingleton<INavigationService, NavigationService>();
+123
View File
@@ -0,0 +1,123 @@
using System.Net.Http;
using System.Text;
using System.Text.Json;
using TuneBoss.Core.Models;
namespace TuneBossPC.Services;
/// <summary>
/// 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 <see cref="EcuStatusInterpreter"/>.
///
/// Endpoint + request shape mirror the Flutter app's <c>checkEmailStatus</c>:
/// POST https://apiv3.tracboss.com/account/task
/// header Auth-Key: asdwqe123asd.dv2lr14
/// body { task:"status", tbid, serialNum, firmware_version, model, make }
/// </summary>
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<EcuStatusResult> CheckAsync(EcuInfo info, string serialNumber, CancellationToken ct = default)
{
var payload = new Dictionary<string, object?>
{
["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);
}
}
/// <summary>
/// Pull the integer <c>success</c> code and optional <c>message</c> out of the JSON body.
/// Tolerant of <c>success</c> arriving as a number or a numeric string.
/// </summary>
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;
}
}
}
+19
View File
@@ -0,0 +1,19 @@
using TuneBoss.Core.Models;
namespace TuneBossPC.Services;
/// <summary>
/// Post-unlock ECU status/registration check against the TracBoss account server.
/// Called once, right after a successful password unlock, before the app loads tables.
/// </summary>
public interface IEcuStatusService
{
/// <summary>
/// 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 <see cref="EcuStatusOutcome"/> via <see cref="EcuStatusInterpreter.Unreachable"/>.
/// </summary>
/// <param name="info">The connected unit's parsed info (tbid, firmware, bike ids).</param>
/// <param name="serialNumber">Unit serial — the advertised BLE name with the "B_" prefix stripped.</param>
Task<EcuStatusResult> CheckAsync(EcuInfo info, string serialNumber, CancellationToken ct = default);
}
+10
View File
@@ -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",
+37
View File
@@ -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,6 +51,7 @@ 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,
@@ -59,6 +61,7 @@ public partial class ConnectViewModel : ObservableObject, IDisposable
_ble = ble;
_mainVm = mainVm;
_auth = auth;
_ecuStatus = ecuStatus;
_session = session;
_tablesVm = tablesVm;
_oneDimVm = oneDimVm;
@@ -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");
}
/// <summary>
/// The unit serial the status server expects: the advertised BLE name with the
/// leading "B_" prefix stripped (e.g. "B_TBYA028A0498" → "TBYA028A0498").
/// </summary>
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;
@@ -138,9 +138,17 @@ public partial class DiagnosticsStripViewModel : ObservableObject, IDisposable
{
private readonly IBleService _ble;
private IDisposable? _diagSub;
private IDisposable? _connSub;
[ObservableProperty] private bool _isRunning;
/// <summary>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).</summary>
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(ToggleCommand))]
[NotifyCanExecuteChangedFor(nameof(StartCommand))]
private bool _isConnected;
// The 6 configurable gauge slots
public ObservableCollection<GaugeSlotViewModel> Slots { get; } = new()
{
@@ -159,19 +167,49 @@ 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]
/// <summary>Start/Stop can only run with a connected device.</summary>
public bool CanToggle => IsConnected;
[RelayCommand(CanExecute = nameof(CanToggle))]
public async Task StartAsync()
{
if (IsRunning) return;
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]
public async Task StopAsync()
@@ -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
@@ -370,6 +370,24 @@ public partial class OneDimTablesViewModel : ObservableObject, IDisposable
finally { IsReading = false; await ResumeDiagnosticsIfLiveAsync(); }
}
/// <summary>
/// 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.
/// </summary>
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 */ }
}
/// <summary>Reads all available 1D tables so they're cached for instant viewing. Mirrors the 2D init.</summary>
public async Task InitializeAllAsync(IProgress<string>? progress = null)
{
@@ -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,10 +443,20 @@ 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 ──────────────────────────────────────────────────────────────────
+14 -1
View File
@@ -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;
/// <summary>1D slot of the Throttle Position (TPS conversion) table — the one the
/// calibration write at 0x0078 lands in, refreshed after a successful cal.</summary>
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