commit 14f870619822678c0fa9d90c583d3f3c8f4de382 Author: suffian Date: Mon Sep 28 16:55:31 2026 +0800 Initial Commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0808c4a --- /dev/null +++ b/.gitignore @@ -0,0 +1,482 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from `dotnet new gitignore` + +# dotenv files +.env + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +# but not Directory.Build.rsp, as it configures directory-level build defaults +!Directory.Build.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea/ + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# content below from: https://github.com/github/gitignore/blob/main/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/main/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Vim temporary swap files +*.swp diff --git a/TuneBoss.Core.Tests/MapFileTests.cs b/TuneBoss.Core.Tests/MapFileTests.cs new file mode 100644 index 0000000..c657054 --- /dev/null +++ b/TuneBoss.Core.Tests/MapFileTests.cs @@ -0,0 +1,86 @@ +using TuneBoss.Core.IO; +using Xunit; + +namespace TuneBoss.Core.Tests; + +public class MapFileTests +{ + [Fact] + public void Md5Hex_is_uppercase_no_separators() + => Assert.Equal("D41D8CD98F00B204E9800998ECF8427E", MapFile.Md5Hex("")); + + [Fact] + public void Envelope_round_trips() + { + var env = MapFile.BuildEnvelope("the-tag", "the data section"); + var r = MapFile.TryParse(env); + Assert.True(r.Ok); + Assert.Equal("the-tag", r.Tag); + Assert.Equal("the data section", r.Data); + } + + [Fact] + public void Envelope_tolerates_crlf_newlines() + { + var env = MapFile.BuildEnvelope("t", "d").Replace("\n", "\r\n"); + Assert.True(MapFile.TryParse(env).Ok); + } + + [Fact] + public void Tampered_tag_is_rejected() + { + var env = MapFile.BuildEnvelope("original", "data"); + var bad = env.Replace("_____original", "_____TAMPERED"); + var r = MapFile.TryParse(bad); + Assert.False(r.Ok); + Assert.Contains("Tag checksum", r.Error); + } + + [Fact] + public void Tampered_data_is_rejected() + { + var env = MapFile.BuildEnvelope("tag", "good"); + var bad = env.Replace("_____good", "_____bad!"); + Assert.False(MapFile.TryParse(bad).Ok); + } + + [Fact] + public void Missing_data_record_is_rejected() + => Assert.False(MapFile.TryParse(MapFile.Md5Hex("x") + "_____x").Ok); + + [Fact] + public void Tag_round_trips_all_fields() + { + var t = new MapTag + { + CreatorId = "TUNER01", FwVersion = 193, HwVersion = 10, + Make = 1, Model = 6, CylinderCount = 1, SaveType = MapSaveType.FullConfig, + EngineBlock = "stock", Camshaft = "stage2", Exhaust = "akra", + AirFilter = "k&n", CylinderHead = "ported", Injector = "440cc", + ThrottleBody = "34mm", JackRod = "none", MiscNote = "dyno 18.2hp", + }; + var back = MapTag.Parse(t.Build()); + + Assert.Equal(t.CreatorId, back.CreatorId); + Assert.Equal(t.FwVersion, back.FwVersion); + Assert.Equal(t.Make, back.Make); + Assert.Equal(t.Model, back.Model); + Assert.Equal(t.CylinderCount, back.CylinderCount); + Assert.Equal(t.SaveType, back.SaveType); + Assert.Equal(t.Exhaust, back.Exhaust); + Assert.Equal(t.MiscNote, back.MiscNote); + } + + [Fact] + public void Tag_has_16_fields() + => Assert.Equal(MapTag.FieldCount, new MapTag().Build().Split(MapTag.FieldSep).Length); + + [Fact] + public void Tag_parse_tolerates_short_input() + { + var t = MapTag.Parse("CREATOR___193___10___1___6___1___4"); + Assert.Equal("CREATOR", t.CreatorId); + Assert.Equal(MapSaveType.FullConfig, t.SaveType); + Assert.Equal("", t.MiscNote); // absent field → empty, no throw + } +} diff --git a/TuneBoss.Core.Tests/MapTableFormatTests.cs b/TuneBoss.Core.Tests/MapTableFormatTests.cs new file mode 100644 index 0000000..14e6472 --- /dev/null +++ b/TuneBoss.Core.Tests/MapTableFormatTests.cs @@ -0,0 +1,101 @@ +using TuneBoss.Core.IO; +using TuneBoss.Core.Models; +using Xunit; + +namespace TuneBoss.Core.Tests; + +public class MapTableFormatTests +{ + private static byte[] Ramp(int n, int start = 0, int step = 1) + { + var a = new byte[n]; + for (int i = 0; i < n; i++) a[i] = (byte)((start + i * step) & 0xFF); + return a; + } + + [Fact] + public void Section2D_round_trips() + { + var t = new TuningTable + { + Data = Ramp(TuningTable.DataBytes, 1), + LoadAxis = Ramp(TuningTable.Rows, 10, 5), + RpmAxis = Ramp(TuningTable.Cols, 8, 9), + MaxRaw = 250, MinRaw = 3, Mult = 1, Sign = 0, + }; + var section = MapTableFormat.Section2D("Fuel_PulseWidth_Adjust1", t); + Assert.Equal("Fuel_PulseWidth_Adjust1", MapTableFormat.LabelOf(section)); + + // Single section + trailing empty after the ____ terminator. + var parts = MapTableFormat.SplitSections(section); + var back = MapTableFormat.Parse2D(parts[0]); + + Assert.Equal(t.Data, back.Data); + Assert.Equal(t.LoadAxis, back.LoadAxis); + Assert.Equal(t.RpmAxis, back.RpmAxis); + Assert.Equal(t.MaxRaw, back.MaxRaw); + Assert.Equal(t.MinRaw, back.MinRaw); + Assert.Equal(t.Mult, back.Mult); + Assert.Equal(t.Sign, back.Sign); + } + + [Fact] + public void Afr_round_trips_without_modifiers() + { + var t = new AfrTable + { + Data = Ramp(AfrTable.DataBytes, 130), + LoadAxis = Ramp(AfrTable.Rows, 20), + RpmAxis = Ramp(AfrTable.Cols, 5, 7), + }; + var back = MapTableFormat.ParseAfr(MapTableFormat.SplitSections(MapTableFormat.SectionAfr("AFR_Target1", t))[0]); + Assert.Equal(t.Data, back.Data); + Assert.Equal(t.LoadAxis, back.LoadAxis); + Assert.Equal(t.RpmAxis, back.RpmAxis); + } + + [Fact] + public void Sub_derives_rpm_from_parent() + { + var parentRpm = Ramp(TuningTable.Cols, 0, 1); // 0,1,2,...,23 + var sub = new SubTable { Data = Ramp(SubTable.DataBytes, 100) }; + var section = MapTableFormat.SplitSections(MapTableFormat.SectionSub("Spark_Angle_Adjust1_SubTable", sub))[0]; + + var back = MapTableFormat.ParseSub(section, parentRpm); + Assert.Equal(sub.Data, back.Data); + for (int x = 0; x < SubTable.Cols; x++) + { + Assert.Equal(parentRpm[x * 4], back.RpmAxis[x * 2]); + Assert.Equal(parentRpm[x * 4 + 3], back.RpmAxis[x * 2 + 1]); + } + } + + [Fact] + public void OneD_round_trips_24_byte_wire() + { + var t = new OneDimTable + { + MaxRaw = 200, MinRaw = 0, RawSignedFlag = 0, ConvSignedFlag = 1, + RawMultiplier = 2, ConvMultiplier = 3, RawRounding = 0, ConvOffset = -5, + }; + for (int i = 0; i < OneDimTable.PointCount; i++) { t.RawAxis[i] = i * 8; t.ConvValues[i] = 40 - i; } + + var section = MapTableFormat.SplitSections(MapTableFormat.Section1D("O2_Conversion_Table", t))[0]; + var back = MapTableFormat.Parse1D(section); + Assert.Equal(t.ToWirePayload(), back.ToWirePayload()); // metadata + axes + values round-trip verbatim + } + + [Fact] + public void ParseBytes_handles_trailing_space() + => Assert.Equal(new byte[] { 10, 20, 255 }, MapTableFormat.ParseBytes("10 20 255 ")); + + [Fact] + public void Two_sections_split_positionally() + { + var t = new TuningTable(); + var doc = MapTableFormat.Section2D("A", t) + MapTableFormat.Section2D("B", t); + var parts = MapTableFormat.SplitSections(doc); + Assert.Equal("A", MapTableFormat.LabelOf(parts[0])); + Assert.Equal("B", MapTableFormat.LabelOf(parts[1])); + } +} diff --git a/TuneBoss.Core.Tests/MemoryLayoutTests.cs b/TuneBoss.Core.Tests/MemoryLayoutTests.cs new file mode 100644 index 0000000..542c15a --- /dev/null +++ b/TuneBoss.Core.Tests/MemoryLayoutTests.cs @@ -0,0 +1,71 @@ +using TuneBoss.Core.Models; +using Xunit; + +namespace TuneBoss.Core.Tests; + +public class MemoryLayoutTests +{ + [Theory] + [InlineData(70)] + [InlineData(80)] + [InlineData(83)] + [InlineData(90)] + [InlineData(130)] + [InlineData(193)] + public void Gen3_1D_availability_matches_registry_firmware_gating(byte fw) + { + var layout = MemoryLayout.For(TestData.Ecu(TestData.Gen3, fw), EcuVariant.TwoCylinderR15); + + Assert.Equal(37, layout.OneDimTables.Length); + + foreach (var def in OneDimTableRegistry.All) + { + var region = layout.OneDimTables[def.Slot - 1]; + Assert.Equal(fw >= def.MinFirmware, region.IsAvailable); + } + } + + [Theory] + [InlineData(149, false)] + [InlineData(150, true)] + [InlineData(193, true)] + public void Gen3_misc_padding_is_gated_at_fw150(byte fw, bool available) + { + var l = MemoryLayout.For(TestData.Ecu(TestData.Gen3, fw), EcuVariant.TwoCylinder); + + Assert.Equal(available, l.MiscLaunchFuel.IsAvailable); + Assert.Equal(available, l.MiscLaunchFuel2.IsAvailable); + Assert.Equal(available, l.MiscAuxOut.IsAvailable); + Assert.Equal(available, l.MiscExtended.IsAvailable); + } + + [Theory] + [InlineData(70)] + [InlineData(150)] + [InlineData(193)] + public void MiscCore_is_always_present_and_136_bytes(byte fw) + { + var l = MemoryLayout.For(TestData.Ecu(TestData.Gen3, fw), EcuVariant.TwoCylinder); + Assert.True(l.MiscCore.IsAvailable); + Assert.Equal(0x88, l.MiscCore.Length); + } + + [Theory] + [InlineData(EcuVariant.SingleCylinder)] + [InlineData(EcuVariant.TwoCylinder)] + [InlineData(EcuVariant.TwoCylinderR15)] + public void MiscExtended_length_follows_variant_when_available(EcuVariant variant) + { + var l = MemoryLayout.For(TestData.Ecu(TestData.Gen3, 193), variant); + Assert.True(l.MiscExtended.IsAvailable); + Assert.Equal((byte)MiscValues.ExtendedLengthFor(variant), l.MiscExtended.Length); + } + + [Fact] + public void Gen1_exposes_only_the_base_18_oneDim_tables() + { + var l = MemoryLayout.For(TestData.Ecu(TestData.Gen1, 193), EcuVariant.SingleCylinder); + for (int i = 0; i < 37; i++) + Assert.Equal(i < 18, l.OneDimTables[i].IsAvailable); + } +} diff --git a/TuneBoss.Core.Tests/MiscBitSpecTests.cs b/TuneBoss.Core.Tests/MiscBitSpecTests.cs new file mode 100644 index 0000000..692580f --- /dev/null +++ b/TuneBoss.Core.Tests/MiscBitSpecTests.cs @@ -0,0 +1,104 @@ +using System.Numerics; +using TuneBoss.Core.Models; +using Xunit; + +namespace TuneBoss.Core.Tests; + +/// +/// These are the high-value regression tests: they tie the bit-editor specs to the +/// field registry and validate every mask. The "spec key exists" test is exactly what +/// would have caught the ShiftBoss byte-84 mislabel and the Core_25/31/33/120 key drift. +/// +public class MiscBitSpecTests +{ + [Fact] + public void Every_spec_key_resolves_to_a_field() + { + foreach (var spec in MiscBitSpecRegistry.All) + { + bool found = MiscFieldRegistry.All.Any( + f => f.Block == spec.Block && f.Label == spec.FieldLabel); + + Assert.True(found, + $"Spec '{spec.FieldLabel}' ({spec.Block}) has no matching MiscField — " + + "the bit editor will silently fail to attach."); + } + } + + [Fact] + public void Find_returns_spec_by_key() + { + var s = MiscBitSpecRegistry.Find(MiscBlock.Core, "ShiftBoss_Enable"); + Assert.NotNull(s); + Assert.Equal("ShiftBoss_Enable", s!.FieldLabel); + + Assert.Null(MiscBitSpecRegistry.Find(MiscBlock.Core, "does_not_exist")); + } + + [Fact] + public void All_masks_are_within_a_byte_and_nonzero() + { + foreach (var spec in MiscBitSpecRegistry.All) + foreach (var f in spec.Fields) + Assert.InRange(f.Mask, 1, 255); + } + + [Fact] + public void Flag_fields_are_a_single_bit() + { + foreach (var spec in MiscBitSpecRegistry.All) + foreach (var f in spec.Fields) + if (f.Kind == MiscEditorKind.Flag) + Assert.Equal(1, BitOperations.PopCount((uint)f.Mask)); + } + + [Fact] + public void Enum_options_fit_the_mask_range() + { + foreach (var spec in MiscBitSpecRegistry.All) + foreach (var f in spec.Fields) + { + if (f.Kind != MiscEditorKind.Enum) continue; + Assert.NotNull(f.Options); + int shift = BitOperations.TrailingZeroCount((uint)f.Mask); + int maxVal = f.Mask >> shift; // e.g. 0x06 -> 3 + Assert.True(f.Options!.Length >= 2, + $"{spec.FieldLabel}/{f.Label}: enum needs >= 2 options"); + Assert.True(f.Options.Length <= maxVal + 1, + $"{spec.FieldLabel}/{f.Label}: {f.Options.Length} options exceed mask range {maxVal + 1}"); + } + } + + [Fact] + public void Fields_within_a_spec_do_not_overlap_bits() + { + foreach (var spec in MiscBitSpecRegistry.All) + { + int used = 0; + foreach (var f in spec.Fields) + { + Assert.True((used & f.Mask) == 0, + $"{spec.FieldLabel}: field '{f.Label}' mask 0x{f.Mask:X2} overlaps another field"); + used |= f.Mask; + } + } + } + + [Fact] + public void Constraint_indices_are_valid_bit_positions() + { + foreach (var spec in MiscBitSpecRegistry.All) + { + foreach (var (a, b) in spec.MutualExclusive ?? Enumerable.Empty<(int, int)>()) + { + Assert.InRange(a, 0, 7); + Assert.InRange(b, 0, 7); + } + foreach (var (a, b) in spec.Linked ?? Enumerable.Empty<(int, int)>()) + { + Assert.InRange(a, 0, 7); + Assert.InRange(b, 0, 7); + } + } + } +} diff --git a/TuneBoss.Core.Tests/MiscFieldRegistryTests.cs b/TuneBoss.Core.Tests/MiscFieldRegistryTests.cs new file mode 100644 index 0000000..d7d3c10 --- /dev/null +++ b/TuneBoss.Core.Tests/MiscFieldRegistryTests.cs @@ -0,0 +1,43 @@ +using TuneBoss.Core.Models; +using Xunit; + +namespace TuneBoss.Core.Tests; + +public class MiscFieldRegistryTests +{ + private static int BlockSize(MiscBlock b) => b switch + { + MiscBlock.Core => 136, + MiscBlock.LaunchFuel => 12, + MiscBlock.LaunchFuel2 => 12, + MiscBlock.AuxOut => 12, + MiscBlock.Extended => 152, + _ => 0, + }; + + [Fact] + public void All_field_indices_are_within_their_block() + { + foreach (var f in MiscFieldRegistry.All) + Assert.InRange(f.Index, 0, BlockSize(f.Block) - 1); + } + + [Fact] + public void No_two_fields_share_a_block_and_index() + { + var dupes = MiscFieldRegistry.All + .GroupBy(f => (f.Block, f.Index)) + .Where(g => g.Count() > 1) + .Select(g => $"{g.Key.Block}[{g.Key.Index}]: {string.Join(", ", g.Select(x => x.Label))}") + .ToList(); + + Assert.True(dupes.Count == 0, "Duplicate (block,index) mappings:\n" + string.Join("\n", dupes)); + } + + [Fact] + public void All_labels_are_nonblank() + { + foreach (var f in MiscFieldRegistry.All) + Assert.False(string.IsNullOrWhiteSpace(f.Label)); + } +} diff --git a/TuneBoss.Core.Tests/MiscValuesTests.cs b/TuneBoss.Core.Tests/MiscValuesTests.cs new file mode 100644 index 0000000..a962938 --- /dev/null +++ b/TuneBoss.Core.Tests/MiscValuesTests.cs @@ -0,0 +1,58 @@ +using TuneBoss.Core.Models; +using Xunit; + +namespace TuneBoss.Core.Tests; + +public class MiscValuesTests +{ + [Fact] + public void Core_is_sliced_from_offset_4() + { + var data = new byte[136]; + for (int i = 0; i < data.Length; i++) data[i] = (byte)i; + + var mv = MiscValues.FromPayloads(TestData.WithHeader(data, 0x46)); + + Assert.Equal(136, mv.Core.Length); + Assert.Equal(0, mv.Core[0]); // header skipped + Assert.Equal(135, mv.Core[135]); + } + + [Fact] + public void Short_core_payload_yields_empty() + { + // 4 header + 100 data = 104 < 4 + 136, so Slice returns empty. + var mv = MiscValues.FromPayloads(TestData.WithHeader(new byte[100])); + Assert.Empty(mv.Core); + } + + [Fact] + public void Optional_blocks_default_to_empty() + { + var mv = MiscValues.FromPayloads(TestData.WithHeader(new byte[136])); + Assert.Empty(mv.LaunchFuel); + Assert.Empty(mv.LaunchFuel2); + Assert.Empty(mv.AuxOut); + Assert.Empty(mv.Extended); + } + + [Theory] + [InlineData(EcuVariant.SingleCylinder, 0x29)] + [InlineData(EcuVariant.TwoCylinder, 0x73)] + [InlineData(EcuVariant.TwoCylinderR15, 0x97)] + public void ExtendedLengthFor_matches_variant(EcuVariant v, int expected) + { + Assert.Equal(expected, MiscValues.ExtendedLengthFor(v)); + } + + [Fact] + public void Extended_slice_size_follows_payload_length() + { + int n = MiscValues.ExtendedLengthFor(EcuVariant.TwoCylinderR15); // 0x97 + var mv = MiscValues.FromPayloads( + corePayload: new byte[140], // 4 + 136 + extendedPayload: TestData.WithHeader(new byte[n])); + + Assert.Equal(n, mv.Extended.Length); + } +} diff --git a/TuneBoss.Core.Tests/OneDimDisplayTests.cs b/TuneBoss.Core.Tests/OneDimDisplayTests.cs new file mode 100644 index 0000000..965d43c --- /dev/null +++ b/TuneBoss.Core.Tests/OneDimDisplayTests.cs @@ -0,0 +1,54 @@ +using TuneBoss.Core.Models; +using Xunit; + +namespace TuneBoss.Core.Tests; + +public class OneDimDisplayTests +{ + [Theory] + [InlineData(0, 1)] + [InlineData(1, 1)] + [InlineData(100, 100)] + [InlineData(50, 50)] + public void Multiplier_0_or_1_is_unscaled(int mult, int expected) + => Assert.Equal(expected, OneDimDisplay.EffectiveMultiplier(mult)); + + [Theory] + [InlineData(130, 100, 13000)] // RPM + [InlineData(45, 1, 45)] // unscaled + [InlineData(7, 0, 7)] // mult 0 -> ×1 + [InlineData(-5, 2, -10)] // signed + public void ToDisplay_scales(int raw, int mult, long expected) + => Assert.Equal(expected, OneDimDisplay.ToDisplay(raw, mult)); + + [Theory] + [InlineData(13000, 100, 130)] + [InlineData(13100, 100, 131)] + [InlineData(42, 1, 42)] + [InlineData(-10, 2, -5)] + public void TryFromDisplay_accepts_multiples(double display, int mult, int expectedRaw) + { + Assert.True(OneDimDisplay.TryFromDisplay(display, mult, out int raw)); + Assert.Equal(expectedRaw, raw); + } + + [Theory] + [InlineData(13050, 100)] // not a multiple of 100 + [InlineData(42.5, 1)] // not a whole number + [InlineData(13, 5)] // not a multiple of 5 + public void TryFromDisplay_rejects_non_multiples(double display, int mult) + { + Assert.False(OneDimDisplay.TryFromDisplay(display, mult, out _)); + } + + [Fact] + public void Round_trips_display_then_raw() + { + for (int raw = -120; raw <= 120; raw += 7) + { + long disp = OneDimDisplay.ToDisplay(raw, 100); + Assert.True(OneDimDisplay.TryFromDisplay(disp, 100, out int back)); + Assert.Equal(raw, back); + } + } +} diff --git a/TuneBoss.Core.Tests/OneDimRegistryTests.cs b/TuneBoss.Core.Tests/OneDimRegistryTests.cs new file mode 100644 index 0000000..07e76d4 --- /dev/null +++ b/TuneBoss.Core.Tests/OneDimRegistryTests.cs @@ -0,0 +1,42 @@ +using TuneBoss.Core.Models; +using Xunit; + +namespace TuneBoss.Core.Tests; + +public class OneDimRegistryTests +{ + [Fact] + public void Has_37_tables() + { + Assert.Equal(37, OneDimTableRegistry.All.Count); + } + + [Fact] + public void Slots_are_unique_and_contiguous_1_to_37() + { + var slots = OneDimTableRegistry.All.Select(d => d.Slot).OrderBy(s => s).ToList(); + Assert.Equal(Enumerable.Range(1, 37), slots); + } + + [Fact] + public void Min_firmware_values_are_known_tiers() + { + var allowed = new[] { 0, 80, 83, 90, 130 }; + foreach (var d in OneDimTableRegistry.All) + Assert.Contains(d.MinFirmware, allowed); + } + + [Fact] + public void Every_group_used_appears_in_group_order() + { + foreach (var d in OneDimTableRegistry.All) + Assert.Contains(d.Group, OneDimTableRegistry.GroupOrder); + } + + [Fact] + public void Labels_are_nonblank() + { + foreach (var d in OneDimTableRegistry.All) + Assert.False(string.IsNullOrWhiteSpace(d.Label)); + } +} diff --git a/TuneBoss.Core.Tests/OneDimTableTests.cs b/TuneBoss.Core.Tests/OneDimTableTests.cs new file mode 100644 index 0000000..48b1c22 --- /dev/null +++ b/TuneBoss.Core.Tests/OneDimTableTests.cs @@ -0,0 +1,99 @@ +using TuneBoss.Core.Models; +using Xunit; + +namespace TuneBoss.Core.Tests; + +public class OneDimTableTests +{ + [Fact] + public void FromWire_then_ToWire_is_byte_identical_unsigned() + { + var wire = TestData.OneDimWire( + axis: new byte[] { 0, 10, 20, 40, 80, 120, 200, 255 }, + conv: new byte[] { 5, 6, 7, 8, 9, 10, 11, 12 }, + rawMult: 100, convMult: 1, maxRaw: 255, minRaw: 0, convOffset: -3); + + var t = OneDimTable.FromWire(wire); + var rt = t.ToWirePayload(); + + Assert.Equal(wire, rt); // full verbatim round-trip + } + + [Fact] + public void Metadata_bytes_round_trip_verbatim() + { + var wire = TestData.OneDimWire( + axis: new byte[8], conv: new byte[8], + rawSigned: 1, convSigned: 1, rawMult: 100, convMult: 50, + maxRaw: 200, minRaw: 10, rawRound: 7, convOffset: -12); + + var t = OneDimTable.FromWire(wire); + + Assert.Equal(1, t.RawSignedFlag); + Assert.Equal(1, t.ConvSignedFlag); + Assert.Equal(100, t.RawMultiplier); + Assert.Equal(50, t.ConvMultiplier); + Assert.Equal(7, t.RawRounding); + Assert.Equal(-12, t.ConvOffset); + Assert.Equal(wire, t.ToWirePayload()); + } + + [Fact] + public void Signed_axis_and_values_decode_negative() + { + var wire = TestData.OneDimWire( + axis: new byte[] { 0xFF, 0xFE, 0, 1, 2, 3, 4, 5 }, // -1, -2, 0, 1... + conv: new byte[] { 0x80, 0xFF, 0, 1, 2, 3, 4, 5 }, // -128, -1, 0... + rawSigned: 1, convSigned: 1); + + var t = OneDimTable.FromWire(wire); + + Assert.Equal(-1, t.RawAxis[0]); + Assert.Equal(-2, t.RawAxis[1]); + Assert.Equal(-128, t.ConvValues[0]); + Assert.Equal(-1, t.ConvValues[1]); + Assert.Equal(wire, t.ToWirePayload()); // signed values re-encode exactly + } + + [Fact] + public void Unsigned_high_byte_stays_positive() + { + var wire = TestData.OneDimWire( + axis: new byte[] { 200, 255, 0, 0, 0, 0, 0, 0 }, + conv: new byte[] { 255, 200, 0, 0, 0, 0, 0, 0 }, + rawSigned: 0, convSigned: 0); + + var t = OneDimTable.FromWire(wire); + + Assert.Equal(200, t.RawAxis[0]); + Assert.Equal(255, t.RawAxis[1]); + Assert.Equal(255, t.ConvValues[0]); + } + + [Fact] + public void FromWire_honours_offset() + { + var inner = TestData.OneDimWire(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, new byte[8]); + var framed = TestData.WithHeader(inner); // 4-byte header + 24-byte block + + var t = OneDimTable.FromWire(framed, 4); + + Assert.Equal(1, t.RawAxis[0]); + Assert.Equal(8, t.RawAxis[7]); + } + + [Fact] + public void FromWire_short_payload_throws() + { + Assert.Throws(() => OneDimTable.FromWire(new byte[10])); + } + + [Fact] + public void Clone_is_independent() + { + var t = OneDimTable.FromWire(TestData.OneDimWire(new byte[8], new byte[8])); + var c = t.Clone(); + c.ConvValues[0] = 99; + Assert.NotEqual(99, t.ConvValues[0]); + } +} diff --git a/TuneBoss.Core.Tests/TestData.cs b/TuneBoss.Core.Tests/TestData.cs new file mode 100644 index 0000000..f939920 --- /dev/null +++ b/TuneBoss.Core.Tests/TestData.cs @@ -0,0 +1,46 @@ +using TuneBoss.Core.Models; + +namespace TuneBoss.Core.Tests; + +/// Shared builders for synthetic device data. +internal static class TestData +{ + public const byte Gen1 = 245, Gen2 = 1, Gen3 = 2; + + public static EcuInfo Ecu(byte appInfoVersion, byte fw, byte rpmMax = 130) => new() + { + Username = "SIM-RIDER", + UniqueId = "AABBCCDD-EEFF0011-22334455", + AppInfoVersion = appInfoVersion, + FwVersion = fw, + HwVersion = 10, + UpgradeRpmMax = rpmMax, + BikeManufacturer = 1, + }; + + /// Wraps a data block in the 4-byte response header the parsers skip (51 xx xx 00). + public static byte[] WithHeader(byte[] data, byte cmd = 0x43) + { + var p = new byte[4 + data.Length]; + p[0] = 0x51; p[1] = cmd; p[2] = (byte)data.Length; p[3] = 0x00; + Buffer.BlockCopy(data, 0, p, 4, data.Length); + return p; + } + + /// A valid 24-byte 1D block with chosen sign flags / multipliers. + public static byte[] OneDimWire( + byte[] axis, byte[] conv, + byte rawSigned = 0, byte convSigned = 0, + byte rawMult = 1, byte convMult = 1, + byte maxRaw = 255, byte minRaw = 0, byte rawRound = 0, sbyte convOffset = 0) + { + var d = new byte[OneDimTable.WireLength]; + Array.Copy(axis, 0, d, 0, 8); + Array.Copy(conv, 0, d, 8, 8); + d[16] = maxRaw; d[17] = minRaw; + d[18] = rawSigned; d[19] = convSigned; + d[20] = rawMult; d[21] = convMult; + d[22] = rawRound; d[23] = unchecked((byte)convOffset); + return d; + } +} diff --git a/TuneBoss.Core.Tests/TpsCalibrationTests.cs b/TuneBoss.Core.Tests/TpsCalibrationTests.cs new file mode 100644 index 0000000..f0b3252 --- /dev/null +++ b/TuneBoss.Core.Tests/TpsCalibrationTests.cs @@ -0,0 +1,82 @@ +using TuneBoss.Core.Models; +using TuneBoss.Core.Protocol; +using Xunit; + +namespace TuneBoss.Core.Tests; + +public class TpsCalibrationTests +{ + // ── Write payload ─────────────────────────────────────────────────────────── + [Fact] + public void CalWritePayload_matches_legacy_ramp() + { + var p = TpsCalibration.BuildCalWritePayload(10, 180); + Assert.Equal(new byte[] { 10, 180, 182, 184, 186, 188, 190, 192 }, p); + } + + [Fact] + public void CalWritePayload_wraps_high_max_into_byte() + { + // max+12 above 255 wraps (unchecked byte), matching the legacy (byte) cast. + var p = TpsCalibration.BuildCalWritePayload(8, 250); + Assert.Equal(8, p[0]); + Assert.Equal(250, p[1]); + Assert.Equal((byte)(250 + 12), p[7]); // 262 & 0xFF = 6 + } + + // ── Validation ────────────────────────────────────────────────────────────── + [Fact] + public void Validate_in_range_is_ok() + => Assert.Equal(TpsCalibration.Validation.Ok, + TpsCalibration.Validate(minRaw: 10, maxRaw: 188, absMin: 5, absMax: 195)); + + [Fact] + public void Validate_min_below_floor() + => Assert.Equal(TpsCalibration.Validation.MinBelowFloor, + TpsCalibration.Validate(minRaw: 3, maxRaw: 188, absMin: 5, absMax: 195)); + + [Fact] + public void Validate_max_above_ceiling() + => Assert.Equal(TpsCalibration.Validation.MaxAboveCeiling, + TpsCalibration.Validate(minRaw: 10, maxRaw: 200, absMin: 5, absMax: 195)); + + [Fact] + public void Validate_extreme_crossed_values() + => Assert.Equal(TpsCalibration.Validation.Extreme, + TpsCalibration.Validate(minRaw: 196, maxRaw: 196, absMin: 5, absMax: 195)); + + // ── Address resolution ────────────────────────────────────────────────────── + [Fact] + public void Gen3_uses_small_address_layout() + { + var a = TpsCalibration.For(GenerationType.Gen3, fwVersion: 193); + Assert.Equal(0x0078, a.CalWrite); + Assert.Equal(0x0088, a.AbsBounds); + Assert.Equal(0x0094, a.AdvSettings); + Assert.True(a.AdvSupported); // 193 >= 152 + } + + [Fact] + public void Gen3_below_152_has_no_advanced_settings() + => Assert.False(TpsCalibration.For(GenerationType.Gen3, 150).AdvSupported); + + [Fact] + public void Gen2_shares_gen3_addresses() + { + var g2 = TpsCalibration.For(GenerationType.Gen2, 100); + var g3 = TpsCalibration.For(GenerationType.Gen3, 100); + Assert.Equal(g3.CalWrite, g2.CalWrite); + Assert.Equal(g3.AbsBounds, g2.AbsBounds); + } + + [Fact] + public void Gen1_uses_legacy_high_addresses() + { + var a = TpsCalibration.For(GenerationType.Gen1, 70); + Assert.Equal(0x06FC, a.CalWrite); + Assert.False(a.AdvSupported); + } + + [Fact] + public void CalDoneFlag_is_one() => Assert.Equal(1, TpsCalibration.CalDoneFlag); +} diff --git a/TuneBoss.Core.Tests/TuneBoss.Core.Tests.csproj b/TuneBoss.Core.Tests/TuneBoss.Core.Tests.csproj new file mode 100644 index 0000000..9aea594 --- /dev/null +++ b/TuneBoss.Core.Tests/TuneBoss.Core.Tests.csproj @@ -0,0 +1,26 @@ + + + + net9.0 + enable + enable + false + true + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + + diff --git a/TuneBoss.Core/BLE/BleManager.cs b/TuneBoss.Core/BLE/BleManager.cs new file mode 100644 index 0000000..8931ed9 --- /dev/null +++ b/TuneBoss.Core/BLE/BleManager.cs @@ -0,0 +1,668 @@ +using System.Collections.Concurrent; +using System.Reactive.Linq; +using System.Reactive.Subjects; +using Windows.Devices.Bluetooth; +using Windows.Devices.Bluetooth.Advertisement; +using Windows.Devices.Bluetooth.GenericAttributeProfile; +using Windows.Storage.Streams; +using TuneBoss.Core.Models; +using TuneBoss.Core.Protocol; +using System.Runtime.InteropServices.WindowsRuntime; + +namespace TuneBoss.Core.BLE; + +/// +/// Windows WinRT BLE implementation of IBleService. +/// Uses Nordic UART Service (NUS) over a single bidirectional characteristic. +/// +public sealed class BleManager : IBleService +{ + // ── NUS UUIDs ──────────────────────────────────────────────────────────── + private static readonly Guid NusServiceUuid = new("0000f0f0-0000-1000-8000-00805f9b34fb"); + private static readonly Guid NusCharUuid = new("0000f0f1-0000-1000-8000-00805f9b34fb"); + + // ── Config ─────────────────────────────────────────────────────────────── + private const int CommandTimeoutMs = 3000; // 3s default timeout + private const int SilenceWindowMs = 300; // diag silence detection window + private const int MaxSilenceWaitMs = 5000; // max wait for diagnostics drain + private const int KeepaliveIdleMs = 15000; // send keepalive after 15s idle + + // ── GATT resources ─────────────────────────────────────────────────────── + private BluetoothLEDevice? _device; + private GattDeviceService? _nusService; + private GattCharacteristic? _nusChar; + + // ── State ──────────────────────────────────────────────────────────────── + private BleConnectionState _connectionState = BleConnectionState.Disconnected; + private GenerationConfig? _genConfig; + private byte _seqNum = 1; + + // ── Rx processing ──────────────────────────────────────────────────────── + private readonly ConcurrentQueue _bleQueue = new(); + private readonly SemaphoreSlim _bleSignal = new(0); + private CancellationTokenSource? _loopCts; + + // ── Packet parser state ────────────────────────────────────────────────── + private readonly PacketParser _parser; + + // ── Response rendezvous ────────────────────────────────────────────────── + // The BLE receive loop sets this when a non-streaming packet arrives. + private readonly SemaphoreSlim _responseReady = new(0); + private volatile byte[]? _responsePayload; + private readonly object _responseLock = new(); + + // ── Diagnostics ────────────────────────────────────────────────────────── + private readonly Subject _diagSubject = new(); + private volatile bool _diagnosticsRunning; + private long _lastDiagTickUtc; + + // ── Observables ────────────────────────────────────────────────────────── + private readonly BehaviorSubject _connSubject = + new(BleConnectionState.Disconnected); + + private readonly Subject _scanSubject = new(); + private BluetoothLEAdvertisementWatcher? _watcher; + + // ── Keepalive ──────────────────────────────────────────────────────────── + private long _lastCommandTickUtc; + + // ──────────────────────────────────────────────────────────────────────── + // Constructor + // ──────────────────────────────────────────────────────────────────────── + public BleManager() + { + _parser = new PacketParser(OnFullPacketReceived); + } + + // ── IBleService: State ─────────────────────────────────────────────────── + public BleConnectionState ConnectionState => _connectionState; + public bool IsConnected => _connectionState == BleConnectionState.Connected; + public IObservable ConnectionStateChanged => _connSubject.AsObservable(); + public IObservable DiagnosticsFrames => _diagSubject.AsObservable(); + public bool DiagnosticsRunning => _diagnosticsRunning; + + // ──────────────────────────────────────────────────────────────────────── + // SCANNING + // ──────────────────────────────────────────────────────────────────────── + public IObservable StartScan() + { + var seen = new Dictionary(); + + _watcher = new BluetoothLEAdvertisementWatcher + { + ScanningMode = BluetoothLEScanningMode.Active + }; + _watcher.SignalStrengthFilter.InRangeThresholdInDBm = -127; + _watcher.SignalStrengthFilter.OutOfRangeThresholdInDBm = -127; + _watcher.SignalStrengthFilter.OutOfRangeTimeout = null; + + _watcher.Received += (_, args) => + { + ulong addr = args.BluetoothAddress; + string name = args.Advertisement.LocalName?.Trim() ?? string.Empty; + bool hasName = !string.IsNullOrWhiteSpace(name); + + lock (seen) + { + if (!seen.ContainsKey(addr)) + { + seen[addr] = hasName ? name : $"Unknown [{new BleDeviceInfo(addr, "", 0).MacAddress}]"; + _scanSubject.OnNext(new BleDeviceInfo(addr, seen[addr], args.RawSignalStrengthInDBm)); + } + else if (hasName && seen[addr].StartsWith("Unknown")) + { + seen[addr] = name; + _scanSubject.OnNext(new BleDeviceInfo(addr, name, args.RawSignalStrengthInDBm)); + } + } + }; + + _watcher.Start(); + return _scanSubject.AsObservable(); + } + + public void StopScan() + { + _watcher?.Stop(); + _watcher = null; + } + + // ──────────────────────────────────────────────────────────────────────── + // CONNECTION + // ──────────────────────────────────────────────────────────────────────── + public async Task ConnectAsync(BleDeviceInfo device, CancellationToken ct = default) + { + SetState(BleConnectionState.Connecting); + + try + { + // Step 1: Resolve device + _device = await BluetoothLEDevice.FromBluetoothAddressAsync(device.Address); + if (_device == null) return Fail("Could not resolve device from address."); + + _device.ConnectionStatusChanged += OnDeviceConnectionStatusChanged; + + // Step 2: Open GATT channel with retry + if (!await OpenGattChannelAsync(ct)) return Fail("Could not open GATT channel."); + + // Step 3: Stabilize + await Task.Delay(1500, ct); + + // Step 4: Get NUS service + _nusService = await GetServiceAsync(NusServiceUuid, ct); + if (_nusService == null) return Fail("NUS service not found."); + + // Step 5: Get characteristic + _nusChar = await GetCharacteristicAsync(_nusService, NusCharUuid, ct); + if (_nusChar == null) return Fail("NUS characteristic not found."); + + // Step 6: Enable notifications + _nusChar.ValueChanged += OnCharValueChanged; + await _nusChar.WriteClientCharacteristicConfigurationDescriptorAsync( + GattClientCharacteristicConfigurationDescriptorValue.Notify); + + // Step 7: Start BLE processing loop + StartProcessingLoop(); + + SetState(BleConnectionState.Connected); + return true; + } + catch (OperationCanceledException) { return Fail("Connection cancelled."); } + catch (Exception ex) { return Fail($"Connection error: {ex.Message}"); } + } + + public async Task DisconnectAsync() + { + SetState(BleConnectionState.Disconnecting); + + if (_diagnosticsRunning) + await StopDiagnosticsAsync(); + + StopProcessingLoop(); + + if (_nusChar != null) + { + _nusChar.ValueChanged -= OnCharValueChanged; + try { await _nusChar.WriteClientCharacteristicConfigurationDescriptorAsync( + GattClientCharacteristicConfigurationDescriptorValue.None); } catch { } + } + + _nusChar = null; + _nusService?.Dispose(); + _nusService = null; + + if (_device != null) + { + _device.ConnectionStatusChanged -= OnDeviceConnectionStatusChanged; + _device.Dispose(); + _device = null; + } + + SetState(BleConnectionState.Disconnected); + } + + // ──────────────────────────────────────────────────────────────────────── + // DEVICE INFO + // ──────────────────────────────────────────────────────────────────────── + public async Task ReadEcuInfoAsync(CancellationToken ct = default) + { + var frame = PacketBuilder.BuildReadInfo(NextSeq()); + var result = await SendAndWaitAsync(frame, ct); + if (!result.Success) return null; + + var info = EcuInfo.Parse(result.Payload); + + // Store generation config for subsequent table operations + var gen = GenerationConfig.ResolveGeneration(info.AppInfoVersion); + _genConfig = GenerationConfig.For(gen); + + return info; + } + + // ──────────────────────────────────────────────────────────────────────── + // AUTH + // ──────────────────────────────────────────────────────────────────────── + public async Task UnlockAsync(string password, CancellationToken ct = default) + { + var payload = BuildUnlockPayload(_genConfig?.UnlockCmd ?? Commands.APP_UNLOCK, password, isReset: false); + var frame = PacketBuilder.Build(Commands.TL_NONPOSTED, NextSeq(), payload); + return await SendAndWaitAsync(frame, ct); + } + + public async Task UnlockTunerAsync(string password, CancellationToken ct = default) + { + var payload = BuildUnlockPayload(Commands.APP_UNLOCK_TUNER, password, isReset: false); + var frame = PacketBuilder.Build(Commands.TL_NONPOSTED, NextSeq(), payload); + return await SendAndWaitAsync(frame, ct); + } + + // ──────────────────────────────────────────────────────────────────────── + // TABLE OPERATIONS + // ──────────────────────────────────────────────────────────────────────── + public Task ReadTable2DAsync(ushort address, byte lengthBytes, bool userTable = false, CancellationToken ct = default) + => ReadTableAsync( + userTable ? (_genConfig?.ReadCmd2DUser ?? Commands.APP_MEMRD_2D_USER) + : (_genConfig?.ReadCmd2D ?? Commands.APP_MEMRD_2D), + address, lengthBytes, ct); + + public Task WriteTable2DAsync(ushort address, byte[] data, bool userTable = false, CancellationToken ct = default) + => WriteTableAsync( + userTable ? (_genConfig?.WriteCmd2DUser ?? Commands.APP_MEMWR_2D_USER) + : (_genConfig?.WriteCmd2D ?? Commands.APP_MEMWR_2D), + address, data, ct); + + public Task ReadTable1DAsync(ushort address, byte lengthBytes, CancellationToken ct = default) + => ReadTableAsync(_genConfig?.ReadCmd1D ?? Commands.APP_MEMRD_1D, address, lengthBytes, ct); + + public Task WriteTable1DAsync(ushort address, byte[] data, CancellationToken ct = default) + => WriteTableAsync(_genConfig?.WriteCmd1D ?? Commands.APP_MEMWR_1D, address, data, ct); + + public Task ReadSubTableAsync(ushort address, CancellationToken ct = default) + => ReadTableAsync(_genConfig?.ReadCmdSubT ?? Commands.APP_MEMRD_SUBT, address, + (byte)TuneBoss.Core.Models.SubTable.TotalBytes, ct); + + public Task WriteSubTableAsync(ushort address, byte[] data, CancellationToken ct = default) + => WriteTableAsync(_genConfig?.WriteCmdSubT ?? Commands.APP_MEMWR_SUBT, address, data, ct); + + public Task ReadMiscAsync(ushort address, byte lengthBytes, CancellationToken ct = default) + => ReadTableAsync(_genConfig?.ReadCmdMisc ?? Commands.APP_MEMRD_MISC, address, lengthBytes, ct); + + public Task WriteMiscAsync(ushort address, byte[] data, CancellationToken ct = default) + => WriteTableAsync(_genConfig?.WriteCmdMisc ?? Commands.APP_MEMWR_MISC, address, data, ct); + + // ──────────────────────────────────────────────────────────────────────── + // FLASH WRITE + // ──────────────────────────────────────────────────────────────────────── + public async Task FlashWriteAsync(CancellationToken ct = default) + { + await StopDiagnosticsIfRunningAsync(ct); + + var now = DateTime.Now; + var payload = new byte[] + { + Commands.APP_FLASH_WR, + (byte)'F', (byte)'S', (byte)'R', + (byte)now.Day, + (byte)now.Month, + (byte)(now.Year % 100), + 0x00 + }; + var frame = PacketBuilder.Build(Commands.TL_NONPOSTED, NextSeq(), payload); + var result = await SendAndWaitAsync(frame, ct); + + await RestartDiagnosticsIfStoppedAsync(ct); + return result; + } + + // ──────────────────────────────────────────────────────────────────────── + // FIRST-USE SETTINGS (APP_FIRSTUSE) + // ──────────────────────────────────────────────────────────────────────── + public async Task WriteFirstUseAsync(byte[] fourBytes, CancellationToken ct = default) + { + if (fourBytes is null || fourBytes.Length < 4) + return CommandResult.Fail(0x00, "First-use payload must be 4 bytes."); + + // Legacy updateFirstUseSettings layout: [APP_FIRSTUSE, 0x00, 0x00, 0x00, b0, b1, b2, b3] + var payload = new byte[] + { + Commands.APP_FIRSTUSE, 0x00, 0x00, 0x00, + fourBytes[0], fourBytes[1], fourBytes[2], fourBytes[3], + }; + var frame = PacketBuilder.Build(Commands.TL_NONPOSTED, NextSeq(), payload); + return await SendAndWaitAsync(frame, ct); + } + + // ──────────────────────────────────────────────────────────────────────── + // DIAGNOSTICS + // ──────────────────────────────────────────────────────────────────────── + public async Task StartDiagnosticsAsync(CancellationToken ct = default) + { + if (_diagnosticsRunning) return; + _diagnosticsRunning = true; + Interlocked.Exchange(ref _lastDiagTickUtc, DateTime.UtcNow.Ticks); + await SendRawAsync(PacketBuilder.BuildMonStart()); + } + + public async Task StopDiagnosticsAsync(CancellationToken ct = default) + { + if (!_diagnosticsRunning) return; + _diagnosticsRunning = false; + + await SendRawAsync(PacketBuilder.BuildMonStop()); + + // Wait for silence — device keeps sending 0x70s for a while after STOP + Interlocked.Exchange(ref _lastDiagTickUtc, DateTime.UtcNow.Ticks); + int waited = 0; + while (waited < MaxSilenceWaitMs) + { + await Task.Delay(100, ct); + waited += 100; + long elapsed = (DateTime.UtcNow.Ticks - Interlocked.Read(ref _lastDiagTickUtc)) + / TimeSpan.TicksPerMillisecond; + if (elapsed >= SilenceWindowMs) break; + } + + // Flush residual 0x70 packets + _parser.Reset(); + while (_bleQueue.TryDequeue(out byte[]? _)) { } + } + + // ──────────────────────────────────────────────────────────────────────── + // KEEPALIVE + // ──────────────────────────────────────────────────────────────────────── + public void OnKeepaliveTimer() + { + if (!IsConnected) return; + long idleMs = (DateTime.UtcNow.Ticks - Interlocked.Read(ref _lastCommandTickUtc)) + / TimeSpan.TicksPerMillisecond; + if (idleMs >= KeepaliveIdleMs) + _ = SendRawAsync(PacketBuilder.BuildReadInfo(NextSeq())); + } + + // ──────────────────────────────────────────────────────────────────────── + // PRIVATE: Table helpers + // ──────────────────────────────────────────────────────────────────────── + private async Task ReadTableAsync( + byte cmd, ushort address, byte lengthBytes, CancellationToken ct) + { + await StopDiagnosticsIfRunningAsync(ct); + + var addrBytes = BitConverter.GetBytes(address); // little-endian + var payload = new byte[] { cmd, lengthBytes, addrBytes[0], addrBytes[1] }; + var frame = PacketBuilder.Build(Commands.TL_NONPOSTED, NextSeq(), payload); + + // Flush residual diagnostic packets before sending + _parser.Reset(); + while (_bleQueue.TryDequeue(out byte[]? _)) { } + + var result = await SendAndWaitAsync(frame, ct); + + await RestartDiagnosticsIfStoppedAsync(ct); + return result; + } + + private async Task WriteTableAsync( + byte cmd, ushort address, byte[] data, CancellationToken ct) + { + await StopDiagnosticsIfRunningAsync(ct); + + var addrBytes = BitConverter.GetBytes(address); + var payload = new byte[4 + data.Length]; + payload[0] = cmd; + // The length byte is the LAST inclusive offset the device writes (offset 0..N), + // exactly like the read commands — so N = data.Length - 1. Sending the raw count + // wrote one byte past the region and returned 0x54 (APP_MEMADDR_INV) — seen on the + // tightly-packed 1D tables and on 2D part-2 writes (100-byte tail region). + payload[1] = (byte)(data.Length - 1); + payload[2] = addrBytes[0]; + payload[3] = addrBytes[1]; + data.CopyTo(payload, 4); + + var frame = PacketBuilder.Build(Commands.TL_NONPOSTED, NextSeq(), payload); + var result = await SendAndWaitAsync(frame, ct); + + await RestartDiagnosticsIfStoppedAsync(ct); + return result; + } + + private async Task StopDiagnosticsIfRunningAsync(CancellationToken ct) + { + if (_diagnosticsRunning) + await StopDiagnosticsAsync(ct); + } + + private async Task RestartDiagnosticsIfStoppedAsync(CancellationToken ct) + { + // Intentionally does NOT auto-restart here. Resume is driven by the ViewModel + // layer (ResumeDiagnosticsIfLiveAsync) which knows whether the strip should be + // live. Restarting here as well caused a double MON_START and a frame storm that + // disrupted the next command's response matching (froze edits / writes). + } + + // ──────────────────────────────────────────────────────────────────────── + // PRIVATE: Send and wait for response + // ──────────────────────────────────────────────────────────────────────── + private async Task SendAndWaitAsync(byte[] frame, CancellationToken ct) + { + lock (_responseLock) + { + _responsePayload = null; + // drain any stale ready signal + while (_responseReady.CurrentCount > 0) + _responseReady.Wait(0); + } + + await SendRawAsync(frame); + Interlocked.Exchange(ref _lastCommandTickUtc, DateTime.UtcNow.Ticks); + + using var timeout = new CancellationTokenSource(CommandTimeoutMs); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeout.Token); + + try + { + await _responseReady.WaitAsync(linked.Token); + } + catch (OperationCanceledException) + { + return timeout.IsCancellationRequested + ? CommandResult.Timeout() + : CommandResult.Fail(0x00, "Cancelled"); + } + + var payload = _responsePayload; + if (payload == null || payload.Length == 0) + return CommandResult.Fail(0x00, "Empty response"); + + return payload[0] == 0x51 + ? CommandResult.Ok(payload) + : CommandResult.Fail(payload[0], $"Device returned 0x{payload[0]:X2}"); + } + + private async Task SendRawAsync(byte[] frame) + { + if (_nusChar == null) return; + + var writer = new DataWriter(); + writer.WriteBytes(frame); + + var writeOption = _nusChar.CharacteristicProperties + .HasFlag(GattCharacteristicProperties.WriteWithoutResponse) + ? GattWriteOption.WriteWithoutResponse + : GattWriteOption.WriteWithResponse; + + await _nusChar.WriteValueAsync(writer.DetachBuffer(), writeOption); + } + + // ──────────────────────────────────────────────────────────────────────── + // PRIVATE: BLE receive path + // ──────────────────────────────────────────────────────────────────────── + private void OnCharValueChanged(GattCharacteristic _, GattValueChangedEventArgs args) + { + try + { + var chunk = args.CharacteristicValue.ToArray(); + if (chunk.Length == 0) return; + _bleQueue.Enqueue(chunk); + _bleSignal.Release(); + } + catch { /* non-critical */ } + } + + private void StartProcessingLoop() + { + _loopCts = new CancellationTokenSource(); + var token = _loopCts.Token; + + Task.Run(async () => + { + while (!token.IsCancellationRequested) + { + await _bleSignal.WaitAsync(token); + + while (_bleQueue.TryDequeue(out byte[]? chunk)) + { + foreach (byte b in chunk) + _parser.ProcessByte(b); + } + } + }, token); + } + + private void StopProcessingLoop() + { + _loopCts?.Cancel(); + _loopCts?.Dispose(); + _loopCts = null; + } + + // ──────────────────────────────────────────────────────────────────────── + // PRIVATE: Packet dispatch + // ──────────────────────────────────────────────────────────────────────── + private void OnFullPacketReceived(PacketParser.ParsedPacket packet) + { + // ── Diagnostics frame ──────────────────────────────────────────────── + if (packet.TlResponse == Commands.APP_MONITORING) + { + + Interlocked.Exchange(ref _lastDiagTickUtc, DateTime.UtcNow.Ticks); + + if (_diagnosticsRunning) + { + try + { + var frame = DiagnosticsFrame.Parse(packet.Payload, packet.SeqNum, DateTime.UtcNow); + _diagSubject.OnNext(frame); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"[DIAG] Parse error: {ex.Message}"); + } + } + return; + } + + // ── Non-posted response ────────────────────────────────────────────── + lock (_responseLock) + { + _responsePayload = packet.Payload; + } + _responseReady.Release(); + } + + // ──────────────────────────────────────────────────────────────────────── + // PRIVATE: GATT helpers + // ──────────────────────────────────────────────────────────────────────── + private async Task OpenGattChannelAsync(CancellationToken ct, int maxAttempts = 6) + { + for (int i = 1; i <= maxAttempts; i++) + { + try + { + var result = await _device!.GetGattServicesAsync(BluetoothCacheMode.Uncached); + if (result.Status == GattCommunicationStatus.Success) return true; + + if (result.Status == GattCommunicationStatus.AccessDenied) + await TrySilentPairAsync(); + } + catch { } + + if (i < maxAttempts) await Task.Delay(2000, ct); + } + return false; + } + + private async Task GetServiceAsync(Guid uuid, CancellationToken ct, int maxAttempts = 4) + { + for (int i = 1; i <= maxAttempts; i++) + { + var result = await _device!.GetGattServicesAsync(BluetoothCacheMode.Uncached); + if (result.Status == GattCommunicationStatus.Success) + { + var svc = result.Services.FirstOrDefault(s => s.Uuid == uuid); + if (svc != null) return svc; + } + if (i < maxAttempts) await Task.Delay(1500, ct); + } + return null; + } + + private async Task GetCharacteristicAsync( + GattDeviceService service, Guid uuid, CancellationToken ct, int maxAttempts = 3) + { + for (int i = 1; i <= maxAttempts; i++) + { + var result = await service.GetCharacteristicsForUuidAsync(uuid, BluetoothCacheMode.Uncached); + if (result.Status == GattCommunicationStatus.Success && result.Characteristics.Count > 0) + return result.Characteristics[0]; + if (i < maxAttempts) await Task.Delay(1000, ct); + } + return null; + } + + private async Task TrySilentPairAsync() + { + var pairing = _device!.DeviceInformation.Pairing; + if (pairing.IsPaired || !pairing.CanPair) return; + await pairing.PairAsync(Windows.Devices.Enumeration.DevicePairingProtectionLevel.None); + await Task.Delay(800); + } + + private void OnDeviceConnectionStatusChanged(BluetoothLEDevice sender, object _) + { + if (sender.ConnectionStatus == BluetoothConnectionStatus.Disconnected && IsConnected) + { + _diagnosticsRunning = false; + _parser.Reset(); + while (_bleQueue.TryDequeue(out byte[]? _)) { } + SetState(BleConnectionState.Disconnected); + } + } + + // ──────────────────────────────────────────────────────────────────────── + // PRIVATE: Misc helpers + // ──────────────────────────────────────────────────────────────────────── + private void SetState(BleConnectionState state) + { + _connectionState = state; + _connSubject.OnNext(state); + } + + private bool Fail(string _) { SetState(BleConnectionState.Disconnected); return false; } + + private byte NextSeq() => _seqNum == 0xFF ? (_seqNum = 1) : _seqNum++; + + private static byte[] BuildUnlockPayload(byte unlockCmd, string password, bool isReset) + { + var now = DateTime.Now; + var pwd = System.Text.Encoding.ASCII.GetBytes(password.Trim()); + var data = new List + { + unlockCmd, 0x00, 0x00, 0x00 + }; + + // 16-byte password field (null-padded) + for (int i = 0; i < 16; i++) + data.Add(i < pwd.Length ? pwd[i] : (byte)0x00); + + data.Add((byte)now.Day); + data.Add((byte)now.Month); + data.Add((byte)(now.Year % 100)); + data.Add(0x00); // reserved + + // Sentinel bytes matching original + data.AddRange(new byte[] { 0xF3, 0xF3, 0xF3, 0xF3 }); + + return data.ToArray(); + } + + public void Dispose() + { + StopProcessingLoop(); + _nusService?.Dispose(); + _device?.Dispose(); + _diagSubject.Dispose(); + _connSubject.Dispose(); + _responseReady.Dispose(); + _bleSignal.Dispose(); + } +} diff --git a/TuneBoss.Core/BLE/IBleService.cs b/TuneBoss.Core/BLE/IBleService.cs new file mode 100644 index 0000000..195585a --- /dev/null +++ b/TuneBoss.Core/BLE/IBleService.cs @@ -0,0 +1,196 @@ +using TuneBoss.Core.Models; +using TuneBoss.Core.Protocol; + +namespace TuneBoss.Core.BLE; + +/// +/// Represents a discovered BLE device before connection. +/// +public sealed record BleDeviceInfo( + ulong Address, + string Name, + short Rssi) +{ + public string MacAddress => FormatMac(Address); + + private static string FormatMac(ulong a) + { + var b = BitConverter.GetBytes(a); + return $"{b[5]:X2}:{b[4]:X2}:{b[3]:X2}:{b[2]:X2}:{b[1]:X2}:{b[0]:X2}"; + } + + public override string ToString() => $"{Name} | {MacAddress} | {Rssi} dBm"; +} + +/// +/// Connection state published to observers. +/// +public enum BleConnectionState +{ + Disconnected, + Connecting, + Connected, + Disconnecting, +} + +/// +/// Result of a command sent to the device. +/// +public sealed record CommandResult( + bool Success, + byte ResponseCode, // 0x51 = success, 0x52 = fail, etc. + byte[] Payload, + string? ErrorMessage = null) +{ + public static CommandResult Ok(byte[] payload) => + new(true, 0x51, payload); + + public static CommandResult Fail(byte responseCode, string message) => + new(false, responseCode, Array.Empty(), message); + + public static CommandResult Timeout() => + new(false, 0x00, Array.Empty(), "Command timed out"); +} + +/// +/// The primary BLE service contract. +/// All table and device operations go through this interface. +/// The UI layer never touches BLE APIs directly. +/// +public interface IBleService : IDisposable +{ + // ── State ──────────────────────────────────────────────────────────────── + + BleConnectionState ConnectionState { get; } + bool IsConnected { get; } + + /// Observable connection state changes. + IObservable ConnectionStateChanged { get; } + + // ── Scanning ───────────────────────────────────────────────────────────── + + /// Starts BLE advertisement scanning. Emits discovered devices. + IObservable StartScan(); + + /// Stops active scan. + void StopScan(); + + // ── Connection ─────────────────────────────────────────────────────────── + + /// + /// Connects to a device. Handles GATT channel opening, NUS service + /// discovery, notification subscription, and the post-connect APP_READ_INFO. + /// + Task ConnectAsync(BleDeviceInfo device, CancellationToken ct = default); + + /// Gracefully disconnects, stops diagnostics, cleans up GATT resources. + Task DisconnectAsync(); + + // ── Device info ────────────────────────────────────────────────────────── + + /// + /// Reads ECU info (APP_READ_INFO). Returns null on timeout or failure. + /// Also sets the active GenerationConfig internally. + /// + Task ReadEcuInfoAsync(CancellationToken ct = default); + + // ── Auth ───────────────────────────────────────────────────────────────── + + /// Sends unlock command with password and current date. + Task UnlockAsync(string password, CancellationToken ct = default); + + /// Sends tuner unlock command. + Task UnlockTunerAsync(string password, CancellationToken ct = default); + + // ── Table operations ───────────────────────────────────────────────────── + + /// + /// Reads a 2D table (split read: two halves, with diagnostics pause/resume). + /// Returns the raw combined payload. + /// + Task ReadTable2DAsync( + ushort address, + byte lengthBytes, + bool userTable = false, + CancellationToken ct = default); + + /// Writes a 2D table (split write). + Task WriteTable2DAsync( + ushort address, + byte[] data, + bool userTable = false, + CancellationToken ct = default); + + /// Reads a 1D table. + Task ReadTable1DAsync( + ushort address, + byte lengthBytes, + CancellationToken ct = default); + + /// Writes a 1D table. + Task WriteTable1DAsync( + ushort address, + byte[] data, + CancellationToken ct = default); + + /// Reads a subtable. + Task ReadSubTableAsync( + ushort address, + CancellationToken ct = default); + + /// Writes a subtable. + Task WriteSubTableAsync( + ushort address, + byte[] data, + CancellationToken ct = default); + + /// Reads misc values block. + Task ReadMiscAsync( + ushort address, + byte lengthBytes, + CancellationToken ct = default); + + /// Writes misc values block. + Task WriteMiscAsync( + ushort address, + byte[] data, + CancellationToken ct = default); + + // ── Flash ──────────────────────────────────────────────────────────────── + + /// Sends APP_FLASH_WR to persist all writes to ECU flash. + Task FlashWriteAsync(CancellationToken ct = default); + + /// + /// Writes the 4-byte first-use settings block via APP_FIRSTUSE (0x35). + /// Byte[0] (DD slot) carries the TPS-calibration-done flag. + /// + Task WriteFirstUseAsync(byte[] fourBytes, CancellationToken ct = default); + + // ── Diagnostics streaming ──────────────────────────────────────────────── + + /// + /// Observable stream of diagnostics frames (APP_MONITORING 0x70). + /// Emits continuously while diagnostics are running. + /// + IObservable DiagnosticsFrames { get; } + + bool DiagnosticsRunning { get; } + + /// Sends APP_MON_START and begins emitting DiagnosticsFrames. + Task StartDiagnosticsAsync(CancellationToken ct = default); + + /// + /// Sends APP_MON_STOP and waits for silence before returning. + /// Safe to call even if diagnostics aren't running. + /// + Task StopDiagnosticsAsync(CancellationToken ct = default); + + // ── Keepalive ──────────────────────────────────────────────────────────── + + /// + /// Called by the keepalive timer. Sends APP_READ_INFO if idle for > 15s. + /// Internally managed — exposed for test visibility only. + /// + void OnKeepaliveTimer(); +} diff --git a/TuneBoss.Core/BLE/PacketParser.cs b/TuneBoss.Core/BLE/PacketParser.cs new file mode 100644 index 0000000..d690497 --- /dev/null +++ b/TuneBoss.Core/BLE/PacketParser.cs @@ -0,0 +1,168 @@ +namespace TuneBoss.Core.BLE; + +/// +/// Stateful byte-stream parser for TuneBoss BLE packets. +/// Extracted from Form1_BLEhelper.cs ProcessByte() / OnFullPacketReceived(). +/// Thread-safe only when all calls are serialized (BLE processing loop does this). +/// +public sealed class PacketParser +{ + public sealed record ParsedPacket( + byte DlCommand, + byte SeqNum, + byte DwCount, + byte TlResponse, + byte TlCommand, + byte TlLength, + byte[] Payload); + + private readonly Action _onPacketReceived; + + // ── Parser state ───────────────────────────────────────────────────────── + private int _byteCycle; + private int _startSeqCycle; + private int _packetHeaderCycle; + private int _dWordByteTrack; + private int _dWordCheckSumTrack; + + private readonly byte[] _startSeq = new byte[4]; + private readonly byte[] _packetHeader = new byte[4]; + private readonly List _dataBuffer = new(); + private readonly List _csBuffer = new(); + + private byte _currDlCommand; + private byte _currDlSeqCount; + private byte _currDlDWordCount; + private byte _currTlResp; + private byte _currTlCommand; + private byte _currTlLength; + + public PacketParser(Action onPacketReceived) + { + _onPacketReceived = onPacketReceived; + } + + public void Reset() + { + _byteCycle = 0; + _startSeqCycle = 0; + _packetHeaderCycle = 0; + _dWordByteTrack = 0; + _dWordCheckSumTrack = 0; + _dataBuffer.Clear(); + _csBuffer.Clear(); + _currDlCommand = 0; + _currDlSeqCount = 0; + _currDlDWordCount = 0; + _currTlResp = 0; + _currTlCommand = 0; + _currTlLength = 0; + } + + public void ProcessByte(byte b) + { + // ── Zone 1: bytes 0–3 — preamble FF 00 FF 00 ───────────────────── + if (_byteCycle <= 3) + { + _startSeq[_startSeqCycle] = b; + + if (_startSeqCycle == 3) + { + bool valid = _startSeq[0] == 0xFF && _startSeq[1] == 0x00 + && _startSeq[2] == 0xFF && _startSeq[3] == 0x00; + if (!valid) { Reset(); return; } + } + + _startSeqCycle++; + _byteCycle++; + return; + } + + // ── Zone 2: bytes 4–7 — packet header ──────────────────────────── + if (_byteCycle <= 7) + { + _packetHeader[_packetHeaderCycle] = b; + + if (_packetHeaderCycle == 3) + { + if (!HeaderIntegrityOk(_packetHeader)) { Reset(); return; } + + _currDlCommand = _packetHeader[0]; + _currDlSeqCount = _packetHeader[1]; + _currDlDWordCount = _packetHeader[2]; + } + + _packetHeaderCycle++; + _byteCycle++; + return; + } + + // ── Zone 3: no payload ──────────────────────────────────────────── + if (_currDlDWordCount == 0) { Reset(); return; } + + // ── Zone 4: bytes 8–11 — TL header (first DWord of payload) ────── + if (_byteCycle <= 11) + { + switch (_byteCycle) + { + case 8: _currTlResp = b; break; + case 9: _currTlCommand = b; break; + case 10: _currTlLength = b; break; + } + + _dataBuffer.Add(b); + _byteCycle++; + return; + } + + // ── Zone 5: bytes 12+ — payload bytes + checksum ───────────────── + _byteCycle++; + + int payloadBytes = 4 * (_currDlDWordCount - 1); // DWords after the TL header + + if (_dWordByteTrack < payloadBytes) + { + _dataBuffer.Add(b); + _dWordByteTrack++; + } + else if (_dWordCheckSumTrack < 4) + { + _csBuffer.Add(b); + _dWordCheckSumTrack++; + + if (_dWordCheckSumTrack == 4) + OnFullPacketReceived(); + } + } + + private void OnFullPacketReceived() + { + byte[] data = _dataBuffer.ToArray(); + byte[] cs = _csBuffer.ToArray(); + + // Verify checksum + var expected = Protocol.ChecksumHelper.GenChecksumDW(data); + var receivedCs = (uint)(cs[0] | (cs[1] << 8) | (cs[2] << 16) | (cs[3] << 24)); + + if (expected != receivedCs) { Reset(); return; } + + var packet = new ParsedPacket( + DlCommand: _currDlCommand, + SeqNum: _currDlSeqCount, + DwCount: _currDlDWordCount, + TlResponse: _currTlResp, + TlCommand: _currTlCommand, + TlLength: _currTlLength, + Payload: data); + + Reset(); + _onPacketReceived(packet); + } + + private static bool HeaderIntegrityOk(byte[] h) + { + byte sum = unchecked((byte)(h[0] + h[1] + h[2])); + byte invSum = unchecked((byte)~sum); + return invSum == h[3]; + } +} diff --git a/TuneBoss.Core/BLE/SimBleService.cs b/TuneBoss.Core/BLE/SimBleService.cs new file mode 100644 index 0000000..a13c4e1 --- /dev/null +++ b/TuneBoss.Core/BLE/SimBleService.cs @@ -0,0 +1,368 @@ +using System.Reactive.Disposables; +using System.Reactive.Linq; +using System.Reactive.Subjects; +using TuneBoss.Core.Models; +using TuneBoss.Core.Protocol; + +namespace TuneBoss.Core.BLE; + +/// +/// A fully in-memory for hardware-free testing. +/// +/// • Scan/connect/unlock succeed instantly. +/// • Reads synthesize correctly-framed wire payloads (4-byte header, data at offset 4, +/// the device len+1 convention, and the 2D split-read halves) so every table, +/// misc block and 1D table populates in the real UI. +/// • Diagnostics stream a LIVE, moving RPM + load (sine sweep, ~20 Hz) so the 2D +/// tuning-table tracker visibly walks across the grid. The six gauge channels +/// move with it (MAP follows load, ETemp warms up, AFR wobbles, spark advances). +/// +/// Swap it in via DI (see the App.xaml.cs snippet in SimBleService_DI_README). +/// +public sealed class SimBleService : IBleService +{ + // ── Tunables (change before connecting to exercise different cases) ──────── + public byte SimAppInfoVersion { get; set; } = 2; // 2=Gen3, 1=Gen2, 245=Gen1 + public byte SimFwVersion { get; set; } = 193; // try 70 / 100 / 150 to see FW gating + public bool SimTpsCalibrated { get; set; } = false; // false => connect warns + jumps to TPS cal + public byte SimRpmMax { get; set; } = 130; // ×100 = 13000 rpm limit + public double SweepSeconds { get; set; } = 6.0; // one full idle→redline→idle cycle + public int EmitHz { get; set; } = 20; // diagnostics frames per second + + // ── Plumbing ────────────────────────────────────────────────────────────── + private readonly BehaviorSubject _state = new(BleConnectionState.Disconnected); + private readonly Subject _diag = new(); + private CancellationTokenSource? _diagCts; + private byte _seq; + private readonly Random _rng = new(1234); + + public BleConnectionState ConnectionState => _state.Value; + public bool IsConnected => _state.Value == BleConnectionState.Connected; + public IObservable ConnectionStateChanged => _state.AsObservable(); + + // ── Scan ────────────────────────────────────────────────────────────────── + public IObservable StartScan() => Observable.Create(o => + { + o.OnNext(new BleDeviceInfo(0xAABBCCDDEEFF, "B_SIM-PG1", -42)); + o.OnNext(new BleDeviceInfo(0x0011223344556, "B_SIM-R15", -57)); + return Disposable.Empty; // stay "scanning" (no completion) + }); + + public void StopScan() { } + + // ── Connect ─────────────────────────────────────────────────────────────── + public async Task ConnectAsync(BleDeviceInfo device, CancellationToken ct = default) + { + _state.OnNext(BleConnectionState.Connecting); + await Task.Delay(120, ct); + _state.OnNext(BleConnectionState.Connected); + + // Auto-start the live stream so the persistent gauge strip + table tracker + // come alive immediately. Idempotent — a later StartDiagnosticsAsync() is a no-op. + await StartDiagnosticsAsync(ct); + return true; + } + + public async Task DisconnectAsync() + { + await StopDiagnosticsAsync(); + _state.OnNext(BleConnectionState.Disconnecting); + _state.OnNext(BleConnectionState.Disconnected); + } + + // ── Device info ─────────────────────────────────────────────────────────── + public Task ReadEcuInfoAsync(CancellationToken ct = default) => + Task.FromResult(new EcuInfo + { + Username = "SIM-RIDER", + UniqueId = "51A0-0000-0000-0001", + AppInfoVersion = SimAppInfoVersion, + FwVersion = SimFwVersion, + HwVersion = 10, + UpgradeRpmMax = SimRpmMax, + BikeManufacturer = 1, // Yamaha + UpgradeLogImmo = 0x0F, // dual-injector unlocked + FirstUseInfo0 = SimTpsCalibrated ? TpsCalibration.CalDoneFlag : (byte)0, + }); + + // ── Auth ────────────────────────────────────────────────────────────────── + public Task UnlockAsync(string password, CancellationToken ct = default) + => Task.FromResult(CommandResult.Ok(Array.Empty())); + + public Task UnlockTunerAsync(string password, CancellationToken ct = default) + => Task.FromResult(CommandResult.Ok(Array.Empty())); + + // ── 2D tables (split read) ──────────────────────────────────────────────── + // The VM reads part 1 with len = SplitFirstLength (0x7F) at the base address, + // then part 2 (len = 100) at base+128. FromSplitResponses copies from offset 4 + // of each. We branch on the requested length. Tuning + AFR share this layout. + public Task ReadTable2DAsync(ushort address, byte lengthBytes, + bool userTable = false, CancellationToken ct = default) + { + var combined = Canonical2D(); // 228 bytes + const int firstCount = TuningTable.SplitFirstLength + 1; // 128 + + if (lengthBytes == TuningTable.SplitFirstLength) + return OkFramed(Slice(combined, 0, firstCount), Commands.APP_MEMRD_2D); + + int secondCount = TuningTable.TotalPayloadBytes - firstCount; // 100 + return OkFramed(Slice(combined, firstCount, secondCount), Commands.APP_MEMRD_2D); + } + + public Task WriteTable2DAsync(ushort address, byte[] data, + bool userTable = false, CancellationToken ct = default) + => Task.FromResult(CommandResult.Ok(data)); + + // ── 1D tables ───────────────────────────────────────────────────────────── + public Task ReadTable1DAsync(ushort address, byte lengthBytes, + CancellationToken ct = default) + { + // TPS absolute bounds live at a fixed address; return [max, min, ...] so the + // calibration page validates a full sweep successfully. + var addr = TpsCalibration.For((GenerationType)SimAppInfoVersion, SimFwVersion); + if (address == addr.AbsBounds) + return OkFramed(TpsAbsBounds(), Commands.APP_MEMRD_1D); + + return OkFramed(Canonical1D(), Commands.APP_MEMRD_1D); + } + + /// 8-byte TPS abs-bounds block: [absMax, absMin, store2, store3, ...]. + private static byte[] TpsAbsBounds() + => new byte[] { 195, 5, 197, 199, 201, 203, 205, 207 }; + + public Task WriteTable1DAsync(ushort address, byte[] data, + CancellationToken ct = default) + => Task.FromResult(CommandResult.Ok(data)); + + // ── Subtables ───────────────────────────────────────────────────────────── + public Task ReadSubTableAsync(ushort address, CancellationToken ct = default) + => OkFramed(CanonicalSub(), Commands.APP_MEMRD_SUBT); + + public Task WriteSubTableAsync(ushort address, byte[] data, + CancellationToken ct = default) + => Task.FromResult(CommandResult.Ok(data)); + + // ── Misc ────────────────────────────────────────────────────────────────── + public Task ReadMiscAsync(ushort address, byte lengthBytes, + CancellationToken ct = default) + => OkFramed(CanonicalMisc(lengthBytes), Commands.APP_MEMRD_MISC); + + public Task WriteMiscAsync(ushort address, byte[] data, + CancellationToken ct = default) + => Task.FromResult(CommandResult.Ok(data)); + + // ── Flash ───────────────────────────────────────────────────────────────── + public Task FlashWriteAsync(CancellationToken ct = default) + => Task.FromResult(CommandResult.Ok(Array.Empty())); + + // ── First-use settings ────────────────────────────────────────────────────── + public Task WriteFirstUseAsync(byte[] fourBytes, CancellationToken ct = default) + { + if (fourBytes is { Length: >= 1 }) + SimTpsCalibrated = fourBytes[0] == TpsCalibration.CalDoneFlag; + return Task.FromResult(CommandResult.Ok(Array.Empty())); + } + + // ── Diagnostics (the moving part) ───────────────────────────────────────── + public IObservable DiagnosticsFrames => _diag.AsObservable(); + public bool DiagnosticsRunning => _diagCts is not null; + + public Task StartDiagnosticsAsync(CancellationToken ct = default) + { + if (_diagCts is not null) return Task.CompletedTask; + _diagCts = new CancellationTokenSource(); + _ = RunDiagnosticsLoop(_diagCts.Token); + return Task.CompletedTask; + } + + public Task StopDiagnosticsAsync(CancellationToken ct = default) + { + _diagCts?.Cancel(); + _diagCts?.Dispose(); + _diagCts = null; + return Task.CompletedTask; + } + + public void OnKeepaliveTimer() { /* no-op in sim */ } + + private async Task RunDiagnosticsLoop(CancellationToken ct) + { + var period = TimeSpan.FromMilliseconds(1000.0 / Math.Max(1, EmitHz)); + using var timer = new PeriodicTimer(period); + var start = DateTime.UtcNow; + + // RPM raw sweep range — must sit inside the canonical RpmAxis (10..217) + const double rpmIdle = 12, rpmRedline = 205; + const double loadLo = 22, loadHi = 95; + + try + { + while (await timer.WaitForNextTickAsync(ct)) + { + double tSec = (DateTime.UtcNow - start).TotalSeconds; + double phase = tSec / Math.Max(0.5, SweepSeconds) * 2 * Math.PI; + double s = (Math.Sin(phase) + 1) / 2; // 0..1 + bool rising = Math.Cos(phase) >= 0; + + byte rpmRaw = (byte)Math.Round(rpmIdle + s * (rpmRedline - rpmIdle)); + byte load = (byte)Math.Round(loadLo + s * (loadHi - loadLo) + Noise(2)); + byte tps = (byte)Math.Clamp(Math.Round(s * 100 + Noise(2)), 0, 100); + byte map = (byte)Math.Clamp(load + Noise(2), 0, 255); + byte etemp = (byte)Math.Clamp(40 + tSec * 3, 40, 92); // warm-up ramp + byte afrx10 = (byte)Math.Clamp(Math.Round(145 + Noise(8)), 120, 170); + + _diag.OnNext(new DiagnosticsFrame + { + SeqNum = _seq++, + ReceivedAt = DateTime.UtcNow, + + // tracker channels + Load = load, + RPM_Raw = rpmRaw, + TPS_Percent = tps, + TPS_Raw = (byte)Math.Clamp(Math.Round(10 + s * 178), 0, 255), + + // gauges + Baro_kPa = 101, + Baro_Dynamic = 101, + VBAT_deciV = (byte)(138 - (int)(s * 6)), // sags under load + ETEMP_DegC = etemp, + IAT_DegC = 32, + MAP_kPa = map, + MAP_Lo_Avg = (byte)Math.Max(0, map - 4), + MAP_Hi_Avg_Raw = (byte)Math.Clamp(s * 120, 0, 255), // doubles as meter speed + O2_AFR_x10 = afrx10, + FuelStartAngle1_Raw = (byte)Math.Clamp(20 + s * 30, 0, 255), + FuelStartAngle2_Raw = (byte)Math.Clamp(20 + s * 30, 0, 255), + FuelPulseWidth1 = (int)(1500 + s * 6000), + FuelEndAngle = (int)(s * 360), + SparkAngle1 = (sbyte)Math.Clamp(5 + s * 30, -30, 60), + SparkAngle2 = (sbyte)Math.Clamp(5 + s * 30, -30, 60), + SparkPulseWidth = 25, + CrankSyncLostCounter = 0, + + // packed state bytes + CrankState_Raw = 0x06, // 6 = RUNNING (low nibble), TC_Mode 0 (high) + UMState_Packed = 0x33, // UMState 3 = RUN, gear 3 (high nibble) + ThrottleState_Packed = (byte)(rising ? 0x01 : 0x02), // Accel / Decel + RPMState_Packed = (byte)((rising ? 0x02 : 0x01) | 0x80), // Accel/Decel + StayTuned + + // no faults + ErrorsFatal = 0, + AnalogError_Current = 0, AnalogError_Persistent = 0, + OutputError_Current = 0, OutputError_Persistent = 0, + }); + } + } + catch (OperationCanceledException) { /* normal stop */ } + } + + private double Noise(double amp) => (_rng.NextDouble() - 0.5) * 2 * amp; + + // ── Canonical payloads ──────────────────────────────────────────────────── + + /// 228-byte 2D combined payload: smooth fuel surface, realistic axes. + private static byte[] Canonical2D() + { + var data = new byte[TuningTable.DataBytes]; // 24 cols × 8 rows + for (int r = 0; r < TuningTable.Rows; r++) + for (int c = 0; c < TuningTable.Cols; c++) + data[r * TuningTable.Cols + c] = (byte)Math.Clamp(30 + c * 8 + r * 3, 0, 255); + + var loadAxis = new byte[TuningTable.Rows]; + for (int r = 0; r < TuningTable.Rows; r++) loadAxis[r] = (byte)(20 + r * 10); // 20..90 + + var rpmAxis = new byte[TuningTable.Cols]; + for (int c = 0; c < TuningTable.Cols; c++) rpmAxis[c] = (byte)(10 + c * 9); // 10..217 (×100) + + var t = new TuningTable + { + Data = data, LoadAxis = loadAxis, RpmAxis = rpmAxis, + MaxRaw = 255, MinRaw = 0, Mult = 1, Sign = 0, + }; + return t.ToWirePayload(); // 228 bytes + } + + /// 24-byte 1D table: monotonic axis + ramp values, unscaled. + private static byte[] Canonical1D() + { + var t = new OneDimTable + { + MaxRaw = 255, MinRaw = 0, + RawSignedFlag = 0, ConvSignedFlag = 0, + RawMultiplier = 1, ConvMultiplier = 1, RawRounding = 0, ConvOffset = 0, + }; + for (int i = 0; i < OneDimTable.PointCount; i++) + { + t.RawAxis[i] = i * 10; // 0,10,...,70 + t.ConvValues[i] = 20 + i * 6; // gentle ramp + } + return t.ToWirePayload(); // 24 bytes + } + + /// 40-byte subtable body (4×6) with a monotonic RPM/load axis so it parses cleanly. + private static byte[] CanonicalSub() + { + var buf = new byte[SubTable.TotalBytes]; // 40 + for (int i = 0; i < SubTable.DataBytes; i++) buf[i] = (byte)(40 + i); + // load axis (4) + var lo = SubTable.DefaultLoadAxis; + for (int i = 0; i < SubTable.LoadBytes; i++) buf[SubTable.DataBytes + i] = lo[i]; + // rpm axis (12 = 6 lo/hi pairs) + for (int c = 0; c < SubTable.Cols; c++) + { + buf[SubTable.DataBytes + SubTable.LoadBytes + c * 2] = (byte)(15 + c * 20); + buf[SubTable.DataBytes + SubTable.LoadBytes + c * 2 + 1] = (byte)(20 + c * 20); + } + return buf; + } + + /// + /// Misc block sized for the request (returns len+1 bytes, mimicking the device + /// off-by-one). The 136-byte core block gets a few representative settings bytes + /// set so the bit-editors show real state. + /// + private byte[] CanonicalMisc(byte lengthBytes) + { + var data = new byte[lengthBytes + 1]; // device returns len+1 + + if (lengthBytes >= MemoryLayout.LenMiscCore) // core block (0x88 = 136) + { + data[8] = 131; // Crank_CamSync_Config + data[25] = 0x05; // Fuel_Settings2 (a couple of flags) + data[31] = 0x12; // Spark_Settings + data[33] = 0x01; // O2_Autotune_Enable + data[84] = 0x0F; // ShiftBoss_Enable = enable + both DIN bits + data[88] = 35; // ShiftBoss_Spark_Retard_deg + } + return data; + } + + // ── Framing helpers ─────────────────────────────────────────────────────── + private static byte[] Slice(byte[] src, int start, int count) + { + var b = new byte[count]; + Buffer.BlockCopy(src, start, b, 0, count); + return b; + } + + /// Wraps a data block in the 4-byte response header (51 cmd len 00). + private static Task OkFramed(byte[] data, byte cmd) + { + var buf = new byte[4 + data.Length]; + buf[0] = 0x51; + buf[1] = cmd; + buf[2] = (byte)data.Length; + buf[3] = 0x00; + Buffer.BlockCopy(data, 0, buf, 4, data.Length); + return Task.FromResult(CommandResult.Ok(buf)); + } + + public void Dispose() + { + _diagCts?.Cancel(); + _diagCts?.Dispose(); + _diag.Dispose(); + _state.Dispose(); + } +} diff --git a/TuneBoss.Core/Class1.cs b/TuneBoss.Core/Class1.cs new file mode 100644 index 0000000..f477816 --- /dev/null +++ b/TuneBoss.Core/Class1.cs @@ -0,0 +1,7 @@ +namespace TuneBoss.Core +{ + public class Class1 + { + + } +} diff --git a/TuneBoss.Core/IO/FsrFile.cs b/TuneBoss.Core/IO/FsrFile.cs new file mode 100644 index 0000000..16b226d --- /dev/null +++ b/TuneBoss.Core/IO/FsrFile.cs @@ -0,0 +1,470 @@ +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using TuneBoss.Core.Models; + +namespace TuneBoss.Core.IO; + +/// +/// Reader/writer for the TuneBoss .fsr configuration format (v1) — a +/// text-based, self-describing container for a full ECU tuning configuration. +/// See FSR_FORMAT_SPEC.md for the authoritative specification. +/// +/// This type is model-based and standalone: it (de)serialises the actual table +/// models, so it does not depend on the app's nav-tree/codec plumbing. +/// +public static class FsrFile +{ + public const int FormatVersion = 1; + + // ── Public data structures ────────────────────────────────────────────── + + public sealed class FsrDocument + { + public FsrHeader Header { get; set; } = new(); + public List Sections { get; } = new(); + + public FsrSection? Find(string name) => + Sections.FirstOrDefault(s => string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase)); + } + + public sealed class FsrHeader + { + public int FsrVersion { get; set; } = FormatVersion; + public string Generator { get; set; } = ""; + public string CreatedUtc { get; set; } = ""; + public string CreatorId { get; set; } = ""; + public int FwVersion { get; set; } + public int HwVersion { get; set; } + public int Make { get; set; } + public int Model { get; set; } + public int Cylinders { get; set; } = 1; + public int Generation { get; set; } = 3; + public string SaveType { get; set; } = "full_config"; + public string Note { get; set; } = "none"; + // Modification tags + public string ModEngineBlock { get; set; } = "none"; + public string ModCamshaft { get; set; } = "none"; + public string ModExhaust { get; set; } = "none"; + public string ModAirFilter { get; set; } = "none"; + public string ModCylinderHead { get; set; } = "none"; + public string ModInjector { get; set; } = "none"; + public string ModThrottleBody { get; set; } = "none"; + public string ModJackRod { get; set; } = "none"; + /// Any header keys not recognised — preserved on round-trip. + public Dictionary Extra { get; } = new(StringComparer.OrdinalIgnoreCase); + } + + public enum SectionType { Table2D, Table1D, SubTable, Afr, Misc, Unknown } + + public sealed class FsrSection + { + public SectionType Type { get; set; } + public string TypeToken { get; set; } = ""; // raw token, preserves Unknown + public string Name { get; set; } = ""; // stable feature key + public string Label { get; set; } = ""; + public ushort Addr { get; set; } + public byte Length { get; set; } // last-inclusive-offset (bytes-1) + public int Gen { get; set; } + + // Exactly one of these is populated depending on Type. + public TuningTable? Table2D { get; set; } + public AfrTable? Afr { get; set; } + public OneDimTable? Table1D { get; set; } + public SubTable? Sub { get; set; } + public byte[]? MiscBytes { get; set; } + + /// Raw field lines for Unknown sections / unrecognised keys. + public Dictionary Extra { get; } = new(StringComparer.OrdinalIgnoreCase); + } + + // ════════════════════════════════════════════════════════════════════════ + // WRITE + // ════════════════════════════════════════════════════════════════════════ + + /// Serialises a document to .fsr text (with an optional whole-body sha256). + public static string Write(FsrDocument doc, bool includeSha256 = true) + { + var body = new StringBuilder(); + WriteHeader(body, doc.Header); + body.Append('\n'); + foreach (var s in doc.Sections) + WriteSection(body, s); + + if (!includeSha256) + return body.ToString(); + + // sha256 covers everything after the sha256 line — write header line first. + string bodyText = body.ToString(); + string hash = Sha256Hex(bodyText); + return $"# integrity\nsha256 = {hash}\n{bodyText}"; + } + + private static void WriteHeader(StringBuilder sb, FsrHeader h) + { + sb.Append("# TuneBoss configuration — .fsr v").Append(h.FsrVersion).Append('\n'); + void F(string k, object v) => sb.Append(k).Append(" = ").Append(v).Append('\n'); + F("fsr_version", h.FsrVersion); + if (!string.IsNullOrEmpty(h.Generator)) F("generator", h.Generator); + if (!string.IsNullOrEmpty(h.CreatedUtc)) F("created_utc", h.CreatedUtc); + F("creator_id", h.CreatorId); + F("fw_version", h.FwVersion); + F("hw_version", h.HwVersion); + F("make", h.Make); + F("model", h.Model); + F("cylinders", h.Cylinders); + F("generation", h.Generation); + F("save_type", h.SaveType); + F("mod_engine_block", h.ModEngineBlock); + F("mod_camshaft", h.ModCamshaft); + F("mod_exhaust", h.ModExhaust); + F("mod_air_filter", h.ModAirFilter); + F("mod_cylinder_head", h.ModCylinderHead); + F("mod_injector", h.ModInjector); + F("mod_throttle_body", h.ModThrottleBody); + F("mod_jack_rod", h.ModJackRod); + F("note", h.Note); + foreach (var kv in h.Extra) F(kv.Key, kv.Value); + } + + private static void WriteSection(StringBuilder sb, FsrSection s) + { + string typeToken = s.Type switch + { + SectionType.Table2D => "TABLE2D", + SectionType.Afr => "AFR", + SectionType.Table1D => "TABLE1D", + SectionType.SubTable => "SUBTABLE", + SectionType.Misc => "MISC", + _ => s.TypeToken, + }; + sb.Append('[').Append(typeToken).Append(' ').Append(s.Name).Append("]\n"); + void F(string k, object v) => sb.Append(k).Append(" = ").Append(v).Append('\n'); + F("label", s.Label); + F("addr", Hex16(s.Addr)); + F("length", Hex8(s.Length)); + if (s.Gen != 0) F("gen", s.Gen); + + switch (s.Type) + { + case SectionType.Table2D when s.Table2D is { } t: Write2D(sb, t.Data, t.RpmAxis, t.LoadAxis, t.Sign, t.MaxRaw, t.MinRaw, t.Mult); break; + case SectionType.Afr when s.Afr is { } a: Write2D(sb, a.Data, a.RpmAxis, a.LoadAxis, a.Sign, a.MaxRaw, a.MinRaw, a.Mult); break; + case SectionType.Table1D when s.Table1D is { } o: Write1D(sb, o); break; + case SectionType.SubTable when s.Sub is { } sub: WriteSub(sb, sub); break; + case SectionType.Misc when s.MiscBytes is { } b: WriteBytes(sb, b); break; + default: + foreach (var kv in s.Extra) F(kv.Key, kv.Value); + break; + } + sb.Append('\n'); + } + + private static void Write2D(StringBuilder sb, byte[] data, byte[] rpm, byte[] load, byte sign, byte maxRaw, byte minRaw, byte mult) + { + sb.Append("signed = ").Append(sign > 0 ? 1 : 0).Append('\n'); + sb.Append("mult = ").Append(mult).Append('\n'); + sb.Append("max_raw = ").Append(maxRaw).Append('\n'); + sb.Append("min_raw = ").Append(minRaw).Append('\n'); + sb.Append("rpm_axis = ").Append(HexBytes(rpm)).Append('\n'); + sb.Append("load_axis = ").Append(HexBytes(load)).Append('\n'); + for (int r = 0; r < TuningTable.Rows; r++) + { + sb.Append("row").Append(r).Append(" = "); + for (int c = 0; c < TuningTable.Cols; c++) + { + if (c > 0) sb.Append(' '); + sb.Append(Hex8(data[r * TuningTable.Cols + c])); + } + sb.Append('\n'); + } + } + + private static void Write1D(StringBuilder sb, OneDimTable o) + { + sb.Append("raw_signed = ").Append(o.RawSignedFlag > 0 ? 1 : 0).Append('\n'); + sb.Append("conv_signed = ").Append(o.ConvSignedFlag > 0 ? 1 : 0).Append('\n'); + sb.Append("raw_mult = ").Append(o.RawMultiplier).Append('\n'); + sb.Append("conv_mult = ").Append(o.ConvMultiplier).Append('\n'); + sb.Append("raw_round = ").Append(o.RawRounding).Append('\n'); + sb.Append("conv_offset = ").Append((int)o.ConvOffset).Append('\n'); + sb.Append("max_raw = ").Append(o.MaxRaw).Append('\n'); + sb.Append("min_raw = ").Append(o.MinRaw).Append('\n'); + for (int i = 0; i < OneDimTable.PointCount; i++) + sb.Append('p').Append(i).Append(" = ").Append(o.RawAxis[i]).Append(", ").Append(o.ConvValues[i]).Append('\n'); + } + + private static void WriteSub(StringBuilder sb, SubTable sub) + { + for (int r = 0; r < SubTable.Rows; r++) + { + sb.Append("row").Append(r).Append(" = "); + for (int c = 0; c < SubTable.Cols; c++) + { + if (c > 0) sb.Append(", "); + sb.Append((int)unchecked((sbyte)sub.Data[r * SubTable.Cols + c])); + } + sb.Append('\n'); + } + } + + private static void WriteBytes(StringBuilder sb, byte[] bytes) + { + const int perLine = 32; + for (int off = 0; off < bytes.Length; off += perLine) + { + int n = Math.Min(perLine, bytes.Length - off); + sb.Append("bytes = "); + for (int i = 0; i < n; i++) + { + if (i > 0) sb.Append(' '); + sb.Append(Hex8(bytes[off + i])); + } + sb.Append('\n'); + } + } + + // ════════════════════════════════════════════════════════════════════════ + // READ + // ════════════════════════════════════════════════════════════════════════ + + public static FsrDocument Read(string text) + { + var doc = new FsrDocument(); + FsrSection? cur = null; + var secFields = new Dictionary(StringComparer.OrdinalIgnoreCase); + var rowLines = new List<(string key, string val)>(); + + void Flush() + { + if (cur == null) return; + BuildSection(cur, secFields, rowLines); + doc.Sections.Add(cur); + secFields = new(StringComparer.OrdinalIgnoreCase); + rowLines = new(); + } + + foreach (var raw in text.Split('\n')) + { + var line = raw.TrimEnd('\r'); + var t = line.TrimStart(); + if (t.Length == 0 || t[0] == '#') continue; + + if (t[0] == '[') + { + Flush(); + int close = t.IndexOf(']'); + var inner = (close > 0 ? t[1..close] : t[1..]).Trim(); + int sp = inner.IndexOf(' '); + string typeTok = sp > 0 ? inner[..sp] : inner; + string name = sp > 0 ? inner[(sp + 1)..].Trim() : ""; + cur = new FsrSection { TypeToken = typeTok, Type = ParseType(typeTok), Name = name }; + continue; + } + + int eq = line.IndexOf('='); + if (eq < 0) continue; + string key = line[..eq].Trim(); + string val = line[(eq + 1)..].Trim(); + + if (cur == null) { ApplyHeader(doc.Header, key, val); continue; } + + // Row-style keys accumulate (rowN, pN, bytes); everything else is a field. + if (IsRowKey(key)) rowLines.Add((key, val)); + else secFields[key] = val; + } + Flush(); + return doc; + } + + private static bool IsRowKey(string k) => + k.StartsWith("row", StringComparison.OrdinalIgnoreCase) || + (k.Length >= 2 && (k[0] == 'p' || k[0] == 'P') && char.IsDigit(k[1])) || + k.Equals("bytes", StringComparison.OrdinalIgnoreCase); + + private static SectionType ParseType(string tok) => tok.ToUpperInvariant() switch + { + "TABLE2D" => SectionType.Table2D, + "AFR" => SectionType.Afr, + "TABLE1D" => SectionType.Table1D, + "SUBTABLE" => SectionType.SubTable, + "MISC" => SectionType.Misc, + _ => SectionType.Unknown, + }; + + private static void ApplyHeader(FsrHeader h, string key, string val) + { + switch (key.ToLowerInvariant()) + { + case "fsr_version": h.FsrVersion = ParseInt(val); break; + case "generator": h.Generator = val; break; + case "created_utc": h.CreatedUtc = val; break; + case "creator_id": h.CreatorId = val; break; + case "fw_version": h.FwVersion = ParseInt(val); break; + case "hw_version": h.HwVersion = ParseInt(val); break; + case "make": h.Make = ParseInt(val); break; + case "model": h.Model = ParseInt(val); break; + case "cylinders": h.Cylinders = ParseInt(val); break; + case "generation": h.Generation = ParseInt(val); break; + case "save_type": h.SaveType = val; break; + case "note": h.Note = val; break; + case "mod_engine_block": h.ModEngineBlock = val; break; + case "mod_camshaft": h.ModCamshaft = val; break; + case "mod_exhaust": h.ModExhaust = val; break; + case "mod_air_filter": h.ModAirFilter = val; break; + case "mod_cylinder_head": h.ModCylinderHead = val; break; + case "mod_injector": h.ModInjector = val; break; + case "mod_throttle_body": h.ModThrottleBody = val; break; + case "mod_jack_rod": h.ModJackRod = val; break; + case "sha256": break; // integrity only; not structural + default: h.Extra[key] = val; break; // forward-compat + } + } + + private static void BuildSection(FsrSection s, Dictionary f, List<(string key, string val)> rows) + { + s.Label = f.GetValueOrDefault("label", s.Name); + s.Addr = (ushort)ParseInt(f.GetValueOrDefault("addr", "0")); + s.Length = (byte)ParseInt(f.GetValueOrDefault("length", "0")); + s.Gen = ParseInt(f.GetValueOrDefault("gen", "0")); + + switch (s.Type) + { + case SectionType.Table2D: s.Table2D = Build2D(f, rows); break; + case SectionType.Afr: s.Afr = BuildAfr(f, rows); break; + case SectionType.Table1D: s.Table1D = Build1D(f, rows); break; + case SectionType.SubTable:s.Sub = BuildSub(rows); break; + case SectionType.Misc: s.MiscBytes = BuildBytes(rows); break; + default: + foreach (var kv in f) s.Extra[kv.Key] = kv.Value; + break; + } + } + + private static (byte[] data, byte[] rpm, byte[] load, byte sign, byte maxRaw, byte minRaw, byte mult) Read2DCore( + Dictionary f, List<(string key, string val)> rows) + { + var rpm = ParseHexBytes(f.GetValueOrDefault("rpm_axis", "")); + var load = ParseHexBytes(f.GetValueOrDefault("load_axis", "")); + byte sign = (byte)(ParseInt(f.GetValueOrDefault("signed", "0")) > 0 ? 1 : 0); + byte maxRaw = (byte)ParseInt(f.GetValueOrDefault("max_raw", "0")); + byte minRaw = (byte)ParseInt(f.GetValueOrDefault("min_raw", "0")); + byte mult = (byte)ParseInt(f.GetValueOrDefault("mult", "1")); + var data = new byte[TuningTable.DataBytes]; + foreach (var (key, val) in rows) + { + if (!key.StartsWith("row", StringComparison.OrdinalIgnoreCase)) continue; + int r = ParseInt(key[3..]); + var cells = ParseHexBytes(val); + for (int c = 0; c < cells.Length && c < TuningTable.Cols; c++) + data[r * TuningTable.Cols + c] = cells[c]; + } + return (data, rpm, load, sign, maxRaw, minRaw, mult); + } + + private static TuningTable Build2D(Dictionary f, List<(string, string)> rows) + { + var (data, rpm, load, sign, maxRaw, minRaw, mult) = Read2DCore(f, rows); + return new TuningTable { Data = data, RpmAxis = rpm, LoadAxis = load, Sign = sign, MaxRaw = maxRaw, MinRaw = minRaw, Mult = mult }; + } + + private static AfrTable BuildAfr(Dictionary f, List<(string, string)> rows) + { + var (data, rpm, load, sign, maxRaw, minRaw, mult) = Read2DCore(f, rows); + return new AfrTable { Data = data, RpmAxis = rpm, LoadAxis = load, Sign = sign, MaxRaw = maxRaw, MinRaw = minRaw, Mult = mult }; + } + + private static OneDimTable Build1D(Dictionary f, List<(string key, string val)> rows) + { + var o = new OneDimTable + { + RawSignedFlag = (byte)(ParseInt(f.GetValueOrDefault("raw_signed", "0")) > 0 ? 1 : 0), + ConvSignedFlag = (byte)(ParseInt(f.GetValueOrDefault("conv_signed", "0")) > 0 ? 1 : 0), + RawMultiplier = (byte)ParseInt(f.GetValueOrDefault("raw_mult", "1")), + ConvMultiplier = (byte)ParseInt(f.GetValueOrDefault("conv_mult", "1")), + RawRounding = (byte)ParseInt(f.GetValueOrDefault("raw_round", "0")), + ConvOffset = (sbyte)ParseInt(f.GetValueOrDefault("conv_offset", "0")), + MaxRaw = ParseInt(f.GetValueOrDefault("max_raw", "0")), + MinRaw = ParseInt(f.GetValueOrDefault("min_raw", "0")), + }; + foreach (var (key, val) in rows) + { + if (key.Length < 2 || (key[0] != 'p' && key[0] != 'P')) continue; + int i = ParseInt(key[1..]); + if (i < 0 || i >= OneDimTable.PointCount) continue; + var parts = val.Split(','); + if (parts.Length >= 1) o.RawAxis[i] = ParseInt(parts[0].Trim()); + if (parts.Length >= 2) o.ConvValues[i] = ParseInt(parts[1].Trim()); + } + return o; + } + + private static SubTable BuildSub(List<(string key, string val)> rows) + { + var data = new byte[SubTable.DataBytes]; + foreach (var (key, val) in rows) + { + if (!key.StartsWith("row", StringComparison.OrdinalIgnoreCase)) continue; + int r = ParseInt(key[3..]); + var parts = val.Split(','); + for (int c = 0; c < parts.Length && c < SubTable.Cols; c++) + data[r * SubTable.Cols + c] = unchecked((byte)(sbyte)ParseInt(parts[c].Trim())); + } + return new SubTable { Data = data }; + } + + private static byte[] BuildBytes(List<(string key, string val)> rows) + { + var all = new List(); + foreach (var (key, val) in rows) + if (key.Equals("bytes", StringComparison.OrdinalIgnoreCase)) + all.AddRange(ParseHexBytes(val)); + return all.ToArray(); + } + + // ── Helpers ───────────────────────────────────────────────────────────── + + private static string Hex8(byte b) => "0x" + b.ToString("X2", CultureInfo.InvariantCulture); + private static string Hex16(ushort v) => "0x" + v.ToString("X4", CultureInfo.InvariantCulture); + + private static string HexBytes(byte[] bytes) + { + var sb = new StringBuilder(bytes.Length * 3); + for (int i = 0; i < bytes.Length; i++) + { + if (i > 0) sb.Append(' '); + sb.Append(bytes[i].ToString("X2", CultureInfo.InvariantCulture)); + } + return sb.ToString(); + } + + private static byte[] ParseHexBytes(string s) + { + if (string.IsNullOrWhiteSpace(s)) return Array.Empty(); + var toks = s.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); + var outp = new byte[toks.Length]; + for (int i = 0; i < toks.Length; i++) + { + var tok = toks[i]; + if (tok.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) tok = tok[2..]; + outp[i] = byte.Parse(tok, NumberStyles.HexNumber, CultureInfo.InvariantCulture); + } + return outp; + } + + private static int ParseInt(string s) + { + s = s.Trim(); + if (s.Length == 0) return 0; + if (s.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) + return int.Parse(s[2..], NumberStyles.HexNumber, CultureInfo.InvariantCulture); + return int.Parse(s, NumberStyles.Integer | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture); + } + + private static string Sha256Hex(string body) + { + var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(body)); + var sb = new StringBuilder(bytes.Length * 2); + foreach (var b in bytes) sb.Append(b.ToString("x2", CultureInfo.InvariantCulture)); + return sb.ToString(); + } +} diff --git a/TuneBoss.Core/IO/IMapTableCodec.cs b/TuneBoss.Core/IO/IMapTableCodec.cs new file mode 100644 index 0000000..790687c --- /dev/null +++ b/TuneBoss.Core/IO/IMapTableCodec.cs @@ -0,0 +1,54 @@ +using System.Threading.Tasks; +using TuneBoss.Core.Models; + +namespace TuneBoss.Core.IO; + +/// +/// Serializes / parses the data section of a map file — the space- and +/// __-delimited table dump. Kept behind an interface because its exact +/// table ordering is interop-critical and is filled once the format (legacy-exact +/// vs. new) and the included save-types are confirmed. +/// +/// Implementations live in the app layer, where they can read and write the +/// table view-models that hold the current ECU state. +/// +public interface IMapTableCodec +{ + /// + /// Ensures any device-backed state required to serialize the given type is loaded, + /// re-reading tables whose models are not cached. Called before + /// so a save works even if the user reached this page before a full table load + /// finished (or a table read was missed). Default: nothing to do. + /// + Task PrepareAsync(MapSaveType saveType, int cylinderCount) => Task.CompletedTask; + + /// Runs an on-hardware diagnostic of the user-table read path and returns a report. + Task DiagnoseAsync() => Task.FromResult(string.Empty); + + /// Serializes the current in-app table state into a map data section. + string Serialize(MapSaveType saveType, int cylinderCount); + + /// + /// Writes the currently-applied content for the given save type to the ECU, + /// optionally flashing at the end. Returns a human-readable summary. + /// + Task WriteLoadedAsync(MapSaveType saveType, int cylinderCount, bool flash, + IProgress? progress = null) + => throw new NotImplementedException("Write-to-ECU on load is not wired for this codec."); + + /// Parses a map data section and applies it to the in-app table state. + void Deserialize(string data, MapSaveType saveType, int cylinderCount); + + /// Rebuilds the editor nav trees from the current session layout + /// (used after an offline file establishes a layout, so entries exist to populate). + void RebuildNavTrees() { } + + /// + /// Builds an FSR document from the currently-loaded editors. Walks loaded entries + /// directly and skips anything not loaded (never throws "not loaded"). + /// + FsrFile.FsrDocument BuildFsrFromEditors(Models.EcuInfo? info, MapTag? tag, int cylinderCount); + + /// Applies a parsed FSR document into the editors. + void ApplyFsr(FsrFile.FsrDocument doc); +} diff --git a/TuneBoss.Core/IO/MapCompatibility.cs b/TuneBoss.Core/IO/MapCompatibility.cs new file mode 100644 index 0000000..724997f --- /dev/null +++ b/TuneBoss.Core/IO/MapCompatibility.cs @@ -0,0 +1,44 @@ +using TuneBoss.Core.Models; + +namespace TuneBoss.Core.IO; + +/// +/// Checks whether a loaded map's tag matches the connected ECU. Mirrors the legacy +/// open-time check, which warns (but doesn't hard-block) on make/model mismatch. +/// +public static class MapCompatibility +{ + public enum Result + { + Match, + ModelMismatch, + MakeMismatch, + CylinderMismatch, + } + + public readonly record struct Report(Result Result, string Message) + { + public bool IsMatch => Result == Result.Match; + } + + public static Report Check(MapTag tag, EcuInfo ecu, int connectedCylinders) + { + if (tag.Make != ecu.BikeManufacturer) + return new Report(Result.MakeMismatch, + $"This map is for {BikeRegistry.GetMake((byte)tag.Make)} but the connected unit is " + + $"{BikeRegistry.GetMake(ecu.BikeManufacturer)}. Loading it is not recommended."); + + if (tag.Model != ecu.BikeModel) + return new Report(Result.ModelMismatch, + $"This map is for {BikeRegistry.GetDisplayName((byte)tag.Make, tag.Model)} but the connected unit is " + + $"{BikeRegistry.GetDisplayName(ecu.BikeManufacturer, ecu.BikeModel)}. Loading it is not recommended."); + + if (connectedCylinders > 0 && tag.CylinderCount != connectedCylinders) + return new Report(Result.CylinderMismatch, + $"This map is for a {tag.CylinderCount}-cylinder layout but the connected unit is " + + $"{connectedCylinders}-cylinder."); + + return new Report(Result.Match, + $"Map matches the connected {BikeRegistry.GetDisplayName(ecu.BikeManufacturer, ecu.BikeModel)}."); + } +} diff --git a/TuneBoss.Core/IO/MapFile.cs b/TuneBoss.Core/IO/MapFile.cs new file mode 100644 index 0000000..f10fef8 --- /dev/null +++ b/TuneBoss.Core/IO/MapFile.cs @@ -0,0 +1,77 @@ +using System.Security.Cryptography; +using System.Text; + +namespace TuneBoss.Core.IO; + +/// +/// The on-disk envelope of a TuneBoss .tst map file: +/// +/// MD5(tag)_____tag\nMD5(data)_____data +/// +/// Two records separated by a newline; each record is MD5hex_____payload. +/// The MD5 is upper-case hex with no separators (matching the legacy +/// BitConverter.ToString(...).Replace("-","")). On load, both digests are +/// recomputed and must match or the file is rejected as corrupt/tampered. +/// +public static class MapFile +{ + public const string Extension = ".tst"; + public const string RecordSep = "_____"; + + /// Upper-case, separator-free MD5 hex of a UTF-8 string. + public static string Md5Hex(string s) + { + var hash = MD5.HashData(Encoding.UTF8.GetBytes(s)); + return Convert.ToHexString(hash); // upper-case, no separators + } + + /// Builds the full file text from a tag string and a data string. + public static string BuildEnvelope(string tag, string data) + => $"{Md5Hex(tag)}{RecordSep}{tag}\n{Md5Hex(data)}{RecordSep}{data}"; + + public readonly record struct ParseResult( + bool Ok, + string Tag, + string Data, + string? Error) + { + public static ParseResult Fail(string error) => new(false, "", "", error); + public static ParseResult Success(string tag, string data) => new(true, tag, data, null); + } + + /// + /// Parses and integrity-checks a file's full text. Splits on \r\n or + /// \n, separates each record on _____, and verifies both MD5s. + /// + public static ParseResult TryParse(string fileText) + { + if (string.IsNullOrEmpty(fileText)) + return ParseResult.Fail("File is empty."); + + var lines = fileText.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None); + if (lines.Length < 2) + return ParseResult.Fail("File is not a valid TuneBoss map (missing data record)."); + + var tagRec = SplitOnce(lines[0]); + var dataRec = SplitOnce(lines[1]); + if (tagRec is null || dataRec is null) + return ParseResult.Fail("File is not a valid TuneBoss map (bad record format)."); + + var (tagHash, tag) = tagRec.Value; + var (dataHash, data) = dataRec.Value; + + if (!string.Equals(tagHash, Md5Hex(tag), StringComparison.OrdinalIgnoreCase)) + return ParseResult.Fail("Tag checksum mismatch — the file may be corrupt or edited."); + if (!string.Equals(dataHash, Md5Hex(data), StringComparison.OrdinalIgnoreCase)) + return ParseResult.Fail("Data checksum mismatch — the file may be corrupt or edited."); + + return ParseResult.Success(tag, data); + } + + private static (string Hash, string Payload)? SplitOnce(string record) + { + int i = record.IndexOf(RecordSep, StringComparison.Ordinal); + if (i < 0) return null; + return (record[..i], record[(i + RecordSep.Length)..]); + } +} diff --git a/TuneBoss.Core/IO/MapTableFormat.cs b/TuneBoss.Core/IO/MapTableFormat.cs new file mode 100644 index 0000000..8ac15e4 --- /dev/null +++ b/TuneBoss.Core/IO/MapTableFormat.cs @@ -0,0 +1,139 @@ +using System.Text; +using TuneBoss.Core.Models; + +namespace TuneBoss.Core.IO; + +/// +/// Byte-exact serializer / parser for the table sections inside a .tst map's +/// data string. Replicates the legacy helpers verbatim: +/// +/// 2D : label__data__load__rpm__max min mult sign ____ +/// AFR : label__data__load__rpm____ (no modifiers) +/// Sub : label__data____ (24 data bytes) +/// 1D : label__<24 wire bytes>____ +/// +/// Every value is its unsigned decimal followed by a single space; __ separates +/// fields within a section, ____ terminates each section. Subtable RPM axes are +/// not stored — on load they are derived from the parent 2D table's RPM axis (every +/// 4th breakpoint), matching legacy populateSubTable. +/// +public static class MapTableFormat +{ + public const string SectionSep = "____"; + public const string FieldSep = "__"; + + // ── Value lists ───────────────────────────────────────────────────────────── + private static string Bytes(byte[] a) + { + var sb = new StringBuilder(a.Length * 4); + foreach (var b in a) sb.Append((int)b).Append(' '); // "v v v " + return sb.ToString(); + } + + /// Parses a space-separated decimal list into bytes (empties skipped). + public static byte[] ParseBytes(string s) + { + var parts = s.Split(' ', StringSplitOptions.RemoveEmptyEntries); + var r = new byte[parts.Length]; + for (int i = 0; i < parts.Length; i++) + r[i] = (byte)(int.Parse(parts[i]) & 0xFF); + return r; + } + + // ── Serialize ─────────────────────────────────────────────────────────────── + public static string Section2D(string label, TuningTable t) => + label + FieldSep + Bytes(t.Data) + FieldSep + Bytes(t.LoadAxis) + FieldSep + Bytes(t.RpmAxis) + + FieldSep + $"{t.MaxRaw} {t.MinRaw} {t.Mult} {t.Sign} " + SectionSep; + + public static string SectionAfr(string label, AfrTable t) => + label + FieldSep + Bytes(t.Data) + FieldSep + Bytes(t.LoadAxis) + FieldSep + Bytes(t.RpmAxis) + SectionSep; + + public static string SectionSub(string label, SubTable t) => + label + FieldSep + Bytes(t.Data) + SectionSep; + + public static string Section1D(string label, OneDimTable t) => + label + FieldSep + Bytes(t.ToWirePayload()) + SectionSep; + + /// Generic named byte block (used for the misc regions). label__<bytes>____. + public static string SectionBytes(string label, byte[] data) => + label + FieldSep + Bytes(data) + SectionSep; + + /// Parses a block back into its raw bytes. + public static byte[] ParseBytesSection(string section) + { + var f = Fields(section); + return f.Length > 1 ? ParseBytes(f[1]) : Array.Empty(); + } + + // ── Section splitting ─────────────────────────────────────────────────────── + /// Splits a data string into its ____-terminated sections (positional). + public static string[] SplitSections(string data) => + data.Split(SectionSep, StringSplitOptions.None); + + private static string[] Fields(string section) => + section.Split(FieldSep, StringSplitOptions.None); + + /// The label of a section (its first field), for sanity checks. + public static string LabelOf(string section) => Fields(section)[0]; + + // ── Parse ─────────────────────────────────────────────────────────────────── + public static TuningTable Parse2D(string section) + { + var f = Fields(section); + var data = Fit(ParseBytes(f[1]), TuningTable.DataBytes); + var load = Fit(ParseBytes(f[2]), TuningTable.Rows); + var rpm = Fit(ParseBytes(f[3]), TuningTable.Cols); + var mod = ParseBytes(f.Length > 4 ? f[4] : ""); + return new TuningTable + { + Data = data, LoadAxis = load, RpmAxis = rpm, + MaxRaw = At(mod, 0), MinRaw = At(mod, 1), Mult = At(mod, 2), Sign = At(mod, 3), + }; + } + + public static AfrTable ParseAfr(string section) + { + var f = Fields(section); + return new AfrTable + { + Data = Fit(ParseBytes(f[1]), AfrTable.DataBytes), + LoadAxis = Fit(ParseBytes(f[2]), AfrTable.Rows), + RpmAxis = Fit(ParseBytes(f[3]), AfrTable.Cols), + }; + } + + /// + /// Parses a subtable section. The 12-byte RPM axis is derived from the parent 2D + /// table's 24-byte RPM axis: 6 (lo,hi) pairs taken from indices 4·x and 4·x+3. + /// + public static SubTable ParseSub(string section, byte[] parentRpm) + { + var f = Fields(section); + var sub = new SubTable { Data = Fit(ParseBytes(f[1]), SubTable.DataBytes) }; + for (int x = 0; x < SubTable.Cols; x++) + { + sub.RpmAxis[x * 2] = At(parentRpm, x * 4); + sub.RpmAxis[x * 2 + 1] = At(parentRpm, x * 4 + 3); + } + return sub; + } + + public static OneDimTable Parse1D(string section) + { + var f = Fields(section); + var wire = Fit(ParseBytes(f[1]), OneDimTable.WireLength); + return OneDimTable.FromWire(wire, 0); + } + + // ── Helpers ───────────────────────────────────────────────────────────────── + private static byte At(byte[] a, int i) => i < a.Length ? a[i] : (byte)0; + + /// Returns an array of exactly bytes (pad/truncate). + private static byte[] Fit(byte[] src, int n) + { + if (src.Length == n) return src; + var r = new byte[n]; + Array.Copy(src, r, Math.Min(src.Length, n)); + return r; + } +} diff --git a/TuneBoss.Core/IO/MapTag.cs b/TuneBoss.Core/IO/MapTag.cs new file mode 100644 index 0000000..5826216 --- /dev/null +++ b/TuneBoss.Core/IO/MapTag.cs @@ -0,0 +1,100 @@ +using System.Text; + +namespace TuneBoss.Core.IO; + +/// +/// Which tables a saved map contains. Values match the legacy save-type codes. +/// +public enum MapSaveType +{ + User = 1, // user adjust tables (+ their subtables) + FullTables = 2, // all base + user 2D tables, AFR, subtables, 1D + FullConfig = 4, // FullTables plus the misc / extended config blocks +} + +/// +/// The metadata header of a TuneBoss map file — the legacy "tag", 16 fields joined +/// by ___: +/// creatorID, FW, HW, make, model, cyl, saveType, +/// engineBlock, camshaft, exhaust, airFilter, cylinderHead, injector, throttleBody, jackRod, +/// miscNote +/// +/// The trailing note carries no separator; every other field is followed by ___. +/// +public sealed record MapTag +{ + public const string FieldSep = "___"; + public const int FieldCount = 16; + + public string CreatorId { get; init; } = ""; + public int FwVersion { get; init; } + public int HwVersion { get; init; } + public int Make { get; init; } + public int Model { get; init; } + public int CylinderCount { get; init; } = 1; + public MapSaveType SaveType { get; init; } = MapSaveType.FullConfig; + + public string EngineBlock { get; init; } = "none"; + public string Camshaft { get; init; } = "none"; + public string Exhaust { get; init; } = "none"; + public string AirFilter { get; init; } = "none"; + public string CylinderHead { get; init; } = "none"; + public string Injector { get; init; } = "none"; + public string ThrottleBody { get; init; } = "none"; + public string JackRod { get; init; } = "none"; + + public string MiscNote { get; init; } = "none"; + + /// Serializes to the ___-joined legacy string. + public string Build() + { + var sb = new StringBuilder(); + void F(string v) => sb.Append(v).Append(FieldSep); + + F(CreatorId); + F(FwVersion.ToString()); + F(HwVersion.ToString()); + F(Make.ToString()); + F(Model.ToString()); + F(CylinderCount.ToString()); + F(((int)SaveType).ToString()); + F(EngineBlock); + F(Camshaft); + F(Exhaust); + F(AirFilter); + F(CylinderHead); + F(Injector); + F(ThrottleBody); + F(JackRod); + sb.Append(MiscNote); // no trailing separator + return sb.ToString(); + } + + /// Parses a ___-joined tag string. Tolerates a short mod section. + public static MapTag Parse(string tag) + { + var f = tag.Split(FieldSep); + string At(int i) => i < f.Length ? f[i] : ""; + int AtInt(int i) => int.TryParse(At(i), out var v) ? v : 0; + + return new MapTag + { + CreatorId = At(0), + FwVersion = AtInt(1), + HwVersion = AtInt(2), + Make = AtInt(3), + Model = AtInt(4), + CylinderCount = AtInt(5) is var c && c > 0 ? c : 1, + SaveType = (MapSaveType)AtInt(6), + EngineBlock = At(7), + Camshaft = At(8), + Exhaust = At(9), + AirFilter = At(10), + CylinderHead = At(11), + Injector = At(12), + ThrottleBody = At(13), + JackRod = At(14), + MiscNote = At(15), + }; + } +} diff --git a/TuneBoss.Core/Models/AfrTable.cs b/TuneBoss.Core/Models/AfrTable.cs new file mode 100644 index 0000000..0eb753b --- /dev/null +++ b/TuneBoss.Core/Models/AfrTable.cs @@ -0,0 +1,221 @@ +namespace TuneBoss.Core.Models; + +/// +/// Data model for an AFR Target table (AFR_Target1, AFR_Target2). +/// +/// Structurally identical to TuningTable (24 cols × 8 rows, same split read/write, +/// same wire layout) but with a critical difference in value encoding: +/// +/// ── Fixed-point ×10 encoding ───────────────────────────────────────────────── +/// All cell values are stored as byte × 10 on the wire. +/// Wire byte 145 = AFR 14.5, byte 137 = AFR 13.7, etc. +/// Display range set by caller: minDataVal=0.0, maxDataVal=15.0 (from populateInitTables) +/// +/// ── Modifier encoding ───────────────────────────────────────────────────────── +/// MaxRaw / MinRaw are also stored ×10 on wire: +/// modifiersInArray[0] = (byte)(maxRawVal * 10.0) +/// modifiersInArray[1] = (byte)(minRawVal * 10.0) +/// modifiersInArray[2] = (byte)multRawVal (same as TuningTable) +/// modifiersInArray[3] = (byte)signRawVal (same as TuningTable) +/// Confirmed from writeBtn_Click and prepareAllData() in TuningTablePanelAFR.cs. +/// +/// ── Button increments ──────────────────────────────────────────────────────── +/// +/- large = 5.0 AFR (minusFive_Click / plusFive_Click) +/// +/- small = 0.1 AFR (minusOne_Click / plusOne_Click) ← different from TuningTable +/// Validated as double, displayed as "N1" (1 decimal place). +/// +/// ── Wire format ────────────────────────────────────────────────────────────── +/// Identical layout to TuningTable (228 bytes, split at 0x7F): +/// [0..191] Data — 192 bytes, row-major, each byte = AFR × 10 +/// [192..199] Load — 8 bytes +/// [200..223] RPM — 24 bytes, each × 100 = display RPM +/// [224] MaxRaw — stored as byte = maxAFR × 10 +/// [225] MinRaw — stored as byte = minAFR × 10 +/// [226] Mult +/// [227] Sign +/// +/// Read length from populateInitTables: 0xEF (239) — larger than TuningTable's 0xE3. +/// +public sealed record AfrTable +{ + public const int Cols = 24; + public const int Rows = 8; + public const int DataBytes = Cols * Rows; // 192 + public const int SplitFirstLength = 0x7F; // 127 — same as TuningTable + public const int TotalPayloadBytes = DataBytes + Rows + Cols + 4; // 228 + public const byte ReadLength = 0xEF; // 239 — from populateInitTables + + // ── Raw wire arrays ─────────────────────────────────────────────────────── + /// 192 bytes, row-major [row * 24 + col]. Wire value = AFR × 10. + public byte[] Data { get; init; } = new byte[DataBytes]; + + /// 8 bytes — load axis (0–110). + public byte[] LoadAxis { get; init; } = new byte[Rows]; + + /// 24 bytes — RPM axis, each × 100 = display RPM. + public byte[] RpmAxis { get; init; } = new byte[Cols]; + + // ── Modifiers [224–227] ─────────────────────────────────────────────────── + /// Wire: maxAFR × 10. E.g. byte 150 = AFR 15.0. + public byte MaxRaw { get; init; } + + /// Wire: minAFR × 10. E.g. byte 0 = AFR 0.0. + public byte MinRaw { get; init; } + + public byte Mult { get; init; } + public byte Sign { get; init; } + + // ── Derived display values ──────────────────────────────────────────────── + public bool IsSigned => Sign > 0; + + /// Display AFR value for a cell (wire byte ÷ 10.0). + public double GetCell(int row, int col) + { + byte raw = Data[row * Cols + col]; + return IsSigned + ? unchecked((sbyte)raw) / 10.0 + : raw / 10.0; + } + + /// Max AFR display value. + public double MaxAfrDisplay => IsSigned + ? unchecked((sbyte)MaxRaw) / 10.0 + : MaxRaw / 10.0; + + /// Min AFR display value. + public double MinAfrDisplay => IsSigned + ? unchecked((sbyte)MinRaw) / 10.0 + : MinRaw / 10.0; + + /// RPM axis in display units (raw × 100). + public int[] RpmValues => RpmAxis.Select(r => r * 100).ToArray(); + + /// Load axis values (raw, 0–110). + public int[] LoadValues => LoadAxis.Select(l => (int)l).ToArray(); + + // ── Serialisation ───────────────────────────────────────────────────────── + + /// + /// Builds the combined 228-byte write payload. + /// Matches prepareAllData() / writeBtn_Click() in TuningTablePanelAFR.cs. + /// Modifier bytes [224–225] are stored as AFR × 10. + /// + public byte[] ToWirePayload() + { + var buf = new byte[TotalPayloadBytes]; + Buffer.BlockCopy(Data, 0, buf, 0, DataBytes); + Buffer.BlockCopy(LoadAxis,0, buf, DataBytes, Rows); + Buffer.BlockCopy(RpmAxis, 0, buf, DataBytes + Rows, Cols); + buf[DataBytes + Rows + Cols] = MaxRaw; + buf[DataBytes + Rows + Cols + 1] = MinRaw; + buf[DataBytes + Rows + Cols + 2] = Mult; + buf[DataBytes + Rows + Cols + 3] = Sign; + return buf; + } + + public byte[] ToWirePayloadPart1() => ToWirePayload()[..(SplitFirstLength + 1)]; + public byte[] ToWirePayloadPart2() => ToWirePayload()[(SplitFirstLength + 1)..]; + + // ── Deserialisation ─────────────────────────────────────────────────────── + + /// + /// Parses a combined 228-byte buffer from two split read responses. + /// Matches sendReadSplitTableToPanelThread (AFR path) in Form1_TableHandling.cs. + /// + public static AfrTable FromWirePayload(byte[] combined) + { + if (combined.Length < TotalPayloadBytes) + throw new ArgumentException( + $"Expected {TotalPayloadBytes} bytes, got {combined.Length}.", nameof(combined)); + + var data = new byte[DataBytes]; + var loadAxis = new byte[Rows]; + var rpmAxis = new byte[Cols]; + + Buffer.BlockCopy(combined, 0, data, 0, DataBytes); + Buffer.BlockCopy(combined, DataBytes, loadAxis,0, Rows); + Buffer.BlockCopy(combined, DataBytes + Rows, rpmAxis, 0, Cols); + + int modBase = DataBytes + Rows + Cols; + return new AfrTable + { + Data = data, + LoadAxis = loadAxis, + RpmAxis = rpmAxis, + MaxRaw = combined[modBase], + MinRaw = combined[modBase + 1], + Mult = combined[modBase + 2], + Sign = combined[modBase + 3], + }; + } + + /// + /// Assembles from two raw device response buffers (data starts at offset 4). + /// + public static AfrTable FromSplitResponses(byte[] part1Response, byte[] part2Response) + { + var combined = new byte[TotalPayloadBytes]; + Buffer.BlockCopy(part1Response, 4, combined, 0, SplitFirstLength + 1); + int part2Len = TotalPayloadBytes - (SplitFirstLength + 1); + Buffer.BlockCopy(part2Response, 4, combined, SplitFirstLength + 1, part2Len); + return FromWirePayload(combined); + } + + // ── Mutation ────────────────────────────────────────────────────────────── + + /// + /// Returns a new AfrTable with cell (row, col) adjusted by delta (in AFR units, e.g. 0.1). + /// Delta is converted to wire units (×10) before clamping. + /// Matches minusButton/addButton in TuningTablePanelAFR.cs. + /// + public AfrTable WithCellAdjusted(int row, int col, double deltaAfr, + double minAfr = 0.0, double maxAfr = 15.0) + { + var newData = (byte[])Data.Clone(); + int idx = row * Cols + col; + + double current = GetCell(row, col); + double adjusted = Math.Clamp(current + deltaAfr, minAfr, maxAfr); + + // Round to 1 decimal place then encode ×10 + double rounded = Math.Round(adjusted, 1, MidpointRounding.AwayFromZero); + newData[idx] = IsSigned + ? unchecked((byte)(sbyte)(rounded * 10.0)) + : (byte)(rounded * 10.0); + + return new AfrTable + { + Data = newData, + LoadAxis = LoadAxis, + RpmAxis = RpmAxis, + MaxRaw = MaxRaw, + MinRaw = MinRaw, + Mult = Mult, + Sign = Sign, + }; + } + + // ── Convenience ────────────────────────────────────────────────────────── + + /// + /// Returns modifier bytes as stored on wire. + /// MaxRaw/MinRaw are AFR × 10; Mult/Sign are unchanged. + /// + public byte[] ToModifierBytes() => new[] + { + MaxRaw, MinRaw, Mult, Sign + }; + + /// + /// Builds modifier bytes from display AFR values for writing. + /// Matches: modifiersInArray[0] = (byte)(maxRawVal * 10.0) + /// + public static byte[] BuildModifierBytes(double maxAfr, double minAfr, + byte mult = 1, byte sign = 0) => new[] + { + (byte)(maxAfr * 10.0), + (byte)(minAfr * 10.0), + mult, + sign + }; +} diff --git a/TuneBoss.Core/Models/BikeRegistry.cs b/TuneBoss.Core/Models/BikeRegistry.cs new file mode 100644 index 0000000..7da05f5 --- /dev/null +++ b/TuneBoss.Core/Models/BikeRegistry.cs @@ -0,0 +1,109 @@ +namespace TuneBoss.Core.Models; + +/// +/// Bike manufacturer and model registry. +/// To add a new make: add a new entry to Manufacturers. +/// To add a new model: add a new entry to the Models list for that make. +/// +public static class BikeRegistry +{ + // ── Manufacturer codes ──────────────────────────────────────────────────── + public const byte Yamaha = 1; + public const byte Honda = 2; + public const byte Modenas = 5; + public const byte Suzuki = 6; + + // ── Registry ────────────────────────────────────────────────────────────── + private static readonly Dictionary Models)> _registry + = new() + { + [Yamaha] = ("Yamaha", new() + { + [1] = "FZ150i (2008–2013)", + [2] = "Lagenda 115z EFi", + [3] = "FZ150i (2014)", + [4] = "YZF R15 (2008–2013)", + [5] = "YZF R15 (2014)", + [6] = "Y15ZR / Exciter 150 / MX King 150", + [7] = "FZ150i / YZF R15", + [8] = "FZ150i (2016)", + [9] = "MSLAZ 2015", + [10] = "YZF R25 2018", + [11] = "YZF R3 2015", + [13] = "YZF R15 2015", + [14] = "NMAX", + [15] = "NVX", + [16] = "Y15ZR 2019", + [17] = "Y16ZR", + [18] = "135LC Fi", + [19] = "XMAX", + [20] = "XMAX V2", + [21] = "R15M 2022", + [22] = "MT15 2022", + [23] = "EGO AVANTIZ", + [24] = "R125 2019", + [25] = "R25 2019", + [26] = "R3 2019", + [27] = "R125 2008", + [28] = "XMAX V3", + [29] = "NVX V1", + [30] = "PG1 / EZ115", + }), + + [Honda] = ("Honda", new() + { + [1] = "Dream110 / Wave110 / Wave125 / MSX125", + [2] = "PCX", + [3] = "RS150R / Winner150", + [4] = "CBR250", + [5] = "CRF250L (2013)", + [6] = "CRF250L (2017)", + [7] = "EX5", + [8] = "RSX", + }), + + [Modenas] = ("Modenas", new() + { + [1] = "VF3i", + }), + + [Suzuki] = ("Suzuki", new() + { + [1] = "Raider R150", + }), + }; + + // ── Lookups ─────────────────────────────────────────────────────────────── + + /// Returns the manufacturer name, or empty string if unknown. + public static string GetMake(byte makeCode) + => _registry.TryGetValue(makeCode, out var entry) ? entry.Make : string.Empty; + + /// Returns the model name, or empty string if unknown. + public static string GetModel(byte makeCode, int modelCode) + { + if (!_registry.TryGetValue(makeCode, out var entry)) return string.Empty; + return entry.Models.TryGetValue(modelCode, out var name) ? name : string.Empty; + } + + /// Returns "Make — Model" display string, e.g. "Yamaha — Y15ZR 2019". + public static string GetDisplayName(byte makeCode, int modelCode) + { + string make = GetMake(makeCode); + string model = GetModel(makeCode, modelCode); + + if (string.IsNullOrEmpty(make)) return $"Unknown ({makeCode}/{modelCode})"; + if (string.IsNullOrEmpty(model)) return $"{make} — Unknown model ({modelCode})"; + return $"{make} — {model}"; + } + + /// All registered manufacturers. + public static IEnumerable<(byte Code, string Name)> AllMakes + => _registry.Select(kv => (kv.Key, kv.Value.Make)); + + /// All models for a given manufacturer code. + public static IEnumerable<(int Code, string Name)> ModelsFor(byte makeCode) + => _registry.TryGetValue(makeCode, out var entry) + ? entry.Models.Select(kv => (kv.Key, kv.Value)) + : Enumerable.Empty<(int, string)>(); +} diff --git a/TuneBoss.Core/Models/DiagnosticsFrame.cs b/TuneBoss.Core/Models/DiagnosticsFrame.cs new file mode 100644 index 0000000..9da4e5d --- /dev/null +++ b/TuneBoss.Core/Models/DiagnosticsFrame.cs @@ -0,0 +1,417 @@ +namespace TuneBoss.Core.Models; + +/// +/// Parsed APP_MONITORING (0x70) streaming diagnostics frame. +/// +/// ── Wire layout — 36 bytes (value[0..35]) ──────────────────────────────────── +/// Sourced from UpdateDiagLabel() and label assignment logic in the WinForms app. +/// Column mapping confirmed from tableLayoutPanel1 Designer.cs: +/// col 0/2 = definition label (static text) +/// col 1/3 = value label (updated each frame) +/// +/// Byte Channel Notes / Display +/// ───── ───────────────────────── ────────────────────────────────────────── +/// [0] (TL command = 0x70) Packet type, not a data channel +/// [1] (reserved / seq) +/// [2] (reserved) +/// [3] (reserved) +/// [4] Load Raw load value +/// [5] RPM_raw × 100 = display RPM +/// [6] Baro_kPa Barometric pressure kPa +/// [7] VBAT_deciV Battery voltage (decivolts) +/// [8] FuelStartAngle1_raw × 3 = display degrees (label71) +/// [9] FuelStartAngle2_raw × 3 = display degrees (label71a) +/// [10] FuelPW1_lo Combined: [10] + 256×[11] = fuel PW 1 +/// [11] FuelPW1_hi +/// [12] SparkAngle1 unchecked sbyte +/// [13] SparkAngle2 unchecked sbyte +/// [14] CrankSyncLostCounter +/// [15] SparkPulseWidth +/// [16] FuelEndAngle_lo Combined: [16] + 256×[17] +/// [17] FuelEndAngle_hi +/// [18] TPS_Raw Raw TPS value (label78 = "TPS Raw") +/// [19] CrankState_packed [19] & 0x0F = CrankState, [19] & 0xF0 >> 4 = TC_Mode +/// [20] ETEMP_DegC Engine temperature °C +/// [21] IAT_DegC Intake air temperature °C +/// [22] TPS_Percent TPS as percentage (used for gauge + tracker) +/// [23] MAP_kPa Manifold absolute pressure kPa +/// [24] O2_AirFuel_x10 AFR × 10 (e.g. 145 = 14.5 AFR) +/// [25] MAP_Lo_Avg_kPa +/// [26] MAP_Hi_Avg_kPa + ([29] & 0x10) × 16 = extra speed bit (2026/04/06) +/// [27] Baro_Dynamic +/// [28] ThrottleState_packed [28] & 0x0F = ThrottleState, [28] & 0x10 = FuelPW_Limit +/// [29] RPMState_packed [29] & 0x0F = RPMState, [29] & 0x80 = StayTuned, +/// [29] & 0x20 = Mode, [29] & 0x10 = extra speed bit +/// [30] UMState_packed [30] & 0x0F = UMState, [30] & 0xF0 >> 4 = GearRatio +/// [31] ErrorState1 Bit-packed analog errors (current) +/// [32] ErrorState2 Bit-packed output errors (current) +/// [33] ErrorState1_Persistent Bit-packed analog errors (persistent) +/// [34] ErrorState2_Persistent Bit-packed output errors (persistent) (also captureError arg 3) +/// [35] ErrorState_Extra Bit-packed output errors persistent (captureError arg 4) +/// +/// ── Tracker channels ────────────────────────────────────────────────────────── +/// Load tracker : uses value[4] (Load) +/// RPM tracker : uses value[5] (RPM_raw) +/// TPS tracker : uses value[22] (TPS_Percent) ← for user-adjust tables (diag4/5/10/11/12) +/// +/// ── CrankState display values ───────────────────────────────────────────────── +/// 5 = Yellow (near-sync), 6 = Green (running), other = Red (lost/searching) +/// +/// ── UMState display values ──────────────────────────────────────────────────── +/// 0=INIT, 1=STOP, 2=START, 3=RUN, 4=CUT, 5=SAFEMODE_RUN, 6=SAFEMODE_CUT, +/// 7=LAUNCHBOSS, 8=LAUNCHBOSS_CUT +/// +public sealed class DiagnosticsFrame +{ + public const int FrameBytes = 36; + + // ── Identity ───────────────────────────────────────────────────────────── + public byte SeqNum { get; init; } + public DateTime ReceivedAt { get; init; } + + // ── Primary channels ───────────────────────────────────────────────────── + public byte Load { get; init; } // [4] + public byte RPM_Raw { get; init; } // [5] × 100 = RPM + public byte Baro_kPa { get; init; } // [6] + public byte VBAT_deciV { get; init; } // [7] + + // ── Fuel channels ──────────────────────────────────────────────────────── + public byte FuelStartAngle1_Raw { get; init; } // [8] × 3 = degrees + public byte FuelStartAngle2_Raw { get; init; } // [9] × 3 = degrees + public int FuelPulseWidth1 { get; init; } // [10] + 256×[11] + public int FuelEndAngle { get; init; } // [16] + 256×[17] + + // ── Spark channels ──────────────────────────────────────────────────────── + public sbyte SparkAngle1 { get; init; } // [12] sbyte + public sbyte SparkAngle2 { get; init; } // [13] sbyte + public byte SparkPulseWidth { get; init; } // [15] + + // ── Crank ──────────────────────────────────────────────────────────────── + public byte CrankSyncLostCounter { get; init; } // [14] + public byte CrankState_Raw { get; init; } // [19] raw packed byte + public byte TPS_Raw { get; init; } // [18] + + // ── Sensor channels ────────────────────────────────────────────────────── + public byte ETEMP_DegC { get; init; } // [20] + public byte IAT_DegC { get; init; } // [21] + public byte TPS_Percent { get; init; } // [22] + public byte MAP_kPa { get; init; } // [23] + public byte O2_AFR_x10 { get; init; } // [24] ÷ 10 = AFR + public byte MAP_Lo_Avg { get; init; } // [25] + public byte MAP_Hi_Avg_Raw{ get; init; } // [26] raw (extra bit in [29]) + public byte Baro_Dynamic { get; init; } // [27] + + // ── State packed bytes ──────────────────────────────────────────────────── + public byte ThrottleState_Packed { get; init; } // [28] + public byte RPMState_Packed { get; init; } // [29] + public byte UMState_Packed { get; init; } // [30] + + // ── Error bytes ────────────────────────────────────────────────────────── + // captureError(value[32], value[33], value[34], value[35]) + // = captureError(analogError, analogErrorP, outputError, outputErrorP) + public byte ErrorsFatal { get; init; } // [31] raw display only (label91) + public byte AnalogError_Current { get; init; } // [32] analogError + public byte AnalogError_Persistent { get; init; } // [33] analogErrorP + public byte OutputError_Current { get; init; } // [34] outputError + public byte OutputError_Persistent { get; init; } // [35] outputErrorP + + // ── Derived display values ──────────────────────────────────────────────── + public int RPM => RPM_Raw * 100; + public int FuelStartAngle1_Deg => FuelStartAngle1_Raw * 3; + public int FuelStartAngle2_Deg => FuelStartAngle2_Raw * 3; + public double O2_AFR => O2_AFR_x10 / 10.0; + public double VBAT_Volts => VBAT_deciV / 10.0; + + // [19] CrankState nibbles + public int CrankState => CrankState_Raw & 0x0F; + public int TC_Mode => (CrankState_Raw & 0xF0) >> 4; + + // [28] ThrottleState + public ThrottleStateValue ThrottleState => (ThrottleStateValue)(ThrottleState_Packed & 0x0F); + public bool FuelPW_LimitActive => (ThrottleState_Packed & 0x10) != 0; + + // [29] RPM State + public RPMStateValue RPMState => (RPMStateValue)(RPMState_Packed & 0x0F); + public bool StayTunedRunning => (RPMState_Packed & 0x80) != 0; + public bool ModeSelected => (RPMState_Packed & 0x20) != 0; + public bool SpeedExtraBit => (RPMState_Packed & 0x10) != 0; + + // [26] Meter speed with extra bit from [29] (added 2026/04/06) + public int MeterSpeed => MAP_Hi_Avg_Raw + (SpeedExtraBit ? 0x10 * 16 : 0); + + // [30] UM State + public UMStateValue UMState => (UMStateValue)(UMState_Packed & 0x0F); + public int GearRatio => (UMState_Packed & 0xF0) >> 4; + + // ── Error flags ─────────────────────────────────────────────────────────── + public bool[] AnalogErrors_Current => UnpackBits(AnalogError_Current); + public bool[] OutputErrors_Current => UnpackBits(OutputError_Current); + public bool[] AnalogErrors_Persistent => UnpackBits(AnalogError_Persistent); + public bool[] OutputErrors_Persistent => UnpackBits(OutputError_Persistent); + + public bool HasActiveError => + AnalogError_Current != 0 || OutputError_Current != 0; + + /// Parsed error flags — ready to drive the 16-indicator error panel. + public ErrorFlags Errors => ErrorFlags.From(this); + + // ── Parser ──────────────────────────────────────────────────────────────── + + /// + /// Parses a raw diagnostics frame payload. + /// is the full BLE packet payload starting at byte [0] = 0x70. + /// Byte indices in comments refer to the payload array as used in UpdateDiagLabel(). + /// + public static DiagnosticsFrame Parse(byte[] data, byte seqNum, DateTime? receivedAt = null) + { + if (data.Length < FrameBytes) + throw new ArgumentException( + $"Expected at least {FrameBytes} bytes, got {data.Length}.", nameof(data)); + + return new DiagnosticsFrame + { + SeqNum = seqNum, + ReceivedAt = receivedAt ?? DateTime.UtcNow, + + Load = data[4], + RPM_Raw = data[5], + Baro_kPa = data[6], + VBAT_deciV = data[7], + + FuelStartAngle1_Raw = data[8], + FuelStartAngle2_Raw = data[9], + FuelPulseWidth1 = data[10] + (256 * data[11]), + SparkAngle1 = unchecked((sbyte)data[12]), + SparkAngle2 = unchecked((sbyte)data[13]), + CrankSyncLostCounter = data[14], + SparkPulseWidth = data[15], + FuelEndAngle = data[16] + (256 * data[17]), + + TPS_Raw = data[18], + CrankState_Raw = data[19], + + ETEMP_DegC = data[20], + IAT_DegC = data[21], + TPS_Percent = data[22], + MAP_kPa = data[23], + O2_AFR_x10 = data[24], + MAP_Lo_Avg = data[25], + MAP_Hi_Avg_Raw = data[26], + Baro_Dynamic = data[27], + + ThrottleState_Packed = data[28], + RPMState_Packed = data[29], + UMState_Packed = data[30], + + ErrorsFatal = data[31], + AnalogError_Current = data[32], + AnalogError_Persistent = data[33], + OutputError_Current = data[34], + OutputError_Persistent = data[35], + }; + } + + // ── CSV log format ──────────────────────────────────────────────────────── + + /// + /// Returns a CSV log row matching the format in UpdateDiagLabel(). + /// Columns match the .tbd log format used by TracBoss. + /// + public string ToCsvRow(string timestamp) => + $"{timestamp}," + + $"{Load}," + + $"{RPM}," + + $"{Baro_kPa}," + + $"{VBAT_deciV}," + + $"{FuelPulseWidth1}," + + $"{FuelEndAngle}," + + $"{SparkAngle1}," + + $"{SparkAngle2}," + + $"{CrankSyncLostCounter}," + + $"{SparkPulseWidth}," + + $"{FuelEndAngle}," + + $"{TPS_Raw}," + + $"{CrankState_Raw}," + + $"{ETEMP_DegC}," + + $"{IAT_DegC}," + + $"{TPS_Percent}," + + $"{MAP_kPa}," + + $"{O2_AFR_x10}," + + $"{MAP_Lo_Avg}," + + $"{MAP_Hi_Avg_Raw}," + + $"{Baro_Dynamic}," + + $"{ThrottleState_Packed}," + + $"{RPMState_Packed}," + + $"{UMState_Packed}," + + $"{AnalogError_Current}," + + $"{OutputError_Current}," + + $"{AnalogError_Persistent}," + + $"{OutputError_Persistent},"; + + // ── Helpers ─────────────────────────────────────────────────────────────── + private static bool[] UnpackBits(byte b) => + Enumerable.Range(0, 8).Select(i => (b & (1 << i)) != 0).ToArray(); +} + +// ── State enums ─────────────────────────────────────────────────────────────── + +public enum ThrottleStateValue : byte +{ + Steady = 0, + Accel = 1, + Decel = 2, +} + +public enum RPMStateValue : byte +{ + Steady = 0, + Decel = 1, + Accel = 2, +} + +public enum UMStateValue : byte +{ + Init = 0, + Stop = 1, + Start = 2, + Run = 3, + Cut = 4, + SafeMode_Run = 5, + SafeMode_Cut = 6, + LaunchBoss = 7, + LaunchBoss_Cut = 8, +} + +/// +/// Diagnostics tracker coordinates for highlighting the active cell +/// in a tuning table grid. Produced by getRpmToHighlight/getLoadToHighlight. +/// +public sealed record DiagnosticsTracker( + int ColHighlight, // exact RPM column + int ColLowlight, // next RPM column + int RowHighlight, // exact load/TPS row + int RowLowlight); // next load/TPS row + +/// +/// Parsed error flags from the four error bytes in a DiagnosticsFrame. +/// +/// Call site (UpdateDiagLabel): captureError(value[32], value[33], value[34], value[35]) +/// analogError = [32] AnalogError_Current +/// analogErrorP = [33] AnalogError_Persistent +/// outputError = [34] OutputError_Current +/// outputErrorP = [35] OutputError_Persistent +/// +/// Display: Red = active now, Yellow = persistent (ever triggered), Green = clear +/// +/// ── Analog errors (err1–err8) bit map ──────────────────────────────────────── +/// Bit 0 err1 Throttle Position Sensor +/// Bit 1 err2 Manifold Air Pressure Sensor +/// Bit 2 err3 Intake Air Temperature Sensor +/// Bit 3 err4 Vehicle Down Sensor +/// Bit 4 err5 Engine Temperature Sensor +/// Bit 5 err6 Oxygen Sensor +/// Bit 6 err7 Battery Voltage +/// Bit 7 err8 Aux +/// +/// ── Output errors (err9o–err16o) bit map ───────────────────────────────────── +/// Bit 0 err9o Injector 1 +/// Bit 1 err10o Injector 2 / Idle Solenoid +/// Bit 2 err11o Fuel Pump +/// Bit 3 err12o Radiator Fan +/// Bit 4 err13o Spark Ignition 1 +/// Bit 5 err14o Spark Ignition 2 +/// Bit 6 err15o 5V PSU +/// Bit 7 err16o O2H +/// +public sealed class ErrorFlags +{ + // ── Raw bytes ───────────────────────────────────────────────────────────── + public byte AnalogCurrent { get; init; } // value[32] + public byte AnalogPersistent { get; init; } // value[33] + public byte OutputCurrent { get; init; } // value[34] + public byte OutputPersistent { get; init; } // value[35] + + // ── Analog error channels ───────────────────────────────────────────────── + public ErrorStatus TPS => Get(AnalogCurrent, AnalogPersistent, 0); + public ErrorStatus MAP => Get(AnalogCurrent, AnalogPersistent, 1); + public ErrorStatus IAT => Get(AnalogCurrent, AnalogPersistent, 2); + public ErrorStatus VehicleDown => Get(AnalogCurrent, AnalogPersistent, 3); + public ErrorStatus ETemp => Get(AnalogCurrent, AnalogPersistent, 4); + public ErrorStatus OxygenSensor=> Get(AnalogCurrent, AnalogPersistent, 5); + public ErrorStatus BattVoltage => Get(AnalogCurrent, AnalogPersistent, 6); + public ErrorStatus Aux => Get(AnalogCurrent, AnalogPersistent, 7); + + // ── Output error channels ───────────────────────────────────────────────── + public ErrorStatus Injector1 => Get(OutputCurrent, OutputPersistent, 0); + public ErrorStatus Injector2_IdleSol => Get(OutputCurrent, OutputPersistent, 1); + public ErrorStatus FuelPump => Get(OutputCurrent, OutputPersistent, 2); + public ErrorStatus RadiatorFan => Get(OutputCurrent, OutputPersistent, 3); + public ErrorStatus SparkIgnition1 => Get(OutputCurrent, OutputPersistent, 4); + public ErrorStatus SparkIgnition2 => Get(OutputCurrent, OutputPersistent, 5); + public ErrorStatus PSU_5V => Get(OutputCurrent, OutputPersistent, 6); + public ErrorStatus O2Heater => Get(OutputCurrent, OutputPersistent, 7); + + // ── Summary ─────────────────────────────────────────────────────────────── + public bool HasActiveError => + AnalogCurrent != 0 || OutputCurrent != 0; + + /// All 16 error channels in display order (analog first, then output). + public IEnumerable<(string Name, ErrorStatus Status)> AllErrors() + { + yield return ("Throttle Position Sensor", TPS); + yield return ("Manifold Air Pressure Sensor", MAP); + yield return ("Intake Air Temperature Sensor", IAT); + yield return ("Vehicle Down Sensor", VehicleDown); + yield return ("Engine Temperature Sensor", ETemp); + yield return ("Oxygen Sensor", OxygenSensor); + yield return ("Battery Voltage", BattVoltage); + yield return ("Aux", Aux); + yield return ("Injector 1", Injector1); + yield return ("Injector 2 / Idle Solenoid", Injector2_IdleSol); + yield return ("Fuel Pump", FuelPump); + yield return ("Radiator Fan", RadiatorFan); + yield return ("Spark Ignition 1", SparkIgnition1); + yield return ("Spark Ignition 2", SparkIgnition2); + yield return ("5V PSU", PSU_5V); + yield return ("O2 Heater", O2Heater); + } + + // ── Factory ─────────────────────────────────────────────────────────────── + public static ErrorFlags From(DiagnosticsFrame frame) => new() + { + AnalogCurrent = frame.AnalogError_Current, + AnalogPersistent = frame.AnalogError_Persistent, + OutputCurrent = frame.OutputError_Current, + OutputPersistent = frame.OutputError_Persistent, + }; + + public static ErrorFlags Clear => new() + { + AnalogCurrent = 0, AnalogPersistent = 0, + OutputCurrent = 0, OutputPersistent = 0, + }; + + // ── Helper ──────────────────────────────────────────────────────────────── + private static ErrorStatus Get(byte current, byte persistent, int bit) + { + bool isActive = (current & (1 << bit)) != 0; + bool wasPersistent= (persistent & (1 << bit)) != 0; + + if (isActive) return ErrorStatus.Active; + if (wasPersistent) return ErrorStatus.Persistent; + return ErrorStatus.Clear; + } +} + +/// +/// Three-state error status matching the traffic-light display: +/// Active = Red (currently faulted) +/// Persistent = Yellow (was faulted this session, now cleared) +/// Clear = Green (no fault) +/// +public enum ErrorStatus +{ + Clear, + Persistent, + Active, +} diff --git a/TuneBoss.Core/Models/EcuInfo.cs b/TuneBoss.Core/Models/EcuInfo.cs new file mode 100644 index 0000000..fcb3ca6 --- /dev/null +++ b/TuneBoss.Core/Models/EcuInfo.cs @@ -0,0 +1,190 @@ +namespace TuneBoss.Core.Models; + +/// +/// Parsed response from APP_READ_INFO (0x37). +/// Immutable — constructed once per successful read. +/// +public sealed class EcuInfo +{ + // ── Identity ───────────────────────────────────────────────────────────── + public string Username { get; init; } = string.Empty; + public string UniqueId { get; init; } = string.Empty; // "AABBCCDD-EEFF0011-..." + + // ── Version ────────────────────────────────────────────────────────────── + public byte FwVersion { get; init; } + public byte HwVersion { get; init; } + public byte FwVersion2 { get; init; } // Only present if buffer > 68 + public byte FwSubVersion2 { get; init; } + public byte TableVersion { get; init; } + public byte HwComponentVersion { get; init; } + public byte AppInfoVersion { get; init; } // Generation discriminator + + // ── Bike identity ──────────────────────────────────────────────────────── + public byte BikeManufacturer { get; init; } // 1=Yamaha 2=Honda 3=Kawasaki 6=Suzuki + public byte BikeModel { get; init; } + + // ── Usage counters ─────────────────────────────────────────────────────── + public uint FlashWriteCount { get; init; } + public uint SwitchToggleCount { get; init; } + public byte PwdResetCount { get; init; } + + // ── Dates ──────────────────────────────────────────────────────────────── + public DateOnly? ProgrammingDate { get; init; } + public DateOnly? FirstUseDate { get; init; } + public byte FirstUseInfo0 { get; init; } // raw buf[32] (FirstUseDate DD) + public byte FirstUseInfo1 { get; init; } // raw buf[33] — TPS cal-done flag (Android UIfirstUseDate[1]) + public DateOnly? FirstFlashDate { get; init; } + + // ── Upgrade flags ──────────────────────────────────────────────────────── + public byte UpgradeRpmMax { get; init; } // × 100 = actual RPM limit + public byte UpgradeShiftAuto { get; init; } + public byte UpgradeLogImmo { get; init; } // low nibble = legacy Upgrade_Stage3 (see Stage) + public byte UpgradeFuture12 { get; init; } + public byte UpgradeFuture2 { get; init; } // only if buffer > 68 + + // ── Derived ────────────────────────────────────────────────────────────── + public int RpmLimit => UpgradeRpmMax * 100; + /// + /// Dual injector is a Stage 3 feature — the same nibble the Android app reads as + /// Upgrade_Stage3, so it follows the stage rather than being an independent flag. + /// + public bool IsDualInjectorUnlocked => Stage >= 3; + + /// True once the throttle (TPS) calibration has been completed on this unit. + /// The firmware/Android app stores the flag in the second first-use byte + /// (UIfirstUseDate[1] = buf[33]), not the first. + public bool HasTpsCalibration => FirstUseInfo1 == TpsCalibration.CalDoneFlag; + + /// + /// Legacy Upgrade_Stage2 — high nibble of the shift/stage byte + /// (legacy buf[offset+42] & 0xF0, whose low nibble is Shift Auto). + /// + public byte UpgradeStage2 => (byte)(UpgradeShiftAuto & 0xF0); + + /// + /// Legacy Upgrade_Stage3 — low nibble of the next byte + /// (legacy buf[offset+43] & 0x0F; the WPF parser stores that byte + /// as ). + /// + public byte UpgradeStage3 => (byte)(UpgradeLogImmo & 0x0F); + + /// + /// ECU stage — 1, 2 or 3. Mirrors the Android app's precedence exactly: + /// Stage 3 wins if its nibble is set, else Stage 2, else Stage 1. + /// Stage 1 does not expose the user 24×8 adjust tables (only the subtables). + /// + public int Stage => + UpgradeStage3 > 0 ? 3 : + UpgradeStage2 > 0 ? 2 : 1; + + /// True when the stage exposes the user 24×8 adjust tables (Stage 2+). + public bool HasUserAdjustTables => Stage >= 2; + + // ── Parser ─────────────────────────────────────────────────────────────── + /// + /// Parses a raw APP_READ_INFO response buffer. + /// Buffer[0] must be APP_CMD_SUCCESS (0x51); payload starts at byte 4. + /// + public static EcuInfo Parse(byte[] buf) + { + if (buf[0] != 0x51) + throw new InvalidOperationException($"Expected APP_CMD_SUCCESS (0x51), got 0x{buf[0]:X2}"); + + const int payloadStart = 4; + const int fieldStart = payloadStart + 16; // after 16-byte username + + // Username (16 bytes, null-terminated ASCII) + var username = System.Text.Encoding.ASCII + .GetString(buf, payloadStart, 16) + .TrimEnd('\0'); + + // Little-endian uint32 helper + uint ReadU32(int offset) => + buf[offset] | + ((uint)buf[offset + 1] << 8) | + ((uint)buf[offset + 2] << 16) | + ((uint)buf[offset + 3] << 24); + + var flashWriteCount = ReadU32(fieldStart); + var switchToggleCount = ReadU32(fieldStart + 4); + + // Dates — DD=0 means "Never" + // Day/Month/Year(+2000) as raw bytes. DD==0 means "Never". Some units carry + // uninitialised or garbage bytes in unused date slots (e.g. month 0 or 14, + // day 31 in a 30-day month); those must NOT throw and abort the whole info + // read — treat any non-calendar value as "not set" (null). + DateOnly? ParseDate(int offset) + { + int day = buf[offset], month = buf[offset + 1], year = 2000 + buf[offset + 2]; + if (day == 0) return null; + if (month < 1 || month > 12) return null; + if (day > DateTime.DaysInMonth(year, month)) return null; + return new DateOnly(year, month, day); + } + + var progDate = ParseDate(fieldStart + 8); + var firstUseDate = ParseDate(fieldStart + 12); + var firstUseInfo0 = buf[fieldStart + 12]; // DD slot (first-use date day) + var firstUseInfo1 = buf[fieldStart + 13]; // MM slot — doubles as the TPS cal-done flag + var firstFlashDate = ParseDate(fieldStart + 16); + + // UniqueID — 16 bytes formatted as 4×4 hex groups + var uid = buf.Skip(fieldStart + 20).Take(16).ToArray(); + var uniqueId = $"{Hex(uid, 0, 4)}-{Hex(uid, 4, 4)}-{Hex(uid, 8, 4)}-{Hex(uid, 12, 4)}"; + + int o = fieldStart + 36; // after UniqueID + + var fwVersion = buf[o]; + var hwVersion = buf[o + 1]; + var bikeMfr = buf[o + 2]; + var bikeModel = buf[o + 3]; + var upgradeRpmMax = buf[o + 4]; + var upgradeShift = buf[o + 5]; + var upgradeLogImmo = buf[o + 6]; + var upgradeFuture12 = buf[o + 7]; + + byte upgradeFuture2 = 0, fw2 = 0, fw2sub = 0, tableVer = 0, hwComp = 0; + if (buf.Length > 68) + { + upgradeFuture2 = buf[o + 8]; + fw2 = buf[o + 9]; + fw2sub = buf[o + 10]; + tableVer = buf[o + 11]; + hwComp = buf[o + 12]; + } + + var appInfoVersion = buf[^1]; // last byte + var pwdRstCount = buf[^5]; // 4 bytes from end + + return new EcuInfo + { + Username = username, + UniqueId = uniqueId, + FwVersion = fwVersion, + HwVersion = hwVersion, + FwVersion2 = fw2, + FwSubVersion2 = fw2sub, + TableVersion = tableVer, + HwComponentVersion = hwComp, + AppInfoVersion = appInfoVersion, + BikeManufacturer = bikeMfr, + BikeModel = bikeModel, + FlashWriteCount = flashWriteCount, + SwitchToggleCount = switchToggleCount, + PwdResetCount = pwdRstCount, + ProgrammingDate = progDate, + FirstUseDate = firstUseDate, + FirstUseInfo0 = firstUseInfo0, + FirstUseInfo1 = firstUseInfo1, + FirstFlashDate = firstFlashDate, + UpgradeRpmMax = upgradeRpmMax, + UpgradeShiftAuto = upgradeShift, + UpgradeLogImmo = upgradeLogImmo, + UpgradeFuture12 = upgradeFuture12, + UpgradeFuture2 = upgradeFuture2, + }; + } + + private static string Hex(byte[] src, int start, int count) => + string.Concat(src.Skip(start).Take(count).Select(b => $"{b:X2}")); +} diff --git a/TuneBoss.Core/Models/EcuSession.cs b/TuneBoss.Core/Models/EcuSession.cs new file mode 100644 index 0000000..1e24a66 --- /dev/null +++ b/TuneBoss.Core/Models/EcuSession.cs @@ -0,0 +1,79 @@ +namespace TuneBoss.Core.Models; + +/// +/// Holds all table data loaded from a connected TuneBoss device. +/// Constructed after a successful populateInitTables sequence. +/// +/// Acts as the single source of truth for the current session. +/// ViewModels bind to properties on this object. +/// Immutable by convention — table updates produce new instances. +/// +public sealed record EcuSession +{ + // ── Device identity ─────────────────────────────────────────────────────── + public EcuInfo Info { get; init; } = null!; + public MemoryLayout Layout { get; init; } = null!; + public EcuVariant Variant { get; init; } + + // ── 2D tuning tables — cylinder 1 ──────────────────────────────────────── + public TuningTable? Fuel_PulseWidth1 { get; init; } + public TuningTable? Spark_Angle1 { get; init; } + public TuningTable? Fuel_Angle2D { get; init; } + public TuningTable? Secondary_Load_Conversion { get; init; } + public TuningTable? Fuel_PulseWidth_Adjust1 { get; init; } + public TuningTable? Spark_Angle_Adjust1 { get; init; } + public AfrTable? AFR_Target1 { get; init; } + + // ── Subtables — cylinder 1 ──────────────────────────────────────────────── + public SubTable? AFR_Target1_SubTable { get; init; } + public SubTable? Fuel_PulseWidth_Adjust1_SubTable { get; init; } + public SubTable? Spark_Angle_Adjust1_SubTable { get; init; } + + // ── 2D tuning tables — cylinder 2 (isTwoCylinder only) ─────────────────── + public TuningTable? Fuel_PulseWidth2 { get; init; } + public TuningTable? Spark_Angle2 { get; init; } + public TuningTable? Fuel_Angle2D_2 { get; init; } + public TuningTable? Fuel_PulseWidth_Adjust2 { get; init; } + public TuningTable? Spark_Angle_Adjust2 { get; init; } + public AfrTable? AFR_Target2 { get; init; } + + // ── Subtables — cylinder 2 ──────────────────────────────────────────────── + public SubTable? AFR_Target2_SubTable { get; init; } + public SubTable? Fuel_PulseWidth_Adjust2_SubTable { get; init; } + public SubTable? Spark_Angle_Adjust2_SubTable { get; init; } + + // ── 1D tables (up to 37, null = not available on this FW version) ───────── + public OneDimTable?[] OneDimTables { get; init; } = new OneDimTable?[37]; + + // ── Misc values ─────────────────────────────────────────────────────────── + public MiscValues? Misc { get; init; } + + // ── Derived ────────────────────────────────────────────────────────────── + public bool IsTwoCylinder => Variant != EcuVariant.SingleCylinder; + + public bool HasExtendedMisc => Info.FwVersion >= 150; + + /// + /// True when the session has been fully loaded — + /// i.e. all tables available for this device have been read. + /// + public bool IsFullyLoaded { get; init; } + + // ── Mutation helpers ────────────────────────────────────────────────────── + + /// Returns a new session with Fuel_PulseWidth1 replaced. + public EcuSession WithFuel1(TuningTable t) => this with { Fuel_PulseWidth1 = t }; + public EcuSession WithSpark1(TuningTable t) => this with { Spark_Angle1 = t }; + public EcuSession WithFuelAdjust1(TuningTable t) => this with { Fuel_PulseWidth_Adjust1 = t }; + public EcuSession WithSparkAdjust1(TuningTable t) => this with { Spark_Angle_Adjust1 = t }; + public EcuSession WithFuelAngle(TuningTable t) => this with { Fuel_Angle2D = t }; + public EcuSession WithAfr1(AfrTable t) => this with { AFR_Target1 = t }; + public EcuSession WithMisc(MiscValues m) => this with { Misc = m }; + + public EcuSession WithOneDimTable(int index, OneDimTable t) + { + var arr = (OneDimTable?[])OneDimTables.Clone(); + arr[index] = t; + return this with { OneDimTables = arr }; + } +} diff --git a/TuneBoss.Core/Models/MemoryLayout.cs b/TuneBoss.Core/Models/MemoryLayout.cs new file mode 100644 index 0000000..1e16f13 --- /dev/null +++ b/TuneBoss.Core/Models/MemoryLayout.cs @@ -0,0 +1,302 @@ +using TuneBoss.Core.Protocol; + +namespace TuneBoss.Core.Models; + +/// +/// Describes a single memory region on the device — its address and read length. +/// +public sealed record MemoryRegion(ushort Address, byte Length) +{ + public byte AddrLo => (byte)(Address & 0xFF); + public byte AddrHi => (byte)(Address >> 8); + public byte[] AddrBytes => new[] { AddrLo, AddrHi }; + + /// True if this region exists (address != 0x0000 or explicit availability flag). + public bool IsAvailable { get; init; } = true; + + public static MemoryRegion Unavailable => new(0x0000, 0) { IsAvailable = false }; +} + +/// +/// Complete memory address map for a connected TuneBoss device. +/// Constructed once after EcuInfo is parsed; replaces the static memAddress class. +/// +/// ── Generation mapping ──────────────────────────────────────────────────────── +/// Gen1 (AppInfoVersion=245): legacy addresses, APP_MEMRD_SEQ for all ops +/// Gen2 (AppInfoVersion=1) : dedicated read commands, single-cylinder layout +/// Gen3 (AppInfoVersion=2) : same as Gen2 + separate 2D_USER address space +/// +/// ── 1D table FW gates (from populateInitTables) ─────────────────────────────── +/// Tables 1–18 : always (base set) +/// Tables 19–24 : FW_Version >= 80 +/// Tables 25–26 : FW_Version >= 83 +/// Tables 27–34 : FW_Version >= 90 +/// Tables 35–37 : FW_Version >= 130 +/// +/// ── Misc FW gates ───────────────────────────────────────────────────────────── +/// Core (136B) : always +/// LaunchFuel (12B) : FW_Version >= 150 +/// LaunchFuel2 (12B) : FW_Version >= 150 +/// AuxOut (12B) : FW_Version >= 150 +/// Extended (var B) : FW_Version >= 150, size from EcuVariant +/// +public sealed record MemoryLayout +{ + // ── 2D main tuning tables ───────────────────────────────────────────────── + public MemoryRegion Fuel_PulseWidth1 { get; init; } = MemoryRegion.Unavailable; + public MemoryRegion Spark_Angle1 { get; init; } = MemoryRegion.Unavailable; + public MemoryRegion AFR_Target1 { get; init; } = MemoryRegion.Unavailable; + public MemoryRegion Fuel_Angle2D { get; init; } = MemoryRegion.Unavailable; + public MemoryRegion Secondary_Load_Conversion { get; init; } = MemoryRegion.Unavailable; + + // ── 2D user-adjustable tables (cyl1) ───────────────────────────────────── + public MemoryRegion Fuel_PulseWidth_Adjust1 { get; init; } = MemoryRegion.Unavailable; + public MemoryRegion Spark_Angle_Adjust1 { get; init; } = MemoryRegion.Unavailable; + + // ── Subtables (cyl1) ───────────────────────────────────────────────────── + public MemoryRegion AFR_Target1_SubTable { get; init; } = MemoryRegion.Unavailable; + public MemoryRegion Fuel_PulseWidth_Adjust1_SubTable { get; init; } = MemoryRegion.Unavailable; + public MemoryRegion Spark_Angle_Adjust1_SubTable { get; init; } = MemoryRegion.Unavailable; + + // ── 2D tables cyl2 (isTwoCylinder only) ────────────────────────────────── + public MemoryRegion Fuel_PulseWidth2 { get; init; } = MemoryRegion.Unavailable; + public MemoryRegion Spark_Angle2 { get; init; } = MemoryRegion.Unavailable; + public MemoryRegion AFR_Target2 { get; init; } = MemoryRegion.Unavailable; + public MemoryRegion Fuel_Angle2D_2 { get; init; } = MemoryRegion.Unavailable; + public MemoryRegion Fuel_PulseWidth_Adjust2 { get; init; } = MemoryRegion.Unavailable; + public MemoryRegion Spark_Angle_Adjust2 { get; init; } = MemoryRegion.Unavailable; + + // ── Subtables cyl2 ─────────────────────────────────────────────────────── + public MemoryRegion AFR_Target2_SubTable { get; init; } = MemoryRegion.Unavailable; + public MemoryRegion Fuel_PulseWidth_Adjust2_SubTable { get; init; } = MemoryRegion.Unavailable; + public MemoryRegion Spark_Angle_Adjust2_SubTable { get; init; } = MemoryRegion.Unavailable; + + // ── 1D tables (up to 37 depending on FW_Version) ───────────────────────── + // Index 0-based: OneDimTables[0] = table 1, OneDimTables[36] = table 37 + // Unavailable entries have IsAvailable=false and are skipped by the service layer. + public MemoryRegion[] OneDimTables { get; init; } = new MemoryRegion[37]; + + // ── Misc regions ───────────────────────────────────────────────────────── + public MemoryRegion MiscCore { get; init; } = MemoryRegion.Unavailable; // 136 bytes, always + public MemoryRegion MiscLaunchFuel { get; init; } = MemoryRegion.Unavailable; // 12B, FW>=150 + public MemoryRegion MiscLaunchFuel2 { get; init; } = MemoryRegion.Unavailable; // 12B, FW>=150 + public MemoryRegion MiscAuxOut { get; init; } = MemoryRegion.Unavailable; // 12B, FW>=150 + public MemoryRegion MiscExtended { get; init; } = MemoryRegion.Unavailable; // var, FW>=150 + + // ── RPM limit misc address ──────────────────────────────────────────────── + public MemoryRegion RpmLimitMisc { get; init; } = MemoryRegion.Unavailable; // 0x63 length + + // ── Read lengths (fixed from populateInitTables) ────────────────────────── + public const byte Len2DTable = 0xE3; // 227 — split read + public const byte LenAFRTable = 0xEF; // 239 — AFR split read + public const byte Len1DTable = 0x17; // 23 — single read + public const byte LenSubTable = 0x17; // 23 — single read + public const byte LenMiscCore = 0x88; // 136 + public const byte LenMiscExt12 = 0x0B; // 11 (12 bytes incl [0]) + public const byte LenRpmCheck = 0x63; // 99 + + // ════════════════════════════════════════════════════════════════════════ + // FACTORY + // ════════════════════════════════════════════════════════════════════════ + + /// + /// Constructs the complete memory layout from parsed EcuInfo. + /// This is the single entry point — call once after ReadEcuInfoAsync(). + /// + public static MemoryLayout For(EcuInfo info, EcuVariant variant) + { + var gen = GenerationConfig.ResolveGeneration(info.AppInfoVersion); + byte fw = info.FwVersion; + byte fw2sub = info.FwSubVersion2; + + return gen switch + { + GenerationType.Gen1 => BuildGen1(fw, variant), + GenerationType.Gen2 => BuildGen2(fw, variant, fw2sub), + GenerationType.Gen3 => BuildGen3(fw, variant, fw2sub), + _ => throw new InvalidOperationException($"Unknown generation for AppInfoVersion {info.AppInfoVersion}") + }; + } + + // ════════════════════════════════════════════════════════════════════════ + // GEN1 — legacy, APP_MEMRD_SEQ for all + // ════════════════════════════════════════════════════════════════════════ + private static MemoryLayout BuildGen1(byte fw, EcuVariant variant) + { + static MemoryRegion R(ushort addr, byte len) => new(addr, len); + var layout = new MemoryLayout + { + // 2D tables at fixed GEN1 addresses + Fuel_PulseWidth1 = R(0x0000, Len2DTable), + Spark_Angle1 = R(0x00E4, Len2DTable), + AFR_Target1 = R(0x01C8, LenAFRTable), + Fuel_Angle2D = R(0x02AC, Len2DTable), + Secondary_Load_Conversion = R(0x0390, Len2DTable), + Fuel_PulseWidth_Adjust1 = R(0x048C, Len2DTable), + Spark_Angle_Adjust1 = R(0x0588, Len2DTable), + + // Subtables + AFR_Target1_SubTable = R(0x02AC, LenSubTable), + Fuel_PulseWidth_Adjust1_SubTable = R(0x0570, LenSubTable), + Spark_Angle_Adjust1_SubTable = R(0x066C, LenSubTable), + + // Misc + MiscCore = R(0x0834, LenMiscCore), + RpmLimitMisc = R(0x0840, LenRpmCheck), + + // GEN1 has no extended misc regions + MiscLaunchFuel = MemoryRegion.Unavailable, + MiscLaunchFuel2 = MemoryRegion.Unavailable, + MiscAuxOut = MemoryRegion.Unavailable, + MiscExtended = MemoryRegion.Unavailable, + + OneDimTables = Build1DTables_Gen1(fw), + }; + return layout; + } + + // ════════════════════════════════════════════════════════════════════════ + // GEN2 — dedicated read commands, single/dual cylinder + // ════════════════════════════════════════════════════════════════════════ + private static MemoryLayout BuildGen2(byte fw, EcuVariant variant, byte fw2sub = 0) + { + static MemoryRegion R(ushort addr, byte len) => new(addr, len); + bool isTwoCyl = variant != EcuVariant.SingleCylinder; + + return new MemoryLayout + { + // Cyl1 2D + Fuel_PulseWidth1 = R(0x0000, Len2DTable), + Spark_Angle1 = R(0x00E4, Len2DTable), + AFR_Target1 = R(0x01C8, LenAFRTable), + Fuel_Angle2D = R(0x02AC, Len2DTable), + Secondary_Load_Conversion = R(0x0390, Len2DTable), + Fuel_PulseWidth_Adjust1 = R(0x0474, Len2DTable), + Spark_Angle_Adjust1 = R(0x0558, Len2DTable), + + // Cyl1 subtables + AFR_Target1_SubTable = R(0x0000, LenSubTable), + 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, + Fuel_PulseWidth_Adjust2 = isTwoCyl ? R(0x09CC, Len2DTable) : MemoryRegion.Unavailable, + Spark_Angle_Adjust2 = isTwoCyl ? R(0x0AB0, Len2DTable) : MemoryRegion.Unavailable, + + // Cyl2 subtables + 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, + + // Misc core + MiscCore = R(0x0000, LenMiscCore), + RpmLimitMisc = R(0x000C, LenRpmCheck), + + // Extended misc — FW >= 150 + MiscLaunchFuel = fw >= 150 ? R(0x0088, LenMiscExt12) : MemoryRegion.Unavailable, + MiscLaunchFuel2 = fw >= 150 ? R(0x0094, LenMiscExt12) : MemoryRegion.Unavailable, + MiscAuxOut = fw >= 150 ? R(0x00A0, LenMiscExt12) : MemoryRegion.Unavailable, + MiscExtended = fw >= 150 + ? R(0x00AC, MiscValues.ExtendedLengthFor(fw2sub)) + : MemoryRegion.Unavailable, + + OneDimTables = Build1DTables_Gen2(fw), + }; + } + + // ════════════════════════════════════════════════════════════════════════ + // GEN3 — same as Gen2 but 2D_USER in separate address space + // ════════════════════════════════════════════════════════════════════════ + private static MemoryLayout BuildGen3(byte fw, EcuVariant variant, byte fw2sub = 0) + { + // GEN3 user-adjust tables live in a separate address space: + // Fuel_PulseWidth_Adjust1 = 0x0000, Spark_Angle_Adjust1 = 0x00E4 + // etc. (addressed via APP_MEMRD_2D_USER not APP_MEMRD_2D) + var base2 = BuildGen2(fw, variant, fw2sub); + bool isTwoCyl = variant != EcuVariant.SingleCylinder; + + static MemoryRegion R(ushort addr, byte len) => new(addr, len); + + return base2 with + { + // Override user-adjust addresses for GEN3 + Fuel_PulseWidth_Adjust1 = R(0x0000, Len2DTable), + Spark_Angle_Adjust1 = R(0x00E4, Len2DTable), + Fuel_PulseWidth_Adjust2 = isTwoCyl ? R(0x01C8, Len2DTable) : MemoryRegion.Unavailable, + Spark_Angle_Adjust2 = isTwoCyl ? R(0x02AC, Len2DTable) : MemoryRegion.Unavailable, + }; + } + + // ════════════════════════════════════════════════════════════════════════ + // 1D TABLE ADDRESS BUILDERS + // Note the deliberate addr17→panel19, addr18→panel20 swap observed in + // populateInitTables — preserved here in array order. + // ════════════════════════════════════════════════════════════════════════ + private static MemoryRegion[] Build1DTables_Gen1(byte fw) + { + var t = Enumerable.Repeat(MemoryRegion.Unavailable, 37).ToArray(); + static MemoryRegion R(ushort a) => new(a, Len1DTable); + + // Base 18 (addr 0x0684 onwards, 0x18 = 24 byte stride) + t[0] = R(0x0684); t[1] = R(0x069C); t[2] = R(0x06B4); + t[3] = R(0x06CC); t[4] = R(0x06E4); t[5] = R(0x06FC); + t[6] = R(0x0714); t[7] = R(0x072C); t[8] = R(0x0744); + t[9] = R(0x075C); t[10] = R(0x0774); t[11] = R(0x078C); + t[12] = R(0x07A4); t[13] = R(0x07BC); t[14] = R(0x07D4); + t[15] = R(0x07EC); t[16] = R(0x0804); t[17] = R(0x081C); + return t; + } + + private static MemoryRegion[] Build1DTables_Gen2(byte fw) + { + var t = Enumerable.Repeat(MemoryRegion.Unavailable, 37).ToArray(); + static MemoryRegion R(ushort a) => new(a, Len1DTable); + + // Base 18 — always + t[0] = R(0x0000); t[1] = R(0x0018); t[2] = R(0x0030); + t[3] = R(0x0048); t[4] = R(0x0060); t[5] = R(0x0078); + t[6] = R(0x0090); t[7] = R(0x00A8); t[8] = R(0x00C0); + t[9] = R(0x00D8); t[10] = R(0x00F0); t[11] = R(0x0108); + t[12] = R(0x0120); t[13] = R(0x0138); t[14] = R(0x0150); + t[15] = R(0x0168); t[16] = R(0x0180); t[17] = R(0x0198); + + if (fw >= 80) + { + t[18] = R(0x01B0); t[19] = R(0x01C8); t[20] = R(0x01E0); + t[21] = R(0x01F8); t[22] = R(0x0210); t[23] = R(0x0228); + } + if (fw >= 83) + { + // Slots 25-26 (Speed Fuel/Spark Comp) ship in FW 83, not 80 — + // populateInitTables gates these in a nested FW>=83 check. + t[24] = R(0x0240); t[25] = R(0x0258); + } + if (fw >= 90) + { + t[26] = R(0x0270); t[27] = R(0x0288); t[28] = R(0x02A0); + t[29] = R(0x02B8); t[30] = R(0x02D0); t[31] = R(0x02E8); + t[32] = R(0x0300); t[33] = R(0x0318); + } + if (fw >= 130) + { + t[34] = R(0x0330); t[35] = R(0x0348); t[36] = R(0x0360); + } + + return t; + } + + // ── Convenience ────────────────────────────────────────────────────────── + + /// + /// Returns all available 1D table regions in index order. + /// Skips Unavailable entries (FW-gated tables not present on this device). + /// + public IEnumerable<(int Index, MemoryRegion Region)> Available1DTables => + OneDimTables + .Select((r, i) => (i, r)) + .Where(x => x.r.IsAvailable); +} diff --git a/TuneBoss.Core/Models/MiscBitSpec.cs b/TuneBoss.Core/Models/MiscBitSpec.cs new file mode 100644 index 0000000..44d6553 --- /dev/null +++ b/TuneBoss.Core/Models/MiscBitSpec.cs @@ -0,0 +1,34 @@ +namespace TuneBoss.Core.Models; + +/// How a sub-field of a settings byte is edited. +public enum MiscEditorKind +{ + Flag, // single bit → checkbox + Enum, // bit range → combo (Options indexed by value) + Number, // bit range → numeric 0..(mask>>shift) +} + +/// +/// One sub-field occupying a contiguous bit range of a byte. +/// Value = (byte & Mask) >> shift(Mask); written back masked. +/// +public sealed record MiscBitField( + string Label, + int Mask, // e.g. 0x01 (flag), 0xF0 (high nibble), 0x7F (7-bit value) + MiscEditorKind Kind = MiscEditorKind.Flag, + string[]? Options = null) // Enum only: option labels indexed by value +{ + /// Human-readable label: underscores → spaces, shortforms expanded. + public string DisplayText => MiscDisplayText.For(Label); +} + +/// +/// Decomposition of a single settings byte into bit sub-fields, plus optional +/// inter-bit constraints (bit indices 0..7). +/// +public sealed record MiscByteSpec( + MiscBlock Block, + string FieldLabel, // must match a MiscField.Label in MiscFieldRegistry + MiscBitField[] Fields, + (int A, int B)[]? MutualExclusive = null, // checking one clears the other + (int A, int B)[]? Linked = null); // toggling one toggles the other diff --git a/TuneBoss.Core/Models/MiscBitSpecRegistry.cs b/TuneBoss.Core/Models/MiscBitSpecRegistry.cs new file mode 100644 index 0000000..a3d6370 --- /dev/null +++ b/TuneBoss.Core/Models/MiscBitSpecRegistry.cs @@ -0,0 +1,228 @@ +namespace TuneBoss.Core.Models; + +/// +/// Per-byte bit decompositions for the misc "settings" bytes. +/// Labels are taken verbatim from the legacy Form1.Designer.cs CheckedListBox / +/// ComboBox item strings (TuneBossPCAppBLE2026), so bit order is authoritative. +/// +/// KEYING: each spec attaches by (Block, FieldLabel); FieldLabel matches a MiscField.Label +/// in MiscFieldRegistry. Keys were resolved against the legacy core write-map +/// (returnBytes[N] = textBox(N+1)), so byte indices are exact. The flag bytes your model +/// left unnamed map to the raw placeholders: Core_8 (CamSync), Core_25 (Fuel_Settings2), +/// Core_31 (Spark_Settings), Core_33 (O2_Autotune_Enable), Core_120 (TPS_Accel_Type). +/// +/// MODEL FIX NEEDED — ShiftBoss Enable: byte 84 is the enable flags byte (legacy value +/// 15 = 0x0F), but MiscValues.cs currently names Core[84] "ShiftBoss_Retard_Degrees". +/// Rename that accessor (and its MiscFieldRegistry entry) to "ShiftBoss_Enable" so this +/// spec attaches. The real retard degrees is the low 7 bits of byte 88 (ShiftBoss_Spark_Retard_deg). +/// +public static class MiscBitSpecRegistry +{ + private static MiscBitField Flag(string label, int mask) => new(label, mask, MiscEditorKind.Flag); + private static MiscBitField Num (string label, int mask) => new(label, mask, MiscEditorKind.Number); + private static MiscBitField Enum(string label, int mask, params string[] opts) => new(label, mask, MiscEditorKind.Enum, opts); + + // VRS combo option labels (index = nibble value 0..15), from the designer. + private static readonly string[] VrsMilliVolt = { "10","14","20","28","40","56","80","110","150","215","300","425","600","850","1210","1715" }; + private static readonly string[] VrsBlanking = { "0","3.12","6.25","9.37","12.5","15.62","18.75","21.87","25","28.1","31.3","34.4","37.5","40.6","43.8","46.9" }; + + public static readonly IReadOnlyList All = new[] + { + // ── Crank CamSync Config — raw byte Core_8 (value 131 on test device) (rename Core_8 → Crank_CamSync_Config) + new MiscByteSpec(MiscBlock.Core, "Crank_CamSync_Config", new[] + { + Flag("MAP Sync - Enable", 0x01), + Flag("Rotation Sync - whole rotation compare", 0x02), + Flag("Rotation Sync - No min RPM", 0x04), + Flag("Rotation Sync - Disable", 0x08), + Flag("MAP Sync - sync TPS < 50pct", 0x10), + Flag("MAP Sync - disable min RPM", 0x20), + Flag("Unused [2025/03/06]", 0x40), + Flag("Startup Fixed Spark Trigger Tooth", 0x80), + }), + + // ── O2 Autotune Enable + new MiscByteSpec(MiscBlock.Core, "O2_Autotune_Enable", new[] + { + Flag("Enable Autotune", 0x01), + Flag("Average with current table value", 0x02), + Flag("Write to Fuel Table", 0x04), + Flag("Read initial value from Fuel Table", 0x08), + Flag("Ignore TPS State", 0x10), + Flag("Ignore RPM State", 0x20), + Flag("Unused [2025/04/24]", 0x40), + Flag("Enable Autotune in all conditions", 0x80), + }), + + // ── ShiftBoss Enable ─ bit2<->bit3 linked (DIN) + new MiscByteSpec(MiscBlock.Core, "ShiftBoss_Enable", new[] + { + Flag("Enable ShiftBoss", 0x01), + Flag("Unused [2025/04/25]", 0x02), + Flag("Enable DIN (uncheck for Analog)", 0x04), + Flag("Enable DIN (uncheck for Analog)", 0x08), + Flag("Enable AutoTrigger RPM", 0x10), + Flag("Use Fuel Cut 1D Table", 0x20), + Flag("Use Spark Cut 1D Table", 0x40), + Flag("Use Spark Retard 1D Table", 0x80), + }, + Linked: new[] { (2, 3) }), + + // ── ShiftBoss Spark Retard deg + new MiscByteSpec(MiscBlock.Core, "ShiftBoss_Spark_Retard_deg", new[] + { + Num ("Retard Degrees (0-127)", 0x7F), + Flag("Retard reference = Current Spark Angle", 0x80), + }), + + // ── ShiftBoss Input Active High + new MiscByteSpec(MiscBlock.Core, "ShiftBoss_Input_Active_High", new[] + { + Flag("Input Active High", 0x01), + }), + + // ── ShiftBoss Input Debounce ms + new MiscByteSpec(MiscBlock.Core, "ShiftBoss_Input_Debounce_ms", new[] + { + Num ("Debounce ms (0-63)", 0x3F), + Flag("Input Display - Engine Light", 0x40), + Flag("Input Display - Overheat Light", 0x80), + }), + + // ── MAP Settings + new MiscByteSpec(MiscBlock.Core, "MAP_Settings", new[] + { + Flag("Auto Temperature Correction", 0x01), + Flag("Baro Compensation Static", 0x02), + Flag("Static Error Detect", 0x04), + Flag("UNUSED", 0x08), + Flag("CamSync on MAP Hi->Lo transition", 0x10), + Flag("Cam sync use MAP tooth average", 0x20), + Flag("MAP Avg use tooth average", 0x40), + Flag("Unsync use Lowest MAP_Lo_Avg reading across 2 cycles", 0x80), + }), + + // ── TPS Accel Type + new MiscByteSpec(MiscBlock.Core, "TPS_Accel_Type", new[] + { + Enum("TPS source", 0x01, "TPS Raw", "TPS Percent"), + Enum("1D Table Raw", 0x02, "Start_Value", "Diff"), + Flag("Unused [2025/05/16]", 0x04), + Enum("1D Table Conv", 0x08, "Absolute PW", "% Table"), + Flag("Unused [2025/05/16] (0x10)", 0x10), + Flag("Unused [2025/05/16] (0x20)", 0x20), + Flag("Unused [2025/05/16] (0x40)", 0x40), + Flag("Unused [2025/05/16] (0x80)", 0x80), + }), + + // ── Fuel Settings + new MiscByteSpec(MiscBlock.Core, "Fuel_Settings", new[] + { + Enum("Reference Angle", 0x01, "End Angle", "Start Angle"), + Flag("2nd Injector Enable (see 0x80)", 0x02), + Flag("1D Fuel Idle Table - Enable", 0x04), + Flag("Unused [2025/07/04]", 0x08), + Flag("Combine Fuel Base Tables", 0x10), + Flag("Combine Fuel Adjustment Tables", 0x20), + Flag("Combine Fuel Angle Tables", 0x40), + Flag("AFR Table change to 2nd Injector Table (see 0x02)", 0x80), + }), + + // ── Fuel Settings 2 ─ bits1-2 form a MAP-source mode + new MiscByteSpec(MiscBlock.Core, "Fuel_Settings2", new[] + { + Flag("1D idle table MAP scaling factor (see 0x02)", 0x01), + Enum("Idle MAP source", 0x06, "MAP Avg", "Baro Static", "Map Lo Avg", "(reserved)"), + Flag("Unused [2025/07/04] (0x08)", 0x08), + Flag("Unused [2025/07/04] (0x10)", 0x10), + Flag("Unused [2025/07/04] (0x20)", 0x20), + Flag("Unused [2025/07/04] (0x40)", 0x40), + Flag("Enable Baro/Map scaling for 1D idle table", 0x80), + }), + + // ── Spark Settings + new MiscByteSpec(MiscBlock.Core, "Spark_Settings", new[] + { + Flag("Spark cut when fuel cut", 0x01), + Flag("Max dwell time clamping - Enable", 0x02), + Flag("OverCurrent dwell AutoClamp - Enable", 0x04), + Flag("Spark end time recalc - Enable", 0x08), + Flag("Combine Spark Base Tables", 0x10), + Flag("Combine Spark Adjust Tables", 0x20), + Enum("VBAT Table axis", 0x40, "RPM", "RawVal"), + Enum("Spark Table units", 0x80, "Degrees", "Timer ticks"), + }), + + // ── MC33814 VRS Misc Params + new MiscByteSpec(MiscBlock.Core, "MC33814_VRS_Misc_Params", new[] + { + Flag("Disable 2.5V reference", 0x01), + Flag("Swap VRSN & VRSP", 0x02), + Flag("Single ended mode (VRSN=GND)", 0x04), + Flag("De-glitch enable", 0x08), + Enum("Blanking time calc ref", 0x10, "High PW", "Low PW"), + Flag("reserved", 0x20), + Flag("Disable VRS", 0x40), + Flag("Automatic Mode VRS", 0x80), + }), + + // ── VRS Manual Control (Running): hi nibble = mV, lo nibble = blanking% + new MiscByteSpec(MiscBlock.Core, "MC33814_Cfg_VRS_Manual_Control", new[] + { + Enum("Running blanking %", 0x0F, VrsBlanking), + Enum("Running miliVolt", 0xF0, VrsMilliVolt), + }), + + // ── VRS Conditioner (Cranking): hi nibble = mV, lo nibble = blanking% + new MiscByteSpec(MiscBlock.Core, "MC33814_Ctrl_VRS_Conditioner", new[] + { + Enum("Cranking blanking %", 0x0F, VrsBlanking), + Enum("Cranking miliVolt", 0xF0, VrsMilliVolt), + }), + + // ── ISM Settings 1 (Extended/R25 block) ─ bit0/bit1 mutually exclusive (Mode) + new MiscByteSpec(MiscBlock.Extended, "ISM_Settings1", new[] + { + Flag("Mode - Test", 0x01), + Flag("Mode - Normal", 0x02), + Flag("Mode - Unused [2025/03/19]", 0x04), + Flag("Mode - Unused [2025/03/19]", 0x08), + Flag("Off Throttle ISM - Enable", 0x10), + Flag("OffThrottle ISM - Ignore TPS", 0x20), + Flag("Fixed position for Engine Start", 0x40), + Flag("ISM Auto target RPM", 0x80), + }, + MutualExclusive: new[] { (0, 1) }), + + // ── ISM PID Config (Extended block) + new MiscByteSpec(MiscBlock.Extended, "ISM_PID_Config", new[] + { + Flag("Init use stored target step", 0x01), + Flag("Clutch Input for stored tgt step", 0x02), + Flag("Speed Input for stored tgt step", 0x04), + Flag("Always enable stored tgt step", 0x08), + Flag("RPM ramp down detect", 0x10), + Flag("Reduce tgt step when > table val", 0x20), + Flag("Increase tgt step when < table val", 0x40), + Flag("Unused", 0x80), + }), + + // ── Mode Switch Settings (low nibble flags; high nibble = input selection 0-15) + new MiscByteSpec(MiscBlock.Extended, "Mode_Switch_Settings", new[] + { + Flag("Enable Mode Switch", 0x01), + Flag("Invert Input", 0x02), + Flag("Unused (0x04)", 0x04), + Flag("Unused (0x08)", 0x08), + Num ("Input selection (0-15)", 0xF0), + }), + }; + + /// Lookup a spec by block + field label, or null. + public static MiscByteSpec? Find(MiscBlock block, string label) + { + foreach (var s in All) + if (s.Block == block && s.FieldLabel == label) return s; + return null; + } +} diff --git a/TuneBoss.Core/Models/MiscDisplayText.cs b/TuneBoss.Core/Models/MiscDisplayText.cs new file mode 100644 index 0000000..33b6fdf --- /dev/null +++ b/TuneBoss.Core/Models/MiscDisplayText.cs @@ -0,0 +1,120 @@ +namespace TuneBoss.Core.Models; + +/// +/// Converts raw config field identifiers into human-readable display text: +/// underscores become spaces, and engineering shortforms expand to their meaning +/// (e.g. RPM_Limit_div100 → "RPM Limit (divided by 100)", +/// Fuel_Max_PW_Mult → "Fuel Max Pulse Width Multiplier"). +/// Unknown tokens pass through unchanged, so new fields degrade gracefully. +/// +public static class MiscDisplayText +{ + // Case-insensitive single-token expansions. + private static readonly Dictionary Map = new(StringComparer.OrdinalIgnoreCase) + { + // scaling / units + ["div100"] = "(divided by 100)", + ["div10"] = "(divided by 10)", + ["div5"] = "(divided by 5)", + ["x10"] = "(times 10)", + ["x100"] = "(times 100)", + ["ms"] = "(in milliseconds)", + ["5ms"] = "(in 5 ms steps)", + ["10ms"] = "(in 10 ms steps)", + ["100ms"] = "(in 100 ms steps)", + ["us"] = "(in microseconds)", + ["degC"] = "(in Celsius degrees)", + ["deg"] = "(in degrees)", + ["kph"] = "(in km/h)", + ["kmh"] = "(in km/h)", + ["pct"] = "Percent", + ["raw"] = "(raw)", + + // engineering shortforms + ["PW"] = "Pulse Width", + ["Decel"] = "Deceleration", + ["Accel"] = "Acceleration", + ["Etemp"] = "Engine Temperature", + ["VBAT"] = "Battery Voltage", + ["IAT"] = "Intake Air Temperature", + ["BARO"] = "Barometric", + ["NOS"] = "Nitrous", + ["ISM"] = "Idle Stepper Motor", + ["AIS"] = "Air Induction System", + ["O2H"] = "O2 Heater", + ["FC"] = "Fuel Consumption", + ["PerSec"] = "Per Second", + ["Hi"] = "High", + ["Lo"] = "Low", + ["Neg"] = "Negative", + ["Pos"] = "Positive", + ["Mult"] = "Multiplier", + ["Div"] = "Divider", + ["Num"] = "Number", + ["Init"] = "Initial", + ["Cfg"] = "Config", + ["Ctrl"] = "Control", + ["Rsvd"] = "Reserved", + ["Isol"] = "Idle Solenoid", + ["Ref"] = "Reference", + ["Retard"] = "Retard", + ["Solenoid"] = "Solenoid", + ["Samplepoint"] = "Sample Point", + }; + + // Case-SENSITIVE tokens (too dangerous to match loosely). + private static readonly Dictionary ExactMap = new(StringComparer.Ordinal) + { + ["s"] = "(in seconds)", + }; + + // Multi-token sequences consumed together (checked before single tokens). + private static readonly (string A, string B, string Text)[] Pairs = + { + ("ms", "div5", "(in milliseconds, divided by 5)"), + ("ms", "div10", "(in milliseconds, divided by 10)"), + }; + + private static readonly Dictionary Cache = new(); + + /// Display text for a raw field identifier. + public static string For(string raw) + { + if (string.IsNullOrEmpty(raw)) return raw; + lock (Cache) + { + if (Cache.TryGetValue(raw, out var hit)) return hit; + } + + var tokens = raw.Split('_', StringSplitOptions.RemoveEmptyEntries); + var outParts = new List(tokens.Length); + + for (int i = 0; i < tokens.Length; i++) + { + bool paired = false; + if (i + 1 < tokens.Length) + { + foreach (var (a, b, text) in Pairs) + { + if (tokens[i].Equals(a, StringComparison.OrdinalIgnoreCase) && + tokens[i + 1].Equals(b, StringComparison.OrdinalIgnoreCase)) + { + outParts.Add(text); + i++; // consume both + paired = true; + break; + } + } + } + if (paired) continue; + + if (ExactMap.TryGetValue(tokens[i], out var exact)) outParts.Add(exact); + else if (Map.TryGetValue(tokens[i], out var mapped)) outParts.Add(mapped); + else outParts.Add(tokens[i]); + } + + var result = string.Join(" ", outParts); + lock (Cache) { Cache[raw] = result; } + return result; + } +} diff --git a/TuneBoss.Core/Models/MiscFieldRegistry.cs b/TuneBoss.Core/Models/MiscFieldRegistry.cs new file mode 100644 index 0000000..859543d --- /dev/null +++ b/TuneBoss.Core/Models/MiscFieldRegistry.cs @@ -0,0 +1,349 @@ +namespace TuneBoss.Core.Models; + +/// Which raw misc block a field lives in. +public enum MiscBlock { Core, LaunchFuel, LaunchFuel2, AuxOut, Extended } + +/// One editable misc setting: a single raw byte in a block. +/// Generated from MiscValues.cs accessor map; unnamed bytes are exposed as +/// raw placeholders (rename in this file later). +public sealed record MiscField(string Section, string Label, MiscBlock Block, int Index) +{ + /// Human-readable label: underscores → spaces, shortforms expanded. + public string DisplayText => MiscDisplayText.For(Label); +} + +public static class MiscFieldRegistry +{ + public static readonly IReadOnlyList All = new MiscField[] + { + // ── Core ── + new("Crank", "Crank_Teeth", MiscBlock.Core, 0), + new("Crank", "Crank_Missing_Teeth", MiscBlock.Core, 1), + new("Crank", "Crank_Detect_Edge", MiscBlock.Core, 2), + new("Crank", "CrankTooth_Positive_Period_Pct", MiscBlock.Core, 3), + new("Crank", "CrankTooth_Negative_Period_Pct", MiscBlock.Core, 4), + new("Crank", "Crank_Timeout_Pct", MiscBlock.Core, 5), + new("Crank", "Crank_CamSync_Detect_Method", MiscBlock.Core, 6), + new("Crank", "Crank_CamSync_Detect_Cycle", MiscBlock.Core, 7), + new("Crank", "Crank_CamSync_Config", MiscBlock.Core, 8), + new("Crank", "Crank_CamSync_MAP_Detect_Cycle", MiscBlock.Core, 9), + new("Crank", "Crank_CamSync_Rotation_Tooth", MiscBlock.Core, 10), + new("Crank", "Crank_CamSync_Num_Fast_Rotations", MiscBlock.Core, 11), + new("RPM", "RPM_Limit_div100", MiscBlock.Core, 12), + new("RPM", "RPM_Limit_Recovery_div100", MiscBlock.Core, 13), + new("RPM", "RPM_Limit_Failsafe_div100", MiscBlock.Core, 14), + new("RPM", "RPM_Limit_Failsafe_Recovery_div100", MiscBlock.Core, 15), + new("RPM", "RPM_Detect_Min_div100", MiscBlock.Core, 16), + new("RPM", "RPM_Detect_Min_Recovery_div100", MiscBlock.Core, 17), + new("RPM", "RPM_Stall_div100", MiscBlock.Core, 18), + new("RPM", "RPM_Stall_Recovery_div100", MiscBlock.Core, 19), + new("RPM", "RPM_Decel_Threshold_PerSec_div100", MiscBlock.Core, 20), + new("RPM", "RPM_Accel_Threshold_PerSec_div100", MiscBlock.Core, 21), + new("RPM", "RPM_Meter_Divider", MiscBlock.Core, 22), + new("Fuel", "Fuel_Settings", MiscBlock.Core, 23), + new("Fuel", "Fuel_Max_PW_Mult", MiscBlock.Core, 24), + new("Fuel", "Fuel_Settings2", MiscBlock.Core, 25), + new("Fuel", "Fuel_Cut_Min_LOAD", MiscBlock.Core, 26), + new("Fuel", "Fuel_Cut_Min_TPS_pct", MiscBlock.Core, 27), + new("Fuel", "Fuel_Cut_Min_RPM_div100", MiscBlock.Core, 28), + new("Fuel", "Fuel_Cut_Disable_LOAD", MiscBlock.Core, 29), + new("Fuel", "Fuel_Cut_Min_Etemp_degC", MiscBlock.Core, 30), + new("Fuel", "Spark_Settings", MiscBlock.Core, 31), + new("Fuel", "VBAT_Trim_deciV", MiscBlock.Core, 32), + new("Fuel", "O2_Autotune_Enable", MiscBlock.Core, 33), + new("O2 Sensor / Autotune", "O2_Sensor_Sample_Rate_ms", MiscBlock.Core, 34), + new("O2 Sensor / Autotune", "O2_Sensor_Delay_ms_div5", MiscBlock.Core, 35), + new("O2 Sensor / Autotune", "O2_Fuel_Max_Add_Pct", MiscBlock.Core, 36), + new("O2 Sensor / Autotune", "O2_Fuel_Max_Sub_Pct", MiscBlock.Core, 37), + new("O2 Sensor / Autotune", "O2_Autotune_Max_RPM_div100", MiscBlock.Core, 38), + new("O2 Sensor / Autotune", "O2_Autotune_Min_RPM_div100", MiscBlock.Core, 39), + new("O2 Sensor / Autotune", "O2_Autotune_Max_Load", MiscBlock.Core, 40), + new("O2 Sensor / Autotune", "O2_Autotune_Min_Load", MiscBlock.Core, 41), + new("O2 Sensor / Autotune", "O2_Autotune_StepUp_Pct", MiscBlock.Core, 42), + new("O2 Sensor / Autotune", "O2_Autotune_Average_Weight", MiscBlock.Core, 43), + new("O2 Sensor / Autotune", "O2_Autotune_AFR_x10_Diff", MiscBlock.Core, 44), + new("O2 Sensor / Autotune", "O2_Autotune_Start_Delay_s", MiscBlock.Core, 45), + new("O2 Sensor / Autotune", "O2_Autotune_Min_ETemp", MiscBlock.Core, 46), + new("O2 Sensor / Autotune", "O2_Autotune_Max_ETemp", MiscBlock.Core, 47), + new("TPS", "TPS_Accel_Threshold_PctPer100ms", MiscBlock.Core, 48), + new("TPS", "TPS_Decel_Threshold_PctPer100ms", MiscBlock.Core, 49), + new("TPS", "TPS_Threshold_10ms_sample_gap", MiscBlock.Core, 50), + new("TPS", "TPS_Accel_Fuel_Adjust_Hold_Time_10ms", MiscBlock.Core, 51), + new("TPS", "TPS_Accel_Fuel_Adjust_Decay_Time_10ms", MiscBlock.Core, 52), + new("TPS", "TPS_Accel_Spark_Adjust_Hold_Time_10ms", MiscBlock.Core, 53), + new("TPS", "TPS_Accel_Spark_Adjust_Decay_Time_10ms", MiscBlock.Core, 54), + new("TPS", "TPS_Steady_State_Delay_Time_10ms", MiscBlock.Core, 55), + new("MAP", "MAP_Settings", MiscBlock.Core, 56), + new("MAP", "MAP_Lo_Hyst_Mult", MiscBlock.Core, 57), + new("MAP", "MAP_Ref_Temp_DegC", MiscBlock.Core, 58), + new("MAP", "MAP_Intake_Tooth_End", MiscBlock.Core, 59), + new("MAP", "MAP_Intake_Num_Teeth", MiscBlock.Core, 60), + new("MAP", "MAP_Baro_Tooth_End", MiscBlock.Core, 61), + new("MAP", "MAP_Baro_Num_Teeth", MiscBlock.Core, 62), + new("MAP", "MAP_Baro_RPM_div100_Limit", MiscBlock.Core, 63), + new("MAP", "MAP_Baro_TPS_Limit", MiscBlock.Core, 64), + new("MAP", "MAP_Baro_Static_Delay_10ms", MiscBlock.Core, 65), + new("MAP", "MAP_Settings2", MiscBlock.Core, 66), + new("Radiator / Overheat", "RadFan_On_Temp_DegC", MiscBlock.Core, 67), + new("Radiator / Overheat", "RadFan_Off_Temp_DegC", MiscBlock.Core, 68), + new("Radiator / Overheat", "Etemp_Overheat_On_Temp_DegC", MiscBlock.Core, 69), + new("Radiator / Overheat", "Etemp_Overheat_Off_Temp_DegC", MiscBlock.Core, 70), + new("Radiator / Overheat", "Etemp_Sensor_Error_Temp", MiscBlock.Core, 71), + new("Bluetooth / MC33814", "Bluetooth_PowerOn_Timeout_s", MiscBlock.Core, 72), + new("Bluetooth / MC33814", "MC33814_Init_Delay_10ms", MiscBlock.Core, 73), + new("Bluetooth / MC33814", "MC33814_Tacho_Control", MiscBlock.Core, 74), + new("Bluetooth / MC33814", "MC33814_VRS_Misc_Params", MiscBlock.Core, 75), + new("Bluetooth / MC33814", "MC33814_Cfg_VRS_Manual_Control", MiscBlock.Core, 76), + new("Bluetooth / MC33814", "MC33814_Ctrl_VRS_Conditioner", MiscBlock.Core, 77), + new("Fuel Pump / Solenoid", "Fuel_Pump_Timeout_100ms", MiscBlock.Core, 78), + new("Fuel Pump / Solenoid", "Idle_Solenoid_Off_Tooth", MiscBlock.Core, 79), + new("Fuel Pump / Solenoid", "Idle_Solenoid_Reset_RPM_div100", MiscBlock.Core, 80), + new("Fuel Pump / Solenoid", "Idle_Solenoid_Step_Down", MiscBlock.Core, 81), + new("Fuel Pump / Solenoid", "Idle_Solenoid_PID_Kp", MiscBlock.Core, 82), + new("Fuel Pump / Solenoid", "Idle_Solenoid_Min_Open_Angle_deg", MiscBlock.Core, 83), + new("ShiftBoss", "ShiftBoss_Enable", MiscBlock.Core, 84), + new("ShiftBoss", "ShiftBoss_Fuel_Cut_ms", MiscBlock.Core, 85), + new("ShiftBoss", "ShiftBoss_Spark_Cut_ms", MiscBlock.Core, 86), + new("ShiftBoss", "ShiftBoss_Spark_Retard_ms", MiscBlock.Core, 87), + new("ShiftBoss", "ShiftBoss_Spark_Retard_deg", MiscBlock.Core, 88), + new("ShiftBoss", "ShiftBoss_Interval_Time_10ms", MiscBlock.Core, 89), + new("ShiftBoss", "ShiftBoss_Min_RPM_div100", MiscBlock.Core, 90), + new("ShiftBoss", "ShiftBoss_Input_Active_High", MiscBlock.Core, 91), + new("ShiftBoss", "ShiftBoss_Input_Debounce_ms", MiscBlock.Core, 92), + new("ShiftBoss", "ShiftBoss_Autotrigger_RPM_div100", MiscBlock.Core, 93), + new("Load selection", "Load_Primary_Select", MiscBlock.Core, 94), + new("Load selection", "Load_Fuel_PulseWidth1_Select", MiscBlock.Core, 95), + new("Load selection", "Load_Spark_Angle1_Select", MiscBlock.Core, 96), + new("Load selection", "Load_AFR_Target1_Select", MiscBlock.Core, 97), + new("Load selection", "Load_Fuel_Angle2D_Select", MiscBlock.Core, 98), + new("Load selection", "Load_Fuel_PulseWidth_Adjust1_Select", MiscBlock.Core, 99), + new("Load selection", "Load_Spark_Angle_Adjust1_Select", MiscBlock.Core, 100), + new("Extended config", "VBAT_Min_deciV", MiscBlock.Core, 101), + new("Extended config", "VBAT_Max_deciV", MiscBlock.Core, 102), + new("Extended config", "O2_Sensor_Present", MiscBlock.Core, 103), + new("Extended config", "VDS_Present", MiscBlock.Core, 104), + new("Extended config", "TPS_Accel_Taper_Start_RPM_div100", MiscBlock.Core, 105), + new("Extended config", "TPS_Accel_Taper_End_RPM_div100", MiscBlock.Core, 106), + new("Extended config", "Error_Check_Startup_Delay", MiscBlock.Core, 107), + new("Extended config", "ErrorLog_Recording_Delay", MiscBlock.Core, 108), + new("Extended config", "ShiftLight_On_RPM_div100", MiscBlock.Core, 109), + new("Extended config", "ShiftLight_Off_RPM_div100", MiscBlock.Core, 110), + new("Extended config", "ShiftLight_Output_Select", MiscBlock.Core, 111), + new("Extended config", "MC33814_Lamp_Config", MiscBlock.Core, 112), + new("Extended config", "MC33814_O2H_Config", MiscBlock.Core, 113), + new("Extended config", "VBAT_Longterm_Min_DeciV", MiscBlock.Core, 114), + new("Extended config", "ErrorLog_MC33814_Mask_Lo", MiscBlock.Core, 115), + new("Extended config", "ErrorLog_MC33814_Mask_Hi", MiscBlock.Core, 116), + new("Extended config", "ErrorLog_MC33814_EngineOff_Enable", MiscBlock.Core, 117), + new("Extended config", "ErrorLog_MC33814_OL_Hysteresis", MiscBlock.Core, 118), + new("Extended config", "ErrorLog_MC33814_Killswitch_Mask", MiscBlock.Core, 119), + new("Extended config", "TPS_Accel_Type", MiscBlock.Core, 120), + new("Extended config", "TPS_Accel_Fuel_TempComp", MiscBlock.Core, 121), + new("Extended config", "TPS_Accel_Threshold_Fast_PctPer100ms", MiscBlock.Core, 122), + new("Extended config", "TPS_Decel_Fuel_Adjust_Pct", MiscBlock.Core, 123), + new("Extended config", "TPS_Accel_Modifier_Cyclecount", MiscBlock.Core, 124), + new("Extended config", "TPS_Accel_Threshold_SuperFast_PctPer100ms", MiscBlock.Core, 125), + new("Extended config", "VBAT_longterm_min_DeciV", MiscBlock.Core, 126), + new("Extended config", "ErrorLog_MC33814_SafeMode_Trigger_Lo", MiscBlock.Core, 127), + new("Extended config", "ErrorLog_MC33814_SafeMode_Trigger_Hi", MiscBlock.Core, 128), + new("Extended config", "VDS_Time_Delay_100ms", MiscBlock.Core, 129), + new("Extended config", "UM_Stop_Timer_Delay_100ms", MiscBlock.Core, 130), + new("Extended config", "Start_Fuel_Enrichment_Hold_100ms", MiscBlock.Core, 131), + new("Extended config", "Start_Fuel_Enrichment_Decay_100ms", MiscBlock.Core, 132), + new("Extended config", "TPS_Accel_Recursive_Accel", MiscBlock.Core, 133), + new("Extended config", "Idle_Solenoid_Reset_Timeout_100ms", MiscBlock.Core, 134), + new("Extended config", "Speed_Adjust_Percent", MiscBlock.Core, 135), + // ── LaunchFuel (spark/fuel reference angles + init) ── + new("Timing", "RPM_Table_2Samplepoint_div100", MiscBlock.LaunchFuel, 0), + new("Timing", "Fuel_Init_Cycles", MiscBlock.LaunchFuel, 1), + new("Timing", "Idle_Solenoid_Settings", MiscBlock.LaunchFuel, 2), + new("Timing", "Spark_Ref_Angle_Lo", MiscBlock.LaunchFuel, 3), + new("Timing", "Spark_Ref_Angle_Hi", MiscBlock.LaunchFuel, 4), + new("Timing", "Fuel_Ref_Angle_Lo", MiscBlock.LaunchFuel, 5), + new("Timing", "Fuel_Ref_Angle_Hi", MiscBlock.LaunchFuel, 6), + new("Timing", "Fuel_Base_PW_ms_x10", MiscBlock.LaunchFuel, 7), + new("Timing", "Spark2_Ref_Angle_Lo", MiscBlock.LaunchFuel, 8), + new("Timing", "Spark2_Ref_Angle_Hi", MiscBlock.LaunchFuel, 9), + new("Timing", "Fuel2_Ref_Angle_Lo", MiscBlock.LaunchFuel, 10), + new("Timing", "Fuel2_Ref_Angle_Hi", MiscBlock.LaunchFuel, 11), + // ── LaunchFuel2 (launch control + rad fan) ── + new("Launch Control", "TBD_Unused", MiscBlock.LaunchFuel2, 0), + new("Launch Control", "LaunchBoss_Enable", MiscBlock.LaunchFuel2, 1), + new("Launch Control", "LaunchBoss_Settings", MiscBlock.LaunchFuel2, 2), + new("Launch Control", "LaunchBoss_RPM_Limit_Start_div100", MiscBlock.LaunchFuel2, 3), + new("Launch Control", "LaunchBoss_RPM_Limit_End_div100", MiscBlock.LaunchFuel2, 4), + new("Launch Control", "LaunchBoss_RPM_Persec_Up_Rate_div100", MiscBlock.LaunchFuel2, 5), + new("Launch Control", "LaunchBoss_RPM_Up_Speed_Start_kph", MiscBlock.LaunchFuel2, 6), + new("Launch Control", "LaunchBoss_Speed_End_kph", MiscBlock.LaunchFuel2, 7), + new("Launch Control", "LaunchBoss_Spark_Retard_deg", MiscBlock.LaunchFuel2, 8), + new("Launch Control", "RadFan_Settings", MiscBlock.LaunchFuel2, 9), + new("Launch Control", "RadFan_PWM_Width_100ms", MiscBlock.LaunchFuel2, 10), + new("Launch Control", "Analog_Safe_Mode_Trigger", MiscBlock.LaunchFuel2, 11), + // ── AuxOut ── + new("General", "AuxOut_Control", MiscBlock.AuxOut, 0), + new("General", "AuxOut_Control2", MiscBlock.AuxOut, 1), + new("General", "RadFan_On_Temp_NOS_RPM", MiscBlock.AuxOut, 2), + new("General", "RadFan_Off_Temp_NOS_TPS", MiscBlock.AuxOut, 3), + new("General", "NOS_Speed", MiscBlock.AuxOut, 4), + new("General", "AuxOut_Ref_Value2_Off", MiscBlock.AuxOut, 5), + new("General", "AuxOut_Delay1_10ms", MiscBlock.AuxOut, 6), + new("General", "AuxOut_Delay2_10ms", MiscBlock.AuxOut, 7), + new("General", "Idle_Threshold_TPS", MiscBlock.AuxOut, 8), + new("General", "Idle_Threshold_RPM_div100", MiscBlock.AuxOut, 9), + new("General", "Spark_Dwell_Max_100us", MiscBlock.AuxOut, 10), + new("General", "Spark_Dwell_Min_100us", MiscBlock.AuxOut, 11), + // ── Extended ── + new("Spark tab", "Spark_Dwell_Reduction_10us", MiscBlock.Extended, 0), + new("Spark tab", "Spark_Dwell_Min_Deg", MiscBlock.Extended, 1), + new("Spark tab", "Spark_Dwell_Max_Deg_div4", MiscBlock.Extended, 2), + new("Spark tab", "Spark_Dwell_Reserved1", MiscBlock.Extended, 3), + new("Spark tab", "Crank_MissingTooth2_Pos_Period_Mult", MiscBlock.Extended, 4), + new("Spark tab", "Crank_MissingTooth2_Neg_Period_Mult", MiscBlock.Extended, 5), + new("Spark tab", "Crank_MissingTooth_Pos_Period_Mult", MiscBlock.Extended, 6), + new("Spark tab", "Crank_MissingTooth_Neg_Period_Mult", MiscBlock.Extended, 7), + new("Spark tab", "VRS_Threshold_Lo_RPM_div100", MiscBlock.Extended, 8), + new("Spark tab", "VRS_Threshold_Hi_RPM_div100", MiscBlock.Extended, 9), + new("Spark tab", "Spark_Cut_Retard1_RPM_Gap_div100", MiscBlock.Extended, 10), + new("Spark tab", "Spark_Cut_Retard2_RPM_Gap_div100", MiscBlock.Extended, 11), + new("Spark tab", "Spark_Cut_Retard1", MiscBlock.Extended, 12), + new("Spark tab", "Spark_Cut_Retard2", MiscBlock.Extended, 13), + new("Spark tab", "CrankTooth_Pos_Period_Mult_Run", MiscBlock.Extended, 14), + new("Spark tab", "CrankTooth_Neg_Period_Mult_Run", MiscBlock.Extended, 15), + new("Spark tab", "Gear_Ratio_Hysteresis_Count", MiscBlock.Extended, 16), + new("Spark tab", "Gear_Ratio_min_RPM_div100", MiscBlock.Extended, 17), + new("TC tab", "TC_Settings1", MiscBlock.Extended, 18), + new("TC tab", "TC_Settings2", MiscBlock.Extended, 19), + new("TC tab", "TC_Rpm_Min_div100", MiscBlock.Extended, 20), + new("TC tab", "TC_Rpm_Max_div100", MiscBlock.Extended, 21), + new("TC tab", "TC_TPS_Min", MiscBlock.Extended, 22), + new("TC tab", "TC_TPS_Max", MiscBlock.Extended, 23), + new("TC tab", "TC_Speed_Min", MiscBlock.Extended, 24), + new("TC tab", "TC_Speed_Max", MiscBlock.Extended, 25), + new("TC tab", "TC_Consecutive_Error_Trigger", MiscBlock.Extended, 26), + new("TC tab", "TC_Retard_Off_Ramp_deg_per100ms", MiscBlock.Extended, 27), + new("TC tab", "TC_Table_Input_Selection", MiscBlock.Extended, 28), + new("TC tab", "TC_Sample_Rate_ms", MiscBlock.Extended, 29), + new("TC tab", "TC_Speed_Tooth_Skip", MiscBlock.Extended, 30), + new("TC tab", "TC_Tooth_Average_Count", MiscBlock.Extended, 31), + new("TC tab", "TC_Tooth_Compare_Count", MiscBlock.Extended, 32), + new("TC tab", "TC_Gear_Max", MiscBlock.Extended, 33), + new("TC tab", "TC_Button_Modes", MiscBlock.Extended, 34), + new("TC tab", "TC_Button_Sensitivity_Modifier", MiscBlock.Extended, 35), + new("TC tab", "TC_Button_Delay_100ms", MiscBlock.Extended, 36), + new("TC tab", "TC_Tooth_Undriven_Count", MiscBlock.Extended, 37), + new("TC tab", "TC_Reserved6", MiscBlock.Extended, 38), + new("TC tab", "Offthrottle_Threshold_TPS", MiscBlock.Extended, 39), + new("TC tab", "Idle_Rumble_Min_Rpm_div100", MiscBlock.Extended, 40), + new("TC tab", "Speed_Settings1", MiscBlock.Extended, 41), + new("ISM tab", "ISM_Settings1", MiscBlock.Extended, 42), + new("ISM tab", "ISM_Startup_Delay_10ms", MiscBlock.Extended, 43), + new("ISM tab", "ISM_Max_Steps_Lo", MiscBlock.Extended, 44), + new("ISM tab", "ISM_Max_Steps_Hi", MiscBlock.Extended, 45), + new("ISM tab", "ISM_CR0_Init", MiscBlock.Extended, 46), + new("ISM tab", "ISM_CR1_Init", MiscBlock.Extended, 47), + new("ISM tab", "ISM_CR2_Init", MiscBlock.Extended, 48), + new("ISM tab", "ISM_Test_Step_Lo", MiscBlock.Extended, 49), + new("ISM tab", "ISM_Test_Step_Hi", MiscBlock.Extended, 50), + new("ISM tab", "ISM_Off_Delay_10ms", MiscBlock.Extended, 51), + new("ISM tab", "ISM_Max_Open_Steps_Per_Cycle", MiscBlock.Extended, 52), + new("ISM tab", "ISM_Max_Close_Steps_Per_Cycle", MiscBlock.Extended, 53), + new("ISM tab", "ISM_CR0_Run", MiscBlock.Extended, 54), + new("ISM tab", "ISM_CR0_Hold", MiscBlock.Extended, 55), + new("ISM tab", "ISM_Calibrate_Overshoot_Steps", MiscBlock.Extended, 56), + new("ISM tab", "ISM_PID_Delay_5ms", MiscBlock.Extended, 57), + new("ISM tab", "ISM_PID_Kp_lo", MiscBlock.Extended, 58), + new("ISM tab", "ISM_PID_Kp_hi", MiscBlock.Extended, 59), + new("ISM tab", "ISM_PID_Ki_lo", MiscBlock.Extended, 60), + new("ISM tab", "ISM_PID_Ki_hi", MiscBlock.Extended, 61), + new("ISM tab", "ISM_PID_Kd_lo", MiscBlock.Extended, 62), + new("ISM tab", "ISM_PID_Kd_hi", MiscBlock.Extended, 63), + new("ISM tab", "ISM_PID_Error_Threshold", MiscBlock.Extended, 64), + new("ISM tab", "ISM_PID_Config", MiscBlock.Extended, 65), + new("ISM tab", "ISM_Start_Boost_Step_raw", MiscBlock.Extended, 66), + new("ISM tab", "ISM_Stall_Boost_Step_raw", MiscBlock.Extended, 67), + new("ISM tab", "ISM_Start_Boost_Step_Delay_100ms", MiscBlock.Extended, 68), + new("ISM tab", "ISM_Stall_Boost_Step_Delay_100ms", MiscBlock.Extended, 69), + new("ISM tab", "ISM_Stall_Boost_RPM_div100", MiscBlock.Extended, 70), + new("ISM tab", "ISM_Boost_Step_Mult", MiscBlock.Extended, 71), + new("ISM tab", "ISM_PID_Gain_Mult", MiscBlock.Extended, 72), + new("ISM tab", "ISM_PID_Gain_Div_ShiftRight", MiscBlock.Extended, 73), + new("ISM tab", "ISM_PID_RPM_Rampdown_Rate", MiscBlock.Extended, 74), + new("ISM tab", "ISM_Rsvd22", MiscBlock.Extended, 75), + new("AIS tab", "AIS_Settings1", MiscBlock.Extended, 76), + new("AIS tab", "AIS_Settings2", MiscBlock.Extended, 77), + new("AIS tab", "AIS_RPM_Threshold1", MiscBlock.Extended, 78), + new("AIS tab", "AIS_TPS_Threshold1", MiscBlock.Extended, 79), + new("AIS tab", "AIS_RPM_Threshold2", MiscBlock.Extended, 80), + new("AIS tab", "AIS_TPS_Threshold2", MiscBlock.Extended, 81), + new("AIS tab", "AIS_RPM_Threshold3", MiscBlock.Extended, 82), + new("AIS tab", "AIS_TPS_Threshold3", MiscBlock.Extended, 83), + new("O2Heater tab", "AIS_Delay1_10ms", MiscBlock.Extended, 84), + new("O2Heater tab", "AIS_Settings10", MiscBlock.Extended, 85), + new("O2Heater tab", "ETEMP_Sensor_Sample_Rate_ms", MiscBlock.Extended, 86), + new("O2Heater tab", "IAT_Sensor_Sample_Rate_ms", MiscBlock.Extended, 87), + new("O2Heater tab", "O2Heater_Settings1", MiscBlock.Extended, 88), + new("O2Heater tab", "O2Heater_Settings2", MiscBlock.Extended, 89), + new("O2Heater tab", "O2Heater_Delay1_10ms", MiscBlock.Extended, 90), + new("O2Heater tab", "O2Heater_Settings4", MiscBlock.Extended, 91), + new("O2Heater tab", "O2Heater_Settings5", MiscBlock.Extended, 92), + new("O2Heater tab", "O2Heater_Settings6", MiscBlock.Extended, 93), + new("O2Heater tab", "ShiftBoss_Spark_RampDown_ms", MiscBlock.Extended, 94), + new("O2Heater tab", "ShiftBoss_Spark_RampUp_ms", MiscBlock.Extended, 95), + new("O2Heater tab", "VBAT_UVReset_DeciV", MiscBlock.Extended, 96), + new("O2Heater tab", "O2Heater_Settings10", MiscBlock.Extended, 97), + new("O2Heater tab", "LaunchBoss_Settings3", MiscBlock.Extended, 98), + new("O2Heater tab", "LaunchBoss_RPM_Limit_Fixed_div100", MiscBlock.Extended, 99), + new("O2Autotune tab", "O2_Autotune_Settings2", MiscBlock.Extended, 100), + new("O2Autotune tab", "O2_Autotune_Cylinder_Correct", MiscBlock.Extended, 101), + new("O2Autotune tab", "O2_Autotune_Cylinder_Write", MiscBlock.Extended, 102), + new("O2Autotune tab", "O2_Autotune_Settings5", MiscBlock.Extended, 103), + new("O2Autotune tab", "VRS_Settings1", MiscBlock.Extended, 104), + new("O2Autotune tab", "MC33814_VRS_MaxVolt_Val", MiscBlock.Extended, 105), + new("O2Autotune tab", "MC33814_Relay1_Config", MiscBlock.Extended, 106), + new("O2Autotune tab", "MC33814_Relay2_Config", MiscBlock.Extended, 107), + new("MCU Tacho tab", "MCU_Tacho_Settings1", MiscBlock.Extended, 108), + new("MCU Tacho tab", "MCU_Tacho_Divider", MiscBlock.Extended, 109), + new("MCU Tacho tab", "MCU_Tacho_Settings3", MiscBlock.Extended, 110), + new("MCU Tacho tab", "MCU_Tacho_Settings4", MiscBlock.Extended, 111), + new("MCU Tacho tab", "Meter_Speed_Mult", MiscBlock.Extended, 112), + new("MCU Tacho tab", "Meter_Speed_Div", MiscBlock.Extended, 113), + new("MCU Tacho tab", "Meter_Speed_Test", MiscBlock.Extended, 114), + new("MCU Tacho tab", "Meter_FC_Mult", MiscBlock.Extended, 115), + new("VVA tab", "VVA_Settings1", MiscBlock.Extended, 116), + new("VVA tab", "VVA_Settings2", MiscBlock.Extended, 117), + new("VVA tab", "VVA_Settings3", MiscBlock.Extended, 118), + new("VVA tab", "VVA_Settings4", MiscBlock.Extended, 119), + new("VVA tab", "VVA_Etemp_HiVal", MiscBlock.Extended, 120), + new("VVA tab", "VVA_Etemp_LoVal", MiscBlock.Extended, 121), + new("VVA tab", "VVA_EngineOn_Delay1_100ms", MiscBlock.Extended, 122), + new("VVA tab", "VVA_EngineOn_Delay2_10ms", MiscBlock.Extended, 123), + new("VVA tab", "VVA_On_RPM_div100", MiscBlock.Extended, 124), + new("VVA tab", "VVA_Off_RPM_div100", MiscBlock.Extended, 125), + new("VVA tab", "VVA_On_TPS_pct", MiscBlock.Extended, 126), + new("VVA tab", "VVA_Off_TPS_pct", MiscBlock.Extended, 127), + new("VVA tab", "VVA_On_Stage1_PWM_Pct", MiscBlock.Extended, 128), + new("VVA tab", "VVA_On_Stage1_Delay_10ms", MiscBlock.Extended, 129), + new("VVA tab", "VVA_On_Stage2_PWM_Pct", MiscBlock.Extended, 130), + new("VVA tab", "VVA_On_Stage2_Delay_10ms", MiscBlock.Extended, 131), + new("VVA tab", "VVA_On_Stage3_PWM_Pct", MiscBlock.Extended, 132), + new("VVA tab", "VVA_On_Stage3_Delay_10ms", MiscBlock.Extended, 133), + new("VVA tab", "VVA_On_Stage4_PWM_Pct", MiscBlock.Extended, 134), + new("VVA tab", "VVA_On_Stage4_Delay_10ms", MiscBlock.Extended, 135), + new("VVA tab", "VVA_On_TableSwap_Delay_ms_lo", MiscBlock.Extended, 136), + new("VVA tab", "VVA_On_TableSwap_Delay_ms_hi", MiscBlock.Extended, 137), + new("VVA tab", "VVA_Off_TableSwap_Delay_ms_lo", MiscBlock.Extended, 138), + new("VVA tab", "VVA_Off_TableSwap_Delay_ms_hi", MiscBlock.Extended, 139), + new("VVA tab", "VVA_On_Tooth", MiscBlock.Extended, 140), + new("VVA tab", "VVA_Off_Tooth", MiscBlock.Extended, 141), + new("VVA tab", "VVA_HiSide_Toggle_Gap_Rpm_div100", MiscBlock.Extended, 142), + new("VVA tab", "VVA_ErrorCheck_Delay_10ms", MiscBlock.Extended, 143), + new("VVA tab", "VVA_Rsvd9", MiscBlock.Extended, 144), + new("VVA tab", "VVA_Rsvd10", MiscBlock.Extended, 145), + new("VVA tab", "VVA_Rsvd11", MiscBlock.Extended, 146), + new("VVA tab", "VVA_Rsvd12", MiscBlock.Extended, 147), + new("VVA tab", "MAP_Error_Value_Fixed", MiscBlock.Extended, 148), + new("VVA tab", "TPS_Error_Value_Fixed", MiscBlock.Extended, 149), + new("VVA tab", "Digital_Input_Mask", MiscBlock.Extended, 150), + new("VVA tab", "Mode_Switch_Settings", MiscBlock.Extended, 151), + }; +} diff --git a/TuneBoss.Core/Models/MiscValues.cs b/TuneBoss.Core/Models/MiscValues.cs new file mode 100644 index 0000000..1ed1a5e --- /dev/null +++ b/TuneBoss.Core/Models/MiscValues.cs @@ -0,0 +1,482 @@ +namespace TuneBoss.Core.Models; + +/// +/// All ECU configuration parameters outside the 2D/1D tuning tables. +/// +/// Five memory regions, each read via APP_MEMRD_MISC. Addresses from +/// GenerationConfig; regions beyond Core gated on EcuInfo.FwVersion >= 150. +/// +/// Region Address field Size FW gate +/// ──────────── ───────────────────────── ─────── ──────── +/// Core miscValStartAddress 136 B always +/// LaunchFuel extraPaddingStartAddress 12 B FW >= 150 +/// LaunchFuel2 extraPaddingStartAddress2 12 B FW >= 150 +/// AuxOut extraPaddingStartAddress3 12 B FW >= 150 +/// Extended extraPaddingStartAddress4 var B FW >= 150 +/// (FW2_SubVersion & 0x80) == 0 → 0x73 (116 B, up to Ex(115)) +/// (FW2_SubVersion & 0x80) != 0 → 0x97 (152 B, full set) +/// +/// Extended label map is authoritative — derived from: +/// READ: UpdateMiscValuesExtraPadding4New() in Form1_Utils.cs +/// WRITE: getMiscValByteArrayExtraPadding4New() in Form1_TableHandling.cs +/// LABELS: Designer.cs parsed per inner tab of tabControl14 (Spark/TC/ISM/ +/// AIS/O2Heater/O2Autotune/MCU Tacho/VVA) inside tabPage93. +/// Each inner tab parsed independently to avoid cross-column pollution. +/// +public sealed class MiscValues +{ + // ── Raw memory regions ─────────────────────────────────────────────────── + public byte[] Core { get; init; } = new byte[136]; + public byte[] LaunchFuel { get; init; } = Array.Empty(); + public byte[] LaunchFuel2 { get; init; } = Array.Empty(); + public byte[] AuxOut { get; init; } = Array.Empty(); + public byte[] Extended { get; init; } = Array.Empty(); + + // ════════════════════════════════════════════════════════════════════════ + // CORE — 136 bytes (tabControl4, tabPage3 through tabPage2) + // ════════════════════════════════════════════════════════════════════════ + + // ── Crank [0–11] ───────────────────────────────────────────────────────── + public byte Crank_Teeth => Core[0]; + public byte Crank_Missing_Teeth => Core[1]; + public byte Crank_Detect_Edge => Core[2]; + public byte CrankTooth_Positive_Period_Pct => Core[3]; + public byte CrankTooth_Negative_Period_Pct => Core[4]; + public byte Crank_Timeout_Pct => Core[5]; + public byte Crank_CamSync_Detect_Method => Core[6]; + public byte Crank_CamSync_Detect_Cycle => Core[7]; + // [8] reserved + public byte Crank_CamSync_MAP_Detect_Cycle => Core[9]; + public byte Crank_CamSync_Rotation_Tooth => Core[10]; + public byte Crank_CamSync_Num_Fast_Rotations => Core[11]; + + // ── RPM [12–22] ────────────────────────────────────────────────────────── + public byte RPM_Limit_div100 => Core[12]; + public byte RPM_Limit_Recovery_div100 => Core[13]; + public byte RPM_Limit_Failsafe_div100 => Core[14]; + public byte RPM_Limit_Failsafe_Recovery_div100 => Core[15]; + public byte RPM_Detect_Min_div100 => Core[16]; + public byte RPM_Detect_Min_Recovery_div100 => Core[17]; + public byte RPM_Stall_div100 => Core[18]; + public byte RPM_Stall_Recovery_div100 => Core[19]; + public byte RPM_Decel_Threshold_PerSec_div100 => Core[20]; + public byte RPM_Accel_Threshold_PerSec_div100 => Core[21]; + public byte RPM_Meter_Divider => Core[22]; + public int RPM_Limit => RPM_Limit_div100 * 100; + + // ── Fuel [23–32] ───────────────────────────────────────────────────────── + public byte Fuel_Settings => Core[23]; + public byte Fuel_Max_PW_Mult => Core[24]; + // [25] reserved + public byte Fuel_Cut_Min_LOAD => Core[26]; + public byte Fuel_Cut_Min_TPS_pct => Core[27]; + public byte Fuel_Cut_Min_RPM_div100 => Core[28]; + public byte Fuel_Cut_Disable_LOAD => Core[29]; + public byte Fuel_Cut_Min_Etemp_degC => Core[30]; + // [31] reserved + public byte VBAT_Trim_deciV => Core[32]; + + // ── O2 Sensor / Autotune [33–47] ───────────────────────────────────────── + // [33] reserved + public byte O2_Sensor_Sample_Rate_ms => Core[34]; + public byte O2_Sensor_Delay_ms_div5 => Core[35]; + public byte O2_Fuel_Max_Add_Pct => Core[36]; + public byte O2_Fuel_Max_Sub_Pct => Core[37]; + public byte O2_Autotune_Max_RPM_div100 => Core[38]; + public byte O2_Autotune_Min_RPM_div100 => Core[39]; + public byte O2_Autotune_Max_Load => Core[40]; + public byte O2_Autotune_Min_Load => Core[41]; + public byte O2_Autotune_StepUp_Pct => Core[42]; + public byte O2_Autotune_Average_Weight => Core[43]; + public byte O2_Autotune_AFR_x10_Diff => Core[44]; + public byte O2_Autotune_Start_Delay_s => Core[45]; + public byte O2_Autotune_Min_ETemp => Core[46]; + public byte O2_Autotune_Max_ETemp => Core[47]; + + // ── TPS [48–55] ────────────────────────────────────────────────────────── + public byte TPS_Accel_Threshold_PctPer100ms => Core[48]; + public byte TPS_Decel_Threshold_PctPer100ms => Core[49]; + public byte TPS_Threshold_10ms_sample_gap => Core[50]; + public byte TPS_Accel_Fuel_Adjust_Hold_Time_10ms => Core[51]; + public byte TPS_Accel_Fuel_Adjust_Decay_Time_10ms => Core[52]; + public byte TPS_Accel_Spark_Adjust_Hold_Time_10ms => Core[53]; + public byte TPS_Accel_Spark_Adjust_Decay_Time_10ms => Core[54]; + public byte TPS_Steady_State_Delay_Time_10ms => Core[55]; + + // ── MAP [56–66] ────────────────────────────────────────────────────────── + public byte MAP_Settings => Core[56]; + public byte MAP_Lo_Hyst_Mult => Core[57]; + public byte MAP_Ref_Temp_DegC => Core[58]; + public byte MAP_Intake_Tooth_End => Core[59]; + public byte MAP_Intake_Num_Teeth => Core[60]; + public byte MAP_Baro_Tooth_End => Core[61]; + public byte MAP_Baro_Num_Teeth => Core[62]; + public byte MAP_Baro_RPM_div100_Limit => Core[63]; + public byte MAP_Baro_TPS_Limit => Core[64]; + public byte MAP_Baro_Static_Delay_10ms => Core[65]; + public byte MAP_Settings2 => Core[66]; + + // ── Radiator / Overheat [67–71] ────────────────────────────────────────── + public byte RadFan_On_Temp_DegC => Core[67]; + public byte RadFan_Off_Temp_DegC => Core[68]; + public byte Etemp_Overheat_On_Temp_DegC => Core[69]; + public byte Etemp_Overheat_Off_Temp_DegC => Core[70]; + public byte Etemp_Sensor_Error_Temp => Core[71]; + + // ── Bluetooth / MC33814 [72–77] ────────────────────────────────────────── + public byte Bluetooth_PowerOn_Timeout_s => Core[72]; + public byte MC33814_Init_Delay_10ms => Core[73]; + public byte MC33814_Tacho_Control => Core[74]; + public byte MC33814_VRS_Misc_Params => Core[75]; + public byte MC33814_Cfg_VRS_Manual_Control => Core[76]; + public byte MC33814_Ctrl_VRS_Conditioner => Core[77]; + + // ── Fuel Pump / Solenoid [78–83] ───────────────────────────────────────── + public byte Fuel_Pump_Timeout_100ms => Core[78]; + public byte Idle_Solenoid_Off_Tooth => Core[79]; + public byte Idle_Solenoid_Reset_RPM_div100 => Core[80]; + public byte Idle_Solenoid_Step_Down => Core[81]; + public byte Idle_Solenoid_PID_Kp => Core[82]; + public byte Idle_Solenoid_Min_Open_Angle_deg => Core[83]; + + // ── ShiftBoss [84–93] ──────────────────────────────────────────────────── + public byte ShiftBoss_Enable => Core[84]; // byte 84 = enable flags (see MiscBitSpecRegistry); real retard deg = ShiftBoss_Spark_Retard_deg & 0x7F + public byte ShiftBoss_Fuel_Cut_ms => Core[85]; + public byte ShiftBoss_Spark_Cut_ms => Core[86]; + public byte ShiftBoss_Spark_Retard_ms => Core[87]; + public byte ShiftBoss_Spark_Retard_deg => Core[88]; + public byte ShiftBoss_Interval_Time_10ms => Core[89]; + public byte ShiftBoss_Min_RPM_div100 => Core[90]; + public byte ShiftBoss_Input_Active_High => Core[91]; + public byte ShiftBoss_Input_Debounce_ms => Core[92]; + public byte ShiftBoss_Autotrigger_RPM_div100 => Core[93]; + + // ── Load selection [94–100] ────────────────────────────────────────────── + public byte Load_Primary_Select => Core[94]; + public byte Load_Fuel_PulseWidth1_Select => Core[95]; + public byte Load_Spark_Angle1_Select => Core[96]; + public byte Load_AFR_Target1_Select => Core[97]; + public byte Load_Fuel_Angle2D_Select => Core[98]; + public byte Load_Fuel_PulseWidth_Adjust1_Select => Core[99]; + public byte Load_Spark_Angle_Adjust1_Select => Core[100]; + + // ── Extended config [101–135] ───────────────────────────────────────────── + public byte VBAT_Min_deciV => Core[101]; + public byte VBAT_Max_deciV => Core[102]; + public byte O2_Sensor_Present => Core[103]; + public byte VDS_Present => Core[104]; + public byte TPS_Accel_Taper_Start_RPM_div100 => Core[105]; + public byte TPS_Accel_Taper_End_RPM_div100 => Core[106]; + public byte Error_Check_Startup_Delay => Core[107]; + public byte ErrorLog_Recording_Delay => Core[108]; + public byte ShiftLight_On_RPM_div100 => Core[109]; + public byte ShiftLight_Off_RPM_div100 => Core[110]; + public byte ShiftLight_Output_Select => Core[111]; + public byte MC33814_Lamp_Config => Core[112]; + public byte MC33814_O2H_Config => Core[113]; + public byte VBAT_Longterm_Min_DeciV => Core[114]; + public byte ErrorLog_MC33814_Mask_Lo => Core[115]; + public byte ErrorLog_MC33814_Mask_Hi => Core[116]; + public byte ErrorLog_MC33814_EngineOff_Enable => Core[117]; + public byte ErrorLog_MC33814_OL_Hysteresis => Core[118]; + public byte ErrorLog_MC33814_Killswitch_Mask => Core[119]; + // [120] reserved + public byte TPS_Accel_Fuel_TempComp => Core[121]; + public byte TPS_Accel_Threshold_Fast_PctPer100ms => Core[122]; + public byte TPS_Decel_Fuel_Adjust_Pct => Core[123]; + public byte TPS_Accel_Modifier_Cyclecount => Core[124]; + public byte TPS_Accel_Threshold_SuperFast_PctPer100ms => Core[125]; + // [120, 126–131] distinct settings/log bytes — named via MiscFieldRegistry, bound raw in the VM + public byte Start_Fuel_Enrichment_Decay_100ms => Core[132]; + public byte TPS_Accel_Recursive_Accel => Core[133]; + public byte Idle_Solenoid_Reset_Timeout_100ms => Core[134]; + public byte Speed_Adjust_Percent => Core[135]; + + public int ShiftLight_On_RPM => ShiftLight_On_RPM_div100 * 100; + public int ShiftLight_Off_RPM => ShiftLight_Off_RPM_div100 * 100; + + // ════════════════════════════════════════════════════════════════════════ + // LAUNCHFUEL — 12 bytes (spark/fuel reference angles + init) + // ════════════════════════════════════════════════════════════════════════ + public byte? RPM_Table_2Samplepoint_div100 => Lf(0); + public byte? Fuel_Init_Cycles => Lf(1); + public byte? Idle_Solenoid_Settings => Lf(2); + public byte? Spark_Ref_Angle_Lo => Lf(3); + public byte? Spark_Ref_Angle_Hi => Lf(4); + public byte? Fuel_Ref_Angle_Lo => Lf(5); + public byte? Fuel_Ref_Angle_Hi => Lf(6); + public byte? Fuel_Base_PW_ms_x10 => Lf(7); + public byte? Spark2_Ref_Angle_Lo => Lf(8); + public byte? Spark2_Ref_Angle_Hi => Lf(9); + public byte? Fuel2_Ref_Angle_Lo => Lf(10); + public byte? Fuel2_Ref_Angle_Hi => Lf(11); + + // ════════════════════════════════════════════════════════════════════════ + // LAUNCHFUEL2 — 12 bytes (launch control + rad fan) + // ════════════════════════════════════════════════════════════════════════ + public byte? LF2_TBD_Unused => Lf2(0); + public byte? LaunchBoss_Enable => Lf2(1); + public byte? LaunchBoss_Settings => Lf2(2); + public byte? LaunchBoss_RPM_Limit_Start_div100 => Lf2(3); + public byte? LaunchBoss_RPM_Limit_End_div100 => Lf2(4); + public byte? LaunchBoss_RPM_Persec_Up_Rate_div100 => Lf2(5); + public byte? LaunchBoss_RPM_Up_Speed_Start_kph => Lf2(6); + public byte? LaunchBoss_Speed_End_kph => Lf2(7); + public byte? LaunchBoss_Spark_Retard_deg => Lf2(8); + public byte? LF2_RadFan_Settings => Lf2(9); + public byte? LF2_RadFan_PWM_Width_100ms => Lf2(10); + public byte? Analog_Safe_Mode_Trigger => Lf2(11); + + // ════════════════════════════════════════════════════════════════════════ + // AUXOUT — 12 bytes + // ════════════════════════════════════════════════════════════════════════ + public byte? AuxOut_Control => Ao(0); + public byte? AuxOut_Control2 => Ao(1); + public byte? RadFan_On_Temp_NOS_RPM => Ao(2); + public byte? RadFan_Off_Temp_NOS_TPS => Ao(3); + public byte? NOS_Speed => Ao(4); + public byte? AuxOut_Ref_Value2_Off => Ao(5); + public byte? AuxOut_Delay1_10ms => Ao(6); + public byte? AuxOut_Delay2_10ms => Ao(7); + public byte? Idle_Threshold_TPS => Ao(8); + public byte? Idle_Threshold_RPM_div100 => Ao(9); + public byte? Spark_Dwell_Max_100us => Ao(10); + public byte? Spark_Dwell_Min_100us => Ao(11); + public int? AuxOut_Mode_Index => AuxOut_Control is byte b && b <= 3 ? (int?)b : null; + + // ════════════════════════════════════════════════════════════════════════ + // EXTENDED — variable size + // + // Buffer index → textbox → label, sourced from: + // READ: UpdateMiscValuesExtraPadding4New() (Form1_Utils.cs) + // WRITE: getMiscValByteArrayExtraPadding4New() (Form1_TableHandling.cs) + // LABELS: Designer.cs per-inner-tab parsing of tabControl14 inside tabPage93 + // + // Y15 [0–41] — always present when Extended is non-empty + // R25 [42–115] — EcuVariant >= TwoCylinder + // R15 [116–151]— EcuVariant == TwoCylinderR15 + // ════════════════════════════════════════════════════════════════════════ + + // ── Y15: Spark tab [0–17] ──────────────────────────────────────────────── + public byte? Spark_Dwell_Reduction_10us => Ex(0); // textBox261 + public byte? Spark_Dwell_Min_Deg => Ex(1); // textBox262 + public byte? Spark_Dwell_Max_Deg_div4 => Ex(2); // textBox263 + public byte? Spark_Dwell_Reserved1 => Ex(3); // textBox264 + public byte? Crank_MissingTooth2_Pos_Period_Mult => Ex(4); // textBox265 + public byte? Crank_MissingTooth2_Neg_Period_Mult => Ex(5); // textBox266 + public byte? Crank_MissingTooth_Pos_Period_Mult => Ex(6); // textBox267 + public byte? Crank_MissingTooth_Neg_Period_Mult => Ex(7); // textBox268 + public byte? VRS_Threshold_Lo_RPM_div100 => Ex(8); // textBox269 + public byte? VRS_Threshold_Hi_RPM_div100 => Ex(9); // textBox270 + public byte? Spark_Cut_Retard1_RPM_Gap_div100 => Ex(10); // textBox271 + public byte? Spark_Cut_Retard2_RPM_Gap_div100 => Ex(11); // textBox272 + public byte? Spark_Cut_Retard1 => Ex(12); // textBox273 + public byte? Spark_Cut_Retard2 => Ex(13); // textBox274 + public byte? CrankTooth_Pos_Period_Mult_Run => Ex(14); // textBox275 + public byte? CrankTooth_Neg_Period_Mult_Run => Ex(15); // textBox276 + public byte? Gear_Ratio_Hysteresis_Count => Ex(16); // textBox277 + public byte? Gear_Ratio_min_RPM_div100 => Ex(17); // textBox278 + + // ── Y15: TC tab [18–41] ────────────────────────────────────────────────── + public byte? TC_Settings1 => Ex(18); // textBox279 + public byte? TC_Settings2 => Ex(19); // textBox280 + public byte? TC_Rpm_Min_div100 => Ex(20); // textBox281 + public byte? TC_Rpm_Max_div100 => Ex(21); // textBox282 + public byte? TC_TPS_Min => Ex(22); // textBox283 + public byte? TC_TPS_Max => Ex(23); // textBox284 + public byte? TC_Speed_Min => Ex(24); // textBox285 + public byte? TC_Speed_Max => Ex(25); // textBox286 + public byte? TC_Consecutive_Error_Trigger => Ex(26); // textBox287 + public byte? TC_Retard_Off_Ramp_deg_per100ms => Ex(27); // textBox288 + public byte? TC_Table_Input_Selection => Ex(28); // textBox289 + public byte? TC_Sample_Rate_ms => Ex(29); // textBox290 + public byte? TC_Speed_Tooth_Skip => Ex(30); // textBox291 + public byte? TC_Tooth_Average_Count => Ex(31); // textBox292 + public byte? TC_Tooth_Compare_Count => Ex(32); // textBox293 + public byte? TC_Gear_Max => Ex(33); // textBox294 + public byte? TC_Button_Modes => Ex(34); // textBox295 + public byte? TC_Button_Sensitivity_Modifier => Ex(35); // textBox296 + public byte? TC_Button_Delay_100ms => Ex(36); // textBox297 + public byte? TC_Tooth_Undriven_Count => Ex(37); // textBox298 + public byte? TC_Reserved6 => Ex(38); // textBox299 + public byte? Offthrottle_Threshold_TPS => Ex(39); // textBox300 + public byte? Idle_Rumble_Min_Rpm_div100 => Ex(40); // textBox301 + public byte? Speed_Settings1 => Ex(41); // textBox302 + + // ── R25: ISM tab [42–75] ───────────────────────────────────────────────── + public byte? ISM_Settings1 => Ex(42); // textBox303 + public byte? ISM_Startup_Delay_10ms => Ex(43); // textBox304 ✓ + public byte? ISM_Max_Steps_Lo => Ex(44); // textBox305 + public byte? ISM_Max_Steps_Hi => Ex(45); // textBox306 + public byte? ISM_CR0_Init => Ex(46); // textBox307 + public byte? ISM_CR1_Init => Ex(47); // textBox308 + public byte? ISM_CR2_Init => Ex(48); // textBox309 + public byte? ISM_Test_Step_Lo => Ex(49); // textBox310 ✓ + public byte? ISM_Test_Step_Hi => Ex(50); // textBox311 + public byte? ISM_Off_Delay_10ms => Ex(51); // textBox312 + public byte? ISM_Max_Open_Steps_Per_Cycle => Ex(52); // textBox313 + public byte? ISM_Max_Close_Steps_Per_Cycle => Ex(53); // textBox314 + public byte? ISM_CR0_Run => Ex(54); // textBox315 + public byte? ISM_CR0_Hold => Ex(55); // textBox316 + public byte? ISM_Calibrate_Overshoot_Steps => Ex(56); // textBox317 + public byte? ISM_PID_Delay_5ms => Ex(57); // textBox318 + public byte? ISM_PID_Kp_lo => Ex(58); // textBox319 + public byte? ISM_PID_Kp_hi => Ex(59); // textBox320 + public byte? ISM_PID_Ki_lo => Ex(60); // textBox321 + public byte? ISM_PID_Ki_hi => Ex(61); // textBox322 + public byte? ISM_PID_Kd_lo => Ex(62); // textBox323 + public byte? ISM_PID_Kd_hi => Ex(63); // textBox324 + public byte? ISM_PID_Error_Threshold => Ex(64); // textBox325 + public byte? ISM_PID_Config => Ex(65); // textBox326 + public byte? ISM_Start_Boost_Step_raw => Ex(66); // textBox327 + public byte? ISM_Stall_Boost_Step_raw => Ex(67); // textBox328 + public byte? ISM_Start_Boost_Step_Delay_100ms => Ex(68); // textBox329 + public byte? ISM_Stall_Boost_Step_Delay_100ms => Ex(69); // textBox330 + public byte? ISM_Stall_Boost_RPM_div100 => Ex(70); // textBox331 + public byte? ISM_Boost_Step_Mult => Ex(71); // textBox332 + public byte? ISM_PID_Gain_Mult => Ex(72); // textBox333 + public byte? ISM_PID_Gain_Div_ShiftRight => Ex(73); // textBox334 + public byte? ISM_PID_RPM_Rampdown_Rate => Ex(74); // textBox335 + public byte? ISM_Rsvd22 => Ex(75); // textBox336 + + // ── R25: AIS tab [76–83] ───────────────────────────────────────────────── + public byte? AIS_Settings1 => Ex(76); // textBox337 + public byte? AIS_Settings2 => Ex(77); // textBox338 + public byte? AIS_RPM_Threshold1 => Ex(78); // textBox339 + public byte? AIS_TPS_Threshold1 => Ex(79); // textBox340 + public byte? AIS_RPM_Threshold2 => Ex(80); // textBox341 + public byte? AIS_TPS_Threshold2 => Ex(81); // textBox342 + public byte? AIS_RPM_Threshold3 => Ex(82); // textBox343 + public byte? AIS_TPS_Threshold3 => Ex(83); // textBox344 + + // ── R25: O2Heater tab [84–99] ──────────────────────────────────────────── + public byte? AIS_Delay1_10ms => Ex(84); // textBox345 + public byte? AIS_Settings10 => Ex(85); // textBox346 + public byte? ETEMP_Sensor_Sample_Rate_ms => Ex(86); // textBox347 + public byte? IAT_Sensor_Sample_Rate_ms => Ex(87); // textBox348 + public byte? O2Heater_Settings1 => Ex(88); // textBox349 + public byte? O2Heater_Settings2 => Ex(89); // textBox350 + public byte? O2Heater_Delay1_10ms => Ex(90); // textBox351 + public byte? O2Heater_Settings4 => Ex(91); // textBox352 + public byte? O2Heater_Settings5 => Ex(92); // textBox353 + public byte? O2Heater_Settings6 => Ex(93); // textBox354 + public byte? ShiftBoss_Spark_RampDown_ms => Ex(94); // textBox355 + public byte? ShiftBoss_Spark_RampUp_ms => Ex(95); // textBox356 + public byte? VBAT_UVReset_DeciV => Ex(96); // textBox357 + public byte? O2Heater_Settings10 => Ex(97); // textBox358 + public byte? LaunchBoss_Settings3 => Ex(98); // textBox359 + public byte? LaunchBoss_RPM_Limit_Fixed_div100 => Ex(99); // textBox360 + + // ── R25: O2Autotune tab [100–107] ──────────────────────────────────────── + public byte? O2_Autotune_Settings2 => Ex(100); // textBox361 + public byte? O2_Autotune_Cylinder_Correct => Ex(101); // textBox362 + public byte? O2_Autotune_Cylinder_Write => Ex(102); // textBox363 + public byte? O2_Autotune_Settings5 => Ex(103); // textBox364 + public byte? VRS_Settings1 => Ex(104); // textBox365 + public byte? MC33814_VRS_MaxVolt_Val => Ex(105); // textBox366 + public byte? MC33814_Relay1_Config => Ex(106); // textBox367 + public byte? MC33814_Relay2_Config => Ex(107); // textBox368 + + // ── R25: MCU Tacho tab [108–115] ───────────────────────────────────────── + public byte? MCU_Tacho_Settings1 => Ex(108); // textBox369 + public byte? MCU_Tacho_Divider => Ex(109); // textBox370 + public byte? MCU_Tacho_Settings3 => Ex(110); // textBox371 + public byte? MCU_Tacho_Settings4 => Ex(111); // textBox372 + public byte? Meter_Speed_Mult => Ex(112); // textBox373 + public byte? Meter_Speed_Div => Ex(113); // textBox374 + public byte? Meter_Speed_Test => Ex(114); // textBox375 + public byte? Meter_FC_Mult => Ex(115); // textBox376 + + // ── R15: VVA tab [116–151] ─────────────────────────────────────────────── + public byte? VVA_Settings1 => Ex(116); // textBox377 + public byte? VVA_Settings2 => Ex(117); // textBox378 + public byte? VVA_Settings3 => Ex(118); // textBox379 + public byte? VVA_Settings4 => Ex(119); // textBox380 + public byte? VVA_Etemp_HiVal => Ex(120); // textBox381 + public byte? VVA_Etemp_LoVal => Ex(121); // textBox382 + public byte? VVA_EngineOn_Delay1_100ms => Ex(122); // textBox383 + public byte? VVA_EngineOn_Delay2_10ms => Ex(123); // textBox384 + public byte? VVA_On_RPM_div100 => Ex(124); // textBox385 + public byte? VVA_Off_RPM_div100 => Ex(125); // textBox386 + public byte? VVA_On_TPS_pct => Ex(126); // textBox387 + public byte? VVA_Off_TPS_pct => Ex(127); // textBox388 + public byte? VVA_On_Stage1_PWM_Pct => Ex(128); // textBox389 + public byte? VVA_On_Stage1_Delay_10ms => Ex(129); // textBox390 + public byte? VVA_On_Stage2_PWM_Pct => Ex(130); // textBox391 + public byte? VVA_On_Stage2_Delay_10ms => Ex(131); // textBox392 + public byte? VVA_On_Stage3_PWM_Pct => Ex(132); // textBox393 + public byte? VVA_On_Stage3_Delay_10ms => Ex(133); // textBox394 + public byte? VVA_On_Stage4_PWM_Pct => Ex(134); // textBox395 + public byte? VVA_On_Stage4_Delay_10ms => Ex(135); // textBox396 + public byte? VVA_On_TableSwap_Delay_ms_lo => Ex(136); // textBox397 + public byte? VVA_On_TableSwap_Delay_ms_hi => Ex(137); // textBox398 + public byte? VVA_Off_TableSwap_Delay_ms_lo => Ex(138); // textBox399 + public byte? VVA_Off_TableSwap_Delay_ms_hi => Ex(139); // textBox400 + public byte? VVA_On_Tooth => Ex(140); // textBox401 + public byte? VVA_Off_Tooth => Ex(141); // textBox402 + public byte? VVA_HiSide_Toggle_Gap_Rpm_div100 => Ex(142); // textBox403 + public byte? VVA_ErrorCheck_Delay_10ms => Ex(143); // textBox404 + public byte? VVA_Rsvd9 => Ex(144); // textBox405 + public byte? VVA_Rsvd10 => Ex(145); // textBox406 + public byte? VVA_Rsvd11 => Ex(146); // textBox407 + public byte? VVA_Rsvd12 => Ex(147); // textBox408 + public byte? MAP_Error_Value_Fixed => Ex(148); // textBox409 + public byte? TPS_Error_Value_Fixed => Ex(149); // textBox410 + public byte? Digital_Input_Mask => Ex(150); // textBox411 + public byte? Mode_Switch_Settings => Ex(151); // textBox412 + + // ════════════════════════════════════════════════════════════════════════ + // FACTORY + // ════════════════════════════════════════════════════════════════════════ + public static MiscValues FromPayloads( + byte[] corePayload, + byte[]? launchFuelPayload = null, + byte[]? launchFuel2Payload = null, + byte[]? auxOutPayload = null, + byte[]? extendedPayload = null) + { + static byte[] Slice(byte[]? payload, int size) + { + if (payload == null || payload.Length < 4 + size) return Array.Empty(); + var buf = new byte[size]; + Buffer.BlockCopy(payload, 4, buf, 0, size); + return buf; + } + int extSize = extendedPayload != null ? Math.Max(0, extendedPayload.Length - 4) : 0; + return new MiscValues + { + Core = Slice(corePayload, 136), + LaunchFuel = Slice(launchFuelPayload, 12), + LaunchFuel2 = Slice(launchFuel2Payload, 12), + AuxOut = Slice(auxOutPayload, 12), + Extended = extendedPayload != null && extSize > 0 + ? Slice(extendedPayload, extSize) + : Array.Empty(), + }; + } + + /// + /// Extended region byte count to request. Per the legacy firmware, this is gated by + /// bit 7 of FW2_SubVersion, NOT by bike model: + /// (FW2_SubVersion & 0x80) != 0 → full extended set (0x97 = 152 bytes) + /// otherwise → up to Ex(115) (0x73 = 116 bytes) + /// + public static byte ExtendedLengthFor(byte fw2SubVersion) + => (fw2SubVersion & 0x80) != 0 ? (byte)0x97 : (byte)0x73; + + private byte? Lf(int i) => i < LaunchFuel.Length ? LaunchFuel[i] : null; + private byte? Lf2(int i) => i < LaunchFuel2.Length ? LaunchFuel2[i] : null; + private byte? Ao(int i) => i < AuxOut.Length ? AuxOut[i] : null; + private byte? Ex(int i) => i < Extended.Length ? Extended[i] : null; +} + +/// +/// Bike cylinder classification — determines Extended region size. +/// Derived from EcuInfo via TwoCylinderRegistry. +/// +public enum EcuVariant +{ + SingleCylinder, // Y15, NVX etc. — Extended = 0x29 + TwoCylinder, // R25, R3, MT25 — Extended = 0x73 + TwoCylinderR15, // R15M, CBR250RR — Extended = 0x97 +} diff --git a/TuneBoss.Core/Models/OneDimDisplay.cs b/TuneBoss.Core/Models/OneDimDisplay.cs new file mode 100644 index 0000000..53132c5 --- /dev/null +++ b/TuneBoss.Core/Models/OneDimDisplay.cs @@ -0,0 +1,39 @@ +using System; + +namespace TuneBoss.Core.Models +{ + /// + /// Display scaling for 1D tables: displayed value = raw × multiplier. + /// A multiplier of 0 or 1 means unscaled (×1). Editing is done in displayed units + /// and must land on a multiple of the multiplier. + /// + /// This is the single source of truth for the rules the 1D view-model applies + /// (OneDimTablesViewModel can delegate to it so the UI and tests can't drift). + /// + public static class OneDimDisplay + { + /// 0/1 => 1; otherwise the multiplier itself. + public static int EffectiveMultiplier(int multiplier) => multiplier < 1 ? 1 : multiplier; + + /// Raw byte value → displayed value. + public static long ToDisplay(int raw, int multiplier) => + (long)raw * EffectiveMultiplier(multiplier); + + /// + /// Displayed value → raw. Returns false if the displayed value is not an exact + /// multiple of the (effective) multiplier, so the caller can reject the edit. + /// + public static bool TryFromDisplay(double display, int multiplier, out int raw) + { + int m = EffectiveMultiplier(multiplier); + double q = display / m; + if (Math.Abs(q - Math.Round(q)) > 1e-6) + { + raw = 0; + return false; + } + raw = (int)Math.Round(q); + return true; + } + } +} diff --git a/TuneBoss.Core/Models/OneDimTable.cs b/TuneBoss.Core/Models/OneDimTable.cs new file mode 100644 index 0000000..46bfea5 --- /dev/null +++ b/TuneBoss.Core/Models/OneDimTable.cs @@ -0,0 +1,127 @@ +using System; + +namespace TuneBoss.Core.Models +{ + /// + /// A 1D lookup table as stored on the ECU: 8 raw-axis breakpoints mapped to + /// 8 conversion (output) values, plus 8 metadata bytes (scaling / sign / clamp). + /// + /// Fixed 24-byte wire layout: + /// [0..7] raw axis breakpoints (signed when RawSignedFlag > 0) + /// [8..15] conversion/output vals (signed when ConvSignedFlag > 0) + /// [16] MaxRaw (follows raw sign) + /// [17] MinRaw (follows raw sign) + /// [18] RawSignedFlag (> 0 => axis bytes are signed) + /// [19] ConvSignedFlag (> 0 => value bytes are signed) + /// [20] RawMultiplier (firmware-side display scaling) + /// [21] ConvMultiplier + /// [22] RawRounding + /// [23] ConvOffset (ALWAYS signed) + /// + /// Read with APP_MEMRD_1D (0x43), written with APP_MEMWR_1D (0x4B). + /// The sign flags and the four scaling bytes are round-tripped VERBATIM so a + /// write never disturbs metadata the firmware relies on. + /// + public sealed class OneDimTable + { + public const int PointCount = 8; + public const int WireLength = 24; + + public int[] RawAxis { get; } + public int[] ConvValues { get; } + + // metadata (bytes 16..23) + public int MaxRaw { get; set; } + public int MinRaw { get; set; } + public byte RawSignedFlag { get; set; } + public byte ConvSignedFlag { get; set; } + public byte RawMultiplier { get; set; } + public byte ConvMultiplier { get; set; } + public byte RawRounding { get; set; } + public sbyte ConvOffset { get; set; } + + public bool IsRawSigned => RawSignedFlag > 0; + public bool IsConvSigned => ConvSignedFlag > 0; + + public OneDimTable() + { + RawAxis = new int[PointCount]; + ConvValues = new int[PointCount]; + } + + /// Decode a 24-byte block (e.g. the data section of a 0x51 0x43 response). + public static OneDimTable FromWire(byte[] data, int offset = 0) + { + if (data is null) throw new ArgumentNullException(nameof(data)); + if (data.Length - offset < WireLength) + throw new ArgumentException($"1D payload needs {WireLength} bytes from offset {offset}.", nameof(data)); + + var t = new OneDimTable + { + RawSignedFlag = data[offset + 18], + ConvSignedFlag = data[offset + 19], + RawMultiplier = data[offset + 20], + ConvMultiplier = data[offset + 21], + RawRounding = data[offset + 22], + ConvOffset = unchecked((sbyte)data[offset + 23]), + }; + + bool rawSigned = t.RawSignedFlag > 0; + bool convSigned = t.ConvSignedFlag > 0; + + for (int i = 0; i < PointCount; i++) + { + t.RawAxis[i] = Decode(data[offset + i], rawSigned); + t.ConvValues[i] = Decode(data[offset + 8 + i], convSigned); + } + + t.MaxRaw = Decode(data[offset + 16], rawSigned); + t.MinRaw = Decode(data[offset + 17], rawSigned); + return t; + } + + /// Produce the 24-byte data block to send with APP_MEMWR_1D. + public byte[] ToWirePayload() + { + var d = new byte[WireLength]; + bool rawSigned = IsRawSigned; + bool convSigned = IsConvSigned; + + for (int i = 0; i < PointCount; i++) + { + d[i] = Encode(RawAxis[i], rawSigned); + d[8 + i] = Encode(ConvValues[i], convSigned); + } + + d[16] = Encode(MaxRaw, rawSigned); + d[17] = Encode(MinRaw, rawSigned); + d[18] = RawSignedFlag; + d[19] = ConvSignedFlag; + d[20] = RawMultiplier; + d[21] = ConvMultiplier; + d[22] = RawRounding; + d[23] = unchecked((byte)ConvOffset); + return d; + } + + public OneDimTable Clone() + { + var c = new OneDimTable + { + MaxRaw = MaxRaw, MinRaw = MinRaw, + RawSignedFlag = RawSignedFlag, ConvSignedFlag = ConvSignedFlag, + RawMultiplier = RawMultiplier, ConvMultiplier = ConvMultiplier, + RawRounding = RawRounding, ConvOffset = ConvOffset, + }; + Array.Copy(RawAxis, c.RawAxis, PointCount); + Array.Copy(ConvValues, c.ConvValues, PointCount); + return c; + } + + private static int Decode(byte b, bool signed) => signed ? unchecked((sbyte)b) : b; + + private static byte Encode(int v, bool signed) => signed + ? unchecked((byte)(sbyte)Math.Clamp(v, sbyte.MinValue, sbyte.MaxValue)) + : (byte)Math.Clamp(v, byte.MinValue, byte.MaxValue); + } +} diff --git a/TuneBoss.Core/Models/OneDimTableRegistry.cs b/TuneBoss.Core/Models/OneDimTableRegistry.cs new file mode 100644 index 0000000..0bddc2a --- /dev/null +++ b/TuneBoss.Core/Models/OneDimTableRegistry.cs @@ -0,0 +1,102 @@ +using System.Collections.Generic; + +namespace TuneBoss.Core.Models +{ + public enum OneDimGroup + { + SensorCalibration, + FuelCompensation, + SparkCompensation, + IdleControl, + TractionControl, + Quickshifter, + Nitrous, + OutputsAndHardware, + } + + /// + /// Stable identity of a 1D table slot. The ECU ADDRESS is generation-dependent and + /// is resolved at connect time (see MemoryLayout) — it is intentionally NOT stored + /// here. Slot is the 1-based ECU read order. + /// + /// AxisUnit / ValueUnit are display-only labels (proposed defaults — editable in the + /// UI per table). They never affect the wire format. + /// + public sealed record OneDimTableDefinition( + int Slot, + string Label, + OneDimGroup Group, + int MinFirmware, // 0 = base; otherwise 80 / 83 / 90 / 130 + string AxisUnit = "", + string ValueUnit = ""); + + public static class OneDimTableRegistry + { + public static readonly IReadOnlyList All = new[] + { + new OneDimTableDefinition( 1, "Spark Dwell Time", OneDimGroup.OutputsAndHardware, 0, "V", "ms"), + new OneDimTableDefinition( 2, "O2 Sensor", OneDimGroup.SensorCalibration, 0, "mV", "AFR"), + new OneDimTableDefinition( 3, "Intake Air Temperature", OneDimGroup.SensorCalibration, 0, "raw", "\u00B0C"), + new OneDimTableDefinition( 4, "Engine Temperature", OneDimGroup.SensorCalibration, 0, "raw", "\u00B0C"), + new OneDimTableDefinition( 5, "Manifold Air Pressure", OneDimGroup.SensorCalibration, 0, "raw", "kPa"), + new OneDimTableDefinition( 6, "Throttle Position", OneDimGroup.SensorCalibration, 0, "raw", "%"), + new OneDimTableDefinition( 7, "Fuel \u00B7 Engine Temp", OneDimGroup.FuelCompensation, 0, "\u00B0C", "%"), + new OneDimTableDefinition( 8, "Spark \u00B7 Engine Temp", OneDimGroup.SparkCompensation, 0, "\u00B0C", "\u00B0"), + new OneDimTableDefinition( 9, "Fuel \u00B7 Barometer", OneDimGroup.FuelCompensation, 0, "kPa", "%"), + new OneDimTableDefinition(10, "AUX Conversion", OneDimGroup.OutputsAndHardware, 0, "raw", "raw"), + new OneDimTableDefinition(11, "Fuel \u00B7 Intake Air Temp", OneDimGroup.FuelCompensation, 0, "\u00B0C", "%"), + new OneDimTableDefinition(12, "Spark \u00B7 Intake Air Temp", OneDimGroup.SparkCompensation, 0, "\u00B0C", "\u00B0"), + new OneDimTableDefinition(13, "Fuel \u00B7 TPS Accel", OneDimGroup.FuelCompensation, 0, "%", "%"), + new OneDimTableDefinition(14, "Spark \u00B7 TPS Accel", OneDimGroup.SparkCompensation, 0, "%", "\u00B0"), + new OneDimTableDefinition(15, "Battery V / Injector Opening", OneDimGroup.OutputsAndHardware, 0, "V", "\u00B5s"), + new OneDimTableDefinition(16, "TPS / MAP Percentage", OneDimGroup.SensorCalibration, 0, "raw", "%"), + new OneDimTableDefinition(17, "Idle Solenoid Ctrl Pct", OneDimGroup.IdleControl, 0, "RPM", "%"), + new OneDimTableDefinition(18, "Startup Fuel Comp", OneDimGroup.FuelCompensation, 0, "\u00B0C", "%"), + new OneDimTableDefinition(19, "Injector 2 Pct", OneDimGroup.OutputsAndHardware, 80, "RPM", "%"), + new OneDimTableDefinition(20, "RadFan PWM", OneDimGroup.OutputsAndHardware, 80, "\u00B0C", "%"), + new OneDimTableDefinition(21, "Idle Spark Rumble", OneDimGroup.Nitrous, 80, "RPM", "\u00B0"), + new OneDimTableDefinition(22, "Antilag Spark Control", OneDimGroup.Nitrous, 80, "RPM", "\u00B0"), + new OneDimTableDefinition(23, "Idle Fuel Pulse Width", OneDimGroup.IdleControl, 80, "\u00B0C", "\u00B5s"), + new OneDimTableDefinition(24, "Off-Throttle Isol Control", OneDimGroup.OutputsAndHardware, 80, "RPM", "%"), + new OneDimTableDefinition(25, "Speed Fuel Comp", OneDimGroup.FuelCompensation, 83, "km/h", "%"), + new OneDimTableDefinition(26, "Speed Spark Comp", OneDimGroup.SparkCompensation, 83, "km/h", "\u00B0"), + new OneDimTableDefinition(27, "ShiftBoss Fuel Cut", OneDimGroup.Quickshifter, 90, "RPM", "%"), + new OneDimTableDefinition(28, "ShiftBoss Spark Cut", OneDimGroup.Quickshifter, 90, "RPM", "%"), + new OneDimTableDefinition(29, "ShiftBoss Spark Retard", OneDimGroup.Quickshifter, 90, "RPM", "\u00B0"), + new OneDimTableDefinition(30, "TC Sensitivity", OneDimGroup.TractionControl, 90, "RPM", "%"), + new OneDimTableDefinition(31, "TC Spark Retard Degrees", OneDimGroup.TractionControl, 90, "%", "\u00B0"), + new OneDimTableDefinition(32, "TC Spark Retard Duration", OneDimGroup.TractionControl, 90, "%", "ms"), + new OneDimTableDefinition(33, "Gear Ratio Detection", OneDimGroup.TractionControl, 90, "gear", "ratio"), + new OneDimTableDefinition(34, "AUX PWM", OneDimGroup.OutputsAndHardware, 90, "raw", "%"), + new OneDimTableDefinition(35, "Idle Solenoid Control Steps", OneDimGroup.IdleControl, 130, "\u00B0C", "steps"), + new OneDimTableDefinition(36, "BARO Spark Comp", OneDimGroup.SparkCompensation, 130, "kPa", "\u00B0"), + new OneDimTableDefinition(37, "Idle Spark Compensation", OneDimGroup.IdleControl, 130, "RPM", "\u00B0"), + }; + + /// Nav-tree order for the groups. + public static readonly IReadOnlyList GroupOrder = new[] + { + OneDimGroup.SensorCalibration, + OneDimGroup.FuelCompensation, + OneDimGroup.SparkCompensation, + OneDimGroup.IdleControl, + OneDimGroup.TractionControl, + OneDimGroup.Quickshifter, + OneDimGroup.Nitrous, + OneDimGroup.OutputsAndHardware, + }; + + public static string DisplayName(OneDimGroup g) => g switch + { + OneDimGroup.SensorCalibration => "Sensor Calibration", + OneDimGroup.FuelCompensation => "Fuel Compensation", + OneDimGroup.SparkCompensation => "Spark Compensation", + OneDimGroup.IdleControl => "Idle Control", + OneDimGroup.TractionControl => "Traction Control", + OneDimGroup.Quickshifter => "Quickshifter", + OneDimGroup.Nitrous => "Rumble & Antilag", + OneDimGroup.OutputsAndHardware => "Outputs & Hardware", + _ => g.ToString(), + }; + } +} diff --git a/TuneBoss.Core/Models/SubTable.cs b/TuneBoss.Core/Models/SubTable.cs new file mode 100644 index 0000000..f3487b5 --- /dev/null +++ b/TuneBoss.Core/Models/SubTable.cs @@ -0,0 +1,182 @@ +namespace TuneBoss.Core.Models; + +/// +/// Data model for a subtable (AFR_Target_SubTable, Fuel_PulseWidth_Adjust_SubTable, +/// Spark_Angle_Adjust_SubTable — one per cylinder pair). +/// +/// A subtable is a small 2D correction grid: 4 load rows × 6 RPM columns, +/// always signed sbyte values. It provides a secondary axis multiplier on +/// top of the main 2D table, keyed by RPM range pairs rather than absolute RPM. +/// +/// ── Wire format — single read/write, no split ───────────────────────────────── +/// +/// Field Size Notes +/// ─────────── ────── ──────────────────────────────────────────────────── +/// Data cells 24 B sbyte[4 rows × 6 cols], row-major, always signed +/// Load axis 4 B byte[4] — fixed default {5, 15, 40, 70} +/// RPM axis 12 B byte[12] — pairs: [lo÷100, hi÷100] × 6 columns +/// +/// Total 40 B = dataInArray(24) + loadInArray(4) + rpmInArray(12) +/// +/// ── Key differences from TuningTable ───────────────────────────────────────── +/// - Always signed sbyte (no sign flag — hard-coded in the UI's Convert.ToSByte) +/// - Smaller grid: 4 rows × 6 cols vs 8 rows × 24 cols +/// - RPM axis uses pairs (low/high range per column), not single values +/// Each RPM cell displays as "loRPM\nhiRPM" (two lines) +/// - No modifier bytes (no MaxRaw/MinRaw/Mult/Sign trailer) +/// - Write sends only dataOutArray (no RPM/load arrays on write) +/// confirmed from writeSubTableFunctionThread: userDataArrayFromTable = sttp.dataOutArray +/// - Read response length comes from _tableMemReadBuffer[2] (Fix 1 in CheckNPreturn) +/// +/// ── Default load axis ───────────────────────────────────────────────────────── +/// Fixed at {5, 15, 40, 70} — hardcoded in SubTuningTablePanel.InitializeTable() +/// +public sealed record SubTable +{ + public const int Rows = 4; + public const int Cols = 6; + public const int DataBytes = Rows * Cols; // 24 + public const int LoadBytes = Rows; // 4 + public const int RpmBytes = Cols * 2; // 12 (lo+hi pair per column) + public const int TotalBytes = DataBytes + LoadBytes + RpmBytes; // 40 + + // ── Default axis values ─────────────────────────────────────────────────── + public static readonly byte[] DefaultLoadAxis = { 5, 15, 40, 70 }; + + // ── Raw wire arrays ─────────────────────────────────────────────────────── + /// + /// 24 bytes — cell data, row-major [row * 6 + col]. + /// Always signed sbyte on wire (stored as byte, interpreted as sbyte). + /// + public byte[] Data { get; init; } = new byte[DataBytes]; + + /// 4 bytes — load axis values. Default: {5, 15, 40, 70}. + public byte[] LoadAxis { get; init; } = (byte[])DefaultLoadAxis.Clone(); + + /// + /// 12 bytes — RPM axis pairs, [lo÷100, hi÷100] interleaved. + /// rpmInArray[col*2] = lo RPM ÷ 100, rpmInArray[col*2+1] = hi RPM ÷ 100. + /// Display: "loRPM\nhiRPM" (two lines per cell in the UI). + /// + public byte[] RpmAxis { get; init; } = new byte[RpmBytes]; + + // ── Derived display values ──────────────────────────────────────────────── + + /// + /// Gets the signed display value for a data cell. + /// SubTable cells are always sbyte — matches Convert.ToSByte() in the UI. + /// + public int GetCell(int row, int col) => + unchecked((sbyte)Data[row * Cols + col]); + + /// Low RPM bound for a column (display units). + public int GetRpmLo(int col) => RpmAxis[col * 2] * 100; + + /// High RPM bound for a column (display units). + public int GetRpmHi(int col) => RpmAxis[col * 2 + 1] * 100; + + /// Load axis value for a row (raw, 0–110). + public int GetLoad(int row) => LoadAxis[row]; + + // ── Deserialisation ─────────────────────────────────────────────────────── + + /// + /// Parses the device response for a subtable read. + /// The response payload starts at byte offset 4 (after the 4-byte header). + /// Response length is given by _tableMemReadBuffer[2] per CheckNPreturn Fix 1. + /// + /// Layout matches sendReadSplitTableToPanelThread (subtable path): + /// response[4 .. 4+DataBytes-1] → Data + /// response[4+DataBytes .. 4+DataBytes+3] → LoadAxis + /// response[4+DataBytes+4 .. 4+TotalBytes-1] → RpmAxis + /// + public static SubTable FromPayload(byte[] payload) + { + int expectedMin = 4 + TotalBytes; + if (payload.Length < expectedMin) + throw new ArgumentException( + $"Expected at least {expectedMin} bytes, got {payload.Length}.", nameof(payload)); + + const int o = 4; + var data = payload[o..(o + DataBytes)]; + var loadAxis = payload[(o + DataBytes)..(o + DataBytes + LoadBytes)]; + var rpmAxis = payload[(o + DataBytes + LoadBytes)..(o + TotalBytes)]; + + return new SubTable + { + Data = data, + LoadAxis = loadAxis, + RpmAxis = rpmAxis, + }; + } + + /// + /// Parses when only the data segment length is known from the response header. + /// Matches the CheckNPreturn Fix 1 pattern: + /// sttp.dataInArray = new byte[_tableMemReadBuffer[2]] + /// BlockCopy from _tableMemReadBuffer[4] + /// Load/RPM axes use defaults when not included in the response. + /// + public static SubTable FromDataOnlyPayload(byte[] payload, int dataLength) + { + if (payload.Length < 4 + dataLength) + throw new ArgumentException( + $"Payload too short for {dataLength} data bytes.", nameof(payload)); + + var data = new byte[dataLength]; + Buffer.BlockCopy(payload, 4, data, 0, dataLength); + + return new SubTable + { + Data = data, + LoadAxis = (byte[])DefaultLoadAxis.Clone(), + RpmAxis = new byte[RpmBytes], + }; + } + + // ── Serialisation ───────────────────────────────────────────────────────── + + /// + /// Returns the data-only write payload (24 bytes). + /// Matches writeSubTableFunctionThread: only dataOutArray is sent, + /// no RPM/load arrays on write. + /// + public byte[] ToWirePayload() => (byte[])Data.Clone(); + + /// + /// Full 40-byte payload including load and RPM axes. + /// Used when full round-trip serialisation is needed. + /// + public byte[] ToFullPayload() + { + var buf = new byte[TotalBytes]; + Buffer.BlockCopy(Data, 0, buf, 0, DataBytes); + Buffer.BlockCopy(LoadAxis, 0, buf, DataBytes, LoadBytes); + Buffer.BlockCopy(RpmAxis, 0, buf, DataBytes + LoadBytes, RpmBytes); + return buf; + } + + // ── Mutation ────────────────────────────────────────────────────────────── + + /// + /// Returns a new SubTable with cell (row, col) adjusted by delta, + /// clamped to the signed sbyte range [-128, 127]. + /// Matches minusButton/addButton in SubTuningTablePanel using Convert.ToSByte. + /// + public SubTable WithCellAdjusted(int row, int col, int delta, + int minVal = -128, int maxVal = 127) + { + var newData = (byte[])Data.Clone(); + int idx = row * Cols + col; + int current = unchecked((sbyte)newData[idx]); + int adjusted = Math.Clamp(current + delta, minVal, maxVal); + newData[idx] = unchecked((byte)(sbyte)adjusted); + + return new SubTable + { + Data = newData, + LoadAxis = LoadAxis, + RpmAxis = RpmAxis, + }; + } +} diff --git a/TuneBoss.Core/Models/TableTracker.cs b/TuneBoss.Core/Models/TableTracker.cs new file mode 100644 index 0000000..ad8572e --- /dev/null +++ b/TuneBoss.Core/Models/TableTracker.cs @@ -0,0 +1,158 @@ +namespace TuneBoss.Core.Models; + +/// +/// Calculates which table cells to highlight during live diagnostics. +/// +/// Given a live sensor value and a table's axis array, returns two indices: +/// [0] = the primary (exact) cell — the bracket the value falls into +/// [1] = the adjacent cell — either the previous or next bracket +/// (-1 means "before first" or "after last" — no secondary highlight) +/// +/// ── Algorithm ──────────────────────────────────────────────────────────────── +/// For each pair of adjacent axis values, the midpoint defines the boundary +/// between brackets. The live value is assigned to the bracket whose midpoint +/// boundary it falls within, then the adjacent bracket is the one whose axis +/// value is closest to the live value. +/// +/// Reverse-engineered from getRpmToHighlight() and getLoadToHighlight() in the +/// WinForms app. Both functions are identical in structure — only the axis +/// length differs (24 for RPM, 8 for Load/TPS). +/// +/// ── Usage ──────────────────────────────────────────────────────────────────── +/// var (col, adjCol) = TableTracker.FindIndex(table.RpmAxis, frame.RPM_Raw); +/// var (row, adjRow) = TableTracker.FindIndex(table.LoadAxis, frame.Load); +/// +/// // TPS-keyed tables (user-adjust: diag4/5/10/11/12) +/// var (row, adjRow) = TableTracker.FindIndex(table.LoadAxis, frame.TPS_Percent); +/// +public static class TableTracker +{ + /// + /// Finds the highlight and adjacent indices for a live value against an axis array. + /// + /// The table axis (RPM ÷100 bytes or load bytes). + /// The live sensor value in the same units as the axis. + /// + /// (highlight, adjacent) where -1 means "out of range on that side". + /// + public static (int Highlight, int Adjacent) FindIndex(byte[] axis, byte value) + { + int n = axis.Length; + if (n == 0) return (0, -1); + if (n == 1) return (0, -1); + + // Below first midpoint → bracket 0 + if (value < Midpoint(axis, 0, 1)) + { + int adj = value < axis[0] ? -1 : 1; + return (0, adj); + } + + // Middle brackets + for (int i = 1; i < n - 1; i++) + { + int lo = Midpoint(axis, i - 1, i); + int hi = Midpoint(axis, i, i + 1); + + if (lo <= value && value < hi) + { + int adj = value < axis[i] ? i - 1 : i + 1; + return (i, adj); + } + } + + // Above last midpoint → bracket n-1 + { + int adj = value < axis[n - 1] ? n - 2 : -1; + return (n - 1, adj); + } + } + + /// + /// Produces a for a tuning table from live frame data. + /// + /// Table RPM axis (raw bytes, each × 100 = RPM). + /// Table load axis (raw bytes). + /// Live RPM raw value from DiagnosticsFrame.RPM_Raw. + /// Live load/TPS value — use frame.Load for main tables, + /// frame.TPS_Percent for user-adjust tables. + public static DiagnosticsTracker Calculate( + byte[] rpmAxis, + byte[] loadAxis, + byte rpmRaw, + byte loadValue) + { + var (col, adjCol) = FindIndex(rpmAxis, rpmRaw); + var (row, adjRow) = FindIndex(loadAxis, loadValue); + + return new DiagnosticsTracker( + ColHighlight: col, + ColLowlight: adjCol, + RowHighlight: row, + RowLowlight: adjRow); + } + + /// + /// Calculates trackers for all loaded tables in a session from one frame. + /// Returns a dictionary keyed by table name. + /// Only includes tables whose axes are loaded. + /// + public static IReadOnlyDictionary CalculateAll( + EcuSession session, + DiagnosticsFrame frame) + { + var result = new Dictionary(); + + byte rpm = frame.RPM_Raw; + byte load = frame.Load; + byte tps = frame.TPS_Percent; + + void Add(string name, TuningTable? t, byte axisValue) + { + if (t == null) return; + result[name] = Calculate(t.RpmAxis, t.LoadAxis, rpm, axisValue); + } + + void AddAfr(string name, AfrTable? t, byte axisValue) + { + if (t == null) return; + result[name] = Calculate(t.RpmAxis, t.LoadAxis, rpm, axisValue); + } + + // Cyl1 main tables — load-keyed + Add("Fuel_PulseWidth1", session.Fuel_PulseWidth1, load); + Add("Spark_Angle1", session.Spark_Angle1, load); + Add("Fuel_Angle2D", session.Fuel_Angle2D, load); + Add("Secondary_Load_Conversion", session.Secondary_Load_Conversion, load); + AddAfr("AFR_Target1", session.AFR_Target1, load); + + // Cyl1 user-adjust — TPS-keyed + Add("Fuel_PulseWidth_Adjust1", session.Fuel_PulseWidth_Adjust1, tps); + Add("Spark_Angle_Adjust1", session.Spark_Angle_Adjust1, tps); + + if (session.IsTwoCylinder) + { + // Cyl2 main tables — load-keyed + Add("Fuel_PulseWidth2", session.Fuel_PulseWidth2, load); + Add("Spark_Angle2", session.Spark_Angle2, load); + Add("Fuel_Angle2D_2", session.Fuel_Angle2D_2, load); + AddAfr("AFR_Target2", session.AFR_Target2, load); + + // Cyl2 user-adjust — TPS-keyed + Add("Fuel_PulseWidth_Adjust2", session.Fuel_PulseWidth_Adjust2, tps); + Add("Spark_Angle_Adjust2", session.Spark_Angle_Adjust2, tps); + } + + return result; + } + + // ── Helpers ─────────────────────────────────────────────────────────────── + + /// + /// Integer midpoint of two adjacent axis values. + /// Matches (rpmArrayRef[i] + rpmArrayRef[i+1]) / 2 in the original code. + /// Uses integer division — no rounding. + /// + private static byte Midpoint(byte[] axis, int i, int j) + => (byte)((axis[i] + axis[j]) / 2); +} diff --git a/TuneBoss.Core/Models/TpsCalibration.cs b/TuneBoss.Core/Models/TpsCalibration.cs new file mode 100644 index 0000000..e49ec93 --- /dev/null +++ b/TuneBoss.Core/Models/TpsCalibration.cs @@ -0,0 +1,101 @@ +using TuneBoss.Core.Protocol; + +namespace TuneBoss.Core.Models; + +/// +/// Throttle-position-sensor calibration rules, resolved verbatim from the legacy +/// WinForms (saveUserReadInfo / TPS page) and Android (TpsCalPage / +/// BtApp.sendTpsCalWrite) sources. +/// +/// The calibration captures the raw TPS ADC (, +/// channel [18]) at closed and wide-open throttle over several sweeps, validates the +/// captured min/max against the per-unit absolute bounds, then writes an 8-byte 1D +/// block and sets the first-use flag. +/// +/// ── Generation addressing (absolute ECU addresses) ─────────────────────────── +/// Gen2 / Gen3 (small-address layout — PG1/EZ115 is Gen3): +/// CalWrite = 0x0078 (120) ← 8-byte calibration block +/// AbsBounds = 0x0088 (136) ← [max, min, store2, store3] sanity bounds +/// AdvSettings = 0x0094 (148) ← advanced TPS toggle (FW ≥ 152) +/// Gen1 (legacy ~1788 range): CalWrite = 0x06FC, AbsBounds = 0x070C, no adv. +/// +public static class TpsCalibration +{ + public readonly record struct Addresses( + ushort CalWrite, + ushort AbsBounds, + ushort AdvSettings, + bool AdvSupported); + + /// Minimum firmware that exposes the advanced TPS settings byte. + public const int AdvMinFirmware = 152; + + /// Number of full open/close sweeps the guide asks the tuner to perform. + public const int RequiredSweeps = 5; + + /// + /// FirstUseInfo[0] sentinel (READ_INFO buf[32], the DD slot, overloaded as a flag + /// on Gen2/Gen3). The unit is considered calibrated iff this byte == 1. + /// + public const byte CalDoneFlag = 1; + + // Absolute-bounds editor limits (legacy long-press editor ranges). + public const byte AbsMaxFloor = 180, AbsMaxCeil = 198; + public const byte AbsMinFloor = 2, AbsMinCeil = 10; + + /// Resolves the calibration addresses for a generation + firmware. + public static Addresses For(GenerationType generation, byte fwVersion) => generation switch + { + GenerationType.Gen1 => new Addresses(0x06FC, 0x070C, 0x0000, AdvSupported: false), + _ => new Addresses(0x0078, 0x0088, 0x0094, AdvSupported: fwVersion >= AdvMinFirmware), + }; + + /// Convenience overload resolving the generation from . + public static Addresses For(EcuInfo info) => + For((GenerationType)info.AppInfoVersion, info.FwVersion); + + /// + /// Builds the 8-byte 1D calibration payload exactly as the legacy + /// sendTpsCalWrite does: [min, max, max+2, max+4, max+6, max+8, max+10, max+12]. + /// The trailing ramp defines the TPS% curve above wide-open throttle. + /// + public static byte[] BuildCalWritePayload(int minRaw, int maxRaw) + { + byte m = (byte)(maxRaw & 0xFF); + return new[] + { + (byte)(minRaw & 0xFF), + m, + (byte)(m + 2), (byte)(m + 4), (byte)(m + 6), + (byte)(m + 8), (byte)(m + 10), (byte)(m + 12), + }; + } + + public enum Validation + { + Ok, + MinBelowFloor, // captured closed-throttle raw fell below the absolute minimum + MaxAboveCeiling, // captured WOT raw rose above the absolute maximum + Extreme, // crossed/implausible values + } + + /// + /// Replicates the legacy acceptance test against the absolute bounds read from + /// ([0] = absMax, [1] = absMin). + /// + public static Validation Validate(int minRaw, int maxRaw, int absMin, int absMax) + { + if (minRaw < absMin) return Validation.MinBelowFloor; + if (maxRaw > absMax) return Validation.MaxAboveCeiling; + if (minRaw > absMax || maxRaw < absMin) return Validation.Extreme; + return Validation.Ok; + } + + public static string Describe(Validation v, int minRaw, int maxRaw, int absMin, int absMax) => v switch + { + Validation.MinBelowFloor => $"Min raw {minRaw} is below the expected minimum of {absMin}. Please check your throttle.", + Validation.MaxAboveCeiling => $"Max raw {maxRaw} is above the expected maximum of {absMax}. Please check your throttle.", + Validation.Extreme => $"Calibration failed due to extreme TPS values (min {minRaw}, max {maxRaw}). Please check your throttle.", + _ => $"Calibration successful — min {minRaw}, max {maxRaw}.", + }; +} diff --git a/TuneBoss.Core/Models/TuningTable.cs b/TuneBoss.Core/Models/TuningTable.cs new file mode 100644 index 0000000..4dc07d3 --- /dev/null +++ b/TuneBoss.Core/Models/TuningTable.cs @@ -0,0 +1,232 @@ +namespace TuneBoss.Core.Models; + +/// +/// Complete data model for a 2D tuning table (Fuel PulseWidth, Spark Angle, +/// AFR Target, etc.). +/// +/// ── Wire format on the device ──────────────────────────────────────────────── +/// Total payload = 227 bytes, split across two reads/writes at 0x7F boundary: +/// +/// Offset Length Field +/// ─────── ─────── ────────────────────────────────────────────────────── +/// 0 192 Data cells (24 cols × 8 rows, row-major, byte each) +/// 192 8 Load axis (8 bytes, ascending, 0–110 range) +/// 200 24 RPM axis (24 bytes, each × 100 = actual RPM) +/// 224 1 Max raw (byte; sbyte if signed) +/// 225 1 Min raw (byte; sbyte if signed) +/// 226 1 Mult (multiplier for display scaling) +/// 227 1 Sign (0 = unsigned byte, >0 = signed sbyte) +/// +/// Split read: +/// Part 1: bytes [0..127] → lengthFirstPart = 0x7F (127) +/// Part 2: bytes [128..227] → lengthSecondPart = 227 - 127 - 1 = 99 +/// Part 2 address = baseAddress + 0x7F + 1 +/// +/// Split write (same split, different order — data is written first): +/// Part 1 writes dataArray[0..127] +/// Part 2 writes dataArray[128..191] + loadArray[0..7] +/// + rpmArray[0..23] + modifiers[0..3] +/// +/// ── Display / UI mapping ───────────────────────────────────────────────────── +/// RPM axis : stored as raw byte (÷100 on wire), displayed × 100 (e.g. 50→5000) +/// Load axis : stored as raw byte (0–110), displayed as-is +/// Data cells: if Sign > 0 → sbyte interpretation, else byte +/// minDataVal/maxDataVal derived from min/maxRawVal via sign flag +/// Color map : 7 linear bands from minDataVal to maxDataVal (red→green) +/// +public sealed record TuningTable +{ + // ── Dimensions ──────────────────────────────────────────────────────────── + public const int Cols = 24; // RPM columns + public const int Rows = 8; // Load rows + public const int DataBytes = Cols * Rows; // 192 + + // ── Split constants (match TableHandling lengthFirstPart) ───────────────── + public const int SplitFirstLength = 0x7F; // 127 + public const int TotalPayloadBytes = DataBytes + Rows + Cols + 4; // 228 + + // ── Raw wire arrays ─────────────────────────────────────────────────────── + /// 192 bytes, row-major [row * 24 + col]. + public byte[] Data { get; init; } = new byte[DataBytes]; + + /// 8 bytes — load axis values (0–110). + public byte[] LoadAxis { get; init; } = new byte[Rows]; + + /// 24 bytes — RPM axis, each × 100 = actual RPM. + public byte[] RpmAxis { get; init; } = new byte[Cols]; + + // ── Modifiers (bytes 224–227) ───────────────────────────────────────────── + /// Raw max value from device (index [0] in modifiersInArray). + public byte MaxRaw { get; init; } + + /// Raw min value from device (index [1] in modifiersInArray). + public byte MinRaw { get; init; } + + /// Multiplier for display scaling (index [2]). + public byte Mult { get; init; } + + /// Sign flag: 0 = unsigned byte, >0 = signed sbyte (index [3]). + public byte Sign { get; init; } + + // ── Derived display values ──────────────────────────────────────────────── + public bool IsSigned => Sign > 0; + + /// Display min — sbyte if signed, byte if unsigned. + public int MinDataVal => IsSigned + ? unchecked((sbyte)MinRaw) + : (int)MinRaw; + + /// Display max — sbyte if signed, byte if unsigned. + public int MaxDataVal => IsSigned + ? unchecked((sbyte)MaxRaw) + : (int)MaxRaw; + + /// + /// Gets the display value for a cell. + /// Applies sign interpretation matching UpdateTable(readCmd=1) in TuningTablePanel. + /// + public int GetCell(int row, int col) => + IsSigned + ? unchecked((sbyte)Data[row * Cols + col]) + : Data[row * Cols + col]; + + /// RPM axis values in display units (raw × 100). + public int[] RpmValues => RpmAxis.Select(r => r * 100).ToArray(); + + /// Load axis values (raw, 0–110 range). + public int[] LoadValues => LoadAxis.Select(l => (int)l).ToArray(); + + /// + /// 7-band color range thresholds, matching setDataValRange() in TuningTablePanel. + /// dataValRange[x] = minDataVal + (x * (maxDataVal - minDataVal)) / 7 + /// + public double[] ColorBandThresholds() + { + var range = new double[8]; + int span = MaxDataVal - MinDataVal; + for (int x = 0; x < 8; x++) + range[x] = MinDataVal + (x * span) / 7.0; + return range; + } + + // ── Serialisation (write path) ──────────────────────────────────────────── + + /// + /// Builds the combined 228-byte payload for the write path. + /// Matches the order in writeTableFunctionSplitThreadCustom: + /// [0..191] data cells + /// [192..199] load axis + /// [200..223] rpm axis + /// [224] MaxRaw + /// [225] MinRaw + /// [226] Mult + /// [227] Sign + /// + public byte[] ToWirePayload() + { + var buf = new byte[TotalPayloadBytes]; + Buffer.BlockCopy(Data, 0, buf, 0, DataBytes); + Buffer.BlockCopy(LoadAxis,0, buf, DataBytes, Rows); + Buffer.BlockCopy(RpmAxis, 0, buf, DataBytes + Rows, Cols); + buf[DataBytes + Rows + Cols] = MaxRaw; + buf[DataBytes + Rows + Cols + 1] = MinRaw; + buf[DataBytes + Rows + Cols + 2] = Mult; + buf[DataBytes + Rows + Cols + 3] = Sign; + return buf; + } + + /// First 128 bytes of the payload — sent as part 1 of split write. + public byte[] ToWirePayloadPart1() => ToWirePayload()[..( SplitFirstLength + 1)]; + + /// Remaining bytes — sent as part 2 of split write. + public byte[] ToWirePayloadPart2() => ToWirePayload()[(SplitFirstLength + 1)..]; + + // ── Deserialisation (read path) ─────────────────────────────────────────── + + /// + /// Parses a combined 228-byte buffer assembled from the two split reads. + /// Matches sendReadSplitTableToPanelThreadCustom() in Form1_TableHandling.cs. + /// + /// Part 1 response[4..131] → dataCombined[0..127] + /// Part 2 response[4..103] → dataCombined[128..227] + /// + public static TuningTable FromWirePayload(byte[] combined) + { + if (combined.Length < TotalPayloadBytes) + throw new ArgumentException( + $"Expected {TotalPayloadBytes} bytes, got {combined.Length}.", nameof(combined)); + + var data = new byte[DataBytes]; + var loadAxis = new byte[Rows]; + var rpmAxis = new byte[Cols]; + + Buffer.BlockCopy(combined, 0, data, 0, DataBytes); + Buffer.BlockCopy(combined, DataBytes, loadAxis,0, Rows); + Buffer.BlockCopy(combined, DataBytes + Rows, rpmAxis, 0, Cols); + + int modBase = DataBytes + Rows + Cols; + byte maxRaw = combined[modBase]; + byte minRaw = combined[modBase + 1]; + byte mult = combined[modBase + 2]; + byte sign = combined[modBase + 3]; + + return new TuningTable + { + Data = data, + LoadAxis = loadAxis, + RpmAxis = rpmAxis, + MaxRaw = maxRaw, + MinRaw = minRaw, + Mult = mult, + Sign = sign, + }; + } + + /// + /// Assembles the combined payload from the two raw device response buffers. + /// Each response buffer has a 4-byte header; data starts at offset 4. + /// + public static TuningTable FromSplitResponses(byte[] part1Response, byte[] part2Response) + { + var combined = new byte[TotalPayloadBytes]; + + // Part 1: bytes [4 .. 4+SplitFirstLength] → combined[0..SplitFirstLength] + Buffer.BlockCopy(part1Response, 4, combined, 0, + SplitFirstLength + 1); + + // Part 2: bytes [4 ..] → combined[SplitFirstLength+1..] + int part2Len = TotalPayloadBytes - (SplitFirstLength + 1); + Buffer.BlockCopy(part2Response, 4, combined, SplitFirstLength + 1, + part2Len); + + return FromWirePayload(combined); + } + + // ── Mutation (for +1/-1/+5/-5 operations) ──────────────────────────────── + + /// + /// Returns a new TuningTable with the cell at (row, col) adjusted by delta, + /// clamped to [MinDataVal, MaxDataVal]. + /// + public TuningTable WithCellAdjusted(int row, int col, int delta) + { + var newData = (byte[])Data.Clone(); + int idx = row * Cols + col; + int current = IsSigned ? unchecked((sbyte)newData[idx]) : newData[idx]; + int adjusted = Math.Clamp(current + delta, MinDataVal, MaxDataVal); + newData[idx] = IsSigned + ? unchecked((byte)(sbyte)adjusted) + : (byte)adjusted; + + return new TuningTable + { + Data = newData, + LoadAxis = LoadAxis, + RpmAxis = RpmAxis, + MaxRaw = MaxRaw, + MinRaw = MinRaw, + Mult = Mult, + Sign = Sign, + }; + } +} diff --git a/TuneBoss.Core/Models/TwoCylinderRegistry.cs b/TuneBoss.Core/Models/TwoCylinderRegistry.cs new file mode 100644 index 0000000..2f77878 --- /dev/null +++ b/TuneBoss.Core/Models/TwoCylinderRegistry.cs @@ -0,0 +1,68 @@ +using System.Xml.Linq; + +namespace TuneBoss.Core.Models; + +/// +/// Determines whether a bike is a two-cylinder model based on +/// manufacturer + model code, driven by twoCylModels.xml. +/// +public sealed class TwoCylinderRegistry +{ + // Manufacturer codes + public const byte Yamaha = 1; + public const byte Honda = 2; + public const byte Kawasaki = 3; + public const byte Suzuki = 6; + + private readonly Dictionary> _models = new(); + + private TwoCylinderRegistry() { } + + /// + /// Loads from a twoCylModels.xml file path. + /// + public static TwoCylinderRegistry Load(string xmlPath) + { + var doc = XDocument.Load(xmlPath); + var registry = new TwoCylinderRegistry(); + + registry.LoadTag(doc, "ym", Yamaha); + registry.LoadTag(doc, "hn", Honda); + registry.LoadTag(doc, "kw", Kawasaki); + registry.LoadTag(doc, "su", Suzuki); + + return registry; + } + + /// + /// Loads from an XML string (useful for embedding or testing). + /// + public static TwoCylinderRegistry LoadFromString(string xml) + { + var doc = XDocument.Parse(xml); + var registry = new TwoCylinderRegistry(); + + registry.LoadTag(doc, "ym", Yamaha); + registry.LoadTag(doc, "hn", Honda); + registry.LoadTag(doc, "kw", Kawasaki); + registry.LoadTag(doc, "su", Suzuki); + + return registry; + } + + public bool IsTwoCylinder(byte manufacturer, uint model) + { + return _models.TryGetValue(manufacturer, out var set) && set.Contains(model); + } + + private void LoadTag(XDocument doc, string tag, byte manufacturerCode) + { + var models = doc.Descendants(tag) + .Select(e => uint.TryParse(e.Value.Trim(), out var v) ? (uint?)v : null) + .Where(v => v.HasValue) + .Select(v => v!.Value) + .ToHashSet(); + + _models[manufacturerCode] = models; + } +} diff --git a/TuneBoss.Core/Models/VvaModelRegistry.cs b/TuneBoss.Core/Models/VvaModelRegistry.cs new file mode 100644 index 0000000..340a68d --- /dev/null +++ b/TuneBoss.Core/Models/VvaModelRegistry.cs @@ -0,0 +1,114 @@ +using System.Collections.Generic; +using System.Linq; +using System.Xml.Linq; + +namespace TuneBoss.Core.Models; + +/// +/// Which bike models have VVA (variable valve actuation), so the RPM Settings page can +/// gate the VVA RPM Trigger. Mirrors the legacy vvaModels.xml / checkVvaModels. +/// +/// The list is loaded from an EDITABLE external file at +/// %APPDATA%\TuneBoss\vvaModels.xml so it can be changed without recompiling. +/// The file is auto-created (seeded with the defaults below) on first use if missing. +/// If it can't be read, the built-in defaults are used. +/// +/// XML schema (same as legacy): <vvaModels><ym>14</ym>…<hn>…</hn> +/// <su>…</su><kw>…</kw></vvaModels>. +/// Element → manufacturer code: ym=1 Yamaha, hn=2 Honda, kw=3 Kawasaki, su=6 Suzuki. +/// +public static class VvaModelRegistry +{ + private static readonly object _lock = new(); + private static Dictionary>? _map; + + /// Editable list file. Sits beside settings.json in %APPDATA%\TuneBoss. + public static string FilePath => System.IO.Path.Combine( + System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData), + "TuneBoss", "vvaModels.xml"); + + // Element name → manufacturer code. + private static readonly (string Elem, byte Mfr)[] Makes = + { + ("ym", 1), ("hn", 2), ("kw", 3), ("su", 6), + }; + + // Built-in defaults (legacy vvaModels.xml): only these Yamaha models carry VVA. + private static Dictionary> Defaults() => new() + { + [1] = new HashSet { 14, 17, 21, 22 }, + }; + + /// True when the given make/model is known to have VVA. + public static bool IsVvaModel(byte manufacturer, byte model) + { + var map = EnsureLoaded(); + return map.TryGetValue(manufacturer, out var models) && models.Contains(model); + } + + /// Force a re-read of the file on the next lookup (call after editing it). + public static void Reload() + { + lock (_lock) { _map = null; } + } + + private static Dictionary> EnsureLoaded() + { + lock (_lock) + { + if (_map != null) return _map; + + try + { + if (System.IO.File.Exists(FilePath)) + { + _map = Parse(XDocument.Load(FilePath)); + return _map; + } + + // First run — seed the editable file with the defaults, then use them. + _map = Defaults(); + TrySeedFile(); + } + catch + { + // Missing / malformed / unreadable → fall back to the built-in list. + _map = Defaults(); + } + + return _map; + } + } + + private static Dictionary> Parse(XDocument doc) + { + var map = new Dictionary>(); + foreach (var (elem, mfr) in Makes) + { + var set = new HashSet(); + foreach (var node in doc.Descendants(elem)) + { + if (byte.TryParse(node.Value.Trim(), out byte m)) + set.Add(m); // a 999 placeholder simply never matches a real model + } + if (set.Count > 0) map[mfr] = set; + } + return map.Count > 0 ? map : Defaults(); + } + + private static void TrySeedFile() + { + try + { + var dir = System.IO.Path.GetDirectoryName(FilePath); + if (!string.IsNullOrEmpty(dir)) System.IO.Directory.CreateDirectory(dir); + + var doc = new XDocument(new XElement("vvaModels", + new XElement("ym", 14), new XElement("ym", 17), + new XElement("ym", 21), new XElement("ym", 22), + new XElement("hn", 999), new XElement("su", 999), new XElement("kw", 999))); + doc.Save(FilePath); + } + catch { /* seeding is best-effort; defaults still apply in memory */ } + } +} diff --git a/TuneBoss.Core/Protocol/ChecksumHelper.cs b/TuneBoss.Core/Protocol/ChecksumHelper.cs new file mode 100644 index 0000000..7a685ed --- /dev/null +++ b/TuneBoss.Core/Protocol/ChecksumHelper.cs @@ -0,0 +1,73 @@ +namespace TuneBoss.Core.Protocol; + +/// +/// Checksum helpers for the TuneBoss BLE packet protocol. +/// +/// genCheckSumDW: accumulates payload as little-endian uint32 DWords, +/// sums them (wrapping uint32), then returns the bitwise inverse (~sum). +/// Verified against debug log 17-Mar-2026. +/// +public static class ChecksumHelper +{ + /// + /// Computes the DWord checksum over a byte span. + /// The span length must be a multiple of 4 (pad before calling if needed). + /// + public static uint GenChecksumDW(ReadOnlySpan data) + { + if (data.Length % 4 != 0) + throw new ArgumentException("Data length must be a multiple of 4.", nameof(data)); + + uint cumResult = 0; + for (int i = 0; i < data.Length; i += 4) + { + uint dword = data[i] + | ((uint)data[i + 1] << 8) + | ((uint)data[i + 2] << 16) + | ((uint)data[i + 3] << 24); + cumResult += dword; // wrapping uint32 addition + } + + return ~cumResult; // bitwise inverse + } + + /// + /// Writes the 4-byte little-endian checksum into . + /// + public static void WriteChecksumDW(ReadOnlySpan data, Span dest) + { + uint cs = GenChecksumDW(data); + dest[0] = (byte)(cs); + dest[1] = (byte)(cs >> 8); + dest[2] = (byte)(cs >> 16); + dest[3] = (byte)(cs >> 24); + } + + /// + /// Computes the single-byte header inverse sum. + /// sum = TL_type + seqNum + dwCount; result = 0xFF - sum (byte wrap). + /// Verified: TL=02 seq=01 dw=02 → sum=05 → invSum=FA ✓ + /// + public static byte HeaderInverseSum(byte tlType, byte seqNum, byte dwCount) + => unchecked((byte)(0xFF - (tlType + seqNum + dwCount))); + + /// + /// Verifies an inbound packet's DWord checksum. + /// The last 4 bytes of are the checksum; + /// the preceding bytes are the data. + /// + public static bool VerifyChecksumDW(ReadOnlySpan payload) + { + if (payload.Length < 8 || payload.Length % 4 != 0) + return false; + int dataLen = payload.Length - 4; + var data = payload.Slice(0, dataLen); + var expected = payload.Slice(dataLen, 4); + uint computed = GenChecksumDW(data); + + return expected[0] == (byte)(computed) + && expected[1] == (byte)(computed >> 8) + && expected[2] == (byte)(computed >> 16) + && expected[3] == (byte)(computed >> 24); + } +} diff --git a/TuneBoss.Core/Protocol/Commands.cs b/TuneBoss.Core/Protocol/Commands.cs new file mode 100644 index 0000000..1ed4857 --- /dev/null +++ b/TuneBoss.Core/Protocol/Commands.cs @@ -0,0 +1,78 @@ +namespace TuneBoss.Core.Protocol; + +/// +/// TuneBoss hardware command bytes. +/// +public static class Commands +{ + // ── Data Link layer ───────────────────────────────────────────────────── + public const byte DL_ACK = 0x11; + public const byte DL_NAK_HDR = 0x12; + public const byte DL_NAK_DATA = 0x13; + public const byte DL_NAK_OVF = 0x14; // Rx buffer overflow — use smaller packet + public const byte DL_NAK_TIMEOUT = 0x15; + + // ── Transport layer ────────────────────────────────────────────────────── + public const byte TL_POSTED = 0x01; // Requires ACK from device + public const byte TL_NONPOSTED = 0x02; // No ACK; device returns a data packet + public const byte TL_NP_RETURN = 0x03; // Return packet for TL_NONPOSTED + public const byte TL_STREAMING = 0x04; // Streaming; no ACK/NAK required + + public const byte DL_PING_NOREPLY = 0x21; // Host connectivity test; device ignores + + // ── App commands — Non-Posted ──────────────────────────────────────────── + public const byte APP_UNLOCK = 0x30; // Password + current date at byte 4 + public const byte APP_LOCK = 0x31; + public const byte APP_MEMRD_SEQ = 0x32; // Legacy: 8-bit len @ b1, 16-bit addr @ b2-3 + public const byte APP_UNLOCK2 = 0x33; // Basic ECU unlock (GEN3) + public const byte APP_MEMWR_SEQ = 0x34; // Legacy: 8-bit len @ b1, 16-bit addr @ b2-3 + public const byte APP_FIRSTUSE = 0x35; + public const byte APP_FLASH_WR = 0x36; + public const byte APP_READ_INFO = 0x37; // Read ECU info / keepalive + public const byte APP_CHANGE_PWD = 0x38; + public const byte APP_IMMOBILIZER = 0x3A; + public const byte APP_READ_DEBUG = 0x3D; + public const byte APP_UPGRADE_MOD = 0x3E; + + public const byte APP_MEM_INFO = 0x40; // Reserved / ignore for now + + // ── App commands — Table read ──────────────────────────────────────────── + public const byte APP_MEMRD_2D = 0x41; // 2D tables (tuner) + public const byte APP_MEMRD_SUBT = 0x42; // Subtables + public const byte APP_MEMRD_1D = 0x43; // 1D tables + public const byte APP_MEMRD_MISC = 0x44; // Misc values + device info + public const byte APP_MEMRD_2D_USER = 0x45; // 2D user tables (GEN3 basic ECU) + + // ── App commands — Table write ─────────────────────────────────────────── + public const byte APP_MEMWR_2D = 0x49; + public const byte APP_MEMWR_SUBT = 0x4A; + public const byte APP_MEMWR_1D = 0x4B; + public const byte APP_MEMWR_MISC = 0x4C; + public const byte APP_MEMWR_2D_USER = 0x4D; // GEN3 basic ECU + + // ── App response codes ─────────────────────────────────────────────────── + public const byte APP_CMD_SUCCESS = 0x51; + public const byte APP_CMD_FAIL = 0x52; + public const byte APP_CMD_INV = 0x53; + public const byte APP_MEMADDR_INV = 0x54; // Invalid read/write address + public const byte APP_MEMLEN_OVF = 0x55; // Length too large for Tx/Rx buffer + public const byte APP_MEMADDR_LOCK = 0x56; // Address locked (basic ECU) + public const byte APP_TUNER_LOCK = 0x57; // Command locked by tuner + + // ── App commands — Diagnostics streaming ──────────────────────────────── + public const byte APP_MONITORING = 0x70; // Streaming diagnostics frame + public const byte APP_MON_START = 0x71; + public const byte APP_MON_STOP = 0x72; + + // ── App commands — Tuner lock domain ──────────────────────────────────── + public const byte APP_UNLOCK_TUNER = 0x60; // Same usage model as APP_UNLOCK + public const byte APP_NEW_PWD_TUNER = 0x61; // Change tuner password (null×16 = disable) + public const byte APP_RST_PWD_TUNER = 0x62; // Reset tuner password (0x55×16 = disable + reset tables) + public const byte APP_ENCRYPT_READ = 0x63; + public const byte APP_ENCRYPT_WRITE = 0x64; + public const byte APP_RESET_SETTINGS = 0x65; + + // ── App commands — Special ─────────────────────────────────────────────── + public const byte APP_ERASE_ALL = 0xF0; + public const byte APP_LOCKED = 0xFF; +} diff --git a/TuneBoss.Core/Protocol/GenerationConfig.cs b/TuneBoss.Core/Protocol/GenerationConfig.cs new file mode 100644 index 0000000..81d4dca --- /dev/null +++ b/TuneBoss.Core/Protocol/GenerationConfig.cs @@ -0,0 +1,135 @@ +namespace TuneBoss.Core.Protocol; + +/// +/// Hardware/firmware generation, discriminated by App_Info_Version byte. +/// +public enum GenerationType +{ + Gen1 = 245, // App_Info_Version 0xF5 — legacy, APP_MEMRD_SEQ for all table ops + Gen2 = 1, // Dedicated read commands per table type; APP_UNLOCK + Gen3 = 2, // Same as Gen2 but 2D_USER uses APP_MEMRD_2D_USER; APP_UNLOCK2 +} + +/// +/// Per-generation command bytes and misc memory addresses resolved after +/// reading App_Info_Version from the device. +/// +public sealed class GenerationConfig +{ + // ── Table read commands ────────────────────────────────────────────────── + public byte ReadCmd1D { get; init; } + public byte ReadCmd2D { get; init; } + public byte ReadCmd2DUser{ get; init; } + public byte ReadCmdSubT { get; init; } + public byte ReadCmdMisc { get; init; } + + // ── Table write commands ───────────────────────────────────────────────── + public byte WriteCmd1D { get; init; } + public byte WriteCmd2D { get; init; } + public byte WriteCmd2DUser{ get; init; } + public byte WriteCmdSubT { get; init; } + public byte WriteCmdMisc { get; init; } + + // ── Unlock command ─────────────────────────────────────────────────────── + public byte UnlockCmd { get; init; } + + // ── Misc memory addresses ──────────────────────────────────────────────── + public ushort RpmLimitAddr { get; init; } + public ushort ShiftRpmLimitAddr { get; init; } + public ushort MusicModeStartAddr { get; init; } + public ushort ExtraPaddingAddr1 { get; init; } + public ushort ExtraPaddingAddr2 { get; init; } + public ushort ExtraPaddingAddr3 { get; init; } + public ushort ExtraPaddingAddr4 { get; init; } + public ushort ExtraPaddingAddr5 { get; init; } + public ushort ExtraPaddingAddr6 { get; init; } + + // ── Factory ───────────────────────────────────────────────────────────── + public static GenerationConfig For(GenerationType gen) => gen switch + { + GenerationType.Gen1 => new GenerationConfig + { + ReadCmd1D = Commands.APP_MEMRD_SEQ, + ReadCmd2D = Commands.APP_MEMRD_SEQ, + ReadCmd2DUser = Commands.APP_MEMRD_SEQ, + ReadCmdSubT = Commands.APP_MEMRD_SEQ, + ReadCmdMisc = Commands.APP_MEMRD_SEQ, + WriteCmd1D = Commands.APP_MEMWR_SEQ, + WriteCmd2D = Commands.APP_MEMWR_SEQ, + WriteCmd2DUser = Commands.APP_MEMWR_SEQ, + WriteCmdSubT = Commands.APP_MEMWR_SEQ, + WriteCmdMisc = Commands.APP_MEMWR_SEQ, + UnlockCmd = Commands.APP_UNLOCK, + RpmLimitAddr = 0x0840, + ShiftRpmLimitAddr = 0x08A0, + MusicModeStartAddr = 0x090E, + ExtraPaddingAddr1 = 0x08BC, + ExtraPaddingAddr2 = 0x08C8, + ExtraPaddingAddr3 = 0x08D4, + ExtraPaddingAddr4 = 0x08E0, + ExtraPaddingAddr5 = 0x08FC, + ExtraPaddingAddr6 = 0x0918, + }, + + GenerationType.Gen2 => new GenerationConfig + { + ReadCmd1D = Commands.APP_MEMRD_1D, + ReadCmd2D = Commands.APP_MEMRD_2D, + ReadCmd2DUser = Commands.APP_MEMRD_2D, + ReadCmdSubT = Commands.APP_MEMRD_SUBT, + ReadCmdMisc = Commands.APP_MEMRD_MISC, + WriteCmd1D = Commands.APP_MEMWR_1D, + WriteCmd2D = Commands.APP_MEMWR_2D, + WriteCmd2DUser = Commands.APP_MEMWR_2D, + WriteCmdSubT = Commands.APP_MEMWR_SUBT, + WriteCmdMisc = Commands.APP_MEMWR_MISC, + UnlockCmd = Commands.APP_UNLOCK, + RpmLimitAddr = 0x000C, + ShiftRpmLimitAddr = 0x006C, + MusicModeStartAddr = 0x00DA, + ExtraPaddingAddr1 = 0x0088, + ExtraPaddingAddr2 = 0x0094, + ExtraPaddingAddr3 = 0x00A0, + ExtraPaddingAddr4 = 0x00AC, + ExtraPaddingAddr5 = 0x00C8, + ExtraPaddingAddr6 = 0x00E4, + }, + + GenerationType.Gen3 => new GenerationConfig + { + ReadCmd1D = Commands.APP_MEMRD_1D, + ReadCmd2D = Commands.APP_MEMRD_2D, + ReadCmd2DUser = Commands.APP_MEMRD_2D_USER, // ← key difference from Gen2 + ReadCmdSubT = Commands.APP_MEMRD_SUBT, + ReadCmdMisc = Commands.APP_MEMRD_MISC, + WriteCmd1D = Commands.APP_MEMWR_1D, + WriteCmd2D = Commands.APP_MEMWR_2D, + WriteCmd2DUser = Commands.APP_MEMWR_2D_USER, // ← key difference from Gen2 + WriteCmdSubT = Commands.APP_MEMWR_SUBT, + WriteCmdMisc = Commands.APP_MEMWR_MISC, + UnlockCmd = Commands.APP_UNLOCK2, // ← different unlock + RpmLimitAddr = 0x000C, + ShiftRpmLimitAddr = 0x006C, + MusicModeStartAddr = 0x00DA, + ExtraPaddingAddr1 = 0x0088, + ExtraPaddingAddr2 = 0x0094, + ExtraPaddingAddr3 = 0x00A0, + ExtraPaddingAddr4 = 0x00AC, + ExtraPaddingAddr5 = 0x00C8, + ExtraPaddingAddr6 = 0x00E4, + }, + + _ => throw new ArgumentOutOfRangeException(nameof(gen), gen, "Unknown generation") + }; + + /// + /// Resolves generation from the App_Info_Version byte on the wire. + /// + public static GenerationType ResolveGeneration(byte appInfoVersion) => appInfoVersion switch + { + 245 => GenerationType.Gen1, + 1 => GenerationType.Gen2, + 2 => GenerationType.Gen3, + _ => throw new InvalidOperationException($"Unknown App_Info_Version: {appInfoVersion}") + }; +} diff --git a/TuneBoss.Core/Protocol/PacketBuilder.cs b/TuneBoss.Core/Protocol/PacketBuilder.cs new file mode 100644 index 0000000..ee6887a --- /dev/null +++ b/TuneBoss.Core/Protocol/PacketBuilder.cs @@ -0,0 +1,163 @@ +namespace TuneBoss.Core.Protocol; + +/// +/// Builds and parses TuneBoss BLE packets over Nordic UART Service (NUS). +/// +/// Outbound frame layout (verified against debug log 17-Mar-2026): +/// [0..3] FF 00 FF 00 Preamble +/// [4] TL_type Transport layer type (TL_POSTED / TL_NONPOSTED / TL_STREAMING) +/// [5] SeqNum Sequence number (0 for streaming) +/// [6] DwCount Payload size in DWords (4-byte units) +/// [7] InvSum 0xFF - (TL_type + SeqNum + DwCount) +/// [8..] Data Command payload (DwCount × 4 bytes) +/// [last4] DataChecksum ~sum of data DWords, little-endian uint32 +/// +/// Total frame size = 8 (header) + DwCount×4 (data) + 4 (checksum) +/// +public static class PacketBuilder +{ + private static readonly byte[] Preamble = { 0xFF, 0x00, 0xFF, 0x00 }; + + // ── Outbound ───────────────────────────────────────────────────────────── + + /// + /// Builds a complete outbound packet. + /// + /// Transport layer type (TL_NONPOSTED, TL_STREAMING etc.) + /// Sequence number. Use 0 for streaming commands. + /// Command payload. Will be zero-padded to DWord boundary. + public static byte[] Build(byte tlType, byte seqNum, ReadOnlySpan data) + { + // Pad data to DWord boundary + int paddedLen = (data.Length + 3) & ~3; + byte[] paddedData = new byte[paddedLen]; + data.CopyTo(paddedData); + + byte dwCount = (byte)(paddedLen / 4); + byte invSum = ChecksumHelper.HeaderInverseSum(tlType, seqNum, dwCount); + + // Total: 4 preamble + 4 header + paddedData + 4 checksum + byte[] frame = new byte[8 + paddedLen + 4]; + + // Preamble + frame[0] = 0xFF; frame[1] = 0x00; frame[2] = 0xFF; frame[3] = 0x00; + + // Header + frame[4] = tlType; + frame[5] = seqNum; + frame[6] = dwCount; + frame[7] = invSum; + + // Data + paddedData.CopyTo(frame, 8); + + // Checksum + ChecksumHelper.WriteChecksumDW(paddedData, frame.AsSpan(8 + paddedLen)); + + return frame; + } + + /// + /// Convenience: builds a TL_NONPOSTED packet with a single command byte + /// and optional parameters, auto-padded. + /// + public static byte[] BuildNonPosted(byte seqNum, byte command, ReadOnlySpan parameters = default) + { + byte[] payload = new byte[1 + parameters.Length]; + payload[0] = command; + parameters.CopyTo(payload.AsSpan(1)); + return Build(Commands.TL_NONPOSTED, seqNum, payload); + } + + /// + /// Convenience: builds a TL_STREAMING packet (always seq=0). + /// + public static byte[] BuildStreaming(byte command) + { + return Build(Commands.TL_STREAMING, seqNum: 0, data: new[] { command }); + } + + /// + /// Builds an APP_MON_START (0x71) streaming packet. + /// + public static byte[] BuildMonStart() => BuildStreaming(Commands.APP_MON_START); + + /// + /// Builds an APP_MON_STOP (0x72) streaming packet. + /// + public static byte[] BuildMonStop() => BuildStreaming(Commands.APP_MON_STOP); + + /// + /// Builds an APP_READ_INFO (0x37) request. + /// Data = [0x37, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] — 2 DWords. + /// Verified: log line 5–7. + /// + public static byte[] BuildReadInfo(byte seqNum) + => BuildNonPosted(seqNum, Commands.APP_READ_INFO, new byte[7]); + + // ── Inbound ────────────────────────────────────────────────────────────── + + /// + /// Result of parsing an inbound packet. + /// + public sealed class InboundPacket + { + public byte TlType { get; init; } + public byte SeqNum { get; init; } + public byte DwCount { get; init; } + public byte ResponseCode { get; init; } // First byte of payload (e.g. 0x51 = success) + public byte OriginalCmd { get; init; } // Second byte of payload (echoed command) + public byte[] Payload { get; init; } = Array.Empty(); // Full payload excl. checksum + public bool ChecksumValid { get; init; } + } + + /// + /// Parses a raw inbound frame received over BLE. + /// Returns null if the preamble is missing or the frame is too short. + /// + public static InboundPacket? Parse(ReadOnlySpan frame) + { + // Minimum: 4 preamble + 4 header + 4 data + 4 checksum = 16 bytes + if (frame.Length < 16) return null; + + // Validate preamble + if (frame[0] != 0xFF || frame[1] != 0x00 || frame[2] != 0xFF || frame[3] != 0x00) + return null; + + byte tlType = frame[4]; + byte seqNum = frame[5]; + byte dwCount = frame[6]; + // frame[7] = invSum (not validated here; add if needed) + + int payloadLen = dwCount * 4; + int expectedLen = 8 + payloadLen + 4; + if (frame.Length < expectedLen) return null; + + var payloadWithChecksum = frame.Slice(8, payloadLen + 4); + var payload = frame.Slice(8, payloadLen).ToArray(); + + bool csValid = ChecksumHelper.VerifyChecksumDW(payloadWithChecksum); + + return new InboundPacket + { + TlType = tlType, + SeqNum = seqNum, + DwCount = dwCount, + ResponseCode = payload.Length > 0 ? payload[0] : (byte)0, + OriginalCmd = payload.Length > 1 ? payload[1] : (byte)0, + Payload = payload, + ChecksumValid = csValid, + }; + } + + // ── Diagnostics helpers ────────────────────────────────────────────────── + + /// + /// Returns true if a raw frame is a diagnostics streaming packet (0x70). + /// Fast check without full parse — used in the hot receive path. + /// + public static bool IsDiagnosticsFrame(ReadOnlySpan frame) + => frame.Length >= 9 + && frame[4] == Commands.TL_STREAMING + && frame[8] == Commands.APP_MONITORING; +} diff --git a/TuneBoss.Core/TuneBoss.Core.csproj b/TuneBoss.Core/TuneBoss.Core.csproj new file mode 100644 index 0000000..27670c6 --- /dev/null +++ b/TuneBoss.Core/TuneBoss.Core.csproj @@ -0,0 +1,15 @@ + + + net9.0-windows10.0.19041.0 + enable + enable + + + + + + + + + + \ No newline at end of file diff --git a/TuneBossPC.slnx b/TuneBossPC.slnx new file mode 100644 index 0000000..6ab51f7 --- /dev/null +++ b/TuneBossPC.slnx @@ -0,0 +1,4 @@ + + + + diff --git a/TuneBossPC/App.xaml b/TuneBossPC/App.xaml new file mode 100644 index 0000000..44505b8 --- /dev/null +++ b/TuneBossPC/App.xaml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + diff --git a/TuneBossPC/App.xaml.cs b/TuneBossPC/App.xaml.cs new file mode 100644 index 0000000..b2eb7f8 --- /dev/null +++ b/TuneBossPC/App.xaml.cs @@ -0,0 +1,81 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using System.Windows; +using TuneBoss.Core.BLE; +using TuneBossPC.Services; +using TuneBossPC.ViewModels; +using TuneBossPC.ViewModels.Tables; +using TuneBossPC.Views; +using Wpf.Ui; + +namespace TuneBossPC; + +public partial class App : Application +{ + private readonly IHost _host; + + public App() + { + _host = Host.CreateDefaultBuilder() + .ConfigureServices(ConfigureServices) + .Build(); + } + + private static void ConfigureServices(IServiceCollection services) + { + // --sim on the command line swaps in the fake ECU. + bool useSim = Environment.GetCommandLineArgs().Contains("--sim"); + if (useSim) + services.AddSingleton(); + else + services.AddSingleton(); + + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddTransient(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddTransient(); + services.AddTransient(); + services.AddSingleton(); + services.AddTransient(); + services.AddTransient(); + services.AddSingleton(); + services.AddSingleton(); + } + + 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.Show(); + base.OnStartup(e); + } + + protected override async void OnExit(ExitEventArgs e) + { + await _host.StopAsync(); + _host.Dispose(); + base.OnExit(e); + } + + public static T GetService() where T : class + => (Current as App)!._host.Services.GetRequiredService(); +} diff --git a/TuneBossPC/AppInfo.cs b/TuneBossPC/AppInfo.cs new file mode 100644 index 0000000..b550dde --- /dev/null +++ b/TuneBossPC/AppInfo.cs @@ -0,0 +1,82 @@ +using System.Reflection; + +namespace TuneBossPC; + +/// +/// Build/version string shown in the UI (top-left, under the logo). +/// +/// When launched as a published ClickOnce install, shows the ClickOnce publish +/// version — the auto-incrementing major.minor.build.revision from the publish +/// profile (ApplicationVersion, e.g. 1.0.0.7). +/// +/// When run outside ClickOnce (Visual Studio / a direct exe run) there is no +/// deployment version, so it falls back to the assembly <Version>. +/// +public static class AppInfo +{ + /// e.g. "v1.0.0.7" (ClickOnce publish) or "v2026.8.13" (assembly fallback). + public static string Version { get; } = ResolveVersion(); + + /// + /// Whether the "advanced" nav items (Config + 1D Tables) are shown. FALSE in the + /// dealer release — a cut-down build for dealers until those pages' UI/UX is + /// cleaned up. Controlled by the DEALER compile symbol: define it (publish with + /// -p:Dealer=true, or a publish profile that sets <Dealer>true</Dealer>) + /// to produce the dealer build; a normal build shows everything. + /// + public static bool ShowAdvancedNav => +#if DEALER + false; +#else + true; +#endif + + private static string ResolveVersion() + { + // 1) ClickOnce publish version, if the app is network-deployed. + // Reflection keeps this compiling even when the ClickOnce API type + // isn't present (e.g. running the plain exe during development). + var clickOnce = TryGetClickOnceVersion(); + if (clickOnce != null) + return "v" + clickOnce; + + // 2) Fallback: assembly InformationalVersion (mirrors ). + var asm = Assembly.GetExecutingAssembly(); + var info = asm.GetCustomAttribute()?.InformationalVersion; + if (!string.IsNullOrWhiteSpace(info)) + { + int plus = info.IndexOf('+'); + if (plus >= 0) info = info[..plus]; + return "v" + info; + } + + // 3) Last resort: numeric assembly version. + var v = asm.GetName().Version; + return v != null ? $"v{v.Major}.{v.Minor}.{v.Build}" : "v—"; + } + + private static string? TryGetClickOnceVersion() + { + try + { + var adType = Type.GetType( + "System.Deployment.Application.ApplicationDeployment, System.Deployment"); + if (adType == null) return null; + + var isDeployed = adType.GetProperty("IsNetworkDeployed", + BindingFlags.Public | BindingFlags.Static)?.GetValue(null) as bool?; + if (isDeployed != true) return null; + + var current = adType.GetProperty("CurrentDeployment", + BindingFlags.Public | BindingFlags.Static)?.GetValue(null); + var version = current?.GetType() + .GetProperty("CurrentVersion")?.GetValue(current); + + return version?.ToString(); // "major.minor.build.revision" + } + catch + { + return null; // not deployed, or API unavailable — use the fallback + } + } +} diff --git a/TuneBossPC/AssemblyInfo.cs b/TuneBossPC/AssemblyInfo.cs new file mode 100644 index 0000000..b0ec827 --- /dev/null +++ b/TuneBossPC/AssemblyInfo.cs @@ -0,0 +1,10 @@ +using System.Windows; + +[assembly: ThemeInfo( + ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located + //(used if a resource is not found in the page, + // or application resource dictionaries) + ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located + //(used if a resource is not found in the page, + // app, or any theme specific resource dictionaries) +)] diff --git a/TuneBossPC/Assets/Fonts/Roboto-Bold.ttf b/TuneBossPC/Assets/Fonts/Roboto-Bold.ttf new file mode 100644 index 0000000..6516185 Binary files /dev/null and b/TuneBossPC/Assets/Fonts/Roboto-Bold.ttf differ diff --git a/TuneBossPC/Assets/Fonts/Roboto-Medium.ttf b/TuneBossPC/Assets/Fonts/Roboto-Medium.ttf new file mode 100644 index 0000000..bc5b170 Binary files /dev/null and b/TuneBossPC/Assets/Fonts/Roboto-Medium.ttf differ diff --git a/TuneBossPC/Assets/Fonts/Roboto-Regular.ttf b/TuneBossPC/Assets/Fonts/Roboto-Regular.ttf new file mode 100644 index 0000000..3db0d1f Binary files /dev/null and b/TuneBossPC/Assets/Fonts/Roboto-Regular.ttf differ diff --git a/TuneBossPC/Assets/Fonts/RobotoCondensed-Bold.ttf b/TuneBossPC/Assets/Fonts/RobotoCondensed-Bold.ttf new file mode 100644 index 0000000..7d42ecb Binary files /dev/null and b/TuneBossPC/Assets/Fonts/RobotoCondensed-Bold.ttf differ diff --git a/TuneBossPC/Assets/Fonts/RobotoCondensed-Medium.ttf b/TuneBossPC/Assets/Fonts/RobotoCondensed-Medium.ttf new file mode 100644 index 0000000..e3f02fd Binary files /dev/null and b/TuneBossPC/Assets/Fonts/RobotoCondensed-Medium.ttf differ diff --git a/TuneBossPC/Assets/Fonts/RobotoCondensed-Regular.ttf b/TuneBossPC/Assets/Fonts/RobotoCondensed-Regular.ttf new file mode 100644 index 0000000..9abc0e9 Binary files /dev/null and b/TuneBossPC/Assets/Fonts/RobotoCondensed-Regular.ttf differ diff --git a/TuneBossPC/Assets/Styles/Colors.xaml b/TuneBossPC/Assets/Styles/Colors.xaml new file mode 100644 index 0000000..ffc0c94 --- /dev/null +++ b/TuneBossPC/Assets/Styles/Colors.xaml @@ -0,0 +1,67 @@ + + + + + + #FF111416 + #FF1A1D21 + #FF22262B + #FF2C3036 + #FF4A505A + #FF16191D + + + #FFFF6B00 + #FF994000 + #33FF6B00 + + + #FFF4F6F8 + #FFB4BAC4 + #FF6E7580 + #FFFF7D1F + + + #FF3DDC84 + #FFFF4D4D + #FFFFD11A + #FF4C90FF + + + #FF0050B4 + #FF0096C8 + #FF00C8C8 + #FF50C850 + #FF96DC00 + #FFDCDC00 + + + + + + + + + + + + + + + + + + + + + + diff --git a/TuneBossPC/Assets/Styles/Controls.xaml b/TuneBossPC/Assets/Styles/Controls.xaml new file mode 100644 index 0000000..34ac579 --- /dev/null +++ b/TuneBossPC/Assets/Styles/Controls.xaml @@ -0,0 +1,615 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/TuneBossPC/Assets/Styles/Typography.xaml b/TuneBossPC/Assets/Styles/Typography.xaml new file mode 100644 index 0000000..b9c74b4 --- /dev/null +++ b/TuneBossPC/Assets/Styles/Typography.xaml @@ -0,0 +1,22 @@ + + + pack://application:,,,/Assets/Fonts/#Roboto Condensed + pack://application:,,,/Assets/Fonts/#Roboto + + pack://application:,,,/Assets/Fonts/#Roboto + + 11 + 12 + 14 + 18 + 32 + + 17 + 18 + 22 + + diff --git a/TuneBossPC/Controls/HoldToConfirmButton.cs b/TuneBossPC/Controls/HoldToConfirmButton.cs new file mode 100644 index 0000000..05b8f9b --- /dev/null +++ b/TuneBossPC/Controls/HoldToConfirmButton.cs @@ -0,0 +1,208 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Threading; + +namespace TuneBossPC.Controls; + +/// +/// A button that fires its command only after being pressed and HELD for +/// seconds. A fill bar (template part "PART_Fill", +/// scaled horizontally) shows progress; releasing early cancels and briefly +/// shows a "HOLD" hint so the gesture is discoverable. +/// +/// Used for destructive/permanent actions (ECU FLASH) where a stray click — +/// or a gloved hand — must never trigger accidentally. A press-and-hold is +/// deliberate in a way a dialog click-through is not. +/// +[TemplatePart(Name = PartFill, Type = typeof(FrameworkElement))] +public class HoldToConfirmButton : ContentControl +{ + private const string PartFill = "PART_Fill"; + private const string PartSuccess = "PART_Success"; + private FrameworkElement? _successLayer; + + private readonly ScaleTransform _fillScale = new(0.0, 1.0); + private readonly DispatcherTimer _tick = new() { Interval = TimeSpan.FromMilliseconds(25) }; + private readonly DispatcherTimer _hintTimer = new() { Interval = TimeSpan.FromMilliseconds(800) }; + + private DateTime _pressedAt; + private bool _holding; + private bool _showingHint; + private object? _originalContent; + private bool _canExecute = true; + + public HoldToConfirmButton() + { + Focusable = true; + Cursor = Cursors.Hand; + _tick.Tick += (_, _) => OnTick(); + _hintTimer.Tick += (_, _) => ClearHint(); + } + + // ── HoldCommand ────────────────────────────────────────────────────────── + public static readonly DependencyProperty HoldCommandProperty = + DependencyProperty.Register(nameof(HoldCommand), typeof(ICommand), typeof(HoldToConfirmButton), + new PropertyMetadata(null, OnHoldCommandChanged)); + + public ICommand? HoldCommand + { + get => (ICommand?)GetValue(HoldCommandProperty); + set => SetValue(HoldCommandProperty, value); + } + + public static readonly DependencyProperty HoldCommandParameterProperty = + DependencyProperty.Register(nameof(HoldCommandParameter), typeof(object), typeof(HoldToConfirmButton)); + + public object? HoldCommandParameter + { + get => GetValue(HoldCommandParameterProperty); + set => SetValue(HoldCommandParameterProperty, value); + } + + /// + /// Increment to flash the success layer (green double-blink). Bind to a counter + /// the view-model bumps after a confirmed flash write, so success is visible + /// without reading the status line. + /// + public static readonly DependencyProperty SuccessSignalProperty = + DependencyProperty.Register(nameof(SuccessSignal), typeof(int), typeof(HoldToConfirmButton), + new PropertyMetadata(0, (d, _) => ((HoldToConfirmButton)d).BlinkSuccess())); + + public int SuccessSignal + { + get => (int)GetValue(SuccessSignalProperty); + set => SetValue(SuccessSignalProperty, value); + } + + private void BlinkSuccess() + { + if (_successLayer == null) return; + var anim = new DoubleAnimation + { + From = 0, To = 0.9, + Duration = new Duration(TimeSpan.FromMilliseconds(170)), + AutoReverse = true, + RepeatBehavior = new RepeatBehavior(2), // two clear green pulses + }; + _successLayer.BeginAnimation(OpacityProperty, anim); + } + + /// Seconds the button must be held before the command fires. + public static readonly DependencyProperty HoldDurationProperty = + DependencyProperty.Register(nameof(HoldDuration), typeof(double), typeof(HoldToConfirmButton), + new PropertyMetadata(1.2)); + + public double HoldDuration + { + get => (double)GetValue(HoldDurationProperty); + set => SetValue(HoldDurationProperty, value); + } + + private static void OnHoldCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + var self = (HoldToConfirmButton)d; + if (e.OldValue is ICommand oldCmd) oldCmd.CanExecuteChanged -= self.OnCanExecuteChanged; + if (e.NewValue is ICommand newCmd) newCmd.CanExecuteChanged += self.OnCanExecuteChanged; + self.RefreshCanExecute(); + } + + private void OnCanExecuteChanged(object? sender, EventArgs e) => RefreshCanExecute(); + + private void RefreshCanExecute() + { + _canExecute = HoldCommand?.CanExecute(HoldCommandParameter) ?? true; + CoerceValue(IsEnabledProperty); + } + + protected override bool IsEnabledCore => base.IsEnabledCore && _canExecute; + + // ── Template ───────────────────────────────────────────────────────────── + public override void OnApplyTemplate() + { + base.OnApplyTemplate(); + if (GetTemplateChild(PartFill) is FrameworkElement fill) + { + fill.RenderTransformOrigin = new Point(0, 0); + fill.RenderTransform = _fillScale; + _fillScale.ScaleX = 0; + } + _successLayer = GetTemplateChild(PartSuccess) as FrameworkElement; + } + + // ── Hold gesture ───────────────────────────────────────────────────────── + protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) + { + base.OnMouseLeftButtonDown(e); + if (!IsEnabled) return; + + ClearHint(); + _holding = true; + _pressedAt = DateTime.UtcNow; + CaptureMouse(); + _tick.Start(); + e.Handled = true; + } + + protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) + { + base.OnMouseLeftButtonUp(e); + if (_holding) CancelHold(showHint: true); + if (IsMouseCaptured) ReleaseMouseCapture(); + e.Handled = true; + } + + protected override void OnLostMouseCapture(MouseEventArgs e) + { + base.OnLostMouseCapture(e); + if (_holding) CancelHold(showHint: false); + } + + private void OnTick() + { + if (!_holding) return; + double frac = (DateTime.UtcNow - _pressedAt).TotalSeconds / Math.Max(0.1, HoldDuration); + _fillScale.ScaleX = Math.Min(1.0, frac); + if (frac >= 1.0) Complete(); + } + + private void Complete() + { + _tick.Stop(); + _holding = false; + if (IsMouseCaptured) ReleaseMouseCapture(); + _fillScale.ScaleX = 0; + + var cmd = HoldCommand; + if (cmd?.CanExecute(HoldCommandParameter) == true) + cmd.Execute(HoldCommandParameter); + } + + private void CancelHold(bool showHint) + { + _tick.Stop(); + _holding = false; + _fillScale.ScaleX = 0; + + // Released early → teach the gesture. + if (showHint && !_showingHint) + { + _showingHint = true; + _originalContent = Content; + Content = "HOLD…"; + _hintTimer.Start(); + } + } + + private void ClearHint() + { + _hintTimer.Stop(); + if (_showingHint) + { + Content = _originalContent; + _showingHint = false; + } + } +} diff --git a/TuneBossPC/Controls/Surface3DControl.cs b/TuneBossPC/Controls/Surface3DControl.cs new file mode 100644 index 0000000..e1c17a5 --- /dev/null +++ b/TuneBossPC/Controls/Surface3DControl.cs @@ -0,0 +1,407 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Media.Media3D; + +namespace TuneBossPC.Controls; + +/// +/// Rotatable 3D surface ("contour map") of a 2D tuning table, rendered with WPF's +/// built-in Viewport3D — no external packages. X = RPM columns, depth = Load rows, +/// height + colour = cell value (same ramp as the grid heatmap, via a 1-D texture). +/// +/// Axis reference: RPM / LOAD tick labels are 2D overlay text projected from 3D +/// anchor points, so they stay screen-readable at any rotation, and they jump to +/// whichever edge currently faces the camera. A live tracker marker (orange +/// diamond) can be placed on any cell via . +/// +/// Interaction: left-drag orbits, mouse wheel zooms. +/// +public sealed class Surface3DControl : Border +{ + private readonly Viewport3D _viewport = new(); + private readonly Canvas _overlay = new() { IsHitTestVisible = false }; + private readonly PerspectiveCamera _camera = new() { FieldOfView = 40 }; + private readonly MeshGeometry3D _mesh = new(); + + // Tracker marker + private readonly TranslateTransform3D _markerPos = new(); + private readonly ScaleTransform3D _markerScale = new(0, 0, 0); // hidden until placed + private int _trackerRow = -1, _trackerCol = -1; + + // Data cache (for marker height + label layout) + private double[]? _values; + private double _min, _max; + private int _cols, _rows; + private string[] _colLabels = Array.Empty(); + private string[] _rowLabels = Array.Empty(); + + // Overlay label pool + private readonly List _labels = new(); + + // Orbit state + // _dist starts at the zoom clamp maximum so the map first appears fully + // zoomed out — the whole surface (and both axis edges) visible at a glance. + private double _yaw = -0.70, _pitch = 0.55, _dist = 95; + private double _fitDist = 95; // recomputed from data + panel aspect + private bool _userZoomed; // once the user zooms, we stop auto-fitting + private Point _lastDrag; + private bool _dragging; + + // World scale + private const double SX = 1.0; // per RPM column + private const double SZ = 2.4; // per Load row + private const double H = 7.0; // full height span + private const int ColLabelStep = 2; // label every 2nd RPM column + + public Surface3DControl() + { + Background = new SolidColorBrush(Color.FromRgb(0x14, 0x17, 0x1A)); + BorderBrush = (Brush?)Application.Current.TryFindResource("BorderBrush") ?? Brushes.DimGray; + BorderThickness = new Thickness(1); + CornerRadius = new CornerRadius(6); + ClipToBounds = true; + + var root = new Grid(); + root.Children.Add(_viewport); + root.Children.Add(_overlay); + Child = root; + + _viewport.Camera = _camera; + + var material = new DiffuseMaterial(BuildRampBrush()); + material.Freeze(); + var surface = new GeometryModel3D(_mesh, material) { BackMaterial = material }; + + var markerBrush = new SolidColorBrush(Color.FromRgb(0xFF, 0xFF, 0xFF)); + var markerMat = new MaterialGroup(); + markerMat.Children.Add(new DiffuseMaterial(markerBrush)); + markerMat.Children.Add(new EmissiveMaterial(new SolidColorBrush(Color.FromRgb(0x88, 0x88, 0x88)))); + markerMat.Freeze(); + var markerXform = new Transform3DGroup(); + markerXform.Children.Add(_markerScale); + markerXform.Children.Add(_markerPos); + var marker = new GeometryModel3D(BuildDiamondMesh(), markerMat) + { + BackMaterial = markerMat, + Transform = markerXform, + }; + + var group = new Model3DGroup(); + group.Children.Add(new AmbientLight(Color.FromRgb(0x8C, 0x8C, 0x8C))); + group.Children.Add(new DirectionalLight(Color.FromRgb(0x90, 0x90, 0x90), + new Vector3D(-0.3, -0.8, -0.5))); + group.Children.Add(surface); + group.Children.Add(marker); + _viewport.Children.Add(new ModelVisual3D { Content = group }); + + UpdateCamera(); + + SizeChanged += (_, _) => { RecomputeFitDistance(); UpdateOverlay(); }; + + MouseLeftButtonDown += (_, e) => + { + _dragging = true; _lastDrag = e.GetPosition(this); CaptureMouse(); + }; + MouseLeftButtonUp += (_, _) => { _dragging = false; ReleaseMouseCapture(); }; + MouseMove += (_, e) => + { + if (!_dragging) return; + var p = e.GetPosition(this); + _yaw += (p.X - _lastDrag.X) * 0.010; + _pitch += (p.Y - _lastDrag.Y) * 0.008; + _pitch = Math.Clamp(_pitch, 0.05, 1.45); + _lastDrag = p; + UpdateCamera(); + }; + MouseWheel += (_, e) => + { + _userZoomed = true; + _dist = Math.Clamp(_dist * Math.Exp(-e.Delta * 0.0009), 10, _fitDist); + UpdateCamera(); + }; + } + + // ── Public API ────────────────────────────────────────────────────────────── + + /// + /// Updates the surface from a row-major value array (values[row*cols+col]) + /// plus axis tick label strings. Heights/colours normalise to the array's own + /// min/max so relief is always visible. + /// + public void SetData(double[] values, int cols, int rows, + string[]? colLabels = null, string[]? rowLabels = null) + { + if (values.Length < cols * rows || cols < 2 || rows < 2) return; + + double min = double.MaxValue, max = double.MinValue; + for (int i = 0; i < cols * rows; i++) + { + if (values[i] < min) min = values[i]; + if (values[i] > max) max = values[i]; + } + + bool rebuildTopology = cols != _cols || rows != _rows; + _values = values; _min = min; _max = max; + _cols = cols; _rows = rows; + _colLabels = colLabels ?? Array.Empty(); + _rowLabels = rowLabels ?? Array.Empty(); + + double span = max - min; + var positions = new Point3DCollection(cols * rows); + var texCoords = new PointCollection(cols * rows); + + for (int r = 0; r < rows; r++) + for (int c = 0; c < cols; c++) + { + double norm = span <= 0 ? 0.5 : (values[r * cols + c] - min) / span; + positions.Add(new Point3D(WX(c), norm * H, WZ(r))); + texCoords.Add(new Point(Math.Clamp(norm, 0.004, 0.996), 0.5)); + } + + _mesh.Positions = positions; + _mesh.TextureCoordinates = texCoords; + + if (rebuildTopology) + { + var idx = new Int32Collection((cols - 1) * (rows - 1) * 6); + for (int r = 0; r < rows - 1; r++) + for (int c = 0; c < cols - 1; c++) + { + int i0 = r * cols + c; + int i1 = i0 + 1; + int i2 = i0 + cols; + int i3 = i2 + 1; + idx.Add(i0); idx.Add(i2); idx.Add(i1); + idx.Add(i1); idx.Add(i2); idx.Add(i3); + } + _mesh.TriangleIndices = idx; + } + + PlaceMarker(); + RecomputeFitDistance(); + UpdateOverlay(); + } + + /// + /// Auto-framing: from the surface's bounding sphere and the panel's aspect + /// ratio, computes the camera distance at which the WHOLE surface (plus label + /// margin) fits in view at any rotation — no guessed constants, no clipping. + /// Applied as the default and the zoom-out limit; a manual zoom sticks. + /// + private void RecomputeFitDistance() + { + if (_cols < 2 || _rows < 2 || ActualWidth <= 0 || ActualHeight <= 0) return; + + double hx = (_cols - 1) * SX / 2.0 + 2.2; // + label margin + double hz = (_rows - 1) * SZ / 2.0 + 2.2; + double hy = H * 0.65; // camera centre sits at 0.35·H + double radius = Math.Sqrt(hx * hx + hy * hy + hz * hz); + + double tanH = Math.Tan(_camera.FieldOfView * Math.PI / 360.0); + double tanV = tanH * ActualHeight / Math.Max(1.0, ActualWidth); + double half = Math.Atan(Math.Min(tanH, tanV)); // tighter of the two FOVs + + _fitDist = radius / Math.Max(0.05, Math.Sin(half)); + + if (!_userZoomed) + { + _dist = _fitDist; + UpdateCamera(); + } + else if (_dist > _fitDist) + { + _dist = _fitDist; + UpdateCamera(); + } + } + + /// Places the live tracker marker on a cell; pass -1,-1 to hide. + public void SetTracker(int row, int col) + { + _trackerRow = row; _trackerCol = col; + PlaceMarker(); + } + + // ── Internals ─────────────────────────────────────────────────────────────── + + private double WX(int c) => (c - (_cols - 1) / 2.0) * SX; + private double WZ(int r) => (r - (_rows - 1) / 2.0) * SZ; + + private double HeightAt(int row, int col) + { + if (_values == null) return 0; + double span = _max - _min; + double v = _values[row * _cols + col]; + return (span <= 0 ? 0.5 : (v - _min) / span) * H; + } + + private void PlaceMarker() + { + bool visible = _values != null && + _trackerRow >= 0 && _trackerRow < _rows && + _trackerCol >= 0 && _trackerCol < _cols; + if (!visible) + { + _markerScale.ScaleX = _markerScale.ScaleY = _markerScale.ScaleZ = 0; + return; + } + + _markerScale.ScaleX = _markerScale.ScaleY = _markerScale.ScaleZ = 1; + _markerPos.OffsetX = WX(_trackerCol); + _markerPos.OffsetY = HeightAt(_trackerRow, _trackerCol) + 0.55; + _markerPos.OffsetZ = WZ(_trackerRow); + } + + private void UpdateCamera() + { + var center = new Point3D(0, H * 0.35, 0); + double cp = Math.Cos(_pitch), sp = Math.Sin(_pitch); + var offset = new Vector3D(cp * Math.Sin(_yaw), sp, cp * Math.Cos(_yaw)) * _dist; + _camera.Position = center + offset; + _camera.LookDirection = center - _camera.Position; + _camera.UpDirection = new Vector3D(0, 1, 0); + UpdateOverlay(); + } + + /// + /// Lays out the axis tick labels: 3D anchor points on the camera-facing edges, + /// projected to 2D and positioned on the overlay canvas. + /// + private void UpdateOverlay() + { + _overlay.Children.Clear(); + int used = 0; + if (_cols < 2 || _rows < 2 || ActualWidth < 40 || ActualHeight < 40) return; + + // Camera-facing edges: RPM labels along the near Z edge, LOAD along the near + // X edge — both flip sides as the map is rotated so they stay toward the viewer. + int zSign = Math.Cos(_yaw) >= 0 ? 1 : -1; + int xSign = Math.Sin(_yaw) >= 0 ? 1 : -1; + double zEdge = (zSign > 0 ? WZ(_rows - 1) : WZ(0)) + zSign * 1.1; + double xEdge = (xSign > 0 ? WX(_cols - 1) : WX(0)) + xSign * 1.2; + + // RPM ticks (every Nth column) along the near Z edge + for (int c = 0; c < _cols && c < _colLabels.Length; c += ColLabelStep) + AddLabel(ref used, _colLabels[c], new Point3D(WX(c), 0, zEdge), centerX: true); + + // RPM caption past the end AWAY from the LOAD edge (avoids overlap) + double rpmCapX = xSign > 0 ? WX(0) - 1.8 : WX(_cols - 1) + 1.8; + AddLabel(ref used, "RPM", new Point3D(rpmCapX, 0, zEdge), centerX: true, bold: true); + + // LOAD ticks (all rows) along the near X edge + for (int r = 0; r < _rows && r < _rowLabels.Length; r++) + AddLabel(ref used, _rowLabels[r], new Point3D(xEdge, 0, WZ(r)), centerX: true); + + // LOAD caption past the end AWAY from the RPM edge + double loadCapZ = zSign > 0 ? WZ(0) - 1.6 : WZ(_rows - 1) + 1.6; + AddLabel(ref used, "LOAD", new Point3D(xEdge, 0, loadCapZ), centerX: true, bold: true); + } + + private void AddLabel(ref int poolIndex, string text, Point3D world, bool centerX, bool bold = false) + { + if (!WorldToScreen(world, out var pt)) return; + if (pt.X < -30 || pt.Y < -14 || pt.X > ActualWidth + 30 || pt.Y > ActualHeight + 14) return; + + TextBlock tb; + if (poolIndex < _labels.Count) tb = _labels[poolIndex]; + else { tb = new TextBlock(); _labels.Add(tb); } + poolIndex++; + + tb.Text = text; + tb.FontSize = bold ? 11 : 10; + tb.FontWeight = bold ? FontWeights.Bold : FontWeights.Normal; + tb.Foreground = bold + ? (Brush?)Application.Current.TryFindResource("TextPrimaryBrush") ?? Brushes.White + : (Brush?)Application.Current.TryFindResource("TextSecondaryBrush") ?? Brushes.Gray; + + tb.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); + Canvas.SetLeft(tb, centerX ? pt.X - tb.DesiredSize.Width / 2 : pt.X); + Canvas.SetTop(tb, pt.Y - tb.DesiredSize.Height / 2); + _overlay.Children.Add(tb); + } + + /// Projects a world point through the perspective camera to canvas pixels. + private bool WorldToScreen(Point3D world, out Point screen) + { + screen = default; + double w = ActualWidth, h = ActualHeight; + if (w <= 0 || h <= 0) return false; + + var fwd = _camera.LookDirection; fwd.Normalize(); + var right = Vector3D.CrossProduct(fwd, _camera.UpDirection); right.Normalize(); + var up = Vector3D.CrossProduct(right, fwd); + + var v = world - _camera.Position; + double zv = Vector3D.DotProduct(v, fwd); + if (zv <= 0.1) return false; // behind the camera + + double xv = Vector3D.DotProduct(v, right); + double yv = Vector3D.DotProduct(v, up); + + double tanH = Math.Tan(_camera.FieldOfView * Math.PI / 360.0); // half horizontal FOV + double xNdc = xv / (zv * tanH); + double yNdc = yv / (zv * tanH * h / w); + + screen = new Point((xNdc + 1) / 2 * w, (1 - yNdc) / 2 * h); + return true; + } + + /// Small octahedron used as the tracker marker. + private static MeshGeometry3D BuildDiamondMesh() + { + const double s = 0.45, hh = 0.62; + var m = new MeshGeometry3D + { + Positions = new Point3DCollection + { + new(0, hh, 0), // top + new(-s, 0, 0), new(0, 0, s), new(s, 0, 0), new(0, 0, -s), + new(0, -hh, 0), // bottom + }, + TriangleIndices = new Int32Collection + { + 0,1,2, 0,2,3, 0,3,4, 0,4,1, + 5,2,1, 5,3,2, 5,4,3, 5,1,4, + }, + }; + m.Freeze(); + return m; + } + + /// 1-D heatmap gradient texture — mirrors the grid's colour ramp. + private static ImageBrush BuildRampBrush() + { + var stops = new (double T, Color C)[] + { + (0.00, Color.FromRgb(0x00, 0x50, 0xB4)), + (0.17, Color.FromRgb(0x00, 0x96, 0xC8)), + (0.34, Color.FromRgb(0x00, 0xC8, 0xC8)), + (0.51, Color.FromRgb(0x50, 0xC8, 0x50)), + (0.68, Color.FromRgb(0x96, 0xDC, 0x00)), + (0.85, Color.FromRgb(0xDC, 0xDC, 0x00)), + (1.00, Color.FromRgb(0xFF, 0x80, 0x00)), + }; + + const int W = 256; + var pixels = new byte[W * 4]; + for (int x = 0; x < W; x++) + { + double t = x / (double)(W - 1); + int s = 0; + while (s < stops.Length - 2 && t > stops[s + 1].T) s++; + double f = (t - stops[s].T) / Math.Max(1e-9, stops[s + 1].T - stops[s].T); + f = Math.Clamp(f, 0, 1); + byte R = (byte)(stops[s].C.R + (stops[s + 1].C.R - stops[s].C.R) * f); + byte G = (byte)(stops[s].C.G + (stops[s + 1].C.G - stops[s].C.G) * f); + byte B = (byte)(stops[s].C.B + (stops[s + 1].C.B - stops[s].C.B) * f); + pixels[x * 4 + 0] = B; pixels[x * 4 + 1] = G; pixels[x * 4 + 2] = R; pixels[x * 4 + 3] = 255; + } + + var bmp = BitmapSource.Create(W, 1, 96, 96, PixelFormats.Bgra32, null, pixels, W * 4); + bmp.Freeze(); + return new ImageBrush(bmp) { ViewportUnits = BrushMappingMode.Absolute }; + } +} diff --git a/TuneBossPC/Converters/EqualityMultiConverter.cs b/TuneBossPC/Converters/EqualityMultiConverter.cs new file mode 100644 index 0000000..3d12c54 --- /dev/null +++ b/TuneBossPC/Converters/EqualityMultiConverter.cs @@ -0,0 +1,15 @@ +using System.Globalization; +using System.Windows.Data; + +namespace TuneBossPC.Converters; + +/// True when the two bound values are equal — used by the nav rail to +/// highlight the button whose Tag matches the currently displayed page. +public sealed class EqualityMultiConverter : IMultiValueConverter +{ + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) => + values.Length >= 2 && Equals(values[0]?.ToString(), values[1]?.ToString()); + + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => + throw new NotSupportedException(); +} diff --git a/TuneBossPC/Converters/ErrorStatusConverters.cs b/TuneBossPC/Converters/ErrorStatusConverters.cs new file mode 100644 index 0000000..b6e7b41 --- /dev/null +++ b/TuneBossPC/Converters/ErrorStatusConverters.cs @@ -0,0 +1,70 @@ +using System.Globalization; +using System.Windows; +using System.Windows.Data; +using System.Windows.Media; +using TuneBoss.Core.Models; + +namespace TuneBossPC.Converters; + +/// +/// Converts ErrorStatus to a background brush: +/// Active → Red +/// Persistent → Yellow +/// Clear → Green +/// +public class ErrorStatusToBrushConverter : IValueConverter +{ + public object Convert(object value, Type t, object p, CultureInfo c) + { + if (value is not ErrorStatus status) return Brushes.Transparent; + return status switch + { + ErrorStatus.Active => new SolidColorBrush(Color.FromRgb(0xFF, 0x44, 0x44)), + ErrorStatus.Persistent => new SolidColorBrush(Color.FromRgb(0xFF, 0xCC, 0x00)), + _ => new SolidColorBrush(Color.FromRgb(0x3D, 0xDC, 0x84)), + }; + } + + public object ConvertBack(object value, Type t, object p, CultureInfo c) + => throw new NotImplementedException(); +} + +/// +/// Converts ErrorStatus to foreground text colour — +/// dark text on yellow, white on red/green. +/// +public class ErrorStatusToForegroundConverter : IValueConverter +{ + public object Convert(object value, Type t, object p, CultureInfo c) + { + if (value is ErrorStatus.Persistent) + return new SolidColorBrush(Color.FromRgb(0x22, 0x22, 0x22)); + return Brushes.White; + } + + public object ConvertBack(object value, Type t, object p, CultureInfo c) + => throw new NotImplementedException(); +} + +/// +/// Converts CrankState int to background brush: +/// 6 → Green (running) +/// 5 → Yellow (near sync) +/// * → Red +/// +public class CrankStateToBrushConverter : IValueConverter +{ + public object Convert(object value, Type t, object p, CultureInfo c) + { + if (value is not int state) return Brushes.Transparent; + return state switch + { + 6 => new SolidColorBrush(Color.FromRgb(0x3D, 0xDC, 0x84)), + 5 => new SolidColorBrush(Color.FromRgb(0xFF, 0xCC, 0x00)), + _ => new SolidColorBrush(Color.FromRgb(0xFF, 0x44, 0x44)), + }; + } + + public object ConvertBack(object value, Type t, object p, CultureInfo c) + => throw new NotImplementedException(); +} diff --git a/TuneBossPC/Properties/launchSettings.json b/TuneBossPC/Properties/launchSettings.json new file mode 100644 index 0000000..a9fd492 --- /dev/null +++ b/TuneBossPC/Properties/launchSettings.json @@ -0,0 +1,11 @@ +{ + "profiles": { + "TuneBossPC": { + "commandName": "Project" + }, + "TuneBossPC Sim": { + "commandName": "Project", + "commandLineArgs": "--sim" + } + } +} \ No newline at end of file diff --git a/TuneBossPC/Services/AuthService.cs b/TuneBossPC/Services/AuthService.cs new file mode 100644 index 0000000..ffe9660 --- /dev/null +++ b/TuneBossPC/Services/AuthService.cs @@ -0,0 +1,137 @@ +using System.Windows; +using TuneBoss.Core.BLE; +using TuneBoss.Core.Protocol; +using TuneBossPC.Views.Dialogs; +using TuneBossPC.ViewModels.Dialogs; + +namespace TuneBossPC.Services; + +/// +/// Implements the ECU password/unlock flow. +/// Mirrors CheckForDeviceLocked() from the WinForms app: +/// 1. Send a table read — if response is APP_LOCKED (0xFF) → show dialog +/// 2. Get password from user → send APP_UNLOCK (or APP_UNLOCK2 for GEN3) +/// 3. Retry up to 3 times +/// 4. On success → caller proceeds to populateInitTables equivalent +/// +public sealed class AuthService : IAuthService +{ + private readonly IBleService _ble; + private readonly ISettingsService _settings; + + public string? SavedPassword { get; private set; } + public string? SavedTunerPassword { get; private set; } + + private const int MaxAttempts = 3; + + public AuthService(IBleService ble, ISettingsService settings) + { + _ble = ble; + _settings = settings; + } + + // ── Basic ECU unlock ────────────────────────────────────────────────── + + public async Task EnsureUnlockedAsync( + string username, + CancellationToken ct = default) + { + // If we have a saved password, try it silently first + if (!string.IsNullOrEmpty(SavedPassword)) + { + var silentResult = await _ble.UnlockAsync(SavedPassword, ct); + if (silentResult.Success) + return UnlockResult.Ok(); + } + + return await RunUnlockLoopAsync( + username, + attempt => _ble.UnlockAsync(attempt.Password, ct), + isTuner: false, + ct); + } + + // ── Tuner unlock ────────────────────────────────────────────────────── + + public async Task EnsureTunerUnlockedAsync( + string username, + CancellationToken ct = default) + { + if (!string.IsNullOrEmpty(SavedTunerPassword)) + { + var silentResult = await _ble.UnlockTunerAsync(SavedTunerPassword, ct); + if (silentResult.Success) + return UnlockResult.Ok(); + } + + return await RunUnlockLoopAsync( + username, + attempt => _ble.UnlockTunerAsync(attempt.Password, ct), + isTuner: true, + ct); + } + + // ── Core loop — mirrors CheckForDeviceLocked ────────────────────────── + + private async Task RunUnlockLoopAsync( + string username, + Func> sendUnlock, + bool isTuner, + CancellationToken ct) + { + string? lastError = null; + + for (int attempt = 1; attempt <= MaxAttempts; attempt++) + { + // Show password dialog on UI thread + PasswordDialogViewModel? vm = null; + PasswordDialogResult dialogResult = PasswordDialogResult.Cancelled; + + await Application.Current.Dispatcher.InvokeAsync(() => + { + vm = new PasswordDialogViewModel + { + Username = username, + LastPassword = _settings.Settings.LastPassword ?? string.Empty, + }; + vm.SetAttempt(attempt, lastError); + + var dialog = new PasswordDialog(vm) + { + Owner = Application.Current.MainWindow + }; + dialog.ShowDialog(); + dialogResult = vm.Result; + }); + + if (dialogResult == PasswordDialogResult.Cancelled) + return UnlockResult.Cancelled(); + + if (vm == null) continue; + + // Send unlock command + var result = await sendUnlock(vm); + + if (result.Success) + { + // Save for auto-reconnect + if (isTuner) + SavedTunerPassword = vm.FinalPassword; + else + SavedPassword = vm.FinalPassword; + + // Persist as the "last used" password for next connection. + _settings.Settings.LastPassword = vm.FinalPassword; + + return UnlockResult.Ok(); + } + + // Wrong password — set error for next attempt + lastError = result.ResponseCode == Commands.APP_LOCKED + ? "Incorrect password. Please try again." + : $"Unlock failed (0x{result.ResponseCode:X2}). Please try again."; + } + + return UnlockResult.TooManyAttempts(); + } +} diff --git a/TuneBossPC/Services/IAuthService.cs b/TuneBossPC/Services/IAuthService.cs new file mode 100644 index 0000000..fdcd032 --- /dev/null +++ b/TuneBossPC/Services/IAuthService.cs @@ -0,0 +1,45 @@ +namespace TuneBossPC.Services; + +/// +/// Result of an unlock attempt. +/// +public sealed record UnlockResult( + bool Success, + string? ErrorMessage = null) +{ + public static UnlockResult Ok() => new(true); + public static UnlockResult Fail(string message) => new(false, message); + public static UnlockResult Cancelled() => new(false, "Cancelled by user"); + public static UnlockResult TooManyAttempts() => new(false, "Too many failed attempts"); +} + +/// +/// Manages the ECU unlock/password flow. +/// Called after connect, before table population. +/// Two unlock domains: basic ECU and tuner tables. +/// +public interface IAuthService +{ + /// + /// Checks if the ECU is locked and runs the unlock flow if needed. + /// Shows password dialog up to 3 times before giving up. + /// Returns Success=true when the device is unlocked and ready. + /// + Task EnsureUnlockedAsync( + string username, + CancellationToken ct = default); + + /// + /// Runs the tuner unlock flow (APP_UNLOCK_TUNER). + /// Only needed for tuner-mode table access. + /// + Task EnsureTunerUnlockedAsync( + string username, + CancellationToken ct = default); + + /// Last password successfully used — stored for auto-reconnect. + string? SavedPassword { get; } + + /// Last tuner password successfully used. + string? SavedTunerPassword { get; } +} diff --git a/TuneBossPC/Services/ISessionService.cs b/TuneBossPC/Services/ISessionService.cs new file mode 100644 index 0000000..7687b0a --- /dev/null +++ b/TuneBossPC/Services/ISessionService.cs @@ -0,0 +1,123 @@ +using TuneBoss.Core.Models; + +namespace TuneBossPC.Services; + +/// +/// Holds the current connected device's session state — +/// EcuInfo, MemoryLayout, and variant. Populated on connect, +/// cleared on disconnect. Shared across all ViewModels. +/// +public interface ISessionService +{ + EcuInfo? Info { get; } + MemoryLayout? Layout { get; } + EcuVariant Variant { get; } + + /// True only when a real device is connected — gates all hardware comms. + bool IsActive { get; } + + /// True when a layout is available to render tables — connected OR offline file view. + bool HasLayout { get; } + + /// Raised whenever the session is established or cleared (connect / disconnect / offline load). + event Action? SessionChanged; + + /// Builds and stores the session after a successful connect. + void Establish(EcuInfo info, EcuVariant variant); + + /// + /// Establishes an OFFLINE, view-only session from a loaded map file's tag so the + /// editor pages can populate without hardware. Assumes the current-generation (Gen3) + /// layout that all shipping units use. IsActive stays FALSE (comms disabled); + /// HasLayout becomes true. + /// + void EstablishOffline(byte make, byte model, byte fw, int cylinderCount); + + /// Clears the session on disconnect / closing an offline file. + void Clear(); +} + +public sealed class SessionService : ISessionService +{ + public EcuInfo? Info { get; private set; } + public MemoryLayout? Layout { get; private set; } + public EcuVariant Variant { get; private set; } + + private bool _offline; + + // Connected = has info+layout AND not an offline file view. + public bool IsActive => Info != null && Layout != null && !_offline; + public bool HasLayout => Layout != null; + + public event Action? SessionChanged; + + public void Establish(EcuInfo info, EcuVariant variant) + { + Info = info; + Variant = variant; + Layout = MemoryLayout.For(info, variant); + _offline = false; + SessionChanged?.Invoke(); + } + + public void EstablishOffline(byte make, byte model, byte fw, int cylinderCount) + { + // Synthesize a minimal EcuInfo from the file tag. AppInfoVersion = 2 (Gen3), + // which every current TuneBoss unit uses; FW drives the extended-layout split. + var info = new EcuInfo + { + BikeManufacturer = make, + BikeModel = model, + FwVersion = fw, + AppInfoVersion = 2, // Gen3 + }; + var variant = cylinderCount >= 2 + ? EcuVariantResolver.Resolve(info) is var v && v != EcuVariant.SingleCylinder + ? v : EcuVariant.TwoCylinderR15 + : EcuVariant.SingleCylinder; + + Info = info; + Variant = variant; + Layout = MemoryLayout.For(info, variant); + _offline = true; + SessionChanged?.Invoke(); + } + + public void Clear() + { + Info = null; + Layout = null; + Variant = default; + _offline = false; + SessionChanged?.Invoke(); + } +} + +/// +/// Resolves the EcuVariant from bike manufacturer + model. +/// For now uses a simple lookup; extend with the two-cylinder registry as needed. +/// +public static class EcuVariantResolver +{ + // Yamaha two-cylinder R-series models (R25/R3) use the R15 variant layout + private static readonly HashSet<(byte mfr, byte model)> TwoCylinderR15 = new() + { + (1, 10), // R25 2018 + (1, 25), // R25 2019 + (1, 26), // R3 2019 + (1, 11), // R3 2015 + }; + + private static readonly HashSet<(byte mfr, byte model)> TwoCylinder = new() + { + // Add genuinely two-cylinder (non-R15-layout) models here as discovered + }; + + public static EcuVariant Resolve(EcuInfo info) + { + var key = (info.BikeManufacturer, info.BikeModel); + if (TwoCylinderR15.Contains(key)) return EcuVariant.TwoCylinderR15; + if (TwoCylinder.Contains(key)) return EcuVariant.TwoCylinder; + return EcuVariant.SingleCylinder; + } +} diff --git a/TuneBossPC/Services/MapTableCodec.cs b/TuneBossPC/Services/MapTableCodec.cs new file mode 100644 index 0000000..e91b888 --- /dev/null +++ b/TuneBossPC/Services/MapTableCodec.cs @@ -0,0 +1,589 @@ +using System.Collections.Generic; +using System.Text; +using System.Windows; +using TuneBoss.Core.BLE; +using TuneBoss.Core.IO; +using TuneBoss.Core.Models; +using TuneBossPC.ViewModels.Tables; + +namespace TuneBossPC.Services; + +/// +/// Real — maps the legacy .tst sections to the WPF +/// view-models. +/// +/// User saves the adjust tables + their subtables (legacy-exact order). +/// Full Config saves every editable in the app: all base/user 2D + AFR +/// tables and their subtables (legacy-exact order), all 37 1D tables (slot order = legacy +/// order), and the misc values. The table/1D sections are legacy-compatible; the misc block +/// is written as named WPF regions (Core / LaunchFuel / LaunchFuel2 / AuxOut / Extended) +/// rather than the legacy 324-byte textbox array — clean and complete for in-app round-trip. +/// +/// Full Config deserialize is label-keyed (each section carries its name), so it is robust to +/// tables a given device/firmware doesn't expose (those are simply skipped). +/// +public sealed class MapTableCodec : IMapTableCodec +{ + private readonly TuningTablesViewModel _tables; + private readonly OneDimTablesViewModel _oneDim; + private readonly MiscValuesViewModel _misc; + private readonly IBleService _ble; + + public MapTableCodec(TuningTablesViewModel tables, OneDimTablesViewModel oneDim, + MiscValuesViewModel misc, IBleService ble) + { + _tables = tables; + _oneDim = oneDim; + _misc = misc; + _ble = ble; + } + + private const string NotWired = + "Full Tables isn't wired — use User or Full Config."; + + // ── User layout (legacy key -> WPF label) ──────────────────────────────────── + private static readonly (string Key, string Label)[] UserCyl1 = + { + ("Fuel_PulseWidth_Adjust1", "User Fuel Pulse Width 1"), + ("Spark_Angle_Adjust1", "User Spark Angle 1"), + }; + private static readonly (string Key, string Label)[] UserCyl2 = + { + ("Fuel_PulseWidth_Adjust1", "User Fuel Pulse Width 1"), + ("Spark_Angle_Adjust1", "User Spark Angle 1"), + ("Fuel_PulseWidth_Adjust2", "User Fuel Pulse Width 2"), + ("Spark_Angle_Adjust2", "User Spark Angle 2"), + }; + + // ── Full Config layout ─────────────────────────────────────────────────────── + private enum K { TwoD, Afr, Sub } + private readonly record struct Spec(string Key, string Label, K Kind); + + // 2D/AFR first (base then user, cyl1 then cyl2), then subtables — legacy Full Config order. + private static IEnumerable ConfigTables(int cyl) + { + yield return new("Fuel_PulseWidth1", "Base Fuel Pulse Width 1", K.TwoD); + yield return new("Spark_Angle1", "Base Spark Angle 1", K.TwoD); + yield return new("AFR_Target1", "Base AFR Target 1", K.Afr); + yield return new("Fuel_Angle2D", "Base Fuel Injection Angle 1", K.TwoD); + yield return new("Secondary_Load_Conversion", "Base MAP Compensation", K.TwoD); + yield return new("Fuel_PulseWidth_Adjust1", "User Fuel Pulse Width 1", K.TwoD); + yield return new("Spark_Angle_Adjust1", "User Spark Angle 1", K.TwoD); + if (cyl >= 2) + { + yield return new("Fuel_PulseWidth2", "Base Fuel Pulse Width 2", K.TwoD); + yield return new("AFR_Target2", "Base AFR Target 2", K.Afr); + yield return new("Fuel_Angle2D_2", "Base Fuel Injection Angle 2", K.TwoD); + yield return new("Spark_Angle2", "Base Spark Angle 2", K.TwoD); + yield return new("Fuel_PulseWidth_Adjust2", "User Fuel Pulse Width 2", K.TwoD); + yield return new("Spark_Angle_Adjust2", "User Spark Angle 2", 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) + { + yield return new("Fuel_PulseWidth_Adjust2_SubTable", "User Fuel Pulse Width 2", K.Sub); + yield return new("Spark_Angle_Adjust2_SubTable", "User Spark Angle 2", K.Sub); + } + } + + // Slot 1..37 -> legacy 1D section name (matches OneDimTableRegistry slot order). + private static readonly string[] OneDimNames = + { + "Spark_DwellTime_Table", "O2_Conversion_Table", "IAT_Conversion_Table", "ETEMP_Conversion_Table", + "MAP_Conversion_Table", "TPS_Conversion_Table", "ETEMP_Fuel_Comp_Table", "ETEMP_Spark_Comp_Table", + "BARO_Fuel_Comp_Table", "AUX_Conversion_Table", "IAT_Fuel_Comp_Table", "IAT_Spark_Comp_Table", + "TPS_Accel_Fuel_Comp_Table_100us", "TPS_Accel_Spark_Comp_Table", "VBAT_IOT_Comp_Table_10us", + "LOAD_Primary_Pct_Table", "Idle_Solenoid_Ctrl_Pct", "Startup_Fuel_Comp", "Injector2_Pct_Table", + "RadFan_PWM_Settings_ms", "NOS_Fuel_Comp_Table", "NOS_Spark_Comp_Table", "Idle_Fuel_PulseWidth", + "OffThrottle_Isol_Control", "Speed_Fuel_Comp_Table", "Speed_Spark_Comp_Table", + "ShiftBoss_Fuel_Cut_ms_Table", "ShiftBoss_Spark_Cut_ms_Table", "ShiftBoss_Spark_Retard_ms_Table", + "TC_Sensitivity_Table_1D", "TC_Spark_Retard_Degrees_1D", "TC_Spark_Retard_Duration_1D", + "Gear_Ratio_Detection_Table", "Aux_PWM_Table_1D", "Idle_Solenoid_Ctrl_Steps", + "BARO_Spark_Comp_Table", "Idle_Spark_Compensation", + }; + + // ── Prepare (re-read uncached editables before serializing) ─────────────────── + public async Task PrepareAsync(MapSaveType saveType, int cylinderCount) + { + switch (saveType) + { + case MapSaveType.User: + var um = cylinderCount >= 2 ? UserCyl2 : UserCyl1; + await _tables.EnsureLoadedAsync( + um.Select(x => x.Label) + .Concat(um.Select(x => StandaloneSubLabel(x.Key + "_SubTable")))); + break; + + case MapSaveType.FullConfig: + await _tables.EnsureLoadedAsync( + ConfigTables(cylinderCount).Where(t => t.Kind != K.Sub).Select(s => s.Label) + .Concat(ConfigTables(cylinderCount).Where(t => t.Kind == K.Sub) + .Select(t => StandaloneSubLabel(t.Key))) + .Distinct()); + await _oneDim.EnsureLoadedAsync(); + await _misc.EnsureLoadedAsync(); + break; + } + } + + public Task DiagnoseAsync() => _tables.DiagnoseUserReadAsync(); + + // ── Serialize ───────────────────────────────────────────────────────────────── + public string Serialize(MapSaveType saveType, int cylinderCount) => saveType switch + { + MapSaveType.User => SerializeUser(cylinderCount), + MapSaveType.FullConfig => SerializeFullConfig(cylinderCount), + _ => throw new NotImplementedException(NotWired), + }; + + private string SerializeUser(int cyl) + { + var map = cyl >= 2 ? UserCyl2 : UserCyl1; + var sb = new StringBuilder(); + foreach (var (key, label) in map) + sb.Append(MapTableFormat.Section2D(key, Entry(label).TuningTable ?? throw NotLoaded(label))); + foreach (var (key, label) in map) + sb.Append(MapTableFormat.SectionSub(key + "_SubTable", + FindEntry(StandaloneSubLabel(key + "_SubTable"))?.SubTable + ?? Entry(label).SubTableEntry?.SubTable + ?? throw NotLoaded(label + " subtable"))); + return sb.ToString(); + } + + private string SerializeFullConfig(int cyl) + { + var sb = new StringBuilder(); + + foreach (var s in ConfigTables(cyl)) + { + var e = FindEntry(s.Label); + if (e == null) continue; // device doesn't expose this table + switch (s.Kind) + { + case K.TwoD: + sb.Append(MapTableFormat.Section2D(s.Key, e.TuningTable ?? throw NotLoaded(s.Label))); + break; + case K.Afr: + sb.Append(MapTableFormat.SectionAfr(s.Key, e.AfrTable ?? throw NotLoaded(s.Label))); + break; + case K.Sub: + // Sub lives on the standalone Stage-1 entry now (fallback to nested). + var subModel = FindEntry(StandaloneSubLabel(s.Key))?.SubTable + ?? e.SubTableEntry?.SubTable + ?? throw NotLoaded(s.Label + " subtable"); + sb.Append(MapTableFormat.SectionSub(s.Key, subModel)); + break; + } + } + + for (int slot = 1; slot <= OneDimNames.Length; slot++) + { + var e = OneDimEntry(slot); + if (e?.Table == null) continue; // gated out for this device/firmware + sb.Append(MapTableFormat.Section1D(OneDimNames[slot - 1], e.Table)); + } + + var misc = _misc.CurrentMisc ?? throw new InvalidOperationException("Misc values are not loaded."); + sb.Append(MapTableFormat.SectionBytes("MiscCore", misc.Core)); + sb.Append(MapTableFormat.SectionBytes("MiscLaunchFuel", misc.LaunchFuel)); + sb.Append(MapTableFormat.SectionBytes("MiscLaunchFuel2", misc.LaunchFuel2)); + sb.Append(MapTableFormat.SectionBytes("MiscAuxOut", misc.AuxOut)); + sb.Append(MapTableFormat.SectionBytes("MiscExtended", misc.Extended)); + return sb.ToString(); + } + + // ── Write applied content to the ECU (file-load "Apply + Write") ────────────── + public async Task WriteLoadedAsync(MapSaveType saveType, int cylinderCount, bool flash, + IProgress? progress = null) + { + int tables, oneD = 0; bool misc = false; + List lockedLabels; + switch (saveType) + { + case MapSaveType.User: + var um = cylinderCount >= 2 ? UserCyl2 : UserCyl1; + var userLabels = um.Select(x => x.Label) + .Concat(um.Select(x => StandaloneSubLabel(x.Key + "_SubTable"))); + (tables, lockedLabels) = await _tables.WriteEntriesFromModelsAsync(userLabels, progress); + break; + + case MapSaveType.FullConfig: + // Base/user 2D + AFR by label, plus the standalone Stage-1 subtable entries. + var cfgLabels = ConfigTables(cylinderCount).Where(t => t.Kind != K.Sub).Select(t => t.Label) + .Concat(ConfigTables(cylinderCount).Where(t => t.Kind == K.Sub) + .Select(t => StandaloneSubLabel(t.Key))) + .Distinct(); + (tables, lockedLabels) = await _tables.WriteEntriesFromModelsAsync(cfgLabels, progress); + oneD = await _oneDim.WriteAllLoadedAsync(progress); + progress?.Report("Writing misc values…"); + await _misc.WriteAsync(); + misc = true; + break; + + default: + throw new NotImplementedException(NotWired); + } + + var summary = misc + ? $"{tables} tables, {oneD} 1D tables, misc values" + : $"{tables} tables (+ subtables)"; + + if (lockedLabels.Count > 0) + summary += $". NOTE: this is a Stage 1 ECU — the user main tables were NOT written ({string.Join(", ", lockedLabels.Distinct())})"; + + if (flash) + { + progress?.Report("Flashing — do not power off…"); + var fr = await _ble.FlashWriteAsync(); + if (!fr.Success) throw new InvalidOperationException($"Flash failed: {fr.ErrorMessage}"); + summary += ", flashed"; + } + + await _tables.ResumeStreamIfLiveAsync(); + return summary; + } + + // ── Deserialize ─────────────────────────────────────────────────────────────── + + /// Rebuilds the tuning + 1D nav trees from the current layout so entries + /// exist to populate (needed after an offline file establishes a layout). + public void RebuildNavTrees() + { + _tables.RebuildNavTree(); + _oneDim.RebuildNavTree(); + } + + public void Deserialize(string data, MapSaveType saveType, int cylinderCount) + { + switch (saveType) + { + case MapSaveType.User: DeserializeUser(data, cylinderCount); break; + case MapSaveType.FullConfig: DeserializeFullConfig(data, cylinderCount); break; + default: throw new NotImplementedException(NotWired); + } + } + + private void DeserializeUser(string data, int cyl) + { + var map = cyl >= 2 ? UserCyl2 : UserCyl1; + var sections = MapTableFormat.SplitSections(data); + int n = map.Length; + if (sections.Length < n * 2) + throw new InvalidOperationException("Map file is missing table sections for this layout."); + + var entries = new TableEntryViewModel[n]; + var tts = new TuningTable[n]; + for (int i = 0; i < n; i++) + { + entries[i] = Entry(map[i].Label); + tts[i] = MapTableFormat.Parse2D(sections[i]); + } + var subs = new SubTable[n]; + for (int i = 0; i < n; i++) + subs[i] = MapTableFormat.ParseSub(sections[n + i], tts[i].RpmAxis); + + Application.Current.Dispatcher.Invoke(() => + { + for (int i = 0; i < n; i++) + { + entries[i].TuningTable = tts[i]; + entries[i].IsLocked = false; + entries[i].IsLoaded = true; + + // Stage-1 subtables are standalone entries now; route by label + // (fall back to the legacy nested slot if present). + var stand = FindEntry(StandaloneSubLabel(map[i].Key + "_SubTable")); + if (stand != null) { stand.SubTable = subs[i]; stand.IsLoaded = true; } + else if (entries[i].SubTableEntry is { } se) { se.SubTable = subs[i]; se.IsLoaded = true; } + } + var sel = _tables.SelectedEntry; + if (sel != null && Array.IndexOf(entries, sel) >= 0) _tables.SelectEntry(sel); + }); + } + + private void DeserializeFullConfig(string data, int cyl) + { + var map = new Dictionary(); + foreach (var sec in MapTableFormat.SplitSections(data)) + { + if (string.IsNullOrWhiteSpace(sec)) continue; + map[MapTableFormat.LabelOf(sec)] = sec; // label-keyed; last wins + } + + Application.Current.Dispatcher.Invoke(() => + { + // 2D/AFR/sub — parents precede subs in ConfigTables, so parent RPM is set first. + foreach (var s in ConfigTables(cyl)) + { + var e = FindEntry(s.Label); + if (e == null || !map.TryGetValue(s.Key, out var sec)) continue; + switch (s.Kind) + { + case K.TwoD: + e.TuningTable = MapTableFormat.Parse2D(sec); + e.IsLocked = false; e.IsLoaded = true; + break; + case K.Afr: + e.AfrTable = MapTableFormat.ParseAfr(sec); + e.IsLoaded = true; + break; + case K.Sub: + // Stage-1 subtables are now STANDALONE entries (own .SubTable), not + // nested under the user table. Route the parsed sub to that entry by + // its own label. Parent RPM axis (if the parent 2D loaded) seeds the + // sub's display axis. Fall back to the legacy nested slot if present. + var parentRpm = e.TuningTable?.RpmAxis ?? Array.Empty(); + var standalone = FindEntry(StandaloneSubLabel(s.Key)); + if (standalone != null) + { + standalone.SubTable = MapTableFormat.ParseSub(sec, parentRpm); + standalone.IsLoaded = true; + } + else if (e.SubTableEntry is { } se) + { + se.SubTable = MapTableFormat.ParseSub(sec, parentRpm); + se.IsLoaded = true; + } + break; + } + } + + // 1D + for (int slot = 1; slot <= OneDimNames.Length; slot++) + { + var e = OneDimEntry(slot); + if (e == null || !map.TryGetValue(OneDimNames[slot - 1], out var sec)) continue; + e.Table = MapTableFormat.Parse1D(sec); + e.IsLoaded = true; + } + + // Misc (applied as a set; missing regions become empty) + if (map.ContainsKey("MiscCore")) + { + _misc.ApplyRegions( + Region(map, "MiscCore"), + Region(map, "MiscLaunchFuel"), + Region(map, "MiscLaunchFuel2"), + Region(map, "MiscAuxOut"), + Region(map, "MiscExtended")); + } + + // Repaint whatever is on screen. + var selT = _tables.SelectedEntry; if (selT != null) _tables.SelectEntry(selT); + var selO = _oneDim.SelectedEntry; if (selO != null) _oneDim.SelectEntry(selO); + }); + } + + private static byte[] Region(Dictionary map, string label) => + map.TryGetValue(label, out var sec) ? MapTableFormat.ParseBytesSection(sec) : Array.Empty(); + + // ── Helpers ─────────────────────────────────────────────────────────────────── + /// Maps a subtable section key to the standalone Stage-1 nav entry's label, + /// so offline-deserialized sub data lands on the entry that actually renders it. + private static string StandaloneSubLabel(string subKey) => subKey switch + { + "Fuel_PulseWidth_Adjust1_SubTable" => "Fuel PW Subtable 1", + "Spark_Angle_Adjust1_SubTable" => "Spark Angle Subtable 1", + "Fuel_PulseWidth_Adjust2_SubTable" => "Fuel PW Subtable 2", + "Spark_Angle_Adjust2_SubTable" => "Spark Angle Subtable 2", + _ => subKey, + }; + + private TableEntryViewModel? FindEntry(string label) => + _tables.Groups.SelectMany(g => g.Entries).FirstOrDefault(e => e.Label == label); + + private TableEntryViewModel Entry(string label) => + FindEntry(label) ?? throw new InvalidOperationException($"Table '{label}' is not present for this device."); + + private OneDimEntryViewModel? OneDimEntry(int slot) => + _oneDim.Groups.SelectMany(g => g.Entries).FirstOrDefault(e => e.Slot == slot); + + // ════════════════════════════════════════════════════════════════════════ + // FSR format — build from loaded editors / apply to editors + // ════════════════════════════════════════════════════════════════════════ + + /// + /// Builds an from whatever is currently loaded in + /// the editors. Unlike the .tst serializer, this walks the loaded entries directly + /// and simply SKIPS anything not loaded — it never throws "not loaded", so a partial + /// configuration still saves what it has. + /// + public FsrFile.FsrDocument BuildFsrFromEditors(EcuInfo? info, MapTag? tag, int cyl) + { + var doc = new FsrFile.FsrDocument(); + var h = doc.Header; + h.FsrVersion = FsrFile.FormatVersion; + h.Generator = "TuneBossPC"; + h.CreatedUtc = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"); + h.CreatorId = tag?.CreatorId ?? (info?.Username ?? "TUNER"); + h.FwVersion = tag?.FwVersion ?? info?.FwVersion ?? 0; + h.HwVersion = tag?.HwVersion ?? info?.HwVersion ?? 0; + h.Make = tag?.Make ?? info?.BikeManufacturer ?? 0; + h.Model = tag?.Model ?? info?.BikeModel ?? 0; + h.Cylinders = cyl; + h.Generation = info != null ? GenInt(info.AppInfoVersion) : 3; + h.SaveType = "full_config"; + if (tag != null) + { + h.Note = tag.MiscNote; + h.ModEngineBlock = tag.EngineBlock; h.ModCamshaft = tag.Camshaft; + h.ModExhaust = tag.Exhaust; h.ModAirFilter = tag.AirFilter; + h.ModCylinderHead = tag.CylinderHead; h.ModInjector = tag.Injector; + h.ModThrottleBody = tag.ThrottleBody; h.ModJackRod = tag.JackRod; + } + + // 2D / AFR / subtable / user tables — walk the tuning nav, emit what's loaded. + foreach (var e in _tables.Groups.SelectMany(g => g.Entries)) + { + if (e.IsPlaceholder) continue; + var key = TuningKey(e.Label); + if (key == null) continue; // not a persisted table (e.g. Dual Injector) + + if (e.IsStandaloneSub && e.SubTable != null) + doc.Sections.Add(new FsrFile.FsrSection + { + Type = FsrFile.SectionType.SubTable, Name = key, Label = e.Label, + Addr = e.Address, Length = e.ReadLength, Sub = e.SubTable, + }); + else if (e.EntryType == TableEntryType.TuningTable && e.TuningTable != null) + doc.Sections.Add(new FsrFile.FsrSection + { + Type = FsrFile.SectionType.Table2D, Name = key, Label = e.Label, + Addr = e.Address, Length = e.ReadLength, Table2D = e.TuningTable, + }); + else if (e.EntryType == TableEntryType.AfrTable && e.AfrTable != null) + doc.Sections.Add(new FsrFile.FsrSection + { + Type = FsrFile.SectionType.Afr, Name = key, Label = e.Label, + Addr = e.Address, Length = e.ReadLength, Afr = e.AfrTable, + }); + } + + // 1D tables + for (int slot = 1; slot <= OneDimNames.Length; slot++) + { + var e = OneDimEntry(slot); + if (e?.Table == null) continue; + doc.Sections.Add(new FsrFile.FsrSection + { + Type = FsrFile.SectionType.Table1D, Name = OneDimNames[slot - 1], Label = e.Label, + Addr = e.Address, Length = e.ReadLength, Table1D = e.Table, + }); + } + + // Misc byte blocks + var misc = _misc.CurrentMisc; + if (misc != null) + { + AddMisc(doc, "MiscCore", misc.Core); + AddMisc(doc, "MiscLaunchFuel", misc.LaunchFuel); + AddMisc(doc, "MiscLaunchFuel2", misc.LaunchFuel2); + AddMisc(doc, "MiscAuxOut", misc.AuxOut); + AddMisc(doc, "MiscExtended", misc.Extended); + } + + return doc; + } + + private void AddMisc(FsrFile.FsrDocument doc, string name, byte[]? bytes) + { + if (bytes == null || bytes.Length == 0) return; + doc.Sections.Add(new FsrFile.FsrSection + { + Type = FsrFile.SectionType.Misc, Name = name, Label = name, + Addr = _misc.RegionAddress(name), + Length = (byte)Math.Max(0, bytes.Length - 1), MiscBytes = bytes, + }); + } + + private static int GenInt(byte appInfoVersion) => appInfoVersion switch + { + 245 => 1, 1 => 2, 2 => 3, _ => 3, + }; + + /// Maps a tuning entry's display label to its stable FSR feature key. + private static string? TuningKey(string label) => label switch + { + "Base Fuel Pulse Width 1" => "Fuel_PulseWidth1", + "Base Fuel Pulse Width 2" => "Fuel_PulseWidth2", + "Base Spark Angle 1" => "Spark_Angle1", + "Base Spark Angle 2" => "Spark_Angle2", + "Base AFR Target 1" => "AFR_Target1", + "Base AFR Target 2" => "AFR_Target2", + "Base Fuel Injection Angle 1" => "Fuel_Angle2D", + "Base Fuel Injection Angle 2" => "Fuel_Angle2D_2", + "Base MAP Compensation" => "Secondary_Load_Conversion", + "User Fuel Pulse Width 1" => "Fuel_PulseWidth_Adjust1", + "User Fuel Pulse Width 2" => "Fuel_PulseWidth_Adjust2", + "User Spark Angle 1" => "Spark_Angle_Adjust1", + "User Spark Angle 2" => "Spark_Angle_Adjust2", + "Fuel PW Subtable 1" => "Fuel_PulseWidth_Adjust1_SubTable", + "Fuel PW Subtable 2" => "Fuel_PulseWidth_Adjust2_SubTable", + "Spark Angle Subtable 1" => "Spark_Angle_Adjust1_SubTable", + "Spark Angle Subtable 2" => "Spark_Angle_Adjust2_SubTable", + _ => null, + }; + + /// Applies a parsed FSR document into the editors (offline or connected view). + public void ApplyFsr(FsrFile.FsrDocument doc) + { + // Reverse of TuningKey — feature key to the nav entry label. + TableEntryViewModel? FindByKey(string key) + { + foreach (var e in _tables.Groups.SelectMany(g => g.Entries)) + if (TuningKey(e.Label) == key) return e; + return null; + } + + foreach (var s in doc.Sections) + { + switch (s.Type) + { + case FsrFile.SectionType.Table2D when s.Table2D != null: + { + var e = FindByKey(s.Name); + if (e != null) { e.TuningTable = s.Table2D; e.IsLoaded = true; } + break; + } + case FsrFile.SectionType.Afr when s.Afr != null: + { + var e = FindByKey(s.Name); + if (e != null) { e.AfrTable = s.Afr; e.IsLoaded = true; } + break; + } + case FsrFile.SectionType.SubTable when s.Sub != null: + { + var e = FindByKey(s.Name); + if (e != null) { e.SubTable = s.Sub; e.IsLoaded = true; } + break; + } + case FsrFile.SectionType.Table1D when s.Table1D != null: + { + var e = _oneDim.Groups.SelectMany(g => g.Entries) + .FirstOrDefault(x => x.Slot >= 1 && x.Slot <= OneDimNames.Length + && OneDimNames[x.Slot - 1] == s.Name); + if (e != null) { e.Table = s.Table1D; e.IsLoaded = true; } + break; + } + case FsrFile.SectionType.Misc when s.MiscBytes != null: + // collected below and applied as a set + break; + } + } + + // Misc as a set (ApplyRegions rebuilds the config sections). + byte[] Region(string name) => + doc.Find(name)?.MiscBytes ?? Array.Empty(); + if (doc.Sections.Any(x => x.Type == FsrFile.SectionType.Misc)) + _misc.ApplyRegions(Region("MiscCore"), Region("MiscLaunchFuel"), + Region("MiscLaunchFuel2"), Region("MiscAuxOut"), Region("MiscExtended")); + + // Repaint whatever is on screen. + var selT = _tables.SelectedEntry; if (selT != null) _tables.SelectEntry(selT); + } + + private static InvalidOperationException NotLoaded(string what) => + new($"'{what}' is not loaded — read it first."); +} diff --git a/TuneBossPC/Services/SettingsService.cs b/TuneBossPC/Services/SettingsService.cs new file mode 100644 index 0000000..4c5b1b8 --- /dev/null +++ b/TuneBossPC/Services/SettingsService.cs @@ -0,0 +1,84 @@ +using System.IO; +using System.Text.Json; +using CommunityToolkit.Mvvm.ComponentModel; + +namespace TuneBossPC.Services; + +/// +/// App-level behaviour settings (not hardware state). Observable so pages bind +/// directly; persisted automatically on every change. +/// +public sealed partial class AppSettings : ObservableObject +{ + /// + /// When on, the live tracker's exact cell becomes the active selection as it + /// moves — SUB/ADD/SET act on it without the tuner clicking the grid. + /// + [ObservableProperty] private bool _trackerAutoSelect; + + /// + /// When on, any tuning-table cell change (typed, SET, SUB/ADD, paste) triggers + /// a debounced write to the ECU so a forgotten WRITE can't lose work. + /// Flash remains manual. + /// + [ObservableProperty] private bool _autoWriteOnChange; + + /// + /// When on, the 2D tuning table is drawn as a flat white grid with no contour + /// heatmap; the live tracker switches to orange (exact) + yellow (adjacent) so + /// it stays visible against the white. Off = the normal colour contour map. + /// + [ObservableProperty] private bool _flatMapNoContour; + + /// The most recently used device password (stored so the user can pick + /// "use last password" on the next connection). Empty when none stored yet. + [ObservableProperty] private string _lastPassword = string.Empty; +} + +public interface ISettingsService +{ + AppSettings Settings { get; } + void Save(); +} + +/// +/// Loads settings from %APPDATA%\TuneBoss\settings.json at startup and saves on +/// every property change. Failures are non-fatal — defaults apply. +/// +public sealed class SettingsService : ISettingsService +{ + private static readonly string Dir = + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "TuneBoss"); + private static readonly string FilePath = Path.Combine(Dir, "settings.json"); + + private static readonly JsonSerializerOptions JsonOpts = new() { WriteIndented = true }; + + public AppSettings Settings { get; } + + public SettingsService() + { + Settings = Load(); + Settings.PropertyChanged += (_, _) => Save(); + } + + private static AppSettings Load() + { + try + { + if (File.Exists(FilePath)) + return JsonSerializer.Deserialize(File.ReadAllText(FilePath)) ?? new AppSettings(); + } + catch { /* corrupted file — fall back to defaults */ } + return new AppSettings(); + } + + public void Save() + { + try + { + Directory.CreateDirectory(Dir); + File.WriteAllText(FilePath, JsonSerializer.Serialize(Settings, JsonOpts)); + } + catch { /* non-fatal */ } + } +} diff --git a/TuneBossPC/TuneBossPC.csproj b/TuneBossPC/TuneBossPC.csproj new file mode 100644 index 0000000..8da9d4a --- /dev/null +++ b/TuneBossPC/TuneBossPC.csproj @@ -0,0 +1,44 @@ + + + WinExe + net9.0-windows10.0.19041.0 + enable + enable + true + TuneBossPC + + 2026.8.13 + + true + + + + + $(DefineConstants);DEALER + + TuneBossPC.Dealer + TuneBoss PC (Dealer) + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/TuneBossPC/ViewModels/ConnectViewModel.cs b/TuneBossPC/ViewModels/ConnectViewModel.cs new file mode 100644 index 0000000..4454f68 --- /dev/null +++ b/TuneBossPC/ViewModels/ConnectViewModel.cs @@ -0,0 +1,263 @@ +using System.Collections.ObjectModel; +using System.Windows; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using TuneBoss.Core.BLE; +using TuneBoss.Core.Models; +using TuneBossPC.Services; +using Wpf.Ui; + +namespace TuneBossPC.ViewModels; + +public partial class ConnectViewModel : ObservableObject, IDisposable +{ + private readonly IBleService _ble; + private readonly MainWindowViewModel _mainVm; + private readonly IAuthService _auth; + private readonly ISessionService _session; + private readonly TuneBossPC.ViewModels.Tables.TuningTablesViewModel _tablesVm; + private readonly TuneBossPC.ViewModels.Tables.OneDimTablesViewModel _oneDimVm; + private readonly TuneBossPC.ViewModels.Tables.MiscValuesViewModel _miscVm; + private readonly ISnackbarService _snackbar; + private IDisposable? _scanSub; + private IDisposable? _connSub; + private EcuInfo? _ecuInfo; + + [ObservableProperty] private bool _isScanning; + [ObservableProperty] private bool _isConnecting; + [ObservableProperty] private bool _isConnected; + [ObservableProperty] private string _scanButtonText = "Scan"; + [ObservableProperty] private string _statusMessage = string.Empty; + [ObservableProperty] private bool _hasStatusMessage; + + // ECU info fields + [ObservableProperty] private string _ecuUsername = string.Empty; + [ObservableProperty] private string _ecuFwVersion = string.Empty; + [ObservableProperty] private string _ecuHwVersion = string.Empty; + [ObservableProperty] private string _ecuRpmLimit = string.Empty; + [ObservableProperty] private string _ecuFlashWrites = string.Empty; + [ObservableProperty] private string _ecuUniqueId = string.Empty; + + public ObservableCollection Devices { get; } = new(); + + [ObservableProperty] + [NotifyCanExecuteChangedFor(nameof(ConnectCommand))] + private BleDeviceInfo? _selectedDevice; + + public bool CanConnect => SelectedDevice != null && !IsConnecting && !IsConnected; + + public ConnectViewModel( + IBleService ble, + MainWindowViewModel mainVm, + IAuthService auth, + 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; + _tablesVm = tablesVm; + _oneDimVm = oneDimVm; + _miscVm = miscVm; + _snackbar = snackbar; + + _connSub = ble.ConnectionStateChanged.Subscribe(state => + { + Application.Current.Dispatcher.Invoke(() => + { + IsConnected = state == BleConnectionState.Connected; + if (state == BleConnectionState.Disconnected) + { + _mainVm.OnDeviceDisconnected(); + SetStatus("Disconnected"); + } + }); + }); + } + + [RelayCommand] + public void StartScan() + { + if (IsScanning) return; + Devices.Clear(); + IsScanning = true; + ScanButtonText = "Stop"; + + _scanSub = _ble.StartScan().Subscribe(device => + { + // Only surface TuneBoss ECUs — their advertised name starts with "B_T". + if (!device.Name.StartsWith("B_T", StringComparison.OrdinalIgnoreCase)) + return; + + Application.Current.Dispatcher.Invoke(() => + { + var existing = Devices.FirstOrDefault(d => d.Address == device.Address); + if (existing != null) + Devices[Devices.IndexOf(existing)] = device; + else + Devices.Add(device); + }); + }); + } + + [RelayCommand] + public void ToggleScan() + { + if (IsScanning) + { + _ble.StopScan(); + _scanSub?.Dispose(); + IsScanning = false; + ScanButtonText = "Scan"; + } + else + { + StartScan(); + } + } + + [RelayCommand(CanExecute = nameof(CanConnect))] + public async Task ConnectAsync() + { + if (SelectedDevice == null) return; + if (IsScanning) ToggleScan(); + + IsConnecting = true; + SetStatus($"Connecting to {SelectedDevice.Name}…"); + + try + { + // Step 1 — BLE connect + bool ok = await _ble.ConnectAsync(SelectedDevice); + if (!ok) { SetStatus("Connection failed."); return; } + + // Step 2 — Read ECU info (determines generation + unlock command) + SetStatus("Reading device info…"); + _ecuInfo = await _ble.ReadEcuInfoAsync(); + if (_ecuInfo == null) { SetStatus("Could not read device info."); return; } + + // Step 3 — Unlock if needed + SetStatus("Checking device lock status…"); + var unlockResult = await _auth.EnsureUnlockedAsync(_ecuInfo.Username); + + if (!unlockResult.Success) + { + SetStatus($"Unlock failed: {unlockResult.ErrorMessage}"); + await _ble.DisconnectAsync(); + return; + } + + // Step 4 — Populate UI + EcuUsername = _ecuInfo.Username; + EcuFwVersion = $"v{_ecuInfo.FwVersion} FW2: {_ecuInfo.FwVersion2}.{_ecuInfo.FwSubVersion2}"; + EcuHwVersion = $"HW {_ecuInfo.HwVersion} Comp {_ecuInfo.HwComponentVersion}"; + EcuRpmLimit = $"{_ecuInfo.RpmLimit:N0} RPM"; + EcuFlashWrites = _ecuInfo.FlashWriteCount.ToString("N0"); + EcuUniqueId = _ecuInfo.UniqueId; + + // Build the memory layout for this device + var variant = EcuVariantResolver.Resolve(_ecuInfo); + _session.Establish(_ecuInfo, variant); + + _mainVm.OnDeviceConnected(SelectedDevice, _ecuInfo); + + // Pre-load all tables (2D + 1D + misc) behind a modal progress dialog + await LoadAllTablesAsync(); + + SetStatus($"Connected · {_ecuInfo.Username}"); + + // Post-clearance gate: if this unit was never TPS-calibrated, warn the + // tuner and jump straight to the calibration page (legacy UIFirstUseInfo[0]). + if (!_ecuInfo.HasTpsCalibration) + { + MessageBox.Show( + "WARNING: TPS Calibration has not been done on this TuneBoss unit yet.", + "TPS Calibration Warning", + MessageBoxButton.OK, MessageBoxImage.Warning); + _mainVm.NavigateTo("TpsCal"); + } + } + catch (Exception ex) + { + SetStatus($"Error: {ex.Message}"); + } + finally + { + IsConnecting = false; + ConnectCommand.NotifyCanExecuteChanged(); + } + } + + /// + /// Reads every available 2D table, 1D table, and misc block while a + /// non-cancellable modal progress dialog blocks the UI. + /// + private async Task LoadAllTablesAsync() + { + _tablesVm.RebuildNavTree(); + _oneDimVm.RebuildNavTree(); + + var owner = Application.Current.MainWindow; + var dialog = new TuneBossPC.Views.ProgressDialog(); + if (owner != null) + { + dialog.Owner = owner; + owner.IsEnabled = false; + } + + var progress = new Progress(msg => + { + dialog.Report(msg); + SetStatus(msg); + }); + + dialog.Show(); + try + { + dialog.SetHeader("Loading tuning tables…"); + await _tablesVm.InitializeAllAsync(progress); + + dialog.SetHeader("Loading 1D tables…"); + await _oneDimVm.InitializeAllAsync(progress); + + dialog.SetHeader("Loading misc values…"); + await _miscVm.InitializeAllAsync(progress); + } + finally + { + dialog.Close(); + if (owner != null) owner.IsEnabled = true; + } + } + + [RelayCommand] + public async Task DisconnectAsync() + { + SetStatus("Disconnecting…"); + await _ble.DisconnectAsync(); + ClearEcuInfo(); + SetStatus("Disconnected"); + } + + private void SetStatus(string msg) + { + StatusMessage = msg; + HasStatusMessage = !string.IsNullOrEmpty(msg); + } + + private void ClearEcuInfo() + { + EcuUsername = EcuFwVersion = EcuHwVersion = + EcuRpmLimit = EcuFlashWrites = EcuUniqueId = string.Empty; + } + + public void Dispose() + { + _scanSub?.Dispose(); + _connSub?.Dispose(); + } +} diff --git a/TuneBossPC/ViewModels/DiagnosticsStripViewModel.cs b/TuneBossPC/ViewModels/DiagnosticsStripViewModel.cs new file mode 100644 index 0000000..f65a3bd --- /dev/null +++ b/TuneBossPC/ViewModels/DiagnosticsStripViewModel.cs @@ -0,0 +1,223 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using System.Collections.ObjectModel; +using TuneBoss.Core.BLE; +using TuneBoss.Core.Models; + +namespace TuneBossPC.ViewModels; + +/// +/// Represents one slot in the 6-gauge persistent bottom strip. +/// +public partial class GaugeSlotViewModel : ObservableObject +{ + [ObservableProperty] private string _label = string.Empty; + [ObservableProperty] private string _value = "—"; + [ObservableProperty] private string _unit = string.Empty; + [ObservableProperty] private DiagChannel _channel; + + public GaugeSlotViewModel(DiagChannel channel) + { + AssignChannel(channel); + } + + public void AssignChannel(DiagChannel channel) + { + Channel = channel; + Label = channel.GetLabel(); + Unit = channel.GetUnit(); + Value = "—"; + } + + public void UpdateFromFrame(DiagnosticsFrame frame) + { + Value = Channel.GetValue(frame); + } +} + +/// +/// Available diagnostics channels that can be assigned to a gauge slot. +/// +public enum DiagChannel +{ + TPS, + RPM, + EngineTemp, + MAP, + SparkAngle1, + SparkAngle2, + Load, + IAT, + VBAT, + AFR, + FuelPulseWidth, + FuelStartAngle1, + FuelEndAngle, + CrankState, + ThrottleState, + RPMState, + UMState, + MeterSpeed, + MapLoAvg, + BaroDynamic, +} + +public static class DiagChannelExtensions +{ + public static string GetLabel(this DiagChannel c) => c switch + { + DiagChannel.TPS => "TPS", + DiagChannel.RPM => "RPM", + DiagChannel.EngineTemp => "Engine Temp", + DiagChannel.MAP => "MAP", + DiagChannel.SparkAngle1 => "Spark Angle 1", + DiagChannel.SparkAngle2 => "Spark Angle 2", + DiagChannel.Load => "Load", + DiagChannel.IAT => "IAT", + DiagChannel.VBAT => "Battery", + DiagChannel.AFR => "AFR", + DiagChannel.FuelPulseWidth => "Fuel PW", + DiagChannel.FuelStartAngle1=> "Fuel St. Angle", + DiagChannel.FuelEndAngle => "Fuel End Angle", + DiagChannel.CrankState => "Crank State", + DiagChannel.ThrottleState => "Throttle State", + DiagChannel.RPMState => "RPM State", + DiagChannel.UMState => "UM State", + DiagChannel.MeterSpeed => "Speed", + DiagChannel.MapLoAvg => "MAP Lo Avg", + DiagChannel.BaroDynamic => "Baro Dynamic", + _ => c.ToString() + }; + + public static string GetUnit(this DiagChannel c) => c switch + { + DiagChannel.RPM => "rpm", + DiagChannel.EngineTemp => "°C", + DiagChannel.MAP => "kPa", + DiagChannel.IAT => "°C", + DiagChannel.VBAT => "V", + DiagChannel.AFR => "λ", + DiagChannel.TPS => "%", + DiagChannel.MeterSpeed => "kph", + DiagChannel.MapLoAvg => "kPa", + DiagChannel.BaroDynamic => "kPa", + _ => string.Empty + }; + + public static string GetValue(this DiagChannel c, DiagnosticsFrame frame) => c switch + { + DiagChannel.TPS => frame.TPS_Percent.ToString(), + DiagChannel.RPM => frame.RPM.ToString("N0"), + DiagChannel.EngineTemp => frame.ETEMP_DegC.ToString(), + DiagChannel.MAP => frame.MAP_kPa.ToString(), + DiagChannel.SparkAngle1 => frame.SparkAngle1.ToString(), + DiagChannel.SparkAngle2 => frame.SparkAngle2.ToString(), + DiagChannel.Load => frame.Load.ToString(), + DiagChannel.IAT => frame.IAT_DegC.ToString(), + DiagChannel.VBAT => frame.VBAT_Volts.ToString("F1"), + DiagChannel.AFR => frame.O2_AFR.ToString("F1"), + DiagChannel.FuelPulseWidth => frame.FuelPulseWidth1.ToString(), + DiagChannel.FuelStartAngle1=> frame.FuelStartAngle1_Deg.ToString(), + DiagChannel.FuelEndAngle => frame.FuelEndAngle.ToString(), + DiagChannel.CrankState => frame.CrankState.ToString(), + DiagChannel.ThrottleState => frame.ThrottleState.ToString(), + DiagChannel.RPMState => frame.RPMState.ToString(), + DiagChannel.UMState => frame.UMState.ToString(), + DiagChannel.MeterSpeed => frame.MeterSpeed.ToString(), + DiagChannel.MapLoAvg => frame.MAP_Lo_Avg.ToString(), + DiagChannel.BaroDynamic => frame.Baro_Dynamic.ToString(), + _ => "—" + }; +} + +/// +/// ViewModel for the persistent 6-gauge bottom strip. +/// Lives in MainWindowViewModel — always active when diagnostics are running. +/// +public partial class DiagnosticsStripViewModel : ObservableObject, IDisposable +{ + private readonly IBleService _ble; + private IDisposable? _diagSub; + + [ObservableProperty] private bool _isRunning; + + // The 6 configurable gauge slots + public ObservableCollection Slots { get; } = new() + { + new GaugeSlotViewModel(DiagChannel.TPS), + new GaugeSlotViewModel(DiagChannel.RPM), + new GaugeSlotViewModel(DiagChannel.EngineTemp), + new GaugeSlotViewModel(DiagChannel.MAP), + new GaugeSlotViewModel(DiagChannel.SparkAngle1), + new GaugeSlotViewModel(DiagChannel.SparkAngle2), + }; + + // All available channels for the slot picker dialog + public static IEnumerable AllChannels + => Enum.GetValues(); + + public DiagnosticsStripViewModel(IBleService ble) + { + _ble = ble; + } + + // ── Start / Stop ────────────────────────────────────────────────────────── + + [RelayCommand] + public async Task StartAsync() + { + if (IsRunning) return; + await _ble.StartDiagnosticsAsync(); + IsRunning = true; + + _diagSub = _ble.DiagnosticsFrames.Subscribe(OnFrame); + } + + [RelayCommand] + public async Task StopAsync() + { + if (!IsRunning) return; + _diagSub?.Dispose(); + _diagSub = null; + await _ble.StopDiagnosticsAsync(); + IsRunning = false; + + foreach (var slot in Slots) + slot.Value = "—"; + } + + // ── Slot assignment ─────────────────────────────────────────────────────── + + /// Assigns a new channel to a slot by index (0–5). + public void AssignSlot(int slotIndex, DiagChannel channel) + { + if (slotIndex < 0 || slotIndex >= Slots.Count) return; + Slots[slotIndex].AssignChannel(channel); + } + + // ── Frame handling ──────────────────────────────────────────────────────── + + private void OnFrame(DiagnosticsFrame frame) + { + System.Diagnostics.Debug.WriteLine($"[STRIP] Frame received RPM={frame.RPM}"); + System.Windows.Application.Current.Dispatcher.Invoke(() => + { + foreach (var slot in Slots) + slot.UpdateFromFrame(frame); + }); + } + + public void Dispose() + { + _diagSub?.Dispose(); + } + + [RelayCommand] + public async Task ToggleAsync() + { + if (IsRunning) + await StopAsync(); + else + await StartAsync(); + } +} diff --git a/TuneBossPC/ViewModels/DiagnosticsViewModel.cs b/TuneBossPC/ViewModels/DiagnosticsViewModel.cs new file mode 100644 index 0000000..3e7b3b8 --- /dev/null +++ b/TuneBossPC/ViewModels/DiagnosticsViewModel.cs @@ -0,0 +1,133 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using TuneBoss.Core.BLE; +using TuneBoss.Core.Models; +using static System.Windows.Forms.AxHost; + +namespace TuneBossPC.ViewModels; + +public partial class DiagnosticsViewModel : ObservableObject, IDisposable +{ + private readonly IBleService _ble; + private IDisposable? _diagSub; + + // ── Secondary channels ──────────────────────────────────────────────────── + [ObservableProperty] private string _load = "—"; + [ObservableProperty] private string _iatDisplay = "—"; + [ObservableProperty] private string _vbatDisplay = "—"; + [ObservableProperty] private string _afrDisplay = "—"; + [ObservableProperty] private string _fuelPW = "—"; + [ObservableProperty] private string _fuelStartAngle = "—"; + [ObservableProperty] private string _fuelEndAngle = "—"; + [ObservableProperty] private string _sparkAngle1 = "—"; + [ObservableProperty] private string _sparkAngle2 = "—"; + [ObservableProperty] private string _baro = "—"; + [ObservableProperty] private string _baroDynamic = "—"; + [ObservableProperty] private string _mapLoAvg = "—"; + [ObservableProperty] private string _meterSpeed = "—"; + [ObservableProperty] private string _crankSyncLost = "—"; + + // ── State indicators ────────────────────────────────────────────────────── + [ObservableProperty] private int _crankState = -1; // -1 = no data + [ObservableProperty] private string _crankStateText = "—"; + [ObservableProperty] private int _tcMode = 0; + [ObservableProperty] private string _umState = "—"; + [ObservableProperty] private int _gearRatio = 0; + [ObservableProperty] private string _throttleStateText = "—"; + [ObservableProperty] private string _rpmState = "—"; + [ObservableProperty] private bool _stayTuned; + [ObservableProperty] private bool _fuelPWLimit; + [ObservableProperty] private bool _modeSelected; + + // ── Error flags ─────────────────────────────────────────────────────────── + // Analog (8 channels) + [ObservableProperty] private ErrorStatus _errTPS = ErrorStatus.Clear; + [ObservableProperty] private ErrorStatus _errMAP = ErrorStatus.Clear; + [ObservableProperty] private ErrorStatus _errIAT = ErrorStatus.Clear; + [ObservableProperty] private ErrorStatus _errVehicleDown = ErrorStatus.Clear; + [ObservableProperty] private ErrorStatus _errETemp = ErrorStatus.Clear; + [ObservableProperty] private ErrorStatus _errO2 = ErrorStatus.Clear; + [ObservableProperty] private ErrorStatus _errVBAT = ErrorStatus.Clear; + [ObservableProperty] private ErrorStatus _errAux = ErrorStatus.Clear; + + // Output (8 channels) + [ObservableProperty] private ErrorStatus _errInjector1 = ErrorStatus.Clear; + [ObservableProperty] private ErrorStatus _errInjector2 = ErrorStatus.Clear; + [ObservableProperty] private ErrorStatus _errFuelPump = ErrorStatus.Clear; + [ObservableProperty] private ErrorStatus _errRadFan = ErrorStatus.Clear; + [ObservableProperty] private ErrorStatus _errSpark1 = ErrorStatus.Clear; + [ObservableProperty] private ErrorStatus _errSpark2 = ErrorStatus.Clear; + [ObservableProperty] private ErrorStatus _errPSU5V = ErrorStatus.Clear; + [ObservableProperty] private ErrorStatus _errO2Heater = ErrorStatus.Clear; + + [ObservableProperty] private bool _hasActiveError; + + public DiagnosticsViewModel(IBleService ble) + { + _ble = ble; + + // Subscribe to the shared strip stream + _diagSub = ble.DiagnosticsFrames.Subscribe(OnFrame); + } + + private void OnFrame(DiagnosticsFrame frame) + { + System.Windows.Application.Current.Dispatcher.Invoke(() => + { + // Secondary channels + Load = frame.Load.ToString(); + IatDisplay = $"{frame.IAT_DegC} °C"; + VbatDisplay = $"{frame.VBAT_Volts:F1} V"; + AfrDisplay = $"{frame.O2_AFR:F1}"; + FuelPW = frame.FuelPulseWidth1.ToString(); + FuelStartAngle = $"{frame.FuelStartAngle1_Deg}°"; + FuelEndAngle = frame.FuelEndAngle.ToString(); + SparkAngle1 = $"{frame.SparkAngle1}°"; + SparkAngle2 = $"{frame.SparkAngle2}°"; + Baro = $"{frame.Baro_kPa} kPa"; + BaroDynamic = $"{frame.Baro_Dynamic} kPa"; + MapLoAvg = $"{frame.MAP_Lo_Avg} kPa"; + MeterSpeed = $"{frame.MeterSpeed} kph"; + CrankSyncLost = frame.CrankSyncLostCounter.ToString(); + + // State indicators + CrankState = frame.CrankState; + CrankStateText = frame.CrankState switch + { + 5 => "NEAR SYNC", + 6 => "RUNNING", + _ => $"SEARCHING ({frame.CrankState})" + }; + TcMode = frame.TC_Mode; + UmState = frame.UMState.ToString().Replace("_", " "); + GearRatio = frame.GearRatio; + ThrottleStateText = frame.ThrottleState.ToString(); + RpmState = frame.RPMState.ToString(); + StayTuned = frame.StayTunedRunning; + FuelPWLimit = frame.FuelPW_LimitActive; + ModeSelected = frame.ModeSelected; + + // Error flags + var err = frame.Errors; + ErrTPS = err.TPS; + ErrMAP = err.MAP; + ErrIAT = err.IAT; + ErrVehicleDown = err.VehicleDown; + ErrETemp = err.ETemp; + ErrO2 = err.OxygenSensor; + ErrVBAT = err.BattVoltage; + ErrAux = err.Aux; + ErrInjector1 = err.Injector1; + ErrInjector2 = err.Injector2_IdleSol; + ErrFuelPump = err.FuelPump; + ErrRadFan = err.RadiatorFan; + ErrSpark1 = err.SparkIgnition1; + ErrSpark2 = err.SparkIgnition2; + ErrPSU5V = err.PSU_5V; + ErrO2Heater = err.O2Heater; + HasActiveError = err.HasActiveError; + }); + } + + public void Dispose() => _diagSub?.Dispose(); +} diff --git a/TuneBossPC/ViewModels/Dialogs/PasswordDialogViewModel.cs b/TuneBossPC/ViewModels/Dialogs/PasswordDialogViewModel.cs new file mode 100644 index 0000000..d87212b --- /dev/null +++ b/TuneBossPC/ViewModels/Dialogs/PasswordDialogViewModel.cs @@ -0,0 +1,100 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; + +namespace TuneBossPC.ViewModels.Dialogs; + +public enum PasswordDialogResult +{ + Confirmed, + Cancelled, +} + +/// How the user wants to supply the device password. +public enum PasswordChoice +{ + EnterNew, // type a password + UseDefault, // use the built-in default + UseLast, // reuse the last successfully used password +} + +public partial class PasswordDialogViewModel : ObservableObject +{ + private const string DefaultPassword = "PASSWORD"; + + [ObservableProperty] private string _username = string.Empty; + [ObservableProperty] private string _password = string.Empty; + [ObservableProperty] private bool _showPassword; + [ObservableProperty] private string _errorMessage = string.Empty; + [ObservableProperty] private bool _hasError; + [ObservableProperty] private int _attemptNumber = 1; + + /// The last successfully used password (from settings); empty if none. + [ObservableProperty] private string _lastPassword = string.Empty; + + [NotifyPropertyChangedFor(nameof(IsEnterNew))] + [ObservableProperty] private PasswordChoice _choice = PasswordChoice.EnterNew; + + /// True when a stored last password exists (enables that radio option). + public bool HasLastPassword => !string.IsNullOrEmpty(LastPassword); + + /// True when the "enter new" option is selected (shows the password box). + public bool IsEnterNew => Choice == PasswordChoice.EnterNew; + + public PasswordDialogResult Result { get; private set; } = PasswordDialogResult.Cancelled; + public string FinalPassword { get; private set; } = string.Empty; + public Action? CloseAction { get; set; } + + partial void OnLastPasswordChanged(string value) => OnPropertyChanged(nameof(HasLastPassword)); + + // Selecting default / last populates the password; enter-new clears it for typing. + partial void OnChoiceChanged(PasswordChoice value) + { + Password = value switch + { + PasswordChoice.UseDefault => DefaultPassword, + PasswordChoice.UseLast => LastPassword, + _ => string.Empty, + }; + } + + // ── Commands ────────────────────────────────────────────────────────────── + + [RelayCommand] + private void Confirm() + { + if (string.IsNullOrWhiteSpace(Password)) + { + SetError("Please enter a password."); + return; + } + + FinalPassword = Password.Trim(); + Result = PasswordDialogResult.Confirmed; + CloseAction?.Invoke(); + } + + [RelayCommand] + private void Cancel() + { + Result = PasswordDialogResult.Cancelled; + CloseAction?.Invoke(); + } + + // ── Helpers ─────────────────────────────────────────────────────────────── + + public void SetAttempt(int attempt, string? errorFromLastAttempt = null) + { + AttemptNumber = attempt; + // Default to reusing the last password when one exists; otherwise type a new one. + Choice = HasLastPassword ? PasswordChoice.UseLast : PasswordChoice.EnterNew; + Password = HasLastPassword ? LastPassword : string.Empty; + + if (errorFromLastAttempt != null) + SetError(errorFromLastAttempt); + else + ClearError(); + } + + private void SetError(string msg) { ErrorMessage = msg; HasError = true; } + private void ClearError() { ErrorMessage = string.Empty; HasError = false; } +} diff --git a/TuneBossPC/ViewModels/FilesViewModel.cs b/TuneBossPC/ViewModels/FilesViewModel.cs new file mode 100644 index 0000000..112c2e5 --- /dev/null +++ b/TuneBossPC/ViewModels/FilesViewModel.cs @@ -0,0 +1,462 @@ +using Microsoft.Win32; +using System.IO; +using System.Windows; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using TuneBoss.Core.IO; +using TuneBoss.Core.Models; +using TuneBossPC.Services; + +namespace TuneBossPC.ViewModels; + +/// +/// Save / open TuneBoss map files (.tst). +/// +/// Open verifies the file's integrity (MD5 of tag + data), parses the metadata tag, +/// and runs a compatibility check against the connected ECU before optionally +/// applying the tables to the editors. Save builds the tag from the connected unit +/// plus a note + save-type, serializes the tables, and writes the MD5-wrapped file. +/// +public partial class FilesViewModel : ObservableObject +{ + private readonly ISessionService _session; + private readonly IMapTableCodec _codec; + + private string? _loadedData; // verified data section awaiting "Apply" + private MapSaveType _loadedSaveType; + private int _loadedCylinders; + private MapTag? _loadedTag; // full tag of the opened file — reused on offline save + private FsrFile.FsrDocument? _loadedFsr; // parsed .fsr awaiting Apply + + // ── Save options ─────────────────────────────────────────────────────────── + public IReadOnlyList SaveTypes { get; } = + new[] { MapSaveType.User, MapSaveType.FullConfig }; + + [ObservableProperty] private MapSaveType _selectedSaveType = MapSaveType.User; + [ObservableProperty] private string _note = string.Empty; + + // ── Loaded-file summary ──────────────────────────────────────────────────── + [ObservableProperty] private bool _hasLoadedFile; + [ObservableProperty] private string _loadedFileName = string.Empty; + [ObservableProperty] private string _tagSummary = string.Empty; + [ObservableProperty] private string _compatMessage = string.Empty; + [ObservableProperty] private bool _isCompatible; + + [ObservableProperty] private string _statusMessage = "Open a map file to inspect it, or save the current tune."; + [ObservableProperty] private string _diagnosticsReport = string.Empty; + + /// Bumped on each confirmed flash — drives the flash button's green blink. + [ObservableProperty] private int _flashSuccessCount; + + public FilesViewModel(ISessionService session, IMapTableCodec codec) + { + _session = session; + _codec = codec; + _session.SessionChanged += NotifyFileCommands; + } + + private int ConnectedCylinders => + _session.Variant == EcuVariant.SingleCylinder ? 1 : 2; + + // ── OPEN ──────────────────────────────────────────────────────────────────── + + [RelayCommand] + private void Open() + { + var dlg = new OpenFileDialog + { + Title = "Open TuneBoss map file", + Filter = "TuneBoss files (*.fsr;*.tst)|*.fsr;*.tst|" + + "FSR config (*.fsr)|*.fsr|" + + "TuneBoss map (*.tst)|*.tst|All files (*.*)|*.*", + }; + if (dlg.ShowDialog() != true) return; + + // .fsr is the new all-encompassing format; .tst stays for user-level data. + if (dlg.FileName.EndsWith(".fsr", StringComparison.OrdinalIgnoreCase)) + { + OpenFsr(dlg.FileName); + return; + } + + try + { + var text = File.ReadAllText(dlg.FileName); // UTF-8 + var parsed = MapFile.TryParse(text); + if (!parsed.Ok) + { + ResetLoaded(); + StatusMessage = parsed.Error ?? "Could not read this file."; + return; + } + + var tag = MapTag.Parse(parsed.Tag); + _loadedData = parsed.Data; + _loadedSaveType = tag.SaveType; + _loadedCylinders = tag.CylinderCount; + _loadedTag = tag; + + LoadedFileName = Path.GetFileName(dlg.FileName); + TagSummary = BuildSummary(tag); + HasLoadedFile = true; + NotifyFileCommands(); + + // Compatibility against the connected unit (if any). + if (_session.IsActive && _session.Info is { } ecu) + { + var report = MapCompatibility.Check(tag, ecu, ConnectedCylinders); + IsCompatible = report.IsMatch; + CompatMessage = report.Message; + } + else + { + IsCompatible = false; + CompatMessage = "No device connected — open, edit and save this map as a new file offline."; + } + + StatusMessage = _session.IsActive + ? "File verified. Review the details, then Apply to load it into the editors." + : "File verified (offline). Apply to editors, edit, then Save as a new file."; + } + catch (Exception ex) + { + ResetLoaded(); + StatusMessage = $"Error reading file: {ex.Message}"; + } + } + + /// Opens a .fsr file: parse, stash the doc, and surface a tag summary. + private void OpenFsr(string path) + { + try + { + var doc = FsrFile.Read(File.ReadAllText(path)); + if (doc.Header.FsrVersion > FsrFile.FormatVersion) + { + ResetLoaded(); + StatusMessage = $"This .fsr is version {doc.Header.FsrVersion}; this app supports up to {FsrFile.FormatVersion}. Update the app."; + return; + } + + _loadedFsr = doc; + _loadedData = null; // FSR path doesn't use the .tst data blob + _loadedSaveType = MapSaveType.FullConfig; + _loadedCylinders = doc.Header.Cylinders; + // Synthesize a MapTag from the FSR header so Save/summary reuse the same credentials. + _loadedTag = new MapTag + { + CreatorId = doc.Header.CreatorId, + FwVersion = doc.Header.FwVersion, + HwVersion = doc.Header.HwVersion, + Make = doc.Header.Make, + Model = doc.Header.Model, + CylinderCount = doc.Header.Cylinders, + SaveType = MapSaveType.FullConfig, + MiscNote = doc.Header.Note, + EngineBlock = doc.Header.ModEngineBlock, Camshaft = doc.Header.ModCamshaft, + Exhaust = doc.Header.ModExhaust, AirFilter = doc.Header.ModAirFilter, + CylinderHead = doc.Header.ModCylinderHead, Injector = doc.Header.ModInjector, + ThrottleBody = doc.Header.ModThrottleBody, JackRod = doc.Header.ModJackRod, + }; + + LoadedFileName = Path.GetFileName(path); + TagSummary = BuildSummary(_loadedTag); + HasLoadedFile = true; + NotifyFileCommands(); + + if (_session.IsActive && _session.Info is { } ecu) + { + var report = MapCompatibility.Check(_loadedTag, ecu, ConnectedCylinders); + IsCompatible = report.IsMatch; + CompatMessage = report.Message; + } + else + { + IsCompatible = false; + CompatMessage = "No device connected — open, edit and save this config offline."; + } + + StatusMessage = "FSR config verified. Apply to load it into the editors."; + } + catch (Exception ex) + { + ResetLoaded(); + StatusMessage = $"Error reading .fsr: {ex.Message}"; + } + } + public bool CanApply => HasLoadedFile; + public bool CanApplyToEcu => HasLoadedFile && _session.IsActive; + + [RelayCommand(CanExecute = nameof(CanApply))] + private Task ApplyToEditors() => ApplyCoreAsync(write: false, flash: false); + + [RelayCommand(CanExecute = nameof(CanApplyToEcu))] + private Task ApplyAndWrite() => ApplyCoreAsync(write: true, flash: false); + + [RelayCommand(CanExecute = nameof(CanApplyToEcu))] + private Task ApplyWriteFlash() => ApplyCoreAsync(write: true, flash: true); + + /// + /// Shared apply pipeline: populate the editors from the verified file, then + /// optionally push everything to the ECU, then optionally flash. Editor-only + /// remains the safe default; flash is behind a hold-to-confirm button. + /// + private async Task ApplyCoreAsync(bool write, bool flash) + { + bool isFsr = _loadedFsr != null; + if (_loadedData is null && !isFsr) return; + try + { + // Offline: no connected device, so synthesize a view-only layout from the + // file's make/model/fw and rebuild the nav trees, so there are entries to + // populate. (Connected: the device's own layout is already in place.) + if (!_session.IsActive && _loadedTag is { } t) + { + _session.EstablishOffline((byte)t.Make, (byte)t.Model, (byte)t.FwVersion, _loadedCylinders); + _codec.RebuildNavTrees(); + NotifyFileCommands(); // HasLayout now true → Save enabled offline + } + + if (isFsr) _codec.ApplyFsr(_loadedFsr!); + else _codec.Deserialize(_loadedData!, _loadedSaveType, _loadedCylinders); + if (!write) + { + StatusMessage = _session.IsActive + ? "Map applied to the editors. Review, then Write / Flash to the ECU." + : "Map applied to the editors (offline view). Open Tuning / 1D / Config to inspect."; + return; + } + + var progress = new Progress(m => StatusMessage = m); + var summary = await _codec.WriteLoadedAsync(_loadedSaveType, _loadedCylinders, flash, progress); + if (flash) FlashSuccessCount++; + StatusMessage = flash + ? $"Applied, written and FLASHED to the ECU ({summary})." + : $"Applied and written to the ECU ({summary}) — flash manually to make permanent."; + } + catch (NotImplementedException ex) + { + StatusMessage = ex.Message; // pending-codec message + } + catch (Exception ex) + { + StatusMessage = $"Could not apply map: {ex.Message}"; + } + } + + // ── SAVE ──────────────────────────────────────────────────────────────────── + + // Save is available when connected (reads from device) OR when an offline file + // has been applied to the editors (HasLayout true) — offline saves the edited + // editor contents into a new file reusing the loaded file's credentials. + public bool CanSave => _session.IsActive || (_loadedTag != null && _session.HasLayout); + + [RelayCommand(CanExecute = nameof(CanSave))] + private async Task Save() + { + bool offline = !_session.IsActive; + if (offline && _loadedTag is null) + { + StatusMessage = "Open and apply a map file first."; + return; + } + + // Offline reuses the opened file's save type/cylinders; connected uses the picker. + var saveType = offline ? _loadedSaveType : SelectedSaveType; + int cyl = offline ? _loadedCylinders : ConnectedCylinders; + + // Full config → new .fsr format; user-level data → legacy .tst (unchanged). + if (saveType == MapSaveType.FullConfig) + { + await SaveFsrCore(offline, cyl); + return; + } + + string data; + try + { + if (!offline) + { + StatusMessage = "Reading tables from the device…"; + await _codec.PrepareAsync(saveType, cyl); + } + // Offline: the editors already hold the applied+edited values — just serialise. + data = _codec.Serialize(saveType, cyl); + } + catch (NotImplementedException ex) + { + StatusMessage = ex.Message; // pending-codec message + return; + } + catch (Exception ex) + { + StatusMessage = $"Could not read the tables to save: {ex.Message}"; + return; + } + + // Reuse the opened file's credentials offline; build from the device when connected. + MapTag tag; + if (offline) + { + tag = _loadedTag! with + { + SaveType = saveType, + MiscNote = string.IsNullOrWhiteSpace(Note) ? _loadedTag!.MiscNote : Note.Trim(), + }; + } + else + { + var ecu = _session.Info!; + tag = new MapTag + { + CreatorId = string.IsNullOrWhiteSpace(ecu.Username) ? "TUNER" : ecu.Username, + FwVersion = ecu.FwVersion, + HwVersion = ecu.HwVersion, + Make = ecu.BikeManufacturer, + Model = ecu.BikeModel, + CylinderCount = cyl, + SaveType = saveType, + MiscNote = string.IsNullOrWhiteSpace(Note) ? "none" : Note.Trim(), + }; + } + + var dlg = new SaveFileDialog + { + Title = "Save TuneBoss map file", + Filter = "TuneBoss map (*.tst)|*.tst|All files (*.*)|*.*", + DefaultExt = "tst", + AddExtension = true, + FileName = offline ? SuggestOfflineName() : SuggestFileName(_session.Info!), + }; + if (dlg.ShowDialog() != true) return; + + try + { + // BuildEnvelope reproduces the per-record MD5 checksums automatically. + File.WriteAllText(dlg.FileName, MapFile.BuildEnvelope(tag.Build(), data)); + StatusMessage = $"Saved {Path.GetFileName(dlg.FileName)} ({saveType}){(offline ? " — offline edit" : "")}."; + } + catch (Exception ex) + { + StatusMessage = $"Could not save file: {ex.Message}"; + } + } + + // ── SAVE AS .fsr (full-config; invoked by Save() when save-type = FullConfig) ── + + private async Task SaveFsrCore(bool offline, int cyl) + { + // Connected: make sure the editors hold current device data first. Unlike the + // .tst path this never throws "not loaded" — BuildFsrFromEditors just skips + // whatever isn't loaded — but PrepareAsync gives a best-effort full read. + if (!offline) + { + try + { + StatusMessage = "Reading tables from the device…"; + await _codec.PrepareAsync(MapSaveType.FullConfig, cyl); + } + catch { /* partial config still saves what loaded */ } + } + + var tag = offline ? _loadedTag : null; + var doc = _codec.BuildFsrFromEditors(_session.Info, tag, cyl); + if (!string.IsNullOrWhiteSpace(Note)) doc.Header.Note = Note.Trim(); + + if (doc.Sections.Count == 0) + { + StatusMessage = "Nothing loaded to save. Read some tables first."; + return; + } + + var dlg = new SaveFileDialog + { + Title = "Save TuneBoss config (.fsr)", + Filter = "FSR config (*.fsr)|*.fsr|All files (*.*)|*.*", + DefaultExt = "fsr", + AddExtension = true, + FileName = offline ? SuggestOfflineName() : SuggestFileName(_session.Info!), + }; + if (dlg.ShowDialog() != true) return; + + try + { + File.WriteAllText(dlg.FileName, FsrFile.Write(doc)); + int n = doc.Sections.Count; + StatusMessage = $"Saved {Path.GetFileName(dlg.FileName)} — {n} section{(n == 1 ? "" : "s")}."; + } + catch (Exception ex) + { + StatusMessage = $"Could not save .fsr: {ex.Message}"; + } + } + + private string SuggestOfflineName() + { + var mk = _loadedTag != null ? BikeRegistry.GetMake((byte)_loadedTag.Make) : "map"; + return $"{mk}_{DateTime.Now:yyyyMMdd}_edited"; + } + + + // ── DIAGNOSE (why aren't user tables reading?) ─────────────────────────────── + [RelayCommand(CanExecute = nameof(CanSave))] + private async Task Diagnose() + { + StatusMessage = "Running read diagnostic…"; + try + { + var report = await _codec.DiagnoseAsync(); + DiagnosticsReport = report; + System.Diagnostics.Debug.WriteLine(report); + StatusMessage = "Diagnostic complete — see the report below."; + } + catch (Exception ex) + { + StatusMessage = $"Diagnostic error: {ex.Message}"; + } + } + + // ── Helpers ────────────────────────────────────────────────────────────────── + + private static string SuggestFileName(EcuInfo ecu) + { + var bike = BikeRegistry.GetModel(ecu.BikeManufacturer, ecu.BikeModel) + .Replace(' ', '_').Replace('/', '-'); + return $"{bike}_{DateTime.Now:yyyyMMdd}"; + } + + private static string BuildSummary(MapTag t) + { + var bike = BikeRegistry.GetDisplayName((byte)t.Make, t.Model); + return + $"Creator: {t.CreatorId}\n" + + $"Firmware: {t.FwVersion} Hardware: {t.HwVersion}\n" + + $"Bike: {bike} ({t.CylinderCount}-cyl)\n" + + $"Contents: {t.SaveType}\n" + + $"Mods: block {t.EngineBlock}, cam {t.Camshaft}, exhaust {t.Exhaust}, " + + $"filter {t.AirFilter}, head {t.CylinderHead}, injector {t.Injector}, " + + $"throttle {t.ThrottleBody}, jackrod {t.JackRod}\n" + + $"Note: {t.MiscNote}"; + } + + private void ResetLoaded() + { + HasLoadedFile = false; + _loadedData = null; + _loadedTag = null; + _loadedFsr = null; + LoadedFileName = TagSummary = CompatMessage = string.Empty; + IsCompatible = false; + NotifyFileCommands(); + } + + partial void OnHasLoadedFileChanged(bool value) => NotifyFileCommands(); + + private void NotifyFileCommands() + { + ApplyToEditorsCommand.NotifyCanExecuteChanged(); + ApplyAndWriteCommand.NotifyCanExecuteChanged(); + ApplyWriteFlashCommand.NotifyCanExecuteChanged(); + SaveCommand.NotifyCanExecuteChanged(); + } +} diff --git a/TuneBossPC/ViewModels/MainWindowViewModel.cs b/TuneBossPC/ViewModels/MainWindowViewModel.cs new file mode 100644 index 0000000..2eadca7 --- /dev/null +++ b/TuneBossPC/ViewModels/MainWindowViewModel.cs @@ -0,0 +1,297 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using TuneBoss.Core.BLE; +using TuneBoss.Core.Models; +using TuneBossPC.Views; + +namespace TuneBossPC.ViewModels; + +public partial class MainWindowViewModel : ObservableObject, IDisposable +{ + private readonly IBleService _ble; + private readonly IServiceProvider _services; + private readonly TuneBossPC.Services.ISessionService _session; + private readonly IDisposable _connSub; + + /// Build/version string shown under the logo. + public string AppVersion => TuneBossPC.AppInfo.Version; + + /// False in the dealer build → the Config and 1D Tables nav items are hidden. + public bool ShowAdvancedNav => TuneBossPC.AppInfo.ShowAdvancedNav; + + [ObservableProperty] private bool _isConnected; + [ObservableProperty] private string _connectionStatusText = "Not connected"; + [ObservableProperty] private string _deviceName = string.Empty; + [ObservableProperty] private string _firmwareInfo = string.Empty; + [ObservableProperty] private string _bikeInfo = string.Empty; + [ObservableProperty] private string _stageInfo = string.Empty; + [ObservableProperty] private string _statusLeft = "Ready"; + [ObservableProperty] private string _statusRight = string.Empty; + [ObservableProperty] private object? _currentPage; + + // ── Killswitch (press-and-hold / momentary) ──────────────────────────────── + // Kills the engine without switching off the bike by zeroing the two RPM-limit + // bytes at misc core[12..13] (RPM_Limit_div100 + Recovery). It only stays killed + // WHILE the button is held; releasing restores the saved value immediately. This + // avoids leaving a latched 0 RPM limit that a stray FLASH could persist. + // Public because [ObservableProperty] generates a public KillPhase property of this type. + public enum KillState { Inactive, Arming, Active, Restoring } + + private const int KillRpmLimitOffset = 12; + private byte _savedRpmLimit; + private byte _savedRpmRecovery; + + private readonly System.Threading.SemaphoreSlim _killGate = new(1, 1); + private volatile bool _killHeld; // mouse currently held on the button + private bool _killZeroed; // the RPM limit is currently zeroed (needs restore) + private System.DateTime _killDownUtc; + private System.Windows.Threading.DispatcherTimer? _killArmTimer; + + [NotifyPropertyChangedFor(nameof(KillswitchLabel))] + [NotifyPropertyChangedFor(nameof(KillswitchBrush))] + [ObservableProperty] private KillState _killPhase = KillState.Inactive; + + public string KillswitchLabel => KillPhase switch + { + KillState.Arming => "KILLSWITCH …", + KillState.Active => "KILLSWITCH ACTIVE", + KillState.Restoring => "KILLSWITCH …", + _ => "KILLSWITCH INACTIVE", + }; + + /// Green when active (engine killed), amber while arming/restoring, red when inactive. + public System.Windows.Media.Brush KillswitchBrush => KillPhase switch + { + KillState.Active => KillBrush(0x1E, 0x8E, 0x3E), // green + KillState.Arming or KillState.Restoring => KillBrush(0xE8, 0xA0, 0x00), // amber (working) + _ => KillBrush(0xC6, 0x28, 0x28), // red + }; + + private static System.Windows.Media.SolidColorBrush KillBrush(byte r, byte g, byte b) + => new(System.Windows.Media.Color.FromRgb(r, g, b)); + + public bool IsNotConnected => !IsConnected; + + /// The persistent diagnostics strip — always alive in the shell. + public DiagnosticsStripViewModel Strip { get; } + + public MainWindowViewModel(IBleService ble, IServiceProvider services, TuneBossPC.Services.ISessionService session, + DiagnosticsStripViewModel strip) + { + _ble = ble; + _services = services; + _session = session; + Strip = strip; + + _connSub = ble.ConnectionStateChanged.Subscribe(OnConnectionStateChanged); + } + + /// Tag of the page currently shown — drives the nav-rail highlight. + [ObservableProperty] private string _currentPageTag = ""; + + public void NavigateTo(string page) + { + // The Throttle Cal page drives the device itself and needs diagnostics off. + // Stop them through the strip VM so its START button resets to the ready state + // (rather than being silently stopped at the BLE layer, leaving the button stuck). + if (page == "TpsCal" && Strip.IsRunning) + _ = Strip.StopAsync(); + + CurrentPageTag = page; + CurrentPage = page switch + { + "Connect" => _services.GetService(typeof(ConnectView)), + "Diagnostics" => _services.GetService(typeof(DiagnosticsView)), + "TuningTables" => _services.GetService(typeof(TuningTablesView)), + "OneDimTables" => _services.GetService(typeof(OneDimTablesView)), + "MiscValues" => _services.GetService(typeof(MiscValuesView)), + "RpmSettings" => _services.GetService(typeof(RpmSettingsView)), + "TpsCal" => _services.GetService(typeof(TpsCalView)), + "Files" => _services.GetService(typeof(FilesView)), + "Settings" => _services.GetService(typeof(SettingsView)), + _ => _services.GetService(typeof(ConnectView)), + }; + } + + private void OnConnectionStateChanged(BleConnectionState state) + { + System.Windows.Application.Current.Dispatcher.Invoke(() => + { + IsConnected = state == BleConnectionState.Connected; + OnPropertyChanged(nameof(IsNotConnected)); + ConnectionStatusText = state switch + { + BleConnectionState.Connected => "Connected", + BleConnectionState.Connecting => "Connecting…", + BleConnectionState.Disconnecting => "Disconnecting…", + _ => "Not connected", + }; + StatusLeft = ConnectionStatusText; + + // Stop strip when disconnected + if (state == BleConnectionState.Disconnected && Strip.IsRunning) + _ = Strip.StopAsync(); + }); + } + + public void OnDeviceConnected(BleDeviceInfo device, EcuInfo info) + { + DeviceName = device.Name; + FirmwareInfo = $"FW {info.FwVersion} HW {info.HwVersion}"; + BikeInfo = BikeRegistry.GetDisplayName(info.BikeManufacturer, info.BikeModel); + StageInfo = $"Stage {info.Stage}"; + StatusRight = $"Flash writes: {info.FlashWriteCount}"; + } + + public void OnDeviceDisconnected() + { + DeviceName = FirmwareInfo = BikeInfo = StageInfo = StatusRight = string.Empty; + // A disconnect drops the live RAM edit anyway; clear killswitch state so a + // fresh connection starts inactive. + _killHeld = false; + _killZeroed = false; + _killArmTimer?.Stop(); + KillPhase = KillState.Inactive; + } + + [RelayCommand] + private async Task DisconnectAsync() + { + await _ble.DisconnectAsync(); + _session.Clear(); + OnDeviceDisconnected(); + NavigateTo("Connect"); + } + + // ── Killswitch: press-and-hold ────────────────────────────────────────────── + // Called on mouse-down: stash the current RPM limit and zero it (engine cuts). + public void KillswitchPress() + { + if (_killHeld) return; + if (!_session.IsActive || _session.Layout is null) + { + StatusLeft = "Killswitch needs a connected device."; + return; + } + _killHeld = true; + _ = KillswitchArmAsync(); + } + + // Called on mouse-up (or lost capture): restore the saved RPM limit. + public void KillswitchRelease() + { + if (!_killHeld) return; + _killHeld = false; + _killArmTimer?.Stop(); + _ = KillswitchRestoreAsync(); + } + + private async Task KillswitchArmAsync() + { + await _killGate.WaitAsync(); + bool zeroedNow = false; + try + { + if (_session.Layout is null) { KillPhase = KillState.Inactive; return; } + + KillPhase = KillState.Arming; + _killZeroed = false; + _killDownUtc = DateTime.UtcNow; + + ushort addr = (ushort)(_session.Layout.MiscCore.Address + KillRpmLimitOffset); + + // Read + stash the two RPM-limit bytes (data begins at payload[4]). + var read = await _ble.ReadMiscAsync(addr, 2); + if (!read.Success || read.Payload is null || read.Payload.Length < 6) + { + StatusLeft = $"Killswitch: read failed ({read.ErrorMessage})."; + KillPhase = KillState.Inactive; + return; + } + _savedRpmLimit = read.Payload[4]; + _savedRpmRecovery = read.Payload[5]; + + // Released before we zeroed anything — nothing to restore. + if (!_killHeld) { KillPhase = KillState.Inactive; return; } + + var write = await _ble.WriteMiscAsync(addr, new byte[] { 0, 0 }); + if (!write.Success) + { + StatusLeft = $"Killswitch: write failed ({write.ErrorMessage})."; + KillPhase = KillState.Inactive; + return; + } + _killZeroed = true; + zeroedNow = true; + StatusLeft = "KILLSWITCH engaged — hold to keep the engine disabled."; + } + catch (Exception ex) { StatusLeft = $"Killswitch error: {ex.Message}"; KillPhase = KillState.Inactive; } + finally { _killGate.Release(); } + + if (!zeroedNow) { await ResumeDiagIfLiveAsync(); return; } + + // Zeroed OK. If released during the write, restore now; else arm the 3s → ACTIVE. + if (!_killHeld) { await KillswitchRestoreAsync(); return; } + ArmActiveTimer(); + } + + // Flip to ACTIVE only after ~3s of continuous hold AND the zero-write has responded. + private void ArmActiveTimer() + { + var remaining = TimeSpan.FromSeconds(3) - (DateTime.UtcNow - _killDownUtc); + if (remaining <= TimeSpan.Zero) + { + if (_killHeld && _killZeroed) KillPhase = KillState.Active; + return; + } + _killArmTimer?.Stop(); + _killArmTimer = new System.Windows.Threading.DispatcherTimer { Interval = remaining }; + _killArmTimer.Tick += (_, _) => + { + _killArmTimer!.Stop(); + if (_killHeld && _killZeroed) KillPhase = KillState.Active; + }; + _killArmTimer.Start(); + } + + private async Task KillswitchRestoreAsync() + { + await _killGate.WaitAsync(); + try + { + // Nothing was zeroed (too-fast tap, or already restored) → just go inactive. + if (!_killZeroed || _session.Layout is null) + { + _killZeroed = false; + KillPhase = KillState.Inactive; + return; + } + + KillPhase = KillState.Restoring; + ushort addr = (ushort)(_session.Layout.MiscCore.Address + KillRpmLimitOffset); + var write = await _ble.WriteMiscAsync( + addr, new byte[] { _savedRpmLimit, _savedRpmRecovery }); + _killZeroed = false; + StatusLeft = write.Success + ? "Killswitch released — RPM limit restored." + : $"Killswitch: restore failed ({write.ErrorMessage})."; + KillPhase = KillState.Inactive; + } + catch (Exception ex) { StatusLeft = $"Killswitch error: {ex.Message}"; KillPhase = KillState.Inactive; } + finally { _killGate.Release(); await ResumeDiagIfLiveAsync(); } + } + + // Misc read/write pause diagnostics at the BLE layer — resume if the strip is live + // (VM-layer resume only; never restart at the BLE layer). + private async Task ResumeDiagIfLiveAsync() + { + try { if (Strip.IsRunning) await _ble.StartDiagnosticsAsync(); } + catch { /* best-effort */ } + } + + public void Dispose() + { + _connSub.Dispose(); + Strip.Dispose(); + } +} diff --git a/TuneBossPC/ViewModels/MiscValuesViewModel.MapSupport.cs b/TuneBossPC/ViewModels/MiscValuesViewModel.MapSupport.cs new file mode 100644 index 0000000..e7d570b --- /dev/null +++ b/TuneBossPC/ViewModels/MiscValuesViewModel.MapSupport.cs @@ -0,0 +1,36 @@ +using TuneBoss.Core.Models; + +namespace TuneBossPC.ViewModels.Tables; + +/// +/// Map-file support for Full Config: expose the raw misc regions for serialization, +/// apply parsed regions back, and ensure misc is read before a save. +/// +public partial class MiscValuesViewModel +{ + /// The currently-loaded misc model (raw regions), or null if not read yet. + public MiscValues? CurrentMisc => _misc; + + /// Reads the misc regions if they aren't loaded yet. + public async Task EnsureLoadedAsync() + { + if (_misc == null) await ReadAllAsync(null); + } + + /// + /// Replaces the misc model from parsed region byte blocks (data-only, no header) + /// and rebuilds the editor sections so the page reflects the loaded values. + /// + public void ApplyRegions(byte[] core, byte[] launchFuel, byte[] launchFuel2, byte[] auxOut, byte[] extended) + { + _misc = new MiscValues + { + Core = core, + LaunchFuel = launchFuel, + LaunchFuel2 = launchFuel2, + AuxOut = auxOut, + Extended = extended, + }; + RebuildSections(); + } +} diff --git a/TuneBossPC/ViewModels/MiscValuesViewModel.cs b/TuneBossPC/ViewModels/MiscValuesViewModel.cs new file mode 100644 index 0000000..96102de --- /dev/null +++ b/TuneBossPC/ViewModels/MiscValuesViewModel.cs @@ -0,0 +1,376 @@ +using System.Collections.ObjectModel; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using TuneBoss.Core.BLE; +using TuneBoss.Core.Models; + +namespace TuneBossPC.ViewModels.Tables; + +// ──────────────────────────────────────────────────────────────────────────── +// One bit sub-field editor (checkbox / combo / number) over a shared byte. +// ──────────────────────────────────────────────────────────────────────────── +public partial class MiscBitEditorViewModel : ObservableObject +{ + private readonly MiscFieldViewModel _owner; + public MiscBitField Field { get; } + private readonly int _shift; + private bool _suppress; + + public string Label => Field.DisplayText; // display text (raw name stays in Field.Label) + public bool IsFlag => Field.Kind == MiscEditorKind.Flag; + public bool IsEnum => Field.Kind == MiscEditorKind.Enum; + public bool IsNumber => Field.Kind == MiscEditorKind.Number; + public string[]? Options => Field.Options; + public int Max => Field.Mask >> _shift; + public int BitIndex => _shift; // meaningful for single-bit flags + + public MiscBitEditorViewModel(MiscFieldViewModel owner, MiscBitField field) + { + _owner = owner; + Field = field; + _shift = Shift(field.Mask); + RefreshFromByte(); + } + + [ObservableProperty] private bool _isChecked; + [ObservableProperty] private int _selectedIndex; + [ObservableProperty] private int _number; + + partial void OnIsCheckedChanged(bool value) { if (!_suppress) Write(value ? 1 : 0); } + partial void OnSelectedIndexChanged(int value) { if (!_suppress && value >= 0) Write(value); } + partial void OnNumberChanged(int value) { if (!_suppress) Write(Math.Clamp(value, 0, Max)); } + + private void Write(int raw) + { + var b = _owner.ByteValue; + b = (byte)((b & ~Field.Mask) | ((raw << _shift) & Field.Mask)); + _owner.ByteValue = b; + _owner.OnBitChanged(this); + } + + public void RefreshFromByte() + { + _suppress = true; + int raw = (_owner.ByteValue & Field.Mask) >> _shift; + if (IsFlag) IsChecked = raw != 0; + else if (IsEnum) SelectedIndex = raw; + else Number = raw; + _suppress = false; + } + + private static int Shift(int mask) + { + if (mask == 0) return 0; + int s = 0; + while ((mask & 1) == 0) { mask >>= 1; s++; } + return s; + } +} + +// ──────────────────────────────────────────────────────────────────────────── +// One editable raw-byte field. Optionally carries a bit-field spec; when present +// it also exposes Bits (checkboxes / combos / numbers) over the same byte. +// ──────────────────────────────────────────────────────────────────────────── +public partial class MiscFieldViewModel : ObservableObject +{ + public MiscField Def { get; } + public MiscByteSpec? Spec { get; } + private readonly byte[] _block; + + public string Label => Def.DisplayText; // display text (raw name stays in Def.Label) + public int Index => Def.Index; + public bool HasSpec => Spec != null; + + public ObservableCollection Bits { get; } = new(); + [ObservableProperty] private bool _isExpanded; + + public MiscFieldViewModel(MiscField def, byte[] block, MiscByteSpec? spec = null) + { + Def = def; + _block = block; + Spec = spec; + _value = def.Index < block.Length ? block[def.Index] : 0; + + if (spec != null) + foreach (var f in spec.Fields) + Bits.Add(new MiscBitEditorViewModel(this, f)); + } + + /// The underlying raw byte, read/written in place. + public byte ByteValue + { + get => Def.Index < _block.Length ? _block[Def.Index] : (byte)0; + set { if (Def.Index < _block.Length) _block[Def.Index] = value; } + } + + [ObservableProperty] private int _value; + private bool _syncing; + + partial void OnValueChanged(int value) + { + int clamped = Math.Clamp(value, 0, 255); + if (clamped != value) { Value = clamped; return; } + ByteValue = (byte)clamped; + if (!_syncing) RefreshBits(); + } + + /// Called after a bit edit: apply constraints, then resync siblings + raw value. + public void OnBitChanged(MiscBitEditorViewModel src) + { + if (Spec?.MutualExclusive != null) + foreach (var (a, b) in Spec.MutualExclusive) + if (BitSet(a) && BitSet(b)) + SetBit(src.BitIndex == a ? b : a, false); + + if (Spec?.Linked != null) + foreach (var (a, b) in Spec.Linked) + { + if (src.BitIndex == a) SetBit(b, BitSet(a)); + else if (src.BitIndex == b) SetBit(a, BitSet(b)); + } + + RefreshBits(); + _syncing = true; Value = ByteValue; _syncing = false; + } + + public void RefreshBits() { foreach (var b in Bits) b.RefreshFromByte(); } + + private bool BitSet(int i) => (ByteValue & (1 << i)) != 0; + private void SetBit(int i, bool on) + { + var b = ByteValue; + ByteValue = (byte)(on ? (b | (1 << i)) : (b & ~(1 << i))); + } +} + +public partial class MiscSectionViewModel : ObservableObject +{ + public string Label { get; init; } = string.Empty; + [ObservableProperty] private bool _isSelected; + public List Fields { get; } = new(); +} + +public partial class MiscBlockGroupViewModel : ObservableObject +{ + public string Label { get; init; } = string.Empty; + [ObservableProperty] private bool _isExpanded = true; + public List Sections { get; } = new(); +} + +// ──────────────────────────────────────────────────────────────────────────── +// Misc Values page +// ──────────────────────────────────────────────────────────────────────────── +public partial class MiscValuesViewModel : ObservableObject, IDisposable +{ + private readonly IBleService _ble; + private readonly TuneBossPC.Services.ISessionService _session; + private MiscValues? _misc; + + public ObservableCollection Groups { get; } = new(); + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(HasSelection))] + private MiscSectionViewModel? _selectedSection; + + public bool HasSelection => SelectedSection != null; + + [ObservableProperty] private bool _isReading; + [ObservableProperty] private bool _isWriting; + /// Bumped on each confirmed flash — drives the FLASH button's green blink. + [ObservableProperty] private int _flashSuccessCount; + [ObservableProperty] private string _statusMessage = string.Empty; + + public MiscValuesViewModel(IBleService ble, TuneBossPC.Services.ISessionService session) + { + _ble = ble; + _session = session; + _session.SessionChanged += () => OnPropertyChanged(nameof(CanComms)); + } + + /// True when hardware comms are allowed — a live session. Offline is view-only. + public bool CanComms => _session.IsActive; + + [RelayCommand] + public void SelectSection(MiscSectionViewModel section) + { + if (SelectedSection != null) SelectedSection.IsSelected = false; + SelectedSection = section; + section.IsSelected = true; + } + + public Task InitializeAllAsync(IProgress? progress = null) => ReadAllAsync(progress); + + [RelayCommand] + public Task ReadAsync() => ReadAllAsync(null); + + /// ECU address of a misc block in the current layout (0 if no layout). + /// Used by the .fsr writer so each MISC section carries its real address. + public ushort RegionAddress(string blockName) + { + var l = _session.Layout; + if (l is null) return 0; + return blockName switch + { + "MiscCore" => l.MiscCore.Address, + "MiscLaunchFuel" => l.MiscLaunchFuel.Address, + "MiscLaunchFuel2" => l.MiscLaunchFuel2.Address, + "MiscAuxOut" => l.MiscAuxOut.Address, + "MiscExtended" => l.MiscExtended.Address, + _ => 0, + }; + } + + private async Task ReadAllAsync(IProgress? progress) + { + if (!_session.HasLayout || _session.Layout is null) return; + var layout = _session.Layout; + + IsReading = true; + StatusMessage = "Reading misc values…"; + try + { + progress?.Report("Reading misc core…"); + var core = await _ble.ReadMiscAsync(layout.MiscCore.Address, layout.MiscCore.Length); + if (!core.Success) { StatusMessage = $"Misc read failed: {core.ErrorMessage}"; return; } + + byte[]? lf = await ReadBlock(layout.MiscLaunchFuel, progress, "launch fuel"); + byte[]? lf2 = await ReadBlock(layout.MiscLaunchFuel2, progress, "launch fuel 2"); + byte[]? ao = await ReadBlock(layout.MiscAuxOut, progress, "aux out"); + byte[]? ext = await ReadBlock(layout.MiscExtended, progress, "extended"); + + _misc = MiscValues.FromPayloads(core.Payload, lf, lf2, ao, ext); + RebuildSections(); + StatusMessage = "Misc read OK"; + } + catch (Exception ex) { StatusMessage = $"Error: {ex.Message}"; } + finally { IsReading = false; } + } + + private async Task ReadBlock(MemoryRegion region, IProgress? progress, string name) + { + if (!region.IsAvailable) return null; + progress?.Report($"Reading misc {name}…"); + var r = await _ble.ReadMiscAsync(region.Address, region.Length); + return r.Success ? r.Payload : null; + } + + [RelayCommand] + public async Task WriteAsync() + { + if (_misc is null || _session.Layout is null) return; + var layout = _session.Layout; + + IsWriting = true; + StatusMessage = "Writing misc values…"; + try + { + if (!await WriteBlock(layout.MiscCore, _misc.Core)) return; + if (!await WriteBlock(layout.MiscLaunchFuel, _misc.LaunchFuel)) return; + if (!await WriteBlock(layout.MiscLaunchFuel2, _misc.LaunchFuel2)) return; + if (!await WriteBlock(layout.MiscAuxOut, _misc.AuxOut)) return; + if (!await WriteBlock(layout.MiscExtended, _misc.Extended)) return; + StatusMessage = "Misc write OK — click Flash to make permanent"; + } + catch (Exception ex) { StatusMessage = $"Error: {ex.Message}"; } + finally { IsWriting = false; } + } + + private async Task WriteBlock(MemoryRegion region, byte[] data) + { + if (!region.IsAvailable || data.Length == 0) return true; + var w = await _ble.WriteMiscAsync(region.Address, data); + if (!w.Success) { StatusMessage = $"Misc write failed: {w.ErrorMessage}"; return false; } + return true; + } + + [RelayCommand] + private async Task FlashAsync() + { + IsWriting = true; + StatusMessage = "Flashing to ECU…"; + try + { + var fr = await _ble.FlashWriteAsync(); + if (fr.Success) FlashSuccessCount++; + StatusMessage = fr.Success + ? "Flash OK — settings saved to ECU" + : $"Flash failed: {fr.ErrorMessage}"; + } + catch (Exception ex) { StatusMessage = $"Error: {ex.Message}"; } + finally { IsWriting = false; } + } + + private void RebuildSections() + { + // Remember which section was open so a Read/refresh doesn't jump back to the top. + string? prevGroup = SelectedSection is null + ? null + : Groups.FirstOrDefault(g => g.Sections.Contains(SelectedSection))?.Label; + string? prevSection = SelectedSection?.Label; + + Groups.Clear(); + SelectedSection = null; + if (_misc is null) return; + + var groupByBlock = new Dictionary(); + var sectionMap = new Dictionary<(MiscBlock, string), MiscSectionViewModel>(); + + foreach (var f in MiscFieldRegistry.All) + { + var arr = BlockArray(f.Block); + if (f.Index >= arr.Length) continue; + + if (!groupByBlock.TryGetValue(f.Block, out var grp)) + { + grp = new MiscBlockGroupViewModel { Label = BlockDisplay(f.Block) }; + groupByBlock[f.Block] = grp; + Groups.Add(grp); + } + + var key = (f.Block, f.Section); + if (!sectionMap.TryGetValue(key, out var sec)) + { + sec = new MiscSectionViewModel { Label = f.Section }; + sectionMap[key] = sec; + grp.Sections.Add(sec); + } + + var spec = MiscBitSpecRegistry.Find(f.Block, f.Label); + sec.Fields.Add(new MiscFieldViewModel(f, arr, spec)); + } + + // Reselect the previously-open section if it still exists; otherwise fall back + // to the first one (initial load, or the section no longer present). + MiscSectionViewModel? restore = null; + if (prevSection != null) + restore = Groups + .Where(g => prevGroup == null || g.Label == prevGroup) + .SelectMany(g => g.Sections) + .FirstOrDefault(s => s.Label == prevSection); + + var target = restore ?? Groups.SelectMany(g => g.Sections).FirstOrDefault(); + if (target != null) SelectSection(target); + } + + private byte[] BlockArray(MiscBlock b) => b switch + { + MiscBlock.Core => _misc!.Core, + MiscBlock.LaunchFuel => _misc!.LaunchFuel, + MiscBlock.LaunchFuel2 => _misc!.LaunchFuel2, + MiscBlock.AuxOut => _misc!.AuxOut, + MiscBlock.Extended => _misc!.Extended, + _ => Array.Empty(), + }; + + private static string BlockDisplay(MiscBlock b) => b switch + { + MiscBlock.Core => "Core", + MiscBlock.LaunchFuel => "Launch Fuel", + MiscBlock.LaunchFuel2 => "Launch Fuel 2", + MiscBlock.AuxOut => "Aux Out", + MiscBlock.Extended => "Extended", + _ => b.ToString(), + }; + + public void Dispose() { } +} diff --git a/TuneBossPC/ViewModels/OneDimTablesViewModel.MapSupport.cs b/TuneBossPC/ViewModels/OneDimTablesViewModel.MapSupport.cs new file mode 100644 index 0000000..9bcd791 --- /dev/null +++ b/TuneBossPC/ViewModels/OneDimTablesViewModel.MapSupport.cs @@ -0,0 +1,35 @@ +namespace TuneBossPC.ViewModels.Tables; + +/// +/// Map-file support: read any 1D tables that aren't cached yet, so a Full Config save +/// captures all 37 tables even if the user hasn't opened the 1D page this session. +/// +public partial class OneDimTablesViewModel +{ + /// Reads every available 1D table whose model isn't loaded. Best-effort. + public async Task EnsureLoadedAsync() + { + foreach (var entry in Groups.SelectMany(g => g.Entries)) + { + if (entry.Table == null && entry.IsAvailable) + { + try { await ReadEntryAsync(entry); } catch { /* reported by caller */ } + } + } + } + + /// Writes every loaded 1D table to the ECU from its model. Throws on first failure. + public async Task WriteAllLoadedAsync(IProgress? progress = null) + { + int written = 0; + foreach (var e in Groups.SelectMany(g => g.Entries)) + { + if (e.Table == null || !e.IsAvailable) continue; + progress?.Report($"Writing 1D: {e.Label}…"); + var w = await _ble.WriteTable1DAsync(e.Address, e.Table.ToWirePayload()); + if (!w.Success) throw new InvalidOperationException($"{e.Label}: {w.ErrorMessage}"); + written++; + } + return written; + } +} diff --git a/TuneBossPC/ViewModels/OneDimTablesViewModel.cs b/TuneBossPC/ViewModels/OneDimTablesViewModel.cs new file mode 100644 index 0000000..2de8433 --- /dev/null +++ b/TuneBossPC/ViewModels/OneDimTablesViewModel.cs @@ -0,0 +1,789 @@ +using System.Collections.ObjectModel; +using System.Windows; +using System.Windows.Media; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using TuneBoss.Core.BLE; +using TuneBoss.Core.Models; + +namespace TuneBossPC.ViewModels.Tables; + +// ──────────────────────────────────────────────────────────────────────────── +// Nav-tree entry / group (1D-specific, parallel to TableEntry/GroupViewModel). +// Kept separate so the shared 2D nav types stay untouched. +// ──────────────────────────────────────────────────────────────────────────── +public partial class OneDimEntryViewModel : ObservableObject +{ + public int Slot { get; init; } + public string Label { get; init; } = string.Empty; + public OneDimGroup Group { get; init; } + public ushort Address { get; init; } + public byte ReadLength { get; init; } + public bool IsAvailable { get; init; } = true; + + /// Display-only unit labels (default from registry, editable in the UI). + [ObservableProperty] private string _axisUnit = string.Empty; + [ObservableProperty] private string _valueUnit = string.Empty; + + [ObservableProperty] private bool _isSelected; + [ObservableProperty] private bool _isLoaded; + [ObservableProperty] private bool _isLoading; + + /// Loaded model (null until first read). + public OneDimTable? Table { get; set; } +} + +public partial class OneDimGroupViewModel : ObservableObject +{ + public string Label { get; init; } = string.Empty; + [ObservableProperty] private bool _isExpanded = true; + [ObservableProperty] private bool _isSelected; + public List Entries { get; } = new(); +} + +// ──────────────────────────────────────────────────────────────────────────── +// 1D Tables page view-model +// ──────────────────────────────────────────────────────────────────────────── +public partial class OneDimTablesViewModel : ObservableObject, IDisposable +{ + private const int N = OneDimTable.PointCount; // 8 + + private readonly IBleService _ble; + private readonly TuneBossPC.Services.ISessionService _session; + + private static readonly Brush CellBg = MakeFrozen(0x22, 0x26, 0x2B); + + // ── Nav tree ────────────────────────────────────────────────────────────── + public ObservableCollection Groups { get; } = new(); + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(HasSelectedTable))] + private OneDimEntryViewModel? _selectedEntry; + + public bool HasSelectedTable => SelectedEntry != null; + + // ── Grid (single value row + editable axis breakpoints) ─────────────────── + public ObservableCollection Cells { get; } = new(); + [ObservableProperty] private ObservableCollection _axisHeaders = new(); + + [ObservableProperty] private TuningTableCellViewModel? _selectedCell; + [ObservableProperty] private TuningTableCellViewModel? _editingCell; + [ObservableProperty] private AxisHeaderViewModel? _editingHeader; + + [ObservableProperty] private string _setValueText = string.Empty; + [ObservableProperty] private string _statusMessage = string.Empty; + [ObservableProperty] private string _metaSummary = string.Empty; + [ObservableProperty] private bool _isReading; + [ObservableProperty] private bool _isWriting; + /// Bumped on each confirmed flash — drives the FLASH button's green blink. + [ObservableProperty] private int _flashSuccessCount; + + /// Raised when the curve needs redrawing (after populate or any value/axis edit). + public event Action? CurveInvalidated; + + private readonly DiagnosticsStripViewModel _strip; + + public OneDimTablesViewModel(IBleService ble, TuneBossPC.Services.ISessionService session, + DiagnosticsStripViewModel strip) + { + _ble = ble; + _session = session; + _strip = strip; + _session.SessionChanged += () => OnPropertyChanged(nameof(CanComms)); + + for (int c = 0; c < N; c++) + Cells.Add(new TuningTableCellViewModel { Row = 0, Col = c }); + + RebuildNavTree(); + } + + /// + /// When true, the Y (value) column is shown raw × value-multiplier; when false + /// (default) the raw stored values are shown as-is. Independent of the X toggle. + /// + [ObservableProperty] private bool _showYMultiplied; + + /// + /// When true, the X (axis/breakpoint) row is shown raw × raw-multiplier; when + /// false (default) the raw stored breakpoints are shown as-is. Independent of Y. + /// + [ObservableProperty] private bool _showXMultiplied; + + partial void OnShowYMultipliedChanged(bool value) + { + if (SelectedEntry?.Table != null) PopulateGrid(SelectedEntry.Table); + CurveInvalidated?.Invoke(); + } + + partial void OnShowXMultipliedChanged(bool value) + { + if (SelectedEntry?.Table != null) PopulateGrid(SelectedEntry.Table); + CurveInvalidated?.Invoke(); + } + + /// Effective value multiplier honouring the Y toggle (1 = unscaled). + private int DisplayConvMult => ShowYMultiplied ? EffConvMult : 1; + + /// Value multiplier the curve axis labels should use (honours the Y toggle). + public int DisplayCurveMult => DisplayConvMult; + + /// X-axis (breakpoint) multiplier — honours the independent X toggle + /// (1 = unscaled when unchecked). + public int AxisDisplayMult => ShowXMultiplied ? EffRawMult : 1; + + // ── Metadata bytes [16..23] of the selected 1D table (read-only display) ────── + // Shown to the right of the curve as a label/value pair list. + /// + /// One row in the metadata panel. Read-only display by default; when the panel is + /// unlocked (5 clicks on the header) the numeric rows expose an editable text box + /// whose committed value writes straight back to the OneDimTable model, so the + /// existing 1D WRITE (which serialises via ToWirePayload) sends the new metadata. + /// + public sealed partial class MetaRow : ObservableObject + { + private readonly System.Func? _read; + private readonly System.Action? _apply; + + public string Label { get; } + public bool IsEditable => _apply != null; + + [ObservableProperty] private string _value = string.Empty; + [ObservableProperty] private string _editText = string.Empty; + + // Display-only row (e.g. Address). + public MetaRow(string label, string value) + { + Label = label; + Value = value; + } + + // Editable row: read() gives the display value, apply(text) parses + writes the model. + public MetaRow(string label, System.Func read, System.Action apply) + { + Label = label; + _read = read; + _apply = apply; + Value = read(); + EditText = Value; + } + + /// Parse the edit box and push into the model; refresh display. Returns + /// false (and reverts the box) if the text isn't a valid byte value. + public bool Commit() + { + if (_apply == null || _read == null) return true; + try { _apply(EditText.Trim()); } + catch { EditText = Value; return false; } + Value = _read(); + EditText = Value; + return true; + } + + public void Revert() + { + if (_read != null) { Value = _read(); EditText = Value; } + } + } + + /// True once the hidden 5-click gesture on the metadata header unlocks editing. + [ObservableProperty] private bool _metadataUnlocked; + + private int _metaClickCount; + private System.DateTime _lastMetaClickUtc; + + /// + /// Hidden gesture: five clicks on the metadata header (within ~2s of each other) + /// unlocks the metadata fields for editing. A sixth click re-locks them. + /// + public void RegisterMetadataHeaderClick() + { + var now = System.DateTime.UtcNow; + if ((now - _lastMetaClickUtc).TotalSeconds > 2) _metaClickCount = 0; + _lastMetaClickUtc = now; + _metaClickCount++; + + if (_metaClickCount >= 5) + { + _metaClickCount = 0; + MetadataUnlocked = !MetadataUnlocked; + StatusMessage = MetadataUnlocked + ? "Metadata editing UNLOCKED — values will be written on WRITE." + : "Metadata editing locked."; + if (!MetadataUnlocked) OnPropertyChanged(nameof(MetaRows)); // discard uncommitted edits + } + } + + public IReadOnlyList MetaRows + { + get + { + var t = SelectedEntry?.Table; + if (t == null) return System.Array.Empty(); + + // Editable numeric row: parse as int, range-check to a byte/sbyte, assign. + MetaRow ByteRow(string label, System.Func get, System.Action set, + int lo, int hi) => + new(label, () => get().ToString(), text => + { + if (!int.TryParse(text, out int v) || v < lo || v > hi) + throw new System.FormatException(); + set(v); + }); + + return new MetaRow[] + { + new("Address", "0x" + SelectedEntry!.Address.ToString("X4")), + ByteRow("Max Raw", () => t.MaxRaw, v => t.MaxRaw = v, -128, 255), + ByteRow("Min Raw", () => t.MinRaw, v => t.MinRaw = v, -128, 255), + ByteRow("Raw Signed", () => t.RawSignedFlag, v => t.RawSignedFlag = (byte)v, 0, 255), + ByteRow("Conv Signed", () => t.ConvSignedFlag, v => t.ConvSignedFlag = (byte)v, 0, 255), + ByteRow("Raw Mult", () => t.RawMultiplier, v => t.RawMultiplier = (byte)v, 0, 255), + ByteRow("Conv Mult", () => t.ConvMultiplier, v => t.ConvMultiplier = (byte)v, 0, 255), + ByteRow("Raw Round", () => t.RawRounding, v => t.RawRounding = (byte)v, 0, 255), + ByteRow("Conv Offset", () => (int)t.ConvOffset, v => t.ConvOffset = (sbyte)v, -128, 127), + }; + } + } + + /// + /// Diagnostics stops at the protocol level on every write and nothing restarts it; + /// resume the live stream if the strip says it should be running. + /// + private async Task ResumeDiagnosticsIfLiveAsync() + { + try { if (_strip.IsRunning) await _ble.StartDiagnosticsAsync(); } + catch { /* best-effort */ } + } + + // ── Nav tree ────────────────────────────────────────────────────────────── + + /// True when hardware comms are allowed — a live session. Offline is view-only. + public bool CanComms => _session.IsActive; + + /// Rebuilds the nav tree from the current session layout. Call after connect. + public void RebuildNavTree() + { + OnPropertyChanged(nameof(CanComms)); + Groups.Clear(); + if (!_session.HasLayout || _session.Layout is null) return; + + var layout = _session.Layout; + + var entries = new List(); + foreach (var def in OneDimTableRegistry.All) + { + int idx = def.Slot - 1; + if (idx < 0 || idx >= layout.OneDimTables.Length) continue; + + var region = layout.OneDimTables[idx]; + if (!region.IsAvailable) continue; // FW / generation gated out + + entries.Add(new OneDimEntryViewModel + { + Slot = def.Slot, + Label = def.Label, + Group = def.Group, + Address = region.Address, + ReadLength = region.Length, + IsAvailable = true, + AxisUnit = def.AxisUnit, + ValueUnit = def.ValueUnit, + }); + } + + foreach (var g in OneDimTableRegistry.GroupOrder) + { + var groupEntries = entries.Where(e => e.Group == g).ToList(); + if (groupEntries.Count == 0) continue; + + var gvm = new OneDimGroupViewModel { Label = OneDimTableRegistry.DisplayName(g) }; + gvm.Entries.AddRange(groupEntries); + Groups.Add(gvm); + } + + // Two-panel nav: default to the first category + SelectGroup(Groups.FirstOrDefault()); + } + + // ── Category (main group) selection — drives the child entry panel ───────── + + [ObservableProperty] private OneDimGroupViewModel? _selectedGroup; + + [RelayCommand] + public void SelectGroup(OneDimGroupViewModel? group) + { + foreach (var g in Groups) g.IsSelected = false; + SelectedGroup = group; + if (group != null) group.IsSelected = true; + } + + // ── Nav selection ───────────────────────────────────────────────────────── + + [RelayCommand] + public void SelectEntry(OneDimEntryViewModel entry) + { + // Keep the category panel in sync when selection comes from code + // (e.g. first-loaded entry after connect). + var owner = Groups.FirstOrDefault(g => g.Entries.Contains(entry)); + if (owner != null && owner != SelectedGroup) SelectGroup(owner); + + // Preserve unwritten edits: harvest the OUTGOING table's on-screen values into + // its model before navigating away, so returning shows edits not the read data. + if (SelectedEntry is { IsLoaded: true, Table: not null } prev && prev != entry) + HarvestToModel(prev); + + if (SelectedEntry != null) SelectedEntry.IsSelected = false; + ClearSelection(); + + SelectedEntry = entry; + entry.IsSelected = true; + + if (entry.IsLoaded && entry.Table != null) + PopulateGrid(entry.Table); + else + { + ClearGrid(); + OnPropertyChanged(nameof(MetaRows)); + StatusMessage = "Click READ to load this table."; + } + } + + // ── Read / Write / Flash ────────────────────────────────────────────────── + + [RelayCommand] + public async Task ReadAsync() + { + var entry = SelectedEntry; + if (entry == null) return; + + IsReading = true; + StatusMessage = "Reading…"; + try + { + if (await ReadEntryAsync(entry) && entry.Table != null) + { + PopulateGrid(entry.Table); + StatusMessage = "Read OK"; + } + } + catch (Exception ex) { StatusMessage = $"Error: {ex.Message}"; } + finally { IsReading = false; await ResumeDiagnosticsIfLiveAsync(); } + } + + /// Reads all available 1D tables so they're cached for instant viewing. Mirrors the 2D init. + public async Task InitializeAllAsync(IProgress? progress = null) + { + IsReading = true; + var all = Groups.SelectMany(g => g.Entries).ToList(); + + int done = 0; + foreach (var e in all) + { + progress?.Report($"Loading {e.Label}… ({++done}/{all.Count})"); + try { await ReadEntryAsync(e); } + catch { /* keep loading the rest */ } + } + IsReading = false; + + var first = all.FirstOrDefault(e => e.IsLoaded); + if (first != null) + Application.Current.Dispatcher.Invoke(() => SelectEntry(first)); + } + + private async Task ReadEntryAsync(OneDimEntryViewModel entry) + { + if (!entry.IsAvailable) return false; + + entry.IsLoading = true; + try + { + var r = await _ble.ReadTable1DAsync(entry.Address, entry.ReadLength); + if (!r.Success) { StatusMessage = $"Read failed: {r.ErrorMessage}"; return false; } + if (r.Payload.Length < 4 + OneDimTable.WireLength) + { StatusMessage = "Read returned a short payload."; return false; } + + entry.Table = OneDimTable.FromWire(r.Payload, 4); // skip 51 43 17 00 + entry.IsLoaded = true; + return true; + } + finally { entry.IsLoading = false; } + } + + [RelayCommand] + public async Task WriteAsync() + { + var entry = SelectedEntry; + if (entry?.Table == null || !entry.IsLoaded) return; + + IsWriting = true; + StatusMessage = "Writing…"; + try + { + HarvestToModel(entry); + var w = await _ble.WriteTable1DAsync(entry.Address, entry.Table.ToWirePayload()); + StatusMessage = w.Success + ? "Write OK — click Flash to make permanent" + : $"Write failed: {w.ErrorMessage}"; + } + catch (Exception ex) { StatusMessage = $"Error: {ex.Message}"; } + finally { IsWriting = false; await ResumeDiagnosticsIfLiveAsync(); } + } + + [RelayCommand] + private async Task FlashAsync() + { + IsWriting = true; + StatusMessage = "Flashing to ECU…"; + try + { + var fr = await _ble.FlashWriteAsync(); + if (fr.Success) FlashSuccessCount++; + StatusMessage = fr.Success + ? "Flash OK — settings saved to ECU" + : $"Flash failed: {fr.ErrorMessage}"; + } + catch (Exception ex) { StatusMessage = $"Error: {ex.Message}"; } + finally { IsWriting = false; } + } + + // ── Bulk adjust / set ───────────────────────────────────────────────────── + + // Effective display multipliers (0/1 => unscaled). Display = raw × mult. + private int EffRawMult => Math.Max(1, (int)(SelectedEntry?.Table?.RawMultiplier ?? 1)); + private int EffConvMult => Math.Max(1, (int)(SelectedEntry?.Table?.ConvMultiplier ?? 1)); + + [RelayCommand] public void AdjustPlus1() => AdjustSelected(+1); + [RelayCommand] public void AdjustMinus1() => AdjustSelected(-1); + + [RelayCommand] + private void ApplySetValue() + { + if (double.TryParse(SetValueText, out double disp)) ApplyDisplayToSelection(disp); + } + + /// Bulk nudge by whole RAW units (one press = ±1 raw = ±multiplier on the display). + private void AdjustSelected(int rawDelta) + { + if (SelectedEntry?.Table == null) return; + foreach (var c in BulkTargets()) SetCellValue(c, c.RawValue + rawDelta); + CurveInvalidated?.Invoke(); + } + + /// Set the selection from a DISPLAYED (scaled) value. Rejects non-multiples of the value multiplier. + public void ApplyDisplayToSelection(double display) + { + if (SelectedEntry?.Table == null) return; + + int mult = DisplayConvMult; + double q = display / mult; + if (Math.Abs(q - Math.Round(q)) > 1e-6) + { + StatusMessage = mult == 1 + ? "Value must be a whole number" + : $"Value must be a multiple of {mult}"; + return; + } + + double raw = Math.Round(q); + foreach (var c in BulkTargets()) SetCellValue(c, raw); + CurveInvalidated?.Invoke(); + } + + /// Stores the RAW value on the cell and shows raw × multiplier. + private void SetCellValue(TuningTableCellViewModel cell, double raw) + { + double cv = ClampConv(raw); + cell.RawValue = cv; + cell.DisplayValue = ((long)Math.Round(cv * DisplayConvMult)).ToString(); + } + + private double ClampConv(double v) + { + var t = SelectedEntry?.Table; + double r = Math.Round(v); + if (t == null) return r; + return t.IsConvSigned ? Math.Clamp(r, -128, 127) : Math.Clamp(r, 0, 255); + } + + // ── Selection (single row → contiguous column span) ─────────────────────── + + private IEnumerable SelectedCells => Cells.Where(c => c.IsSelected); + + public void BeginSelection(TuningTableCellViewModel cell) + { + CommitEdit(); + foreach (var c in Cells) c.IsSelected = false; + SelectedCell = cell; + cell.IsSelected = true; + UpdateSelectionBorders(); + CurveInvalidated?.Invoke(); // recolour the active curve point + } + + public void ExtendSelection(TuningTableCellViewModel target) + { + if (SelectedCell == null) { BeginSelection(target); return; } + int c0 = Math.Min(SelectedCell.Col, target.Col); + int c1 = Math.Max(SelectedCell.Col, target.Col); + foreach (var c in Cells) c.IsSelected = c.Col >= c0 && c.Col <= c1; + UpdateSelectionBorders(); + CurveInvalidated?.Invoke(); + } + + private void UpdateSelectionBorders() + { + const double bw = 2.5; + var cols = new HashSet(SelectedCells.Select(c => c.Col)); + foreach (var c in Cells) + { + if (!c.IsSelected) { c.SelectionBorder = new Thickness(0); continue; } + double l = cols.Contains(c.Col - 1) ? 0 : bw; + double r = cols.Contains(c.Col + 1) ? 0 : bw; + c.SelectionBorder = new Thickness(l, bw, r, bw); + } + } + + private void ClearSelection() + { + CancelEdit(); + foreach (var c in Cells) c.IsSelected = false; + SelectedCell = null; + UpdateSelectionBorders(); + } + + private List BulkTargets() + { + var t = SelectedCells.ToList(); + if (t.Count == 0 && SelectedCell != null) t.Add(SelectedCell); + return t; + } + + // ── In-cell editing ─────────────────────────────────────────────────────── + + public void BeginEdit(string? seed = null) + { + if (SelectedCell == null || SelectedEntry?.Table == null) return; + CancelEdit(); + EditingCell = SelectedCell; + SelectedCell.EditText = seed ?? SelectedCell.DisplayValue; + SelectedCell.IsEditing = true; + } + + public void CommitEdit() + { + var cell = EditingCell; + if (cell == null) return; + cell.IsEditing = false; + EditingCell = null; + if (double.TryParse(cell.EditText, out double v)) ApplyDisplayToSelection(v); + } + + public void CancelEdit() + { + if (EditingCell == null) return; + EditingCell.IsEditing = false; + EditingCell = null; + } + + // ── Copy / paste (horizontal) ───────────────────────────────────────────── + + private double[]? _clipboard; + + [RelayCommand] + private void CopySelection() + { + var cells = SelectedCells.OrderBy(c => c.Col).ToList(); + if (cells.Count == 0) return; + _clipboard = cells.Select(c => c.RawValue).ToArray(); + StatusMessage = $"Copied {_clipboard.Length} cells"; + } + + [RelayCommand] + private void PasteToSelection() + { + if (_clipboard == null || SelectedEntry?.Table == null || SelectedCell == null) return; + + int baseC = SelectedCell.Col; + var pasted = new List(); + for (int i = 0; i < _clipboard.Length; i++) + { + int cc = baseC + i; + if (cc >= N) break; // clamp to last column + SetCellValue(Cells[cc], _clipboard[i]); + pasted.Add(Cells[cc]); + } + + foreach (var c in Cells) c.IsSelected = false; + foreach (var c in pasted) c.IsSelected = true; + UpdateSelectionBorders(); + CurveInvalidated?.Invoke(); + StatusMessage = $"Pasted {pasted.Count} cells"; + } + + // ── Axis breakpoint editing ─────────────────────────────────────────────── + + public void BeginAxisEdit(AxisHeaderViewModel h) + { + CommitEdit(); + foreach (var x in AxisHeaders) x.IsEditing = false; + h.EditText = h.DisplayValue; + h.IsEditing = true; + EditingHeader = h; + } + + public void CommitAxisEdit(AxisHeaderViewModel h) + { + if (!h.IsEditing) return; + h.IsEditing = false; + if (ReferenceEquals(EditingHeader, h)) EditingHeader = null; + + var t = SelectedEntry?.Table; + if (t == null) return; + if (!double.TryParse(h.EditText, out double entered)) return; // revert silently + + // Match whatever the axis is currently displaying: scaled when the ×scale + // toggle is on, unscaled (raw) when off — so the user types what they see. + int mult = ShowXMultiplied ? EffRawMult : 1; + double q = entered / mult; + if (Math.Abs(q - Math.Round(q)) > 1e-6) + { + StatusMessage = mult == 1 + ? "Axis must be a whole number" + : $"Axis must be a multiple of {mult}"; + return; // reject, display reverts + } + + // Bound only to what a raw axis byte can physically store. The table's + // MinRaw/MaxRaw bytes are display metadata and are frequently 0/0, which + // previously clamped every entry to 0 and then failed the sequence check. + // The strict-between-neighbours check below is the real ordering constraint. + int lo = t.IsRawSigned ? -128 : 0; + int hi = t.IsRawSigned ? 127 : 255; + int raw = Math.Clamp((int)Math.Round(q), lo, hi); + + var vals = AxisHeaders.Select(x => x.Value).ToList(); + if (!IsInSequence(vals, h.Index, raw)) + { + StatusMessage = SequenceMessage(vals, h.Index, mult); + return; // out of sequence → reject, display reverts + } + + h.Value = raw; + h.DisplayValue = ((long)raw * mult).ToString(); + StatusMessage = $"Axis[{h.Index}] = {(long)raw * mult}{UnitSuffix(SelectedEntry?.AxisUnit)}"; + CurveInvalidated?.Invoke(); + } + + public void CancelAxisEdit(AxisHeaderViewModel h) + { + h.IsEditing = false; + if (ReferenceEquals(EditingHeader, h)) EditingHeader = null; + } + + /// Strict monotonic check against immediate neighbours (direction auto-detected). + private static bool IsInSequence(IReadOnlyList vals, int index, int newVal) + { + bool ascending = vals.Count < 2 || vals[^1] >= vals[0]; + int? lo = index > 0 ? vals[index - 1] : (int?)null; + int? hi = index < vals.Count - 1 ? vals[index + 1] : (int?)null; + + return ascending + ? (lo is null || newVal > lo) && (hi is null || newVal < hi) + : (lo is null || newVal < lo) && (hi is null || newVal > hi); + } + + private static string SequenceMessage(IReadOnlyList vals, int index, int mult) + { + bool ascending = vals.Count < 2 || vals[^1] >= vals[0]; + int? lo = index > 0 ? vals[index - 1] : (int?)null; + int? hi = index < vals.Count - 1 ? vals[index + 1] : (int?)null; + long? lower = (ascending ? lo : hi) is int a ? (long)a * mult : (long?)null; + long? upper = (ascending ? hi : lo) is int b ? (long)b * mult : (long?)null; + + if (lower is not null && upper is not null) return $"Axis must be between {lower} and {upper}"; + if (lower is not null) return $"Axis must be greater than {lower}"; + if (upper is not null) return $"Axis must be less than {upper}"; + return "Axis out of sequence"; + } + + private static string UnitSuffix(string? u) => string.IsNullOrWhiteSpace(u) ? "" : " " + u; + + // ── Grid population ─────────────────────────────────────────────────────── + + private void PopulateGrid(OneDimTable t) + { + int rawMult = Math.Max(1, (int)t.RawMultiplier); + int convMult = Math.Max(1, (int)t.ConvMultiplier); + + AxisHeaders.Clear(); + for (int i = 0; i < N; i++) + AxisHeaders.Add(new AxisHeaderViewModel + { + Index = i, + Kind = AxisKind.Rpm, // tag only; 1D edit logic is local + Value = t.RawAxis[i], + DisplayValue = ((long)t.RawAxis[i] * (ShowXMultiplied ? rawMult : 1)).ToString(), + }); + + for (int c = 0; c < N; c++) + { + var cell = Cells[c]; + cell.RawValue = t.ConvValues[c]; + cell.DisplayValue = ((long)t.ConvValues[c] * (ShowYMultiplied ? convMult : 1)).ToString(); + cell.Background = CellBg; + cell.Foreground = Brushes.White; + cell.IsSelected = false; + cell.SelectionBorder = new Thickness(0); + } + + MetaSummary = BuildMeta(t); + OnPropertyChanged(nameof(MetaRows)); + CurveInvalidated?.Invoke(); + } + + private void ClearGrid() + { + AxisHeaders.Clear(); + foreach (var c in Cells) + { + c.RawValue = 0; + c.DisplayValue = string.Empty; + c.IsSelected = false; + c.SelectionBorder = new Thickness(0); + } + MetaSummary = string.Empty; + CurveInvalidated?.Invoke(); + } + + private void HarvestToModel(OneDimEntryViewModel entry) + { + var t = entry.Table; + if (t == null) return; + + for (int c = 0; c < N; c++) + t.ConvValues[c] = (int)Math.Round(Cells[c].RawValue); + + for (int i = 0; i < N && i < AxisHeaders.Count; i++) + t.RawAxis[i] = AxisHeaders[i].Value; + + // Metadata bytes (sign / min / max / multipliers / rounding / offset) are + // left untouched and round-trip verbatim via OneDimTable.ToWirePayload(). + } + + private static string BuildMeta(OneDimTable t) + { + int rm = Math.Max(1, (int)t.RawMultiplier), cm = Math.Max(1, (int)t.ConvMultiplier); + string axisRange = $"[{(long)t.MinRaw * rm}\u2026{(long)t.MaxRaw * rm}]"; + return $"axis {(t.IsRawSigned ? "signed" : "unsigned")} {axisRange} \u00D7{rm} " + + $"value {(t.IsConvSigned ? "signed" : "unsigned")} \u00D7{cm} offset {t.ConvOffset} " + + $"(display = raw \u00D7 multiplier)"; + } + + private static Brush MakeFrozen(byte r, byte g, byte b) + { + var br = new SolidColorBrush(Color.FromRgb(r, g, b)); + br.Freeze(); + return br; + } + + public void Dispose() { } +} diff --git a/TuneBossPC/ViewModels/RpmSettingsViewModel.cs b/TuneBossPC/ViewModels/RpmSettingsViewModel.cs new file mode 100644 index 0000000..5a73bc0 --- /dev/null +++ b/TuneBossPC/ViewModels/RpmSettingsViewModel.cs @@ -0,0 +1,256 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using TuneBoss.Core.BLE; +using TuneBoss.Core.Models; +using TuneBossPC.Services; + +namespace TuneBossPC.ViewModels; + +/// +/// One adjustable RPM setting (RPM Limit / Shift Light / VVA Trigger). Values are shown +/// to the user in RPM; the ECU stores each as a single byte = RPM ÷ 100. +/// +public sealed partial class RpmSettingItem : ObservableObject +{ + public const int Step = 100; // one raw unit = 100 RPM + public const int MinRpm = 5000; // legacy − buttons floor at 50 × 100 + public const int ByteMaxRpm = 25500; // 255 × 100 — a single byte cannot hold more + + private readonly System.Func _setAsync; + + public string Title { get; } + public bool HasMaximum { get; } // whether the "Maximum" row is shown (VVA hides it) + + /// Raw units subtracted for the paired recovery/off byte written alongside the + /// value (legacy: RPM Limit −1, Shift Light −2, VVA −5 → 100/200/500 RPM hysteresis). + public int RecoveryDelta { get; } + + /// False when this setting isn't present on the connected unit (e.g. VVA on a non-VVA ECU). + [ObservableProperty] private bool _isAvailable = true; + + [NotifyPropertyChangedFor(nameof(Ceiling))] + [ObservableProperty] private int _maxRpm; // 0 when HasMaximum == false + + [ObservableProperty] private int _currentRpm; + [ObservableProperty] private int _newRpm; + + public RpmSettingItem(string title, bool hasMaximum, int recoveryDelta, + System.Func setAsync) + { + Title = title; + HasMaximum = hasMaximum; + RecoveryDelta = recoveryDelta; + _setAsync = setAsync; + } + + /// Upper bound for the New value — the licensed RPM cap (all three cap at it; + /// VVA just doesn't display the Maximum row), else the byte ceiling. + public int Ceiling => MaxRpm > 0 ? System.Math.Min(MaxRpm, ByteMaxRpm) : ByteMaxRpm; + + /// Apply a freshly-read current value and reset the pending New value to match. + public void SetCurrent(int rpm) + { + CurrentRpm = rpm; + NewRpm = rpm; + } + + [RelayCommand] private void Increment() => NewRpm = System.Math.Min(Ceiling, NewRpm + Step); + [RelayCommand] private void Decrement() => NewRpm = System.Math.Max(MinRpm, NewRpm - Step); + [RelayCommand] private System.Threading.Tasks.Task Set() => _setAsync(this); +} + +/// +/// RPM Settings page — read/adjust/write the RPM Limit, Shift Light and VVA RPM Trigger. +/// Ported from the legacy WinForms "RPM Settings" tab (three Max/Current/New groups). +/// +/// Each value is a single misc-Core / misc-Extended byte (RPM ÷ 100), written with a +/// targeted 1-byte write so nothing else in the block is touched (same approach as the +/// killswitch). "Set" writes to RAM (takes effect immediately); FLASH persists to flash. +/// +public sealed partial class RpmSettingsViewModel : ObservableObject +{ + private readonly IBleService _ble; + private readonly ISessionService _session; + private readonly DiagnosticsStripViewModel _strip; + + // ── Byte offsets within their misc block (from MiscFieldRegistry / legacy layout). + // Change here if a firmware revision moves them. + // NOTE: legacy shiftRpmLimitAddr was Core[108]; the current Gen3 registry places + // ShiftLight_On_RPM at Core[109] — verify the read-back on hardware. + private const int RpmLimitCoreOffset = 12; // Core[12] RPM_Limit_div100 + private const int ShiftLightCoreOffset = 109; // Core[109] ShiftLight_On_RPM_div100 + private const int VvaExtendedOffset = 124; // Extended[124] VVA_On_RPM_div100 + + public RpmSettingItem RpmLimit { get; } + public RpmSettingItem ShiftLight { get; } + public RpmSettingItem Vva { get; } + + [ObservableProperty] private string _statusMessage = "Press READ to load current values."; + [ObservableProperty] private bool _isBusy; + [ObservableProperty] private int _flashSuccessCount; + + public bool CanComms => _session.IsActive; + + public RpmSettingsViewModel(IBleService ble, ISessionService session, DiagnosticsStripViewModel strip) + { + _ble = ble; + _session = session; + _strip = strip; + + // recoveryDelta = raw units for the paired recovery/off byte (matches legacy). + RpmLimit = new RpmSettingItem("RPM Limit", hasMaximum: true, recoveryDelta: 1, WriteItemAsync); + ShiftLight = new RpmSettingItem("Shift Light RPM", hasMaximum: true, recoveryDelta: 2, WriteItemAsync); + Vva = new RpmSettingItem("VVA RPM Trigger", hasMaximum: false, recoveryDelta: 5, WriteItemAsync); + } + + // ── Address resolvers ─────────────────────────────────────────────────────── + private ushort? RpmLimitAddr => Addr(_session.Layout?.MiscCore, RpmLimitCoreOffset); + private ushort? ShiftLightAddr => Addr(_session.Layout?.MiscCore, ShiftLightCoreOffset); + private ushort? VvaAddr => Addr(_session.Layout?.MiscExtended, VvaExtendedOffset); + + private static ushort? Addr(MemoryRegion? region, int offset) + => region is { IsAvailable: true } r && r.Length > offset + ? (ushort)(r.Address + offset) + : (ushort?)null; + + // ── Read ───────────────────────────────────────────────────────────────────── + [RelayCommand] + private async System.Threading.Tasks.Task ReadAllAsync() + { + OnPropertyChanged(nameof(CanComms)); + if (IsBusy) return; + if (!_session.IsActive || _session.Layout is null) + { + StatusMessage = "Connect to a device first."; + return; + } + + IsBusy = true; + try + { + // All three cap at the licensed RPM max (legacy + buttons cap here, VVA too). + int maxRpm = (_session.Info?.UpgradeRpmMax ?? 0) * 100; + RpmLimit.MaxRpm = maxRpm; + ShiftLight.MaxRpm = maxRpm; + Vva.MaxRpm = maxRpm; + + await ReadOneAsync(RpmLimit, RpmLimitAddr); + await ReadOneAsync(ShiftLight, ShiftLightAddr); + + // VVA is gated by the bike model (legacy checkVvaModels / vvaModels.xml), + // and the extended byte must be reachable on this layout. + bool isVvaModel = VvaModelRegistry.IsVvaModel( + _session.Info?.BikeManufacturer ?? 0, _session.Info?.BikeModel ?? 0); + Vva.IsAvailable = isVvaModel && VvaAddr.HasValue; + if (Vva.IsAvailable) await ReadOneAsync(Vva, VvaAddr); + + StatusMessage = "Current values loaded."; + } + catch (System.Exception ex) { StatusMessage = $"Read error: {ex.Message}"; } + finally { IsBusy = false; await ResumeDiagAsync(); } + } + + /// + /// Targeted read of one setting. Misc read responses are [0x51][3-byte header][data…], + /// so the value sits at Payload[4] (same offset MiscValues.FromPayloads slices from). + /// Reads 2 bytes like the proven killswitch read and uses only the first. + /// + private async System.Threading.Tasks.Task ReadOneAsync(RpmSettingItem item, ushort? addr) + { + if (addr is null) { item.IsAvailable = false; return; } + + var r = await _ble.ReadMiscAsync(addr.Value, 2); + if (!r.Success || r.Payload is null || r.Payload.Length < 6) + { + StatusMessage = $"{item.Title}: read failed ({r.ErrorMessage})."; + return; + } + + item.IsAvailable = true; + item.SetCurrent(r.Payload[4] * 100); + } + + // ── Write ──────────────────────────────────────────────────────────────────── + private async System.Threading.Tasks.Task WriteItemAsync(RpmSettingItem item) + { + OnPropertyChanged(nameof(CanComms)); + if (IsBusy) return; + if (!_session.IsActive) + { + StatusMessage = "Connect to a device first."; + return; + } + + if (item == Vva && !Vva.IsAvailable) + { + StatusMessage = "This model does not have VVA."; + return; + } + + ushort? addr = item == RpmLimit ? RpmLimitAddr + : item == ShiftLight ? ShiftLightAddr + : item == Vva ? VvaAddr + : null; + if (addr is null) + { + StatusMessage = $"{item.Title}: not available on this unit."; + return; + } + + // Round to a whole 100-RPM step and clamp to [floor, licensed cap]. + int rpm = System.Math.Clamp( + (int)System.Math.Round(item.NewRpm / 100.0) * 100, + RpmSettingItem.MinRpm, item.Ceiling); + byte raw = (byte)(rpm / 100); + // Paired recovery/off byte written to value+1 (legacy hysteresis: −1/−2/−5 raw). + byte recovery = (byte)System.Math.Max(0, raw - item.RecoveryDelta); + + IsBusy = true; + try + { + // Targeted 2-byte write: [value, recovery/off] — leaves the surrounding + // bytes (failsafe / output-select) untouched, matching the legacy result. + var w = await _ble.WriteMiscAsync(addr.Value, new byte[] { raw, recovery }); + if (!w.Success) + { + StatusMessage = $"{item.Title}: write failed ({w.ErrorMessage})."; + return; + } + + await ReadOneAsync(item, addr); // read back to confirm what the ECU stored + StatusMessage = $"{item.Title} set to {item.CurrentRpm} RPM. Press FLASH to save permanently."; + } + catch (System.Exception ex) { StatusMessage = $"{item.Title}: {ex.Message}"; } + finally { IsBusy = false; await ResumeDiagAsync(); } + } + + // ── Flash (persist RAM edits) ──────────────────────────────────────────────── + [RelayCommand] + private async System.Threading.Tasks.Task FlashAsync() + { + if (IsBusy) return; + if (!_session.IsActive) + { + StatusMessage = "Connect to a device first."; + return; + } + + IsBusy = true; + try + { + var fr = await _ble.FlashWriteAsync(); + if (fr.Success) { FlashSuccessCount++; StatusMessage = "Saved to ECU flash."; } + else { StatusMessage = $"Flash failed: {fr.ErrorMessage}"; } + } + catch (System.Exception ex) { StatusMessage = $"Flash error: {ex.Message}"; } + finally { IsBusy = false; await ResumeDiagAsync(); } + } + + // Misc read/write pause diagnostics at the BLE layer — resume if the strip is live + // (VM-layer resume only; never restart at the BLE layer — a duplicate MON_START storms). + private async System.Threading.Tasks.Task ResumeDiagAsync() + { + try { if (_strip.IsRunning) await _ble.StartDiagnosticsAsync(); } + catch { /* best-effort */ } + } +} diff --git a/TuneBossPC/ViewModels/SettingsViewModel.cs b/TuneBossPC/ViewModels/SettingsViewModel.cs new file mode 100644 index 0000000..023a75f --- /dev/null +++ b/TuneBossPC/ViewModels/SettingsViewModel.cs @@ -0,0 +1,41 @@ +using System.Windows; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using TuneBossPC.Services; + +namespace TuneBossPC.ViewModels; + +public partial class SettingsViewModel : ObservableObject +{ + private readonly ISettingsService _settingsService; + + public AppSettings Settings => _settingsService.Settings; + + [ObservableProperty] private string _statusMessage = string.Empty; + + public SettingsViewModel(ISettingsService settingsService) + { + _settingsService = settingsService; + } + + [RelayCommand] + private void FactoryReset() + { + var confirm = MessageBox.Show( + "This will reset the ECU to factory settings, erasing all tuning changes.\n\n" + + "Are you sure you want to continue?", + "ECU Factory Reset", + MessageBoxButton.YesNo, + MessageBoxImage.Warning, + MessageBoxResult.No); + + if (confirm != MessageBoxResult.Yes) + { + StatusMessage = "Factory reset cancelled."; + return; + } + + // Protocol command (APP_RESET_SETTINGS 0x65) is scaffolded but not wired yet. + StatusMessage = "Factory reset is not implemented yet — coming in a future update."; + } +} diff --git a/TuneBossPC/ViewModels/StubViewModels.cs b/TuneBossPC/ViewModels/StubViewModels.cs new file mode 100644 index 0000000..416b56b --- /dev/null +++ b/TuneBossPC/ViewModels/StubViewModels.cs @@ -0,0 +1,6 @@ +using CommunityToolkit.Mvvm.ComponentModel; + +namespace TuneBossPC.ViewModels; + +// Stubs for pages not yet implemented + diff --git a/TuneBossPC/ViewModels/Tables/AxisHeaderViewModel.cs b/TuneBossPC/ViewModels/Tables/AxisHeaderViewModel.cs new file mode 100644 index 0000000..2582113 --- /dev/null +++ b/TuneBossPC/ViewModels/Tables/AxisHeaderViewModel.cs @@ -0,0 +1,26 @@ +using CommunityToolkit.Mvvm.ComponentModel; + +namespace TuneBossPC.ViewModels.Tables; + +/// Which axis a header belongs to. +public enum AxisKind { Rpm, Load } + +/// +/// An editable axis breakpoint — one RPM column header (top) or one Load row +/// header (side). Edits are validated for monotonic sequence against neighbours +/// and written back into the table model's RpmAxis / LoadAxis by the view-model. +/// +public partial class AxisHeaderViewModel : ObservableObject +{ + /// Position along the axis (0..23 for RPM, 0..7 for Load). + public int Index { get; init; } + + public AxisKind Kind { get; init; } + + /// Numeric display value (RPM in rpm; Load in raw units). + public int Value { get; set; } + + [ObservableProperty] private string _displayValue = ""; + [ObservableProperty] private bool _isEditing; + [ObservableProperty] private string _editText = ""; +} diff --git a/TuneBossPC/ViewModels/Tables/BoolToExpanderGlyphConverter.cs b/TuneBossPC/ViewModels/Tables/BoolToExpanderGlyphConverter.cs new file mode 100644 index 0000000..4af8b68 --- /dev/null +++ b/TuneBossPC/ViewModels/Tables/BoolToExpanderGlyphConverter.cs @@ -0,0 +1,16 @@ +using System.Globalization; +using System.Windows.Data; + +namespace TuneBossPC.ViewModels.Tables; + +/// Shows ▾ when expanded, ▸ when collapsed. +public class BoolToExpanderGlyphConverter : IValueConverter +{ + public static readonly BoolToExpanderGlyphConverter Instance = new(); + + public object Convert(object value, Type t, object p, CultureInfo c) + => value is true ? "▾" : "▸"; + + public object ConvertBack(object value, Type t, object p, CultureInfo c) + => throw new NotImplementedException(); +} diff --git a/TuneBossPC/ViewModels/Tables/HeatmapHelper.cs b/TuneBossPC/ViewModels/Tables/HeatmapHelper.cs new file mode 100644 index 0000000..3246205 --- /dev/null +++ b/TuneBossPC/ViewModels/Tables/HeatmapHelper.cs @@ -0,0 +1,92 @@ +using System.Windows.Media; + +namespace TuneBossPC.ViewModels.Tables; + +/// +/// Computes heatmap colours for tuning table cells. +/// 7-band gradient: blue → cyan → green → yellow-green → yellow +/// Matches setDataValRange() / updateCellBackgroundColors() in TuningTablePanel.cs. +/// +public static class HeatmapHelper +{ + // Heatmap colour stops (cold → hot) + private static readonly Color[] Stops = + { + Color.FromRgb(0x00, 0x50, 0xB4), // 0/7 — deep blue + Color.FromRgb(0x00, 0x96, 0xC8), // 1/7 — blue-cyan + Color.FromRgb(0x00, 0xC8, 0xC8), // 2/7 — cyan + Color.FromRgb(0x00, 0xC8, 0x64), // 3/7 — cyan-green + Color.FromRgb(0x50, 0xC8, 0x00), // 4/7 — green + Color.FromRgb(0x96, 0xDC, 0x00), // 5/7 — yellow-green + Color.FromRgb(0xDC, 0xDC, 0x00), // 6/7 — yellow + Color.FromRgb(0xFF, 0x80, 0x00), // 7/7 — orange (max) + }; + + /// + /// Gets background and foreground brushes for a cell value. + /// + public static (SolidColorBrush Background, SolidColorBrush Foreground) + GetCellColors(double value, double minVal, double maxVal) + { + var bg = GetBackground(value, minVal, maxVal); + + // Always black — the heatmap's lime/cyan midtones made luminance-picked + // white text illegible; black stays readable across the whole ramp. + var fg = Brushes.Black; + + return (bg, fg); + } + + /// + /// Gets the tracker highlight colour — the exact live position. White so it + /// stands out against any heatmap colour (yellow/orange used to blend in). + /// In flat (no-contour) mode the cells are white, so the tracker goes orange. + /// + public static SolidColorBrush TrackerHighlight + => new(Color.FromRgb(0xFF, 0xFF, 0xFF)); // white + + /// + /// Gets the tracker adjacent colour — the three neighbouring cells. + /// + public static SolidColorBrush TrackerAdjacent + => new(Color.FromRgb(0xD3, 0xD3, 0xD3)); // light grey + + // ── Flat (no-contour) mode ─────────────────────────────────────────────── + /// Flat cell fill when the contour heatmap is turned off — plain white. + public static SolidColorBrush FlatBackground + => new(Color.FromRgb(0xFF, 0xFF, 0xFF)); // white + + /// Tracker exact-position colour in flat mode — orange (white would vanish). + public static SolidColorBrush FlatTrackerHighlight + => new(Color.FromRgb(0xFF, 0x80, 0x00)); // orange + + /// Tracker neighbour colour in flat mode — a PALE yellow. Kept light so + /// the orange active cell clearly stands out from its three neighbours. + public static SolidColorBrush FlatTrackerAdjacent + => new(Color.FromRgb(0xFF, 0xF0, 0xB3)); // pale yellow + + private static SolidColorBrush GetBackground(double value, double minVal, double maxVal) + { + double span = maxVal - minVal; + + // All values same — use mid colour + if (span <= 0) + return new SolidColorBrush(Stops[3]); + + double t = Math.Clamp((value - minVal) / span, 0.0, 1.0); + + // Map t to the 7-segment colour scale + double scaled = t * (Stops.Length - 1); + int lo = (int)Math.Floor(scaled); + int hi = Math.Min(lo + 1, Stops.Length - 1); + double frac = scaled - lo; + + var color = Lerp(Stops[lo], Stops[hi], frac); + return new SolidColorBrush(color); + } + + private static Color Lerp(Color a, Color b, double t) => Color.FromRgb( + (byte)(a.R + (b.R - a.R) * t), + (byte)(a.G + (b.G - a.G) * t), + (byte)(a.B + (b.B - a.B) * t)); +} diff --git a/TuneBossPC/ViewModels/Tables/TableEntryViewModel.cs b/TuneBossPC/ViewModels/Tables/TableEntryViewModel.cs new file mode 100644 index 0000000..1ee1ef2 --- /dev/null +++ b/TuneBossPC/ViewModels/Tables/TableEntryViewModel.cs @@ -0,0 +1,134 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using TuneBoss.Core.Models; + +namespace TuneBossPC.ViewModels.Tables; + +/// +/// Type of table entry in the nav tree. +/// +public enum TableEntryType +{ + TuningTable, // 2D main table (TuningTable model) + AfrTable, // 2D AFR table (AfrTable model) + SubTable, // 4×6 subtable (SubTable model) + Placeholder, // Not yet implemented (e.g. Dual Injector) +} + +/// Icon shown beside a 2D table's big title. +public enum TableIconKind +{ + None, + Fuel, // droplet — fuel tables + Spark, // lightning — spark/ignition tables + Angle, // injection angle + Afr, // AFR target +} + +/// +/// A single entry in the tuning table nav tree. +/// Carries the address, label, type, and loaded data. +/// +public partial class TableEntryViewModel : ObservableObject +{ + public string Label { get; init; } = string.Empty; + /// Nav + title text shown to the user. Falls back to Label. The Label + /// remains the internal key (lookups, User→Base mapping), so only this changes. + public string? DisplayNameRaw { get; init; } + public string DisplayName => string.IsNullOrEmpty(DisplayNameRaw) ? Label : DisplayNameRaw!; + /// Hidden from the nav (still constructed so lookups/writes are unaffected). + public bool IsHidden { get; init; } + /// Which icon to show beside the big table title. + public TableIconKind IconKind { get; init; } = TableIconKind.None; + public TableEntryType EntryType { get; init; } + public ushort Address { get; init; } + public byte ReadLength { get; init; } + public bool IsAvailable { get; init; } = true; + public bool IsUserTable { get; init; } + + /// Optional subtable that lives below this table on the same view. + public TableEntryViewModel? SubTableEntry { get; init; } + + [ObservableProperty] private bool _isSelected; + [ObservableProperty] private bool _isLoaded; + [ObservableProperty] private bool _isLoading; + [ObservableProperty] private bool _isLocked; // Stage-1: user 24×8 table not exposed (read returned 0x56) + + /// False when this entry's stage group is above the connected ECU's stage + /// (read-only view). True offline or when the stage is unlocked. + [ObservableProperty] private bool _isStageUnlocked = true; + + /// True for a standalone Stage-1 subtable entry (renders the 4×6 grid only). + public bool IsStandaloneSub => EntryType == TableEntryType.SubTable; + + // Loaded data — only one will be non-null depending on EntryType + public TuningTable? TuningTable { get; set; } + public AfrTable? AfrTable { get; set; } + public SubTable? SubTable { get; set; } + + public bool IsPlaceholder => EntryType == TableEntryType.Placeholder; + public bool HasSubTable => SubTableEntry != null; + + /// Emoji/symbol glyph shown beside the big table title. + public string IconGlyph => IconKind switch + { + TableIconKind.Fuel => "💧", + TableIconKind.Spark => "⚡", + TableIconKind.Angle => "📐", + TableIconKind.Afr => "🎯", + _ => string.Empty, + }; + + /// + /// A distinct tint for this table's RPM row + Load column headers so switching + /// between tables is visually obvious. Deterministic per table (hash of Label), + /// kept dark and low-saturation so header text stays readable. + /// + public System.Windows.Media.Brush HeaderShade + { + get + { + int h = 0; + foreach (char c in Label) h = h * 31 + c; + double hue = ((h % 360) + 360) % 360; + var col = FromHsv(hue, 0.35, 0.28); + var brush = new System.Windows.Media.SolidColorBrush(col); + brush.Freeze(); + return brush; + } + } + + private static System.Windows.Media.Color FromHsv(double h, double s, double v) + { + double c = v * s; + double x = c * (1 - System.Math.Abs((h / 60.0) % 2 - 1)); + double m = v - c; + double r = 0, g = 0, b = 0; + if (h < 60) { r = c; g = x; } + else if (h < 120) { r = x; g = c; } + else if (h < 180) { g = c; b = x; } + else if (h < 240) { g = x; b = c; } + else if (h < 300) { r = x; b = c; } + else { r = c; b = x; } + return System.Windows.Media.Color.FromRgb( + (byte)((r + m) * 255), (byte)((g + m) * 255), (byte)((b + m) * 255)); + } +} + +/// +/// A group in the nav tree (Base Tables / User Tables). +/// +public partial class TableGroupViewModel : ObservableObject +{ + public string Label { get; init; } = string.Empty; + + /// Minimum ECU stage that unlocks this group (1/2/3). 0 = always on. + public int RequiredStage { get; init; } + + [ObservableProperty] private bool _isExpanded = true; + + /// False when the connected ECU is below . + /// Entries stay selectable/viewable (read-only); comms actions are disabled. + [ObservableProperty] private bool _isStageUnlocked = true; + + public List Entries { get; } = new(); +} diff --git a/TuneBossPC/ViewModels/Tables/TableRowViewModel.cs b/TuneBossPC/ViewModels/Tables/TableRowViewModel.cs new file mode 100644 index 0000000..bf05eca --- /dev/null +++ b/TuneBossPC/ViewModels/Tables/TableRowViewModel.cs @@ -0,0 +1,23 @@ +using System; + +namespace TuneBossPC.ViewModels.Tables; + +/// +/// One row in the tuning table for binding: the editable Load breakpoint header +/// plus the 24 cell view-models. +/// +public sealed class TableRowViewModel +{ + public AxisHeaderViewModel LoadHeader { get; init; } = new(); + public TuningTableCellViewModel[] Cells { get; init; } = Array.Empty(); +} + +/// +/// One row in the subtable. Its load header stays a plain label (subtable axis +/// editing is out of scope for now). +/// +public sealed class SubTableRowViewModel +{ + public string LoadHeader { get; init; } = string.Empty; + public TuningTableCellViewModel[] Cells { get; init; } = Array.Empty(); +} diff --git a/TuneBossPC/ViewModels/Tables/TuningTableCellViewModel.cs b/TuneBossPC/ViewModels/Tables/TuningTableCellViewModel.cs new file mode 100644 index 0000000..5bc923f --- /dev/null +++ b/TuneBossPC/ViewModels/Tables/TuningTableCellViewModel.cs @@ -0,0 +1,25 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using System.Windows; +using System.Windows.Media; + +namespace TuneBossPC.ViewModels.Tables; + +public partial class TuningTableCellViewModel : ObservableObject +{ + public int Row { get; init; } + public int Col { get; init; } + + [ObservableProperty] private string _displayValue = "0"; + [ObservableProperty] private Brush _background = Brushes.Transparent; + [ObservableProperty] private Brush _foreground = Brushes.White; + [ObservableProperty] private bool _isSelected; + [ObservableProperty] private bool _isTrackerHighlight; // exact RPM+Load match + [ObservableProperty] private bool _isTrackerAdjacent; // neighbouring cell + [ObservableProperty] private bool _isVisited; // tracker-history: cell entered while recording + [ObservableProperty] private bool _isEditing; // editor TextBox shown + [ObservableProperty] private string _editText = ""; // transient edit buffer + [ObservableProperty] private Thickness _selectionBorder; // region outline (boundary edges only) + + // Raw value (int for TuningTable, double for AfrTable) + public double RawValue { get; set; } +} diff --git a/TuneBossPC/ViewModels/Tables/TuningTablesViewModel.MapSupport.cs b/TuneBossPC/ViewModels/Tables/TuningTablesViewModel.MapSupport.cs new file mode 100644 index 0000000..ffafb3f --- /dev/null +++ b/TuneBossPC/ViewModels/Tables/TuningTablesViewModel.MapSupport.cs @@ -0,0 +1,257 @@ +using TuneBoss.Core.BLE; +using TuneBoss.Core.Models; +using TuneBoss.Core.Protocol; + +namespace TuneBossPC.ViewModels.Tables; + +/// +/// Map-file support: re-read specific tables on demand (so a save isn't blocked by a +/// table that wasn't cached during the connect-time load, whose failures are swallowed), +/// plus an on-hardware diagnostic for the user-table read path. +/// +public partial class TuningTablesViewModel +{ + /// + /// Ensures the named entries — and their subtables — are read from the device. + /// Best-effort: a failed read leaves the model null, and the caller surfaces a + /// clear "not loaded" error rather than crashing. + /// + public async Task EnsureLoadedAsync(IEnumerable labels) + { + foreach (var label in labels) + { + var entry = Groups.SelectMany(g => g.Entries).FirstOrDefault(e => e.Label == label); + if (entry == null) continue; + + // Standalone Stage-1 subtable entry — read its own 4×6 if not loaded. + if (entry.IsStandaloneSub) + { + if (entry.SubTable == null) + { + try + { + var sr = await _ble.ReadSubTableAsync(entry.Address); + if (sr.Success) { entry.SubTable = SubTable.FromPayload(sr.Payload); entry.IsLoaded = true; } + } + catch { /* reported later */ } + } + continue; + } + + bool needMain = + (entry.EntryType == TableEntryType.TuningTable && entry.TuningTable == null) || + (entry.EntryType == TableEntryType.AfrTable && entry.AfrTable == null); + + if (needMain) + { + // Read, retrying once — a transient failure during the rapid save + // sweep otherwise leaves the table null and Save reports "not loaded". + bool ok = false; + for (int attempt = 0; attempt < 2 && !ok; attempt++) + { + try { ok = await ReadEntryAsync(entry); } + catch { ok = false; } + if (!ok) await System.Threading.Tasks.Task.Delay(60); + } + if (!ok) + throw new InvalidOperationException( + $"Couldn't read \u201C{label}\u201D from the ECU while saving. " + + $"Open its table, press READ until it loads, then save again."); + } + + if (entry.HasSubTable && entry.SubTableEntry?.SubTable == null) + { + try { await ReadSubtableInto(entry); } catch { /* reported later */ } + } + } + } + + /// + /// Reads the first user adjust table from the device with full reporting, to pin + /// down why user tables don't load. Prints the resolved generation (the value that + /// decides the opcode), the entry's address/availability, and the result of a + /// USER-opcode read vs a BASE-opcode read at the same address (the base read is + /// for comparison only and is NOT applied to any model). + /// + public async Task DiagnoseUserReadAsync() + { + var sb = new System.Text.StringBuilder(); + sb.AppendLine("── User-table read diagnostic ──"); + + var info = _sessionService.Info; + if (info is null) { sb.AppendLine("No active session — connect first."); return sb.ToString(); } + + GenerationType gen; + try { gen = GenerationConfig.ResolveGeneration(info.AppInfoVersion); } + catch (Exception ex) { sb.AppendLine($"Generation resolve FAILED: {ex.Message}"); return sb.ToString(); } + + byte expUserOp = gen == GenerationType.Gen3 ? (byte)0x45 + : gen == GenerationType.Gen2 ? (byte)0x41 + : (byte)0x00; + + sb.AppendLine($"AppInfoVersion = {info.AppInfoVersion} -> {gen}"); + sb.AppendLine($"Variant = {_sessionService.Variant}"); + sb.AppendLine($"FW / HW = {info.FwVersion} / {info.HwVersion}"); + sb.AppendLine($"Expected user opcode for {gen} = 0x{expUserOp:X2} (Gen3=0x45, Gen2=0x41)"); + if (gen != GenerationType.Gen3) + sb.AppendLine("WARN: NOT Gen3 — user reads will use the BASE opcode at the wrong address. " + + "If this bike is a basic ECU it should resolve to Gen3 (AppInfoVersion 2)."); + sb.AppendLine(); + + var entry = Groups.SelectMany(g => g.Entries).FirstOrDefault(e => e.Label == "User Fuel Pulse Width 1"); + if (entry is null) { sb.AppendLine("Entry 'User Fuel Pulse Width 1' not found."); return sb.ToString(); } + + sb.AppendLine($"Entry: addr=0x{entry.Address:X4} len={entry.ReadLength} " + + $"available={entry.IsAvailable} isUser={entry.IsUserTable}"); + if (!entry.IsAvailable) + sb.AppendLine("WARN: Entry NOT available — layout has no address for this generation."); + sb.AppendLine(); + + const byte p1 = TuneBoss.Core.Models.TuningTable.SplitFirstLength; // 127 + + var ru = await _ble.ReadTable2DAsync(entry.Address, p1, userTable: true); + sb.AppendLine($"USER read (0x{expUserOp:X2}) @0x{entry.Address:X4} len={p1}: {Fmt(ru)}"); + + var rb = await _ble.ReadTable2DAsync(entry.Address, p1, userTable: false); + sb.AppendLine($"BASE read (0x41) @0x{entry.Address:X4} len={p1}: {Fmt(rb)}"); + sb.AppendLine(); + + if (ru.Success) + sb.AppendLine("=> USER read SUCCEEDED. The null model was a one-off; re-reading at save time fixes it."); + else if (rb.Success) + sb.AppendLine("=> USER fails, BASE works at this address. The device isn't accepting the user opcode/address — " + + "confirm generation is Gen3 (0x45) and the user-space address is right for this firmware."); + else + sb.AppendLine("=> Both fail here. Likely addressing/timeout rather than opcode. " + + "resp=0x52 means the device rejected it; a timeout means no response at all."); + + return sb.ToString(); + + static string Fmt(CommandResult r) => + $"success={r.Success} resp=0x{r.ResponseCode:X2} payload={r.Payload?.Length ?? 0}B err={r.ErrorMessage ?? "-"}"; + } + + /// + /// Builds the placeholder shown for a user 24×8 adjust table that the ECU keeps + /// locked (Stage 1). Cells are all zero; the RPM/Load axis is borrowed from the + /// matching base table (read earlier in the load, same grid) so the grid headers — + /// and the subtable RPM derived from them — show a sensible range rather than zeros. + /// + private TuneBoss.Core.Models.TuningTable BuildLockedUserTable(TableEntryViewModel userEntry) + { + var baseLabel = userEntry.Label.Replace("User ", "Base "); + var baseTable = Groups.SelectMany(g => g.Entries) + .FirstOrDefault(e => e.Label == baseLabel)?.TuningTable; + + var rpm = (baseTable?.RpmAxis is byte[] ra && ra.Length == TuneBoss.Core.Models.TuningTable.Cols) + ? (byte[])ra.Clone() : DefaultRpmAxis(); + var load = (baseTable?.LoadAxis is byte[] la && la.Length == TuneBoss.Core.Models.TuningTable.Rows) + ? (byte[])la.Clone() : new byte[TuneBoss.Core.Models.TuningTable.Rows]; + + return new TuneBoss.Core.Models.TuningTable + { + Data = new byte[TuneBoss.Core.Models.TuningTable.DataBytes], + RpmAxis = rpm, + LoadAxis = load, + }; + } + + /// Fallback typical RPM axis (×100 ⇒ 1500…13000 rpm) when no base table is loaded. + private static byte[] DefaultRpmAxis() + { + var a = new byte[TuneBoss.Core.Models.TuningTable.Cols]; + for (int i = 0; i < a.Length; i++) a[i] = (byte)(15 + i * 5); + return a; + } + + /// + /// Writes the given entries to the ECU straight from their MODELS (not the on-screen + /// grid), including each entry's subtable — used by "Apply + Write" on file load, + /// where the loaded models are authoritative and may not be the selected table. + /// Locked (Stage-1) user tables are skipped. Throws on the first failed write. + /// + public async Task<(int Written, List LockedLabels)> WriteEntriesFromModelsAsync( + IEnumerable labels, IProgress? progress = null) + { + int written = 0; + var locked = new List(); + bool IsLock(CommandResult r) => r.ResponseCode == TuneBoss.Core.Protocol.Commands.APP_MEMADDR_LOCK; + + foreach (var label in labels) + { + var e = Groups.SelectMany(g => g.Entries).FirstOrDefault(x => x.Label == label); + if (e == null || !e.IsAvailable) continue; + + if (e.EntryType == TableEntryType.TuningTable && e.TuningTable != null) + { + if (e.IsLocked) + { + progress?.Report($"{label}: skipped (locked on Stage 1)"); + locked.Add(label); + } + else + { + progress?.Report($"Writing {label}…"); + var p1 = e.TuningTable.ToWirePayloadPart1(); + var p2 = e.TuningTable.ToWirePayloadPart2(); + var w1 = await _ble.WriteTable2DAsync(e.Address, p1, userTable: e.IsUserTable); + if (IsLock(w1)) + { + // Stage-1 ECU: user 24×8 space is locked. Note it, keep going — + // the rest of the file still applies. + e.IsLocked = true; + locked.Add(label); + progress?.Report($"{label}: locked (0x56) — skipped"); + continue; + } + if (!w1.Success) throw new InvalidOperationException($"{label}: {w1.ErrorMessage}"); + ushort a2 = (ushort)(e.Address + TuneBoss.Core.Models.TuningTable.SplitFirstLength + 1); + var w2 = await _ble.WriteTable2DAsync(a2, p2, userTable: e.IsUserTable); + if (IsLock(w2)) { e.IsLocked = true; locked.Add(label); continue; } + if (!w2.Success) throw new InvalidOperationException($"{label} (part 2): {w2.ErrorMessage}"); + written++; + } + } + else if (e.EntryType == TableEntryType.AfrTable && e.AfrTable != null) + { + progress?.Report($"Writing {label}…"); + var p1 = e.AfrTable.ToWirePayloadPart1(); + var p2 = e.AfrTable.ToWirePayloadPart2(); + var w1 = await _ble.WriteTable2DAsync(e.Address, p1); + if (IsLock(w1)) { locked.Add(label); continue; } + if (!w1.Success) throw new InvalidOperationException($"{label}: {w1.ErrorMessage}"); + ushort a2 = (ushort)(e.Address + TuneBoss.Core.Models.AfrTable.SplitFirstLength + 1); + var w2 = await _ble.WriteTable2DAsync(a2, p2); + if (IsLock(w2)) { locked.Add(label); continue; } + if (!w2.Success) throw new InvalidOperationException($"{label} (part 2): {w2.ErrorMessage}"); + written++; + } + + // Standalone Stage-1 subtable entry (its own SubTable, no parent). + if (e.IsStandaloneSub) + { + if (e.SubTable != null) + { + progress?.Report($"Writing {label}…"); + var sw0 = await _ble.WriteSubTableAsync(e.Address, e.SubTable.ToWirePayload()); + if (IsLock(sw0)) { locked.Add(label); continue; } + if (!sw0.Success) throw new InvalidOperationException($"{label}: {sw0.ErrorMessage}"); + written++; + } + continue; + } + + if (e.SubTableEntry is { SubTable: not null } se) + { + progress?.Report($"Writing {label} subtable…"); + var sw = await _ble.WriteSubTableAsync(se.Address, se.SubTable.ToWirePayload()); + if (IsLock(sw)) { locked.Add(label + " subtable"); continue; } + if (!sw.Success) throw new InvalidOperationException($"{label} subtable: {sw.ErrorMessage}"); + } + } + return (written, locked); + } + + /// Public wrapper so services can resume the live stream after bulk writes. + public Task ResumeStreamIfLiveAsync() => ResumeDiagnosticsIfLiveAsync(); +} diff --git a/TuneBossPC/ViewModels/Tables/TuningTablesViewModel.cs b/TuneBossPC/ViewModels/Tables/TuningTablesViewModel.cs new file mode 100644 index 0000000..29980ed --- /dev/null +++ b/TuneBossPC/ViewModels/Tables/TuningTablesViewModel.cs @@ -0,0 +1,1518 @@ +using System.Collections.ObjectModel; +using System.Windows; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using TuneBoss.Core.BLE; +using TuneBoss.Core.Models; + +namespace TuneBossPC.ViewModels.Tables; + +public partial class TuningTablesViewModel : ObservableObject, IDisposable +{ + private readonly IBleService _ble; + private IDisposable? _diagSub; + + // ── Nav tree ────────────────────────────────────────────────────────────── + public ObservableCollection Groups { get; } = new(); + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(HasSelectedTable))] + [NotifyPropertyChangedFor(nameof(ShowMainGrid))] + [NotifyPropertyChangedFor(nameof(IsSubtableOnly))] + [NotifyPropertyChangedFor(nameof(CanComms))] + [NotifyPropertyChangedFor(nameof(CommsBlockReason))] + [NotifyPropertyChangedFor(nameof(AdjustMinus5Label))] + [NotifyPropertyChangedFor(nameof(AdjustMinus1Label))] + [NotifyPropertyChangedFor(nameof(AdjustPlus1Label))] + [NotifyPropertyChangedFor(nameof(AdjustPlus5Label))] + private TableEntryViewModel? _selectedEntry; + + public bool HasSelectedTable => SelectedEntry != null && !SelectedEntry.IsPlaceholder; + + /// Border colour of the tracker-history marker. White reads on the colour + /// contour, but is invisible on the flat white map — so use black there. + public System.Windows.Media.Brush HistoryMarkerBrush => + _settings.Settings.FlatMapNoContour + ? System.Windows.Media.Brushes.Black + : System.Windows.Media.Brushes.White; + + /// A standalone Stage-1 subtable entry — show the subtable grid only. + public bool IsSubtableOnly => SelectedEntry?.IsStandaloneSub == true; + + /// Main 24×8 grid + 3D map are shown for everything EXCEPT a standalone subtable. + public bool ShowMainGrid => HasSelectedTable && !IsSubtableOnly; + + /// + /// True when hardware comms (READ / WRITE / FLASH) are allowed for the current entry: + /// a live session AND the entry's stage is unlocked. False offline or read-only stage. + /// + public bool CanComms => + _sessionService.IsActive && (SelectedEntry?.IsStageUnlocked ?? false); + + /// Tooltip explaining why comms is disabled (empty when enabled). + public string CommsBlockReason => + !_sessionService.IsActive ? "No hardware connected — editing offline." + : SelectedEntry is { IsStageUnlocked: false } + ? "This table's stage is not unlocked on the connected ECU (view only)." + : string.Empty; + + /// Raised whenever the visible table's values change — feeds the 3D surface. + public event Action? SurfaceChanged; + + /// Raised on every tracker update with the exact-match (row, col); (-1,-1) = none. + public event Action? TrackerMoved; + + /// + /// Angle-like tables (spark angle, injection angle) keep motorsport RET/ADV wording; + /// quantity tables (fuel pulse width, AFR, MAP comp) read SUB/ADD instead. + /// + private bool SelectedIsAngle => + SelectedEntry?.Label is { } l && (l.Contains("Spark") || l.Contains("Angle")); + + // For angle tables, retard = more positive, advance = more negative — so RET sits + // on the +buttons and ADV on the −buttons (labels only; the math is unchanged). + public string AdjustMinus5Label => SelectedIsAngle ? "ADV 5" : "SUB 5"; + public string AdjustMinus1Label => SelectedIsAngle ? "ADV 1" : "SUB 1"; + public string AdjustPlus1Label => SelectedIsAngle ? "RET 1" : "ADD 1"; + public string AdjustPlus5Label => SelectedIsAngle ? "RET 5" : "ADD 5"; + + // ── Current table cell grid ─────────────────────────────────────────────── + public ObservableCollection Cells { get; } = new(); + public ObservableCollection SubCells { get; } = new(); + public ObservableCollection Rows { get; } = new(); + public ObservableCollection SubRows { get; } = new(); + + [ObservableProperty] private ObservableCollection _rpmHeaders = new(); + [ObservableProperty] private ObservableCollection _loadHeaders = new(); + [ObservableProperty] private ObservableCollection _subRpmHeaders = new(); + [ObservableProperty] private ObservableCollection _subLoadHeaders = new(); + + [ObservableProperty] private TuningTableCellViewModel? _selectedCell; + [ObservableProperty] private TuningTableCellViewModel? _selectedSubCell; + [ObservableProperty] private TuningTableCellViewModel? _editingCell; + [ObservableProperty] private AxisHeaderViewModel? _editingHeader; + [ObservableProperty] private string _setValueText = string.Empty; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(ZoomPercentText))] + private double _zoomFactor = 1.0; + + public string ZoomPercentText => $"{ZoomFactor * 100:0}%"; + [ObservableProperty] private bool _isReading; + [ObservableProperty] private bool _isWriting; + /// Bumped on each confirmed flash — drives the FLASH button's green blink. + [ObservableProperty] private int _flashSuccessCount; + [ObservableProperty] private bool _hasSubTable; + [ObservableProperty] private string _statusMessage = string.Empty; + + // Tracker state from diagnostics + private int _trackerCol = -1, _trackerAdjCol = -1; + private int _trackerRow = -1, _trackerAdjRow = -1; + + // Table dimensions + private const int Cols = TuningTable.Cols; // 24 + private const int Rows_ = TuningTable.Rows; // 8 (underscore to avoid conflict with Rows collection) + private const int SubCols = SubTable.Cols; // 6 + private const int SubRows_ = SubTable.Rows; // 4 + + private readonly TuneBossPC.Services.ISessionService _sessionService; + private readonly TuneBossPC.Services.ISettingsService _settings; + + // Auto-write debounce (Settings → "Auto-write on cell change") + private readonly System.Windows.Threading.DispatcherTimer _autoWriteTimer; + private bool _autoDirtyMain, _autoDirtySub; + + // Tracker auto-select bookkeeping (Settings → "Tracker cell auto-select") + private int _autoSelRow = -1, _autoSelCol = -1; + + private readonly DiagnosticsStripViewModel _strip; + + public TuningTablesViewModel(IBleService ble, TuneBossPC.Services.ISessionService session, + TuneBossPC.Services.ISettingsService settings, + DiagnosticsStripViewModel strip) + { + _ble = ble; + _sessionService = session; + _settings = settings; + _strip = strip; + _sessionService.SessionChanged += () => + { + OnPropertyChanged(nameof(CanComms)); + OnPropertyChanged(nameof(CommsBlockReason)); + }; + + // Live-toggle the flat/contour map: recolour cells + tracker immediately, + // without disturbing the values or the current selection. + _settings.Settings.PropertyChanged += (_, e) => + { + if (e.PropertyName == nameof(TuneBossPC.Services.AppSettings.FlatMapNoContour)) + { + RecomputeHeatRangeAndRecolorAll(); + ApplyTracker(); + OnPropertyChanged(nameof(HistoryMarkerBrush)); + } + }; + + _autoWriteTimer = new System.Windows.Threading.DispatcherTimer + { + Interval = TimeSpan.FromMilliseconds(400) + }; + _autoWriteTimer.Tick += async (_, _) => await AutoWriteTickAsync(); + + InitCellGrids(); + + // Subscribe to diagnostics for live tracker + _diagSub = ble.DiagnosticsFrames.Subscribe(OnDiagFrame); + } + + // ── Auto-write on change ─────────────────────────────────────────────────── + // Any tuning-table value change marks the table dirty and (re)arms a short + // debounce, so a burst of ADD presses produces ONE write, sent 400 ms after + // the last change. Flash is never automatic. + + private void TouchAutoWrite(bool subTable) + { + if (!_settings.Settings.AutoWriteOnChange) return; + if (SelectedEntry == null || SelectedEntry.IsLocked) return; + + if (subTable) _autoDirtySub = true; else _autoDirtyMain = true; + _autoWriteTimer.Stop(); + _autoWriteTimer.Start(); + } + + private async Task AutoWriteTickAsync() + { + _autoWriteTimer.Stop(); + if (IsWriting || IsReading) { _autoWriteTimer.Start(); return; } // busy — retry shortly + + bool main = _autoDirtyMain, sub = _autoDirtySub; + _autoDirtyMain = _autoDirtySub = false; + + if (main) await WriteAsync(); + if (sub) await SubWriteAsync(); + } + + /// + /// Every write stops the ECU's diagnostics stream at the protocol level and + /// nothing restarts it automatically. If the strip says the stream should be + /// live, resume it — so neither auto-writes nor manual WRITE/FLASH silently + /// freeze the gauges and tracker. + /// + private async Task ResumeDiagnosticsIfLiveAsync() + { + try + { + if (_strip.IsRunning) + await _ble.StartDiagnosticsAsync(); + } + catch { /* stream resume is best-effort */ } + } + + /// + /// Builds the nav tree from the current session. Call after connect. + /// + public void RebuildNavTree() + { + OnPropertyChanged(nameof(CanComms)); + OnPropertyChanged(nameof(CommsBlockReason)); + Groups.Clear(); + // Build whenever a layout exists — connected OR offline file view. Offline the + // session has a layout but IsActive is false, so comms stay gated (CanComms). + var ecuSession = _sessionService.HasLayout + ? new EcuSession + { + Info = _sessionService.Info!, + Layout = _sessionService.Layout!, + Variant = _sessionService.Variant + } + : null; + BuildNavTree(ecuSession); + } + + // ── Nav tree builder ────────────────────────────────────────────────────── + + private void BuildNavTree(EcuSession? session) + { + bool isTwoCyl = session?.IsTwoCylinder ?? false; + var layout = session?.Layout; + + // Connected stage gates the groups; offline (no session) shows all, unlocked. + // Stage gating applies ONLY to a real connected device. Offline file view + // (HasLayout but not IsActive) shows every stage unlocked for inspection. + int? connectedStage = _sessionService.IsActive ? session?.Info?.Stage : null; + + // ── Stage 1: subtables, standalone (own entry, own 4×6 grid) ── + var stage1 = new TableGroupViewModel { Label = "STAGE 1", RequiredStage = 1 }; + stage1.Entries.Add(MakeSubEntry("Fuel PW Subtable 1", + layout?.Fuel_PulseWidth_Adjust1_SubTable, "Fuel Subtable 1", TableIconKind.Fuel)); + stage1.Entries.Add(MakeSubEntry("Spark Angle Subtable 1", + layout?.Spark_Angle_Adjust1_SubTable, "Spark Subtable 1", TableIconKind.Spark)); + if (isTwoCyl) + { + stage1.Entries.Add(MakeSubEntry("Fuel PW Subtable 2", + layout?.Fuel_PulseWidth_Adjust2_SubTable, "Fuel Subtable 2", TableIconKind.Fuel)); + stage1.Entries.Add(MakeSubEntry("Spark Angle Subtable 2", + layout?.Spark_Angle_Adjust2_SubTable, "Spark Subtable 2", TableIconKind.Spark)); + } + Groups.Add(stage1); + + // ── Stage 2: user adjust tables + AFR target ── + var stage2 = new TableGroupViewModel { Label = "STAGE 2", RequiredStage = 2 }; + stage2.Entries.Add(MakeEntry("User Fuel Pulse Width 1", + layout?.Fuel_PulseWidth_Adjust1, TableEntryType.TuningTable, + isUser: true, displayName: "Fuel Adjust % 1", icon: TableIconKind.Fuel)); + stage2.Entries.Add(MakeEntry("User Spark Angle 1", + layout?.Spark_Angle_Adjust1, TableEntryType.TuningTable, + isUser: true, displayName: "Spark Adjust 1", icon: TableIconKind.Spark)); + if (isTwoCyl) + { + stage2.Entries.Add(MakeEntry("User Fuel Pulse Width 2", + layout?.Fuel_PulseWidth_Adjust2, TableEntryType.TuningTable, + isUser: true, displayName: "Fuel Adjust % 2", icon: TableIconKind.Fuel)); + stage2.Entries.Add(MakeEntry("User Spark Angle 2", + layout?.Spark_Angle_Adjust2, TableEntryType.TuningTable, + isUser: true, displayName: "Spark Adjust 2", icon: TableIconKind.Spark)); + } + // Base MAP Compensation — kept (functional) but hidden from the nav. + stage2.Entries.Add(MakeEntry("Base MAP Compensation", + layout?.Secondary_Load_Conversion, TableEntryType.TuningTable, + isHidden: true)); + // AFR Target moved here (from Stage 3). + stage2.Entries.Add(MakeEntry("Base AFR Target 1", + layout?.AFR_Target1, TableEntryType.AfrTable, + displayName: "AFR Target 1", icon: TableIconKind.Afr)); + if (isTwoCyl) + stage2.Entries.Add(MakeEntry("Base AFR Target 2", + layout?.AFR_Target2, TableEntryType.AfrTable, + displayName: "AFR Target 2", icon: TableIconKind.Afr)); + Groups.Add(stage2); + + // ── Stage 3: base fuel PW, base spark angle, injection angle ── + var stage3 = new TableGroupViewModel { Label = "STAGE 3", RequiredStage = 3 }; + stage3.Entries.Add(MakeEntry("Base Fuel Pulse Width 1", + layout?.Fuel_PulseWidth1, TableEntryType.TuningTable, + displayName: "Base Fuel 1", icon: TableIconKind.Fuel)); + if (isTwoCyl) + stage3.Entries.Add(MakeEntry("Base Fuel Pulse Width 2", + layout?.Fuel_PulseWidth2, TableEntryType.TuningTable, + displayName: "Base Fuel 2", icon: TableIconKind.Fuel)); + stage3.Entries.Add(MakeEntry("Base Spark Angle 1", + layout?.Spark_Angle1, TableEntryType.TuningTable, + displayName: "Base Angle 1", icon: TableIconKind.Spark)); + if (isTwoCyl) + stage3.Entries.Add(MakeEntry("Base Spark Angle 2", + layout?.Spark_Angle2, TableEntryType.TuningTable, + displayName: "Base Angle 2", icon: TableIconKind.Spark)); + // Injection Angle moved here (from Stage 2). + stage3.Entries.Add(MakeEntry("Base Fuel Injection Angle 1", + layout?.Fuel_Angle2D, TableEntryType.TuningTable, + displayName: "Injection Angle 1", icon: TableIconKind.Angle)); + if (isTwoCyl) + stage3.Entries.Add(MakeEntry("Base Fuel Injection Angle 2", + layout?.Fuel_Angle2D_2, TableEntryType.TuningTable, + displayName: "Injection Angle 2", icon: TableIconKind.Angle)); + // Dual Injector — hidden. + stage3.Entries.Add(new TableEntryViewModel + { + Label = "Dual Injector", + EntryType = TableEntryType.Placeholder, + IsHidden = true, + }); + Groups.Add(stage3); + + // 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. + foreach (var g in Groups) + { + g.IsStageUnlocked = connectedStage == null || connectedStage >= g.RequiredStage; + foreach (var e in g.Entries) e.IsStageUnlocked = g.IsStageUnlocked; + } + } + + private static TableEntryViewModel MakeEntry( + string label, + TuneBoss.Core.Models.MemoryRegion? region, + TableEntryType type, + TableEntryViewModel? subEntry = null, + bool isUser = false, + string? displayName = null, + bool isHidden = false, + TableIconKind icon = TableIconKind.None) => new() + { + Label = label, + DisplayNameRaw = displayName, + IsHidden = isHidden, + IconKind = icon, + EntryType = type, + Address = region?.Address ?? 0, + ReadLength = region?.Length ?? 0, + IsAvailable = region?.IsAvailable ?? false, + IsUserTable = isUser, + SubTableEntry = subEntry, + }; + + private static TableEntryViewModel MakeSubEntry( + string label, + TuneBoss.Core.Models.MemoryRegion? region, + string? displayName = null, + TableIconKind icon = TableIconKind.None) => new() + { + Label = label, + DisplayNameRaw = displayName, + IconKind = icon, + EntryType = TableEntryType.SubTable, + Address = region?.Address ?? 0, + ReadLength = region?.Length ?? 0, + IsAvailable = region?.IsAvailable ?? false, + }; + + // ── Cell grid initialisation ────────────────────────────────────────────── + + private void InitCellGrids() + { + for (int r = 0; r < Rows_; r++) + for (int c = 0; c < Cols; c++) + Cells.Add(new TuningTableCellViewModel { Row = r, Col = c }); + + for (int r = 0; r < SubRows_; r++) + for (int c = 0; c < SubCols; c++) + SubCells.Add(new TuningTableCellViewModel { Row = r, Col = c }); + } + + // ── Nav selection ───────────────────────────────────────────────────────── + + [RelayCommand] + public void SelectEntry(TableEntryViewModel entry) + { + if (entry.IsPlaceholder) return; + + // Preserve unwritten edits: harvest the OUTGOING table's on-screen values + // back into its model before we navigate away, so returning to it (which + // re-populates from the model) shows the edits instead of the last-read data. + if (SelectedEntry is { IsLoaded: true } prev && prev != entry) + { + if (prev.IsStandaloneSub) HarvestSubCellsToModel(prev); + else + { + HarvestCellsToModel(prev); + if (prev.SubTableEntry is { SubTable: not null }) HarvestSubCellsToModel(prev.SubTableEntry); + } + } + + // Deselect previous + if (SelectedEntry != null) SelectedEntry.IsSelected = false; + + ClearCellSelection(); + + SelectedEntry = entry; + entry.IsSelected = true; + HasSubTable = entry.HasSubTable || entry.IsStandaloneSub; + + ClearVisited(); // tracker-history is per-table (axes differ); reset on switch + + // Populate grid from cached data if available + if (entry.IsLoaded) + { + PopulateGridFromEntry(entry); + if (!IsSubtableOnly) + { + RecomputeHeatRangeAndRecolorAll(); + SurfaceChanged?.Invoke(); + } + } + else + StatusMessage = entry.IsStandaloneSub + ? "Click READ to load this subtable." + : "Click READ to load this table."; + } + + // ── Read ────────────────────────────────────────────────────────────────── + + [RelayCommand] + public async Task ReadAsync() + { + if (SelectedEntry == null) return; + IsReading = true; + StatusMessage = "Reading…"; + + try + { + bool ok = await ReadEntryAsync(SelectedEntry); + if (ok) + { + PopulateGridFromEntry(SelectedEntry); + if (!IsSubtableOnly) + { + RecomputeHeatRangeAndRecolorAll(); + SurfaceChanged?.Invoke(); + } + StatusMessage = SelectedEntry.IsLocked + ? "Locked (0x56) — Stage 1 ECU does not expose this user 24×8 table. Showing zeros." + : "Read OK"; + } + } + catch (Exception ex) + { + StatusMessage = $"Error: {ex.Message}"; + } + finally + { + IsReading = false; + await ResumeDiagnosticsIfLiveAsync(); + } + } + + /// + /// Reads all tables on connect so they're cached and instantly viewable. + /// Mirrors populateInitTables() from the WinForms app. + /// + public async Task InitializeAllAsync(IProgress? progress = null) + { + IsReading = true; + var allEntries = Groups + .SelectMany(g => g.Entries) + .Where(e => !e.IsPlaceholder) + .ToList(); + + int done = 0; + foreach (var entry in allEntries) + { + progress?.Report($"Loading {entry.Label}… ({++done}/{allEntries.Count})"); + try + { + await ReadEntryAsync(entry); + await ReadSubtableInto(entry); // cache subtable for instant display + } + catch + { + // Continue loading remaining tables even if one fails + } + } + + IsReading = false; + + // Auto-select the first table so it's visible immediately + var first = allEntries.FirstOrDefault(e => e.IsLoaded); + if (first != null) + System.Windows.Application.Current.Dispatcher.Invoke(() => SelectEntry(first)); + } + + /// + /// Reads a single entry (and its subtable) from the device into the entry's model. + /// Does NOT touch the UI grid — caller decides when to populate. + /// + private async Task ReadEntryAsync(TableEntryViewModel entry) + { + if (!entry.IsAvailable) return false; + + // Standalone Stage-1 subtable — read the 4×6 subtable directly (0x42). + if (entry.IsStandaloneSub) + { + var srr = await _ble.ReadSubTableAsync(entry.Address); + if (!srr.Success) { StatusMessage = $"Read failed: {srr.ErrorMessage}"; return false; } + entry.SubTable = SubTable.FromPayload(srr.Payload); + entry.IsLoaded = true; + return true; + } + + if (entry.EntryType == TableEntryType.TuningTable) + { + const byte p1Len = TuneBoss.Core.Models.TuningTable.SplitFirstLength; + var r1 = await _ble.ReadTable2DAsync(entry.Address, p1Len, userTable: entry.IsUserTable); + if (!r1.Success) + { + // Stage-1 ECUs don't expose the user 24×8 adjust tables: the read is + // rejected with APP_MEMADDR_LOCK (0x56). That's expected, not an error — + // present an all-zero table (with a sensible RPM/Load axis) so the grid + // shows zeros instead of leaving the previously-selected base table up. + if (entry.IsUserTable && + r1.ResponseCode == TuneBoss.Core.Protocol.Commands.APP_MEMADDR_LOCK) + { + entry.TuningTable = BuildLockedUserTable(entry); + entry.IsLocked = true; + entry.IsLoaded = true; + return true; + } + StatusMessage = $"Read failed: {r1.ErrorMessage}"; + return false; + } + + ushort part2Addr = (ushort)(entry.Address + p1Len + 1); + // The device's length byte is the LAST offset to read (inclusive), i.e. + // (bytesWanted - 1) — the same reason part 1 uses 0x7F to fetch 128 bytes. + // Part 2 wants (TotalPayloadBytes - 128) bytes, so the field is that minus 1. + int p2Bytes = TuneBoss.Core.Models.TuningTable.TotalPayloadBytes - (p1Len + 1); + byte p2Len = (byte)(p2Bytes - 1); + var r2 = await _ble.ReadTable2DAsync(part2Addr, p2Len, userTable: entry.IsUserTable); + if (!r2.Success) { StatusMessage = $"Read part 2 failed: {r2.ErrorMessage}"; return false; } + + entry.TuningTable = TuneBoss.Core.Models.TuningTable.FromSplitResponses(r1.Payload, r2.Payload); + entry.IsLocked = false; + entry.IsLoaded = true; + } + else if (entry.EntryType == TableEntryType.AfrTable) + { + const byte p1Len = TuneBoss.Core.Models.AfrTable.SplitFirstLength; + var r1 = await _ble.ReadTable2DAsync(entry.Address, p1Len); + if (!r1.Success) { StatusMessage = $"Read failed: {r1.ErrorMessage}"; return false; } + + ushort part2Addr = (ushort)(entry.Address + p1Len + 1); + // Length field is the last offset to read (inclusive) = bytesWanted - 1, + // same convention as the 2D read (part 1's 0x7F fetches 128 bytes). + int p2Bytes = TuneBoss.Core.Models.AfrTable.TotalPayloadBytes - (p1Len + 1); + byte p2Len = (byte)(p2Bytes - 1); + var r2 = await _ble.ReadTable2DAsync(part2Addr, p2Len); + if (!r2.Success) { StatusMessage = $"Read part 2 failed: {r2.ErrorMessage}"; return false; } + + entry.AfrTable = TuneBoss.Core.Models.AfrTable.FromSplitResponses(r1.Payload, r2.Payload); + entry.IsLoaded = true; + } + + // Subtable is read/written via its own dedicated buttons (see Sub* commands), + // not as part of the main table read. + return true; + } + + /// Reads the entry's subtable into its model. Used by init and the Sub Read button. + private async Task ReadSubtableInto(TableEntryViewModel entry) + { + if (!entry.HasSubTable || entry.SubTableEntry == null || !entry.SubTableEntry.IsAvailable) + return false; + + var sub = entry.SubTableEntry; + var sr = await _ble.ReadSubTableAsync(sub.Address); + if (!sr.Success) return false; + + sub.SubTable = SubTable.FromPayload(sr.Payload); + sub.IsLoaded = true; + return true; + } + + + // ── Write ───────────────────────────────────────────────────────────────── + + [RelayCommand] + public async Task WriteAsync() + { + if (SelectedEntry == null || !SelectedEntry.IsLoaded) return; + if (SelectedEntry.IsLocked) + { + StatusMessage = "This user table is locked on a Stage 1 ECU and can't be written."; + return; + } + IsWriting = true; + StatusMessage = "Writing…"; + + try + { + var entry = SelectedEntry; + + // Standalone Stage-1 subtable — harvest the 4×6 grid and write it (0x4A). + if (entry.IsStandaloneSub) + { + HarvestSubCellsToModel(entry); + if (entry.SubTable == null) { StatusMessage = "Nothing to write."; return; } + var sw = await _ble.WriteSubTableAsync(entry.Address, entry.SubTable.ToWirePayload()); + StatusMessage = sw.Success + ? "Subtable write OK — click Flash to make permanent" + : $"Subtable write failed: {sw.ErrorMessage}"; + return; + } + + // Harvest current cell values back into the model + HarvestCellsToModel(entry); + + if (entry.EntryType == TableEntryType.TuningTable && entry.TuningTable != null) + { + var p1 = entry.TuningTable.ToWirePayloadPart1(); + var p2 = entry.TuningTable.ToWirePayloadPart2(); + var w1 = await _ble.WriteTable2DAsync(entry.Address, p1, userTable: entry.IsUserTable); + if (!w1.Success) { StatusMessage = $"Write failed: {w1.ErrorMessage}"; return; } + ushort part2Addr = (ushort)(entry.Address + TuneBoss.Core.Models.TuningTable.SplitFirstLength + 1); + var w2 = await _ble.WriteTable2DAsync(part2Addr, p2, userTable: entry.IsUserTable); + if (!w2.Success) { StatusMessage = $"Write part 2 failed: {w2.ErrorMessage}"; return; } + } + else if (entry.EntryType == TableEntryType.AfrTable && entry.AfrTable != null) + { + var p1 = entry.AfrTable.ToWirePayloadPart1(); + var p2 = entry.AfrTable.ToWirePayloadPart2(); + var w1 = await _ble.WriteTable2DAsync(entry.Address, p1); + if (!w1.Success) { StatusMessage = $"Write failed: {w1.ErrorMessage}"; return; } + ushort part2Addr = (ushort)(entry.Address + TuneBoss.Core.Models.AfrTable.SplitFirstLength + 1); + var w2 = await _ble.WriteTable2DAsync(part2Addr, p2); + if (!w2.Success) { StatusMessage = $"Write part 2 failed: {w2.ErrorMessage}"; return; } + } + + StatusMessage = "Write OK — click Flash to make permanent"; + } + catch (Exception ex) + { + StatusMessage = $"Error: {ex.Message}"; + } + finally + { + IsWriting = false; + await ResumeDiagnosticsIfLiveAsync(); + } + } + + // ── Subtable read / write (independent of the main table) ────────────────── + + [RelayCommand] + private async Task SubReadAsync() + { + var entry = SelectedEntry; + if (entry == null) return; + + // Standalone Stage-1 subtable: the entry IS the subtable (no SubTableEntry). + if (entry.IsStandaloneSub) + { + IsReading = true; + StatusMessage = "Reading subtable…"; + try + { + var sr = await _ble.ReadSubTableAsync(entry.Address); + if (sr.Success) + { + entry.SubTable = SubTable.FromPayload(sr.Payload); + entry.IsLoaded = true; + PopulateSubGrid(entry.SubTable); + StatusMessage = "Subtable read OK"; + } + else StatusMessage = $"Subtable read failed: {sr.ErrorMessage}"; + } + catch (Exception ex) { StatusMessage = $"Error: {ex.Message}"; } + finally { IsReading = false; } + return; + } + + if (entry.SubTableEntry == null) return; + + IsReading = true; + StatusMessage = "Reading subtable…"; + try + { + if (await ReadSubtableInto(entry) && entry.SubTableEntry.SubTable != null) + { + PopulateSubGrid(entry.SubTableEntry.SubTable); + StatusMessage = "Subtable read OK"; + } + else + { + StatusMessage = "Subtable read failed"; + } + } + catch (Exception ex) + { + StatusMessage = $"Error: {ex.Message}"; + } + finally + { + IsReading = false; + } + } + + [RelayCommand] + private async Task SubWriteAsync() + { + var entry = SelectedEntry; + if (entry == null) return; + + // Standalone Stage-1 subtable: harvest and write the entry's own 4×6 (0x4A). + if (entry.IsStandaloneSub) + { + if (entry.SubTable == null) { StatusMessage = "Read the subtable first."; return; } + IsWriting = true; + StatusMessage = "Writing subtable…"; + try + { + HarvestSubCellsToModel(entry); + var sw = await _ble.WriteSubTableAsync(entry.Address, entry.SubTable.ToWirePayload()); + StatusMessage = sw.Success + ? "Subtable write OK — click Flash to make permanent" + : $"Subtable write failed: {sw.ErrorMessage}"; + } + catch (Exception ex) { StatusMessage = $"Error: {ex.Message}"; } + finally { IsWriting = false; await ResumeDiagnosticsIfLiveAsync(); } + return; + } + + if (entry.SubTableEntry?.SubTable == null) return; + + IsWriting = true; + StatusMessage = "Writing subtable…"; + try + { + HarvestSubCellsToModel(entry.SubTableEntry); + var sw = await _ble.WriteSubTableAsync( + entry.SubTableEntry.Address, + entry.SubTableEntry.SubTable.ToWirePayload()); // data-only (24 bytes) + + StatusMessage = sw.Success + ? "Subtable write OK — click Flash to make permanent" + : $"Subtable write failed: {sw.ErrorMessage}"; + } + catch (Exception ex) + { + StatusMessage = $"Error: {ex.Message}"; + } + finally + { + IsWriting = false; + await ResumeDiagnosticsIfLiveAsync(); + } + } + + // ── Flash (persist all writes to ECU flash) ──────────────────────────────── + + [RelayCommand] + private async Task FlashAsync() + { + IsWriting = true; + StatusMessage = "Flashing to ECU…"; + try + { + var fr = await _ble.FlashWriteAsync(); + if (fr.Success) FlashSuccessCount++; + StatusMessage = fr.Success + ? "Flash OK — settings saved to ECU" + : $"Flash failed: {fr.ErrorMessage}"; + } + catch (Exception ex) + { + StatusMessage = $"Error: {ex.Message}"; + } + finally + { + IsWriting = false; + await ResumeDiagnosticsIfLiveAsync(); + } + } + + [RelayCommand] public void AdjustPlus5() => AdjustSelected(+5); + [RelayCommand] public void AdjustPlus1() => AdjustSelected(+1); + [RelayCommand] public void AdjustMinus1() => AdjustSelected(-1); + [RelayCommand] public void AdjustMinus5() => AdjustSelected(-5); + + [RelayCommand] public void SubAdjustPlus5() => AdjustSubSelected(+5); + [RelayCommand] public void SubAdjustPlus1() => AdjustSubSelected(+1); + [RelayCommand] public void SubAdjustMinus1() => AdjustSubSelected(-1); + [RelayCommand] public void SubAdjustMinus5() => AdjustSubSelected(-5); + + // ── Multi-cell selection ────────────────────────────────────────────────── + + /// Rectangular clipboard buffer from the last Copy (row-major from top-left). + private double[,]? _clipboard; + + /// All currently selected main-grid cells. + private IEnumerable SelectedCells => Cells.Where(c => c.IsSelected); + + /// Begins a new selection at (the drag anchor). + public void BeginSelection(TuningTableCellViewModel cell) + { + CommitEdit(); // commit any open edit before changing selection + foreach (var c in Cells) c.IsSelected = false; + SelectedCell = cell; // anchor + cell.IsSelected = true; + UpdateSelectionBorders(); + } + + /// Extends the selection rectangle from the anchor to . + public void ExtendSelection(TuningTableCellViewModel target) + { + if (SelectedCell == null) { BeginSelection(target); return; } + + int r0 = Math.Min(SelectedCell.Row, target.Row); + int r1 = Math.Max(SelectedCell.Row, target.Row); + int c0 = Math.Min(SelectedCell.Col, target.Col); + int c1 = Math.Max(SelectedCell.Col, target.Col); + + foreach (var c in Cells) + c.IsSelected = c.Row >= r0 && c.Row <= r1 && c.Col >= c0 && c.Col <= c1; + UpdateSelectionBorders(); + } + + private void ClearCellSelection() + { + CancelEdit(); + foreach (var c in Cells) c.IsSelected = false; + SelectedCell = null; + UpdateSelectionBorders(); + } + + /// Draws a thick border only on the outer edges of the selected region. + private void UpdateSelectionBorders() + { + const double bw = 2.5; + var sel = new HashSet<(int, int)>(SelectedCells.Select(c => (c.Row, c.Col))); + foreach (var c in Cells) + { + if (!c.IsSelected) { c.SelectionBorder = new Thickness(0); continue; } + double l = sel.Contains((c.Row, c.Col - 1)) ? 0 : bw; + double t = sel.Contains((c.Row - 1, c.Col)) ? 0 : bw; + double r = sel.Contains((c.Row, c.Col + 1)) ? 0 : bw; + double b = sel.Contains((c.Row + 1, c.Col)) ? 0 : bw; + c.SelectionBorder = new Thickness(l, t, r, b); + } + } + + /// Targets for a bulk op: every selected cell, or the anchor as a fallback. + private List BulkTargets() + { + var t = SelectedCells.ToList(); + if (t.Count == 0 && SelectedCell != null) t.Add(SelectedCell); + return t; + } + + // ── Value application (shared by buttons, type-to-edit, and the Set box) ──── + + private double ClampForEntry(double val) + { + if (SelectedEntry == null) return val; + if (SelectedEntry.EntryType == TableEntryType.AfrTable) + return Math.Round(Math.Clamp(val, + SelectedEntry.AfrTable?.MinAfrDisplay ?? 0, + SelectedEntry.AfrTable?.MaxAfrDisplay ?? 15), 1); + if (SelectedEntry.TuningTable is { } tt) + { + int lo = tt.MinDataVal, hi = tt.MaxDataVal; + // A table with no meaningful bounds (e.g. loaded from an older .fsr that didn't + // carry the max/min bytes) reports lo == hi; clamping to that would pin every + // edit to a single value. Fall back to the full storable byte range instead. + if (hi <= lo) { lo = tt.IsSigned ? -128 : 0; hi = tt.IsSigned ? 127 : 255; } + return Math.Round(Math.Clamp(val, lo, hi)); + } + return val; + } + + private void SetCellValue(TuningTableCellViewModel cell, double rawVal) + { + if (SelectedEntry == null) return; + double v = ClampForEntry(rawVal); + cell.RawValue = v; + cell.DisplayValue = FormatValue(v, SelectedEntry.EntryType); + RecomputeHeatRangeAndRecolorAll(); + TouchAutoWrite(subTable: false); + SurfaceChanged?.Invoke(); + } + + private void AdjustSelected(double delta) + { + if (SelectedEntry == null) return; + foreach (var cell in BulkTargets()) + SetCellValue(cell, cell.RawValue + delta); + } + + /// Writes the same value into every selected cell. + public void ApplyValueToSelection(double val) + { + if (SelectedEntry == null) return; + foreach (var cell in BulkTargets()) + SetCellValue(cell, val); + } + + // ── Copy / paste (Excel-style) ───────────────────────────────────────────── + + /// Copies the selected rectangle into the clipboard buffer. + [RelayCommand] + private void CopySelection() + { + var cells = SelectedCells.ToList(); + if (cells.Count == 0) return; + + int minR = cells.Min(c => c.Row), maxR = cells.Max(c => c.Row); + int minC = cells.Min(c => c.Col), maxC = cells.Max(c => c.Col); + + var buf = new double[maxR - minR + 1, maxC - minC + 1]; + foreach (var c in cells) + buf[c.Row - minR, c.Col - minC] = c.RawValue; + + _clipboard = buf; + StatusMessage = $"Copied {buf.GetLength(0)}×{buf.GetLength(1)} region"; + } + + /// + /// Pastes the clipboard starting at the anchor cell, clamped to the last + /// row/column (pastes as much as fits). + /// + [RelayCommand] + private void PasteToSelection() + { + if (_clipboard == null || SelectedEntry == null || SelectedCell == null) return; + + int rows = _clipboard.GetLength(0); + int cols = _clipboard.GetLength(1); + int baseR = SelectedCell.Row; + int baseC = SelectedCell.Col; + + var pasted = new List(); + for (int r = 0; r < rows; r++) + for (int c = 0; c < cols; c++) + { + int rr = baseR + r, cc = baseC + c; + if (rr >= Rows_ || cc >= Cols) continue; // clamp to last row/col + var cell = Cells[rr * Cols + cc]; + SetCellValue(cell, _clipboard[r, c]); + pasted.Add(cell); + } + + // Reselect the pasted region (anchor stays top-left) + foreach (var c in Cells) c.IsSelected = false; + foreach (var c in pasted) c.IsSelected = true; + UpdateSelectionBorders(); + StatusMessage = $"Pasted {pasted.Count} cells"; + } + + // ── In-cell editing (type-to-edit / double-click) ────────────────────────── + + /// Opens the editor on the anchor cell, optionally seeded with a typed char. + public void BeginEdit(string? seed = null) + { + if (SelectedCell == null || SelectedEntry == null) return; + CancelEdit(); + EditingCell = SelectedCell; + SelectedCell.EditText = seed ?? SelectedCell.DisplayValue; + SelectedCell.IsEditing = true; + } + + /// Commits the editor value to the whole selection. + public void CommitEdit() + { + var cell = EditingCell; + if (cell == null) return; + cell.IsEditing = false; + EditingCell = null; + if (double.TryParse(cell.EditText, out double val)) + ApplyValueToSelection(val); + } + + public void CancelEdit() + { + if (EditingCell == null) return; + EditingCell.IsEditing = false; + EditingCell = null; + } + + // ── Axis breakpoint editing (RPM / Load headers) ─────────────────────────── + + public void BeginHeaderEdit(AxisHeaderViewModel h) + { + CommitEdit(); // close any open cell edit + CancelAllHeaderEdits(); // close any other header edit + h.EditText = h.DisplayValue; + h.IsEditing = true; + EditingHeader = h; + } + + public void CommitHeaderEdit(AxisHeaderViewModel h) + { + if (!h.IsEditing) return; + h.IsEditing = false; + if (ReferenceEquals(EditingHeader, h)) EditingHeader = null; + if (SelectedEntry == null) return; + + if (!double.TryParse(h.EditText, out double entered)) + return; // unparseable → revert silently + + if (h.Kind == AxisKind.Rpm) ApplyRpmEdit(h, entered); + else ApplyLoadEdit(h, entered); + } + + public void CancelHeaderEdit(AxisHeaderViewModel h) + { + h.IsEditing = false; + if (ReferenceEquals(EditingHeader, h)) EditingHeader = null; + } + + private void CancelAllHeaderEdits() + { + foreach (var x in RpmHeaders) x.IsEditing = false; + foreach (var x in LoadHeaders) x.IsEditing = false; + EditingHeader = null; + } + + private void ApplyRpmEdit(AxisHeaderViewModel h, double entered) + { + // RPM is stored as byte × 100 → snap to nearest 100, clamp to byte range. + int raw = Math.Clamp((int)Math.Round(entered / 100.0), 0, 255); + int snapped = raw * 100; + + var vals = RpmHeaders.Select(x => x.Value).ToList(); + if (!IsInSequence(vals, h.Index, snapped)) + { + StatusMessage = SequenceMessage(vals, h.Index, "RPM"); + return; // out of sequence → reject, display reverts + } + + SetAxisByte(AxisKind.Rpm, h.Index, (byte)raw); + h.Value = snapped; + h.DisplayValue = snapped.ToString(); + StatusMessage = $"RPM[{h.Index}] = {snapped}"; + } + + private void ApplyLoadEdit(AxisHeaderViewModel h, double entered) + { + // Load is the raw byte (0–110). + int raw = Math.Clamp((int)Math.Round(entered), 0, 110); + + var vals = LoadHeaders.Select(x => x.Value).ToList(); + if (!IsInSequence(vals, h.Index, raw)) + { + StatusMessage = SequenceMessage(vals, h.Index, "Load"); + return; + } + + SetAxisByte(AxisKind.Load, h.Index, (byte)raw); + h.Value = raw; + h.DisplayValue = raw.ToString(); + StatusMessage = $"Load[{h.Index}] = {raw}"; + } + + /// Strict monotonic check against immediate neighbours (direction auto-detected). + private static bool IsInSequence(IReadOnlyList vals, int index, int newVal) + { + bool ascending = vals.Count < 2 || vals[^1] >= vals[0]; + int? lo = index > 0 ? vals[index - 1] : (int?)null; + int? hi = index < vals.Count - 1 ? vals[index + 1] : (int?)null; + + return ascending + ? (lo is null || newVal > lo) && (hi is null || newVal < hi) + : (lo is null || newVal < lo) && (hi is null || newVal > hi); + } + + private static string SequenceMessage(IReadOnlyList vals, int index, string label) + { + bool ascending = vals.Count < 2 || vals[^1] >= vals[0]; + int? lo = index > 0 ? vals[index - 1] : (int?)null; + int? hi = index < vals.Count - 1 ? vals[index + 1] : (int?)null; + int? lower = ascending ? lo : hi; + int? upper = ascending ? hi : lo; + + if (lower is not null && upper is not null) return $"{label} must be between {lower} and {upper}"; + if (lower is not null) return $"{label} must be greater than {lower}"; + if (upper is not null) return $"{label} must be less than {upper}"; + return $"{label} out of sequence"; + } + + /// Writes one axis byte back into the selected entry's model. + private void SetAxisByte(AxisKind kind, int index, byte raw) + { + if (SelectedEntry == null) return; + + if (SelectedEntry.EntryType == TableEntryType.AfrTable && SelectedEntry.AfrTable != null) + { + if (kind == AxisKind.Rpm) + { + var axis = (byte[])SelectedEntry.AfrTable.RpmAxis.Clone(); + axis[index] = raw; + SelectedEntry.AfrTable = SelectedEntry.AfrTable with { RpmAxis = axis }; + } + else + { + var axis = (byte[])SelectedEntry.AfrTable.LoadAxis.Clone(); + axis[index] = raw; + SelectedEntry.AfrTable = SelectedEntry.AfrTable with { LoadAxis = axis }; + } + } + else if (SelectedEntry.TuningTable != null) + { + if (kind == AxisKind.Rpm) + { + var axis = (byte[])SelectedEntry.TuningTable.RpmAxis.Clone(); + axis[index] = raw; + SelectedEntry.TuningTable = SelectedEntry.TuningTable with { RpmAxis = axis }; + } + else + { + var axis = (byte[])SelectedEntry.TuningTable.LoadAxis.Clone(); + axis[index] = raw; + SelectedEntry.TuningTable = SelectedEntry.TuningTable with { LoadAxis = axis }; + } + } + } + + // ── "Set value" box ──────────────────────────────────────────────────────── + + [RelayCommand] + private void ApplySetValue() + { + if (double.TryParse(SetValueText, out double val)) + ApplyValueToSelection(val); + } + + // ── Zoom ─────────────────────────────────────────────────────────────────── + + private const double MinZoom = 0.6; + private const double ZoomStep = 0.1; + private double _maxZoom = 3.0; + + /// Upper zoom bound, set by the view from the container's fit-to-height. + public double MaxZoom + { + get => _maxZoom; + set + { + _maxZoom = value < 1.0 ? 1.0 : value; + if (ZoomFactor > _maxZoom) ZoomFactor = _maxZoom; + } + } + + [RelayCommand] + private void ZoomIn() => ZoomFactor = Math.Min(MaxZoom, Math.Round(ZoomFactor + ZoomStep, 2)); + + [RelayCommand] + private void ZoomOut() => ZoomFactor = Math.Max(MinZoom, Math.Round(ZoomFactor - ZoomStep, 2)); + + private void AdjustSubSelected(double delta) + { + if (SelectedSubCell == null) return; + double newVal = Math.Clamp(SelectedSubCell.RawValue + delta, -128, 127); + SelectedSubCell.RawValue = newVal; + SelectedSubCell.DisplayValue = ((int)newVal).ToString(); + TouchAutoWrite(subTable: true); + } + + // ── Grid population ─────────────────────────────────────────────────────── + + private void PopulateGridFromEntry(TableEntryViewModel entry) + { + RpmHeaders.Clear(); + LoadHeaders.Clear(); + Rows.Clear(); + SubRows.Clear(); + + // Standalone Stage-1 subtable: render its own 4×6 grid only, no main table. + if (entry.IsStandaloneSub) + { + if (entry.SubTable != null) PopulateSubGrid(entry.SubTable); + return; + } + + if (entry.EntryType == TableEntryType.TuningTable && entry.TuningTable != null) + { + var t = entry.TuningTable; + BuildAxisHeaders(t.RpmValues, t.LoadValues); + + for (int r = 0; r < Rows_; r++) + for (int c = 0; c < Cols; c++) + { + var cell = Cells[r * Cols + c]; + cell.RawValue = t.GetCell(r, c); + cell.DisplayValue = cell.RawValue.ToString(); + RefreshCellColor(cell, entry); + } + + for (int r = 0; r < Rows_; r++) + { + var rowCells = Enumerable.Range(0, Cols) + .Select(c => Cells[r * Cols + c]) + .ToArray(); + Rows.Add(new TableRowViewModel + { + LoadHeader = LoadHeaders[r], + Cells = rowCells, + }); + } + } + else if (entry.EntryType == TableEntryType.AfrTable && entry.AfrTable != null) + { + var t = entry.AfrTable; + BuildAxisHeaders(t.RpmValues, t.LoadValues); + + for (int r = 0; r < Rows_; r++) + for (int c = 0; c < Cols; c++) + { + var cell = Cells[r * Cols + c]; + cell.RawValue = t.GetCell(r, c); + cell.DisplayValue = cell.RawValue.ToString("F1"); + RefreshCellColor(cell, entry); + } + + for (int r = 0; r < Rows_; r++) + { + var rowCells = Enumerable.Range(0, Cols) + .Select(c => Cells[r * Cols + c]) + .ToArray(); + Rows.Add(new TableRowViewModel + { + LoadHeader = LoadHeaders[r], + Cells = rowCells, + }); + } + } + + // Subtable + if (entry.HasSubTable && entry.SubTableEntry?.SubTable != null) + PopulateSubGrid(entry.SubTableEntry.SubTable); + + ApplyTracker(); + } + + /// Builds editable RPM (top) and Load (side) breakpoint headers. + private void BuildAxisHeaders(int[] rpmValues, int[] loadValues) + { + for (int i = 0; i < rpmValues.Length; i++) + RpmHeaders.Add(new AxisHeaderViewModel + { + Index = i, Kind = AxisKind.Rpm, + Value = rpmValues[i], DisplayValue = rpmValues[i].ToString(), + }); + + for (int i = 0; i < loadValues.Length; i++) + LoadHeaders.Add(new AxisHeaderViewModel + { + Index = i, Kind = AxisKind.Load, + Value = loadValues[i], DisplayValue = loadValues[i].ToString(), + }); + } + + private void PopulateSubGrid(SubTable sub) + { + SubRpmHeaders.Clear(); + SubLoadHeaders.Clear(); + SubRows.Clear(); + + // RPM range labels come from the parent full table's RPM axis (display-only, + // never written to the ECU): column c spans parentRpm[4c] (lo) … parentRpm[4c+3] (hi). + var parentRpm = SelectedEntry?.TuningTable?.RpmValues; + for (int c = 0; c < SubCols; c++) + { + int lo, hi; + if (parentRpm != null && parentRpm.Length >= Cols) + { + lo = parentRpm[c * 4]; + hi = parentRpm[c * 4 + 3]; + } + else // fallback to the subtable's own axis if the parent isn't loaded + { + lo = sub.GetRpmLo(c); + hi = sub.GetRpmHi(c); + } + SubRpmHeaders.Add($"{lo}\n{hi}"); + } + + // Load labels are fixed defaults (5, 15, 40, 70) — display-only. + for (int r = 0; r < SubRows_; r++) + SubLoadHeaders.Add(SubTable.DefaultLoadAxis[r].ToString()); + + for (int r = 0; r < SubRows_; r++) + for (int c = 0; c < SubCols; c++) + { + var cell = SubCells[r * SubCols + c]; + cell.RawValue = sub.GetCell(r, c); + cell.DisplayValue = ((int)cell.RawValue).ToString(); + cell.Background = new System.Windows.Media.SolidColorBrush( + System.Windows.Media.Color.FromRgb(0x22, 0x26, 0x2B)); + cell.Foreground = System.Windows.Media.Brushes.White; + } + + for (int r = 0; r < SubRows_; r++) + { + var rowCells = Enumerable.Range(0, SubCols) + .Select(c => SubCells[r * SubCols + c]) + .ToArray(); + SubRows.Add(new SubTableRowViewModel + { + LoadHeader = SubTable.DefaultLoadAxis[r].ToString(), + Cells = rowCells, + }); + } + } + + // Heat range follows the CURRENT table's actual values (matching the 3D + // surface), not the theoretical possible extremes — so the full colour ramp + // is always spent on the spread that's on screen. + private double _heatMin = 0, _heatMax = 255; + + private void RecomputeHeatRangeAndRecolorAll() + { + if (Cells.Count == 0 || SelectedEntry == null) return; + + double min = double.MaxValue, max = double.MinValue; + foreach (var c in Cells) + { + if (c.RawValue < min) min = c.RawValue; + if (c.RawValue > max) max = c.RawValue; + } + if (max <= min) max = min + 1; // flat table — avoid div-by-zero, mid colour + + _heatMin = min; + _heatMax = max; + foreach (var c in Cells) RefreshCellColor(c, SelectedEntry); + } + + private void RefreshCellColor(TuningTableCellViewModel cell, TableEntryViewModel entry) + { + if (_settings.Settings.FlatMapNoContour) + { + cell.Background = HeatmapHelper.FlatBackground; + cell.Foreground = System.Windows.Media.Brushes.Black; + return; + } + var (bg, fg) = HeatmapHelper.GetCellColors(cell.RawValue, _heatMin, _heatMax); + cell.Background = bg; + cell.Foreground = fg; + } + + private static string FormatValue(double val, TableEntryType type) + => type == TableEntryType.AfrTable ? val.ToString("F1") : ((int)val).ToString(); + + // ── Harvest cells back to model ─────────────────────────────────────────── + + private void HarvestCellsToModel(TableEntryViewModel entry) + { + if (entry.EntryType == TableEntryType.TuningTable && entry.TuningTable != null) + { + var data = new byte[TuningTable.DataBytes]; + bool signed = entry.TuningTable.IsSigned; + for (int i = 0; i < Cells.Count; i++) + { + int v = (int)Cells[i].RawValue; + data[i] = signed ? unchecked((byte)(sbyte)v) : (byte)v; + } + entry.TuningTable = entry.TuningTable with { Data = data }; + } + else if (entry.EntryType == TableEntryType.AfrTable && entry.AfrTable != null) + { + var data = new byte[AfrTable.DataBytes]; + for (int i = 0; i < Cells.Count; i++) + data[i] = (byte)(Cells[i].RawValue * 10.0); + entry.AfrTable = entry.AfrTable with { Data = data }; + } + } + + private void HarvestSubCellsToModel(TableEntryViewModel subEntry) + { + if (subEntry.SubTable == null) return; + var data = new byte[SubTable.DataBytes]; + for (int i = 0; i < SubCells.Count; i++) + data[i] = unchecked((byte)(sbyte)(int)SubCells[i].RawValue); + subEntry.SubTable = subEntry.SubTable with { Data = data }; + } + + // ── Live tracker ────────────────────────────────────────────────────────── + + private void OnDiagFrame(DiagnosticsFrame frame) + { + if (SelectedEntry == null || !SelectedEntry.IsLoaded) return; + + byte[] rpmAxis = SelectedEntry.TuningTable?.RpmAxis + ?? SelectedEntry.AfrTable?.RpmAxis + ?? Array.Empty(); + byte[] loadAxis = SelectedEntry.TuningTable?.LoadAxis + ?? SelectedEntry.AfrTable?.LoadAxis + ?? Array.Empty(); + + if (rpmAxis.Length == 0) return; + + // TPS-keyed for user-adjust tables, load-keyed for base tables + bool useTps = SelectedEntry.Label.StartsWith("User"); + var tracker = TableTracker.Calculate(rpmAxis, loadAxis, + frame.RPM_Raw, + useTps ? frame.TPS_Percent : frame.Load); + + _trackerCol = tracker.ColHighlight; + _trackerAdjCol = tracker.ColLowlight; + _trackerRow = tracker.RowHighlight; + _trackerAdjRow = tracker.RowLowlight; + + Application.Current.Dispatcher.Invoke(ApplyTracker); + } + + // ── Tracker history ──────────────────────────────────────────────────────── + // Records the path of the live tracker: every cell the exact-match tracker + // enters while recording gets a sticky white inner frame (IsVisited), so the + // tuner can see which cells have been covered. Markers reset when the selected + // table changes (axes differ per table). + + [ObservableProperty] private bool _isRecordingHistory; + + [RelayCommand] + private void StartTrackerHistory() + { + IsRecordingHistory = true; + StatusMessage = "Tracker history: recording"; + } + + [RelayCommand] + private void StopTrackerHistory() + { + IsRecordingHistory = false; + StatusMessage = "Tracker history: stopped"; + } + + [RelayCommand] + private void ClearTrackerHistory() + { + foreach (var c in Cells) c.IsVisited = false; + StatusMessage = "Tracker history: cleared"; + } + + private void ClearVisited() + { + foreach (var c in Cells) c.IsVisited = false; + } + + private void ApplyTracker() + { + // Settings → tracker cell auto-select: the exact-match tracker cell becomes + // the active selection whenever it moves. Manual selection still works + // between moves; typing in a cell is never interrupted (guarded on edit). + if (_settings.Settings.TrackerAutoSelect && + _trackerRow >= 0 && _trackerCol >= 0 && + (_trackerRow != _autoSelRow || _trackerCol != _autoSelCol) && + EditingCell == null && + SelectedEntry is { IsLoaded: true }) + { + var target = Cells.FirstOrDefault(c => c.Row == _trackerRow && c.Col == _trackerCol); + if (target != null) + { + BeginSelection(target); + _autoSelRow = _trackerRow; + _autoSelCol = _trackerCol; + } + } + + TrackerMoved?.Invoke(_trackerRow, _trackerCol); + + foreach (var cell in Cells) + { + bool isHigh = cell.Col == _trackerCol && cell.Row == _trackerRow; + bool isAdj = (cell.Col == _trackerAdjCol && cell.Row == _trackerRow) || + (cell.Col == _trackerCol && cell.Row == _trackerAdjRow)|| + (cell.Col == _trackerAdjCol && cell.Row == _trackerAdjRow); + + cell.IsTrackerHighlight = isHigh; + cell.IsTrackerAdjacent = isAdj; + + // Paint the tracker/heatmap on EVERY cell, selected or not. The selection + // visual is a translucent overlay (see the cell template), so the tracker + // colour shows through a selection — the active point stays visible even + // when it falls inside a selected range. + bool flat = _settings.Settings.FlatMapNoContour; + if (isHigh) + { + if (IsRecordingHistory) cell.IsVisited = true; // tracker-history: sticky marker + cell.Background = flat ? HeatmapHelper.FlatTrackerHighlight + : HeatmapHelper.TrackerHighlight; + cell.Foreground = new System.Windows.Media.SolidColorBrush( + System.Windows.Media.Color.FromRgb(0x20, 0x20, 0x20)); + } + else if (isAdj) + { + cell.Background = flat ? HeatmapHelper.FlatTrackerAdjacent + : HeatmapHelper.TrackerAdjacent; + cell.Foreground = System.Windows.Media.Brushes.Black; + } + else if (SelectedEntry != null) + { + RefreshCellColor(cell, SelectedEntry); + } + } + } + + public void Dispose() => _diagSub?.Dispose(); +} + + diff --git a/TuneBossPC/ViewModels/TpsCalViewModel.cs b/TuneBossPC/ViewModels/TpsCalViewModel.cs new file mode 100644 index 0000000..c424658 --- /dev/null +++ b/TuneBossPC/ViewModels/TpsCalViewModel.cs @@ -0,0 +1,258 @@ +using System.Windows; +using CommunityToolkit.Mvvm.ComponentModel; +using CommunityToolkit.Mvvm.Input; +using TuneBoss.Core.BLE; +using TuneBoss.Core.Models; +using TuneBossPC.Services; + +namespace TuneBossPC.ViewModels; + +/// +/// Throttle-position-sensor calibration page. +/// +/// Faithful port of the legacy Android TpsCalPage flow: +/// 1. On activation, read the per-unit absolute bounds (max/min) from the ECU. +/// 2. START → stream diagnostics and track the running min/max of the raw TPS +/// ADC () while the tuner sweeps the +/// throttle fully open↔closed ~5 times. +/// 3. FINISH → validate the captured min/max against the bounds, then write the +/// 8-byte calibration block, set the first-use flag, and flash. +/// +/// Diagnostics are paused for the write/flash sequence and resumed afterward so the +/// shared diagnostics strip keeps working. +/// +public partial class TpsCalViewModel : ObservableObject, IDisposable +{ + private readonly IBleService _ble; + private readonly ISessionService _session; + + private IDisposable? _diagSub; + private TpsCalibration.Addresses _addr; + private bool _addrResolved; + + private int _absMaxVal; + private int _absMinVal; + private int _minRaw; + private int _maxRaw; + private bool _firstSample; + + // ── Bound display ────────────────────────────────────────────────────────── + [ObservableProperty] private string _absMax = "—"; + [ObservableProperty] private string _absMin = "—"; + [ObservableProperty] private string _currMax = "—"; + [ObservableProperty] private string _currMin = "—"; + [ObservableProperty] private string _currVal = "—"; + + // ── Guide / status ───────────────────────────────────────────────────────── + [ObservableProperty] private string _heading = "TPS Calibration is Inactive"; + [ObservableProperty] private string _step1 = "1. Open throttle to maximum position"; + [ObservableProperty] private string _step2 = "2. Close throttle to minimum position"; + [ObservableProperty] private string _step3 = $"3. Repeat {TpsCalibration.RequiredSweeps} times"; + [ObservableProperty] private string _step4 = "4. Press FINISH when done"; + [ObservableProperty] private string _statusMessage = "Ready."; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(IsIdle))] + private bool _isCalibrating; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(IsIdle))] + private bool _isBusy; // write / flash in progress — blocks navigation away + + public bool IsIdle => !IsCalibrating && !IsBusy; + + public TpsCalViewModel(IBleService ble, ISessionService session) + { + _ble = ble; + _session = session; + } + + // ── Activation ───────────────────────────────────────────────────────────── + + /// Called when the page is shown. Reads the absolute bounds. + public async Task OnNavigatedToAsync() + { + if (!ResolveAddresses()) + { + StatusMessage = "No active session — connect a device first."; + return; + } + + try + { + var r = await _ble.ReadTable1DAsync(_addr.AbsBounds, 0x03); + if (r.Success && r.Payload.Length >= 6) + { + _absMaxVal = r.Payload[4]; // [4] = absMax, [5] = absMin (offset 4 = after 51 43 .. header) + _absMinVal = r.Payload[5]; + AbsMax = _absMaxVal.ToString(); + AbsMin = _absMinVal.ToString(); + StatusMessage = "Absolute bounds read. Press START to begin."; + } + else + { + StatusMessage = "Could not read TPS absolute bounds."; + } + } + catch (Exception ex) { StatusMessage = $"Error reading bounds: {ex.Message}"; } + } + + private bool ResolveAddresses() + { + if (_addrResolved) return true; + var info = _session.Info; + if (info == null) return false; + _addr = TpsCalibration.For(info); + _addrResolved = true; + return true; + } + + // ── START ────────────────────────────────────────────────────────────────── + + public bool CanStart => IsIdle && _session.IsActive; + + [RelayCommand(CanExecute = nameof(CanStart))] + private async Task StartAsync() + { + if (!ResolveAddresses()) { StatusMessage = "No active session."; return; } + + _minRaw = _maxRaw = 0; + _firstSample = true; + CurrMax = CurrMin = CurrVal = "—"; + + IsCalibrating = true; + Heading = "TPS Calibration — reading values…"; + StatusMessage = "Sweep the throttle fully open and closed several times, then press FINISH."; + RaiseCanExecute(); + + // Make sure frames are flowing (idempotent), then observe TPS_Raw. + await _ble.StartDiagnosticsAsync(); + _diagSub = _ble.DiagnosticsFrames.Subscribe(OnFrame); + } + + private void OnFrame(DiagnosticsFrame frame) + { + if (!IsCalibrating) return; + int raw = frame.TPS_Raw; + + Application.Current.Dispatcher.Invoke(() => + { + if (_firstSample) + { + _minRaw = _maxRaw = raw; + _firstSample = false; + } + else + { + if (raw < _minRaw) _minRaw = raw; + if (raw > _maxRaw) _maxRaw = raw; + } + + CurrMax = _maxRaw.ToString(); + CurrMin = _minRaw.ToString(); + CurrVal = raw.ToString(); + }); + } + + // ── FINISH ───────────────────────────────────────────────────────────────── + + [RelayCommand(CanExecute = nameof(IsCalibratingState))] + private async Task FinishAsync() + { + StopCapture(); + IsCalibrating = false; + Heading = "TPS Calibration is Inactive"; + + // The calibration session is over — leave diagnostics stopped. The tuner can + // restart the stream from the Diagnostics page if they want live data again. + await _ble.StopDiagnosticsAsync(); + RaiseCanExecute(); + + if (_firstSample) // no frames captured at all + { + StatusMessage = "No TPS data captured. Try again."; + return; + } + + var verdict = TpsCalibration.Validate(_minRaw, _maxRaw, _absMinVal, _absMaxVal); + StatusMessage = TpsCalibration.Describe(verdict, _minRaw, _maxRaw, _absMinVal, _absMaxVal); + if (verdict != TpsCalibration.Validation.Ok) + return; + + await WriteCalibrationAsync(); + } + + public bool IsCalibratingState => IsCalibrating; + + // ── CANCEL ───────────────────────────────────────────────────────────────── + + [RelayCommand(CanExecute = nameof(IsCalibratingState))] + private async Task Cancel() + { + StopCapture(); + IsCalibrating = false; + Heading = "TPS Calibration is Inactive"; + StatusMessage = "Calibration cancelled."; + CurrMax = CurrMin = CurrVal = "—"; + await _ble.StopDiagnosticsAsync(); + RaiseCanExecute(); + } + + private void StopCapture() + { + _diagSub?.Dispose(); + _diagSub = null; + } + + // ── Write sequence: cal block → first-use flag → flash ───────────────────── + + private async Task WriteCalibrationAsync() + { + IsBusy = true; + RaiseCanExecute(); + + // Diagnostics was already stopped when the capture phase ended; these writes + // run with the stream quiet (BleManager also keeps it stopped across writes). + try + { + // 1) Write the 8-byte calibration block. + var payload = TpsCalibration.BuildCalWritePayload(_minRaw, _maxRaw); + var w = await _ble.WriteTable1DAsync(_addr.CalWrite, payload); + if (!w.Success) { StatusMessage = $"Calibration write failed: {w.ErrorMessage}"; return; } + + // 2) Set the first-use flag (DD slot = 1, per the WinForms read of UIFirstUseInfo[0]). + var fu = await _ble.WriteFirstUseAsync(FirstUseFlagBytes()); + if (!fu.Success) { StatusMessage = $"First-use flag write failed: {fu.ErrorMessage}"; return; } + + // 3) Persist to flash. + var fr = await _ble.FlashWriteAsync(); + StatusMessage = fr.Success + ? "TPS calibration successful and saved to ECU." + : $"Flash write failed: {fr.ErrorMessage}"; + } + catch (Exception ex) { StatusMessage = $"Error during write: {ex.Message}"; } + finally + { + IsBusy = false; + RaiseCanExecute(); + } + } + + /// + /// First-use block written via APP_FIRSTUSE. The calibration-done flag lives in + /// byte[1] (the MM slot) — matching the Android app, which sets UIfirstUseDate[1]=1 + /// (fus_1) on a successful calibration and reads the same byte to decide whether to + /// warn. byte[0] (DD) is left untouched. + /// + private static byte[] FirstUseFlagBytes() => + new byte[] { 0x00, TpsCalibration.CalDoneFlag, 0x00, 0x00 }; + + private void RaiseCanExecute() + { + StartCommand.NotifyCanExecuteChanged(); + FinishCommand.NotifyCanExecuteChanged(); + CancelCommand.NotifyCanExecuteChanged(); + } + + public void Dispose() => StopCapture(); +} diff --git a/TuneBossPC/Views/ConnectView.xaml b/TuneBossPC/Views/ConnectView.xaml new file mode 100644 index 0000000..b08286f --- /dev/null +++ b/TuneBossPC/Views/ConnectView.xaml @@ -0,0 +1,177 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/TuneBossPC/Views/DiagnosticsStrip.xaml.cs b/TuneBossPC/Views/DiagnosticsStrip.xaml.cs new file mode 100644 index 0000000..2e057a4 --- /dev/null +++ b/TuneBossPC/Views/DiagnosticsStrip.xaml.cs @@ -0,0 +1,32 @@ +using System.Windows; +using System.Windows.Controls; +using TuneBossPC.ViewModels; +using TuneBossPC.Views.Dialogs; + +namespace TuneBossPC.Views; + +public partial class DiagnosticsStrip : UserControl +{ + public DiagnosticsStrip() + { + InitializeComponent(); + } + + private void ChangeChannel_Click(object sender, RoutedEventArgs e) + { + if (sender is not MenuItem mi) return; + if (mi.Tag is not GaugeSlotViewModel slot) return; + if (DataContext is not DiagnosticsStripViewModel stripVm) return; + + int slotIndex = stripVm.Slots.IndexOf(slot); + if (slotIndex < 0) return; + + var dialog = new ChannelPickerDialog(slot.Channel) + { + Owner = Window.GetWindow(this) + }; + + if (dialog.ShowDialog() == true) + stripVm.AssignSlot(slotIndex, dialog.SelectedChannel); + } +} diff --git a/TuneBossPC/Views/DiagnosticsView.xaml b/TuneBossPC/Views/DiagnosticsView.xaml new file mode 100644 index 0000000..fe2d412 --- /dev/null +++ b/TuneBossPC/Views/DiagnosticsView.xaml @@ -0,0 +1,432 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/TuneBossPC/Views/DiagnosticsView.xaml.cs b/TuneBossPC/Views/DiagnosticsView.xaml.cs new file mode 100644 index 0000000..8105aa2 --- /dev/null +++ b/TuneBossPC/Views/DiagnosticsView.xaml.cs @@ -0,0 +1,13 @@ +using System.Windows.Controls; +using TuneBossPC.ViewModels; + +namespace TuneBossPC.Views; + +public partial class DiagnosticsView : UserControl +{ + public DiagnosticsView(DiagnosticsViewModel vm) + { + DataContext = vm; + InitializeComponent(); + } +} diff --git a/TuneBossPC/Views/Dialogs/ChannelPickerDialog.xaml b/TuneBossPC/Views/Dialogs/ChannelPickerDialog.xaml new file mode 100644 index 0000000..c3caa09 --- /dev/null +++ b/TuneBossPC/Views/Dialogs/ChannelPickerDialog.xaml @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/TuneBossPC/Views/MainWindow.xaml.cs b/TuneBossPC/Views/MainWindow.xaml.cs new file mode 100644 index 0000000..9b8c871 --- /dev/null +++ b/TuneBossPC/Views/MainWindow.xaml.cs @@ -0,0 +1,47 @@ +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using TuneBossPC.ViewModels; + +namespace TuneBossPC.Views; + +public partial class MainWindow : Window +{ + private readonly MainWindowViewModel _vm; + + public MainWindow(MainWindowViewModel vm) + { + _vm = vm; + DataContext = vm; + InitializeComponent(); + + // Navigate to Connect on startup + vm.NavigateTo("Connect"); + } + + private void NavButton_Click(object sender, RoutedEventArgs e) + { + if (sender is Button btn && btn.Tag is string tag) + _vm.NavigateTo(tag); + } + + // ── Killswitch: press-and-hold ────────────────────────────────────────────── + // Capture the mouse on press so we still get the release even if the pointer + // leaves the button; release is driven by LostMouseCapture (covers mouse-up, + // dragging away, and the window losing focus). + private void Killswitch_MouseDown(object sender, MouseButtonEventArgs e) + { + if (sender is UIElement el) el.CaptureMouse(); + _vm.KillswitchPress(); + } + + private void Killswitch_MouseUp(object sender, MouseButtonEventArgs e) + { + if (sender is UIElement el) el.ReleaseMouseCapture(); // → fires LostMouseCapture + } + + private void Killswitch_LostCapture(object sender, MouseEventArgs e) + { + _vm.KillswitchRelease(); + } +} diff --git a/TuneBossPC/Views/MiscValuesView.xaml b/TuneBossPC/Views/MiscValuesView.xaml new file mode 100644 index 0000000..8d6ad0e --- /dev/null +++ b/TuneBossPC/Views/MiscValuesView.xaml @@ -0,0 +1,266 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +