Compare commits

...
3 Commits
Author SHA1 Message Date
suffian b22b0df6ed Bluetooth check, avoid crashing 2026-10-14 07:24:06 +08:00
suffian 1ec485701a All fixes before Bluetooth 2026-10-14 07:12:24 +08:00
suffian fbc92d57ba Track ClickOnce publish profiles 2026-10-14 07:11:21 +08:00
19 changed files with 718 additions and 26 deletions
+3
View File
@@ -480,3 +480,6 @@ $RECYCLE.BIN/
# Vim temporary swap files
*.swp
# ClickOnce publish profiles are config, not secrets — keep them tracked
!TuneBossPC/Properties/PublishProfiles/*.pubxml
+33 -1
View File
@@ -84,6 +84,34 @@ public sealed class BleManager : IBleService
// ────────────────────────────────────────────────────────────────────────
// SCANNING
// ────────────────────────────────────────────────────────────────────────
/// <summary>Checks that a Bluetooth adapter exists, supports LE, and its radio is on.
/// Never throws — any failure comes back as IsReady=false with a reason.</summary>
public async Task<BluetoothAvailability> CheckBluetoothAsync()
{
try
{
var adapter = await BluetoothAdapter.GetDefaultAsync();
if (adapter == null)
return new BluetoothAvailability(false, "No Bluetooth adapter found on this PC.");
if (!adapter.IsLowEnergySupported)
return new BluetoothAvailability(false, "This PC's Bluetooth does not support Bluetooth LE.");
var radio = await adapter.GetRadioAsync();
if (radio == null)
return new BluetoothAvailability(false, "Could not access the Bluetooth radio.");
if (radio.State != Windows.Devices.Radios.RadioState.On)
return new BluetoothAvailability(false,
"Bluetooth is turned off. Please turn it on, then press Scan.");
return new BluetoothAvailability(true, string.Empty);
}
catch (Exception ex)
{
return new BluetoothAvailability(false, $"Bluetooth is unavailable: {ex.Message}");
}
}
public IObservable<BleDeviceInfo> StartScan()
{
var seen = new Dictionary<ulong, string>();
@@ -117,7 +145,11 @@ public sealed class BleManager : IBleService
}
};
_watcher.Start();
// Guard the radio-off / adapter-missing case so a scan start can never crash the
// app. Callers should CheckBluetoothAsync() first, but this is the safety net.
try { _watcher.Start(); }
catch (Exception) { _watcher = null; }
return _scanSubject.AsObservable();
}
+8
View File
@@ -6,6 +6,10 @@ namespace TuneBoss.Core.BLE;
/// <summary>
/// Represents a discovered BLE device before connection.
/// </summary>
/// <summary>Result of a Bluetooth-adapter check: whether BLE is ready to scan, and a
/// human-readable reason when it isn't (no adapter / no BLE support / radio off).</summary>
public readonly record struct BluetoothAvailability(bool IsReady, string Message);
public sealed record BleDeviceInfo(
ulong Address,
string Name,
@@ -69,6 +73,10 @@ public interface IBleService : IDisposable
// ── Scanning ─────────────────────────────────────────────────────────────
/// <summary>Whether a Bluetooth adapter is present and its radio is on. Call this
/// before scanning so a radio that's off gives a friendly message instead of a crash.</summary>
Task<BluetoothAvailability> CheckBluetoothAsync();
/// <summary>Starts BLE advertisement scanning. Emits discovered devices.</summary>
IObservable<BleDeviceInfo> StartScan();
+4
View File
@@ -41,6 +41,9 @@ public sealed class SimBleService : IBleService
public IObservable<BleConnectionState> ConnectionStateChanged => _state.AsObservable();
// ── Scan ──────────────────────────────────────────────────────────────────
public Task<BluetoothAvailability> CheckBluetoothAsync() =>
Task.FromResult(new BluetoothAvailability(true, string.Empty));
public IObservable<BleDeviceInfo> StartScan() => Observable.Create<BleDeviceInfo>(o =>
{
o.OnNext(new BleDeviceInfo(0xAABBCCDDEEFF, "B_SIM-PG1", -42));
@@ -83,6 +86,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.
};
}
+54 -6
View File
@@ -16,11 +16,48 @@ public partial class App : Application
public App()
{
// Catch ANY unhandled exception so a startup failure can't die silently — it gets
// written to %APPDATA%\TuneBoss\crash.log and shown in a dialog. (ClickOnce installs
// that crash on launch with no message otherwise leave nothing to go on.)
DispatcherUnhandledException += (_, e) =>
{
LogCrash("UI thread", e.Exception);
e.Handled = true; // already surfaced; keep running if the UI thread can
};
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
LogCrash("AppDomain", e.ExceptionObject as Exception);
System.Threading.Tasks.TaskScheduler.UnobservedTaskException += (_, e) =>
{
LogCrash("Background task", e.Exception);
e.SetObserved();
};
_host = Host.CreateDefaultBuilder()
.ConfigureServices(ConfigureServices)
.Build();
}
/// <summary>Appends an exception to %APPDATA%\TuneBoss\crash.log and shows a dialog.
/// Never throws — logging a crash must not itself crash.</summary>
private static void LogCrash(string source, Exception? ex)
{
try
{
var dir = System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "TuneBoss");
System.IO.Directory.CreateDirectory(dir);
var path = System.IO.Path.Combine(dir, "crash.log");
System.IO.File.AppendAllText(path,
$"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] ({source})\r\n{ex}\r\n\r\n");
MessageBox.Show(
$"TuneBoss PC hit an error.\n\nA log was saved to:\n{path}\n\n" +
$"{ex?.GetType().Name}: {ex?.Message}",
"TuneBoss PC — Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
catch { /* logging must never throw */ }
}
private static void ConfigureServices(IServiceCollection services)
{
// --sim on the command line swaps in the fake ECU.
@@ -31,6 +68,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>();
@@ -61,12 +99,22 @@ public partial class App : Application
protected override async void OnStartup(StartupEventArgs e)
{
await _host.StartAsync();
Wpf.Ui.Appearance.ApplicationThemeManager.Apply(
Wpf.Ui.Appearance.ApplicationTheme.Dark);
var mainWindow = _host.Services.GetRequiredService<MainWindow>();
mainWindow.Show();
base.OnStartup(e);
try
{
await _host.StartAsync();
Wpf.Ui.Appearance.ApplicationThemeManager.Apply(
Wpf.Ui.Appearance.ApplicationTheme.Dark);
var mainWindow = _host.Services.GetRequiredService<MainWindow>();
mainWindow.Show();
base.OnStartup(e);
}
catch (Exception ex)
{
// Service construction (BLE/WinRT, settings, etc.), theme, or window build
// failed — log it and exit cleanly instead of vanishing.
LogCrash("Startup", ex);
Shutdown(-1);
}
}
protected override async void OnExit(ExitEventArgs e)
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Dealer ClickOnce profile. Identical to ClickOnceProfile.pubxml except:
• <Dealer>true</Dealer> → defines the DEALER symbol (hides Config + 1D Tables)
• separate InstallUrl → its own update channel (never clobbers the full build)
• separate Publish dirs → dealer output doesn't overwrite the full build's
• distinct product name → separate shortcut / Add-Remove-Programs entry
Publish this profile for the dealer release; publish ClickOnceProfile for the full build. -->
<Project>
<PropertyGroup>
<!-- Turns on the dealer build. -->
<Dealer>true</Dealer>
<ApplicationRevision>3</ApplicationRevision>
<ApplicationVersion>1.0.0.*</ApplicationVersion>
<BootstrapperEnabled>True</BootstrapperEnabled>
<Configuration>Release</Configuration>
<CreateWebPageOnPublish>False</CreateWebPageOnPublish>
<GenerateManifests>true</GenerateManifests>
<Install>True</Install>
<InstallFrom>Web</InstallFrom>
<IsRevisionIncremented>True</IsRevisionIncremented>
<IsWebBootstrapper>True</IsWebBootstrapper>
<MapFileExtensions>True</MapFileExtensions>
<OpenBrowserOnPublish>False</OpenBrowserOnPublish>
<Platform>Any CPU</Platform>
<PublishDir>bin\Release\net9.0-windows10.0.19041.0\app.publish.dealer\</PublishDir>
<PublishUrl>bin\publish-dealer\</PublishUrl>
<PublishProtocol>ClickOnce</PublishProtocol>
<PublishReadyToRun>False</PublishReadyToRun>
<PublishSingleFile>False</PublishSingleFile>
<SelfContained>False</SelfContained>
<SignatureAlgorithm>(none)</SignatureAlgorithm>
<SignManifests>False</SignManifests>
<SkipPublishVerification>false</SkipPublishVerification>
<TargetFramework>net9.0-windows10.0.19041.0</TargetFramework>
<UpdateEnabled>False</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateRequired>False</UpdateRequired>
<WebPageFileName>Publish.html</WebPageFileName>
<!-- Separate update channel — dealers pull from here, independent of the full build. -->
<InstallUrl>https://app.tracboss.com/pcsoftware2/</InstallUrl>
<!-- Distinct friendly name (shortcut / Add-Remove Programs). -->
<ProductName>TuneBoss PC (Dealer)</ProductName>
<PublisherName>FSR Technology</PublisherName>
<History>True|2026-09-29T03:23:50.2255705Z||;True|2026-09-25T11:23:59.2144127+08:00||;True|2026-09-18T17:14:57.5162745+08:00||;</History>
</PropertyGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.NetCore.DesktopRuntime.9.0.x64">
<Install>true</Install>
<ProductName>.NET Desktop Runtime 9.0.13 (x64)</ProductName>
</BootstrapperPackage>
</ItemGroup>
</Project>
@@ -0,0 +1,41 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- https://go.microsoft.com/fwlink/?LinkID=208121. -->
<Project>
<PropertyGroup>
<ApplicationRevision>18</ApplicationRevision>
<ApplicationVersion>1.0.0.*</ApplicationVersion>
<BootstrapperEnabled>True</BootstrapperEnabled>
<Configuration>Release</Configuration>
<CreateWebPageOnPublish>False</CreateWebPageOnPublish>
<GenerateManifests>true</GenerateManifests>
<Install>True</Install>
<InstallFrom>Web</InstallFrom>
<IsRevisionIncremented>True</IsRevisionIncremented>
<IsWebBootstrapper>True</IsWebBootstrapper>
<MapFileExtensions>True</MapFileExtensions>
<OpenBrowserOnPublish>False</OpenBrowserOnPublish>
<Platform>Any CPU</Platform>
<PublishDir>bin\Release\net9.0-windows10.0.19041.0\app.publish\</PublishDir>
<PublishUrl>bin\publish\</PublishUrl>
<PublishProtocol>ClickOnce</PublishProtocol>
<PublishReadyToRun>False</PublishReadyToRun>
<PublishSingleFile>False</PublishSingleFile>
<SelfContained>False</SelfContained>
<SignatureAlgorithm>(none)</SignatureAlgorithm>
<SignManifests>False</SignManifests>
<SkipPublishVerification>false</SkipPublishVerification>
<TargetFramework>net9.0-windows10.0.19041.0</TargetFramework>
<UpdateEnabled>False</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateRequired>False</UpdateRequired>
<WebPageFileName>Publish.html</WebPageFileName>
<InstallUrl>https://app.tracboss.com/pcsoftware/</InstallUrl>
<History>True|2026-09-30T04:11:40.3267188Z||;True|2026-09-29T11:23:31.0586994+08:00||;True|2026-09-02T17:44:24.0999910+08:00||;True|2026-08-21T09:49:53.6754436+08:00||;True|2026-08-17T10:54:22.4563316+08:00||;True|2026-08-13T13:52:37.0281846+08:00||;True|2026-08-12T16:05:14.2705192+08:00||;True|2026-07-31T22:49:14.5869146+08:00||;True|2026-07-31T17:55:20.4616585+08:00||;True|2026-07-31T17:29:14.9984524+08:00||;True|2026-07-29T17:02:38.3012266+08:00||;True|2026-07-29T12:51:45.6990187+08:00||;True|2026-07-27T15:30:28.6055849+08:00||;</History>
</PropertyGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.NetCore.DesktopRuntime.9.0.x64">
<Install>true</Install>
<ProductName>.NET Desktop Runtime 9.0.13 (x64)</ProductName>
</BootstrapperPackage>
</ItemGroup>
</Project>
+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",
+59 -5
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,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;
@@ -79,6 +82,23 @@ public partial class ConnectViewModel : ObservableObject, IDisposable
});
}
/// <summary>
/// Verifies Bluetooth is on before scanning. If the radio is off / missing, shows a
/// friendly message instead of scanning (which used to throw and crash the app on
/// launch). Called by the auto-scan on page load and by the Scan button.
/// </summary>
public async Task EnsureBluetoothThenScanAsync()
{
if (IsScanning) return;
var bt = await _ble.CheckBluetoothAsync();
if (!bt.IsReady)
{
SetStatus(bt.Message);
return;
}
StartScan();
}
[RelayCommand]
public void StartScan()
{
@@ -116,7 +136,7 @@ public partial class ConnectViewModel : ObservableObject, IDisposable
}
else
{
StartScan();
_ = EnsureBluetoothThenScanAsync();
}
}
@@ -151,6 +171,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 +285,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,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]
/// <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;
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
@@ -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,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 ──────────────────────────────────────────────────────────────────
+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
+3 -1
View File
@@ -9,6 +9,8 @@ public partial class ConnectView : UserControl
{
DataContext = vm;
InitializeComponent();
vm.StartScan();
// Auto-scan on load, but check Bluetooth first. Calling scan synchronously in the
// ctor used to throw (and silently crash the app at launch) when the radio was off.
Loaded += async (_, _) => await vm.EnsureBluetoothThenScanAsync();
}
}