Initial Commit

This commit is contained in:
2026-09-28 16:55:31 +08:00
commit 14f8706198
128 changed files with 19860 additions and 0 deletions
+482
View File
@@ -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
+86
View File
@@ -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
}
}
+101
View File
@@ -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]));
}
}
+71
View File
@@ -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);
}
}
+104
View File
@@ -0,0 +1,104 @@
using System.Numerics;
using TuneBoss.Core.Models;
using Xunit;
namespace TuneBoss.Core.Tests;
/// <summary>
/// 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.
/// </summary>
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);
}
}
}
}
@@ -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));
}
}
+58
View File
@@ -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);
}
}
+54
View File
@@ -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);
}
}
}
@@ -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));
}
}
+99
View File
@@ -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<ArgumentException>(() => 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]);
}
}
+46
View File
@@ -0,0 +1,46 @@
using TuneBoss.Core.Models;
namespace TuneBoss.Core.Tests;
/// <summary>Shared builders for synthetic device data.</summary>
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,
};
/// <summary>Wraps a data block in the 4-byte response header the parsers skip (51 xx xx 00).</summary>
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;
}
/// <summary>A valid 24-byte 1D block with chosen sign flags / multipliers.</summary>
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;
}
}
@@ -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);
}
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<!-- Adjust the path if your Core project lives elsewhere. From a solution
folder this is typically ..\TuneBoss.Core\TuneBoss.Core.csproj -->
<ProjectReference Include="..\TuneBoss.Core\TuneBoss.Core.csproj" />
</ItemGroup>
</Project>
+668
View File
@@ -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;
/// <summary>
/// Windows WinRT BLE implementation of IBleService.
/// Uses Nordic UART Service (NUS) over a single bidirectional characteristic.
/// </summary>
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<byte[]> _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<DiagnosticsFrame> _diagSubject = new();
private volatile bool _diagnosticsRunning;
private long _lastDiagTickUtc;
// ── Observables ──────────────────────────────────────────────────────────
private readonly BehaviorSubject<BleConnectionState> _connSubject =
new(BleConnectionState.Disconnected);
private readonly Subject<BleDeviceInfo> _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<BleConnectionState> ConnectionStateChanged => _connSubject.AsObservable();
public IObservable<DiagnosticsFrame> DiagnosticsFrames => _diagSubject.AsObservable();
public bool DiagnosticsRunning => _diagnosticsRunning;
// ────────────────────────────────────────────────────────────────────────
// SCANNING
// ────────────────────────────────────────────────────────────────────────
public IObservable<BleDeviceInfo> StartScan()
{
var seen = new Dictionary<ulong, string>();
_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<bool> 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<EcuInfo?> 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<CommandResult> 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<CommandResult> 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<CommandResult> 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<CommandResult> 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<CommandResult> ReadTable1DAsync(ushort address, byte lengthBytes, CancellationToken ct = default)
=> ReadTableAsync(_genConfig?.ReadCmd1D ?? Commands.APP_MEMRD_1D, address, lengthBytes, ct);
public Task<CommandResult> WriteTable1DAsync(ushort address, byte[] data, CancellationToken ct = default)
=> WriteTableAsync(_genConfig?.WriteCmd1D ?? Commands.APP_MEMWR_1D, address, data, ct);
public Task<CommandResult> ReadSubTableAsync(ushort address, CancellationToken ct = default)
=> ReadTableAsync(_genConfig?.ReadCmdSubT ?? Commands.APP_MEMRD_SUBT, address,
(byte)TuneBoss.Core.Models.SubTable.TotalBytes, ct);
public Task<CommandResult> WriteSubTableAsync(ushort address, byte[] data, CancellationToken ct = default)
=> WriteTableAsync(_genConfig?.WriteCmdSubT ?? Commands.APP_MEMWR_SUBT, address, data, ct);
public Task<CommandResult> ReadMiscAsync(ushort address, byte lengthBytes, CancellationToken ct = default)
=> ReadTableAsync(_genConfig?.ReadCmdMisc ?? Commands.APP_MEMRD_MISC, address, lengthBytes, ct);
public Task<CommandResult> WriteMiscAsync(ushort address, byte[] data, CancellationToken ct = default)
=> WriteTableAsync(_genConfig?.WriteCmdMisc ?? Commands.APP_MEMWR_MISC, address, data, ct);
// ────────────────────────────────────────────────────────────────────────
// FLASH WRITE
// ────────────────────────────────────────────────────────────────────────
public async Task<CommandResult> 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<CommandResult> 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<CommandResult> 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<CommandResult> 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<CommandResult> 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<bool> 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<GattDeviceService?> 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<GattCharacteristic?> 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<byte>
{
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();
}
}
+196
View File
@@ -0,0 +1,196 @@
using TuneBoss.Core.Models;
using TuneBoss.Core.Protocol;
namespace TuneBoss.Core.BLE;
/// <summary>
/// Represents a discovered BLE device before connection.
/// </summary>
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";
}
/// <summary>
/// Connection state published to observers.
/// </summary>
public enum BleConnectionState
{
Disconnected,
Connecting,
Connected,
Disconnecting,
}
/// <summary>
/// Result of a command sent to the device.
/// </summary>
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<byte>(), message);
public static CommandResult Timeout() =>
new(false, 0x00, Array.Empty<byte>(), "Command timed out");
}
/// <summary>
/// The primary BLE service contract.
/// All table and device operations go through this interface.
/// The UI layer never touches BLE APIs directly.
/// </summary>
public interface IBleService : IDisposable
{
// ── State ────────────────────────────────────────────────────────────────
BleConnectionState ConnectionState { get; }
bool IsConnected { get; }
/// <summary>Observable connection state changes.</summary>
IObservable<BleConnectionState> ConnectionStateChanged { get; }
// ── Scanning ─────────────────────────────────────────────────────────────
/// <summary>Starts BLE advertisement scanning. Emits discovered devices.</summary>
IObservable<BleDeviceInfo> StartScan();
/// <summary>Stops active scan.</summary>
void StopScan();
// ── Connection ───────────────────────────────────────────────────────────
/// <summary>
/// Connects to a device. Handles GATT channel opening, NUS service
/// discovery, notification subscription, and the post-connect APP_READ_INFO.
/// </summary>
Task<bool> ConnectAsync(BleDeviceInfo device, CancellationToken ct = default);
/// <summary>Gracefully disconnects, stops diagnostics, cleans up GATT resources.</summary>
Task DisconnectAsync();
// ── Device info ──────────────────────────────────────────────────────────
/// <summary>
/// Reads ECU info (APP_READ_INFO). Returns null on timeout or failure.
/// Also sets the active GenerationConfig internally.
/// </summary>
Task<EcuInfo?> ReadEcuInfoAsync(CancellationToken ct = default);
// ── Auth ─────────────────────────────────────────────────────────────────
/// <summary>Sends unlock command with password and current date.</summary>
Task<CommandResult> UnlockAsync(string password, CancellationToken ct = default);
/// <summary>Sends tuner unlock command.</summary>
Task<CommandResult> UnlockTunerAsync(string password, CancellationToken ct = default);
// ── Table operations ─────────────────────────────────────────────────────
/// <summary>
/// Reads a 2D table (split read: two halves, with diagnostics pause/resume).
/// Returns the raw combined payload.
/// </summary>
Task<CommandResult> ReadTable2DAsync(
ushort address,
byte lengthBytes,
bool userTable = false,
CancellationToken ct = default);
/// <summary>Writes a 2D table (split write).</summary>
Task<CommandResult> WriteTable2DAsync(
ushort address,
byte[] data,
bool userTable = false,
CancellationToken ct = default);
/// <summary>Reads a 1D table.</summary>
Task<CommandResult> ReadTable1DAsync(
ushort address,
byte lengthBytes,
CancellationToken ct = default);
/// <summary>Writes a 1D table.</summary>
Task<CommandResult> WriteTable1DAsync(
ushort address,
byte[] data,
CancellationToken ct = default);
/// <summary>Reads a subtable.</summary>
Task<CommandResult> ReadSubTableAsync(
ushort address,
CancellationToken ct = default);
/// <summary>Writes a subtable.</summary>
Task<CommandResult> WriteSubTableAsync(
ushort address,
byte[] data,
CancellationToken ct = default);
/// <summary>Reads misc values block.</summary>
Task<CommandResult> ReadMiscAsync(
ushort address,
byte lengthBytes,
CancellationToken ct = default);
/// <summary>Writes misc values block.</summary>
Task<CommandResult> WriteMiscAsync(
ushort address,
byte[] data,
CancellationToken ct = default);
// ── Flash ────────────────────────────────────────────────────────────────
/// <summary>Sends APP_FLASH_WR to persist all writes to ECU flash.</summary>
Task<CommandResult> FlashWriteAsync(CancellationToken ct = default);
/// <summary>
/// Writes the 4-byte first-use settings block via APP_FIRSTUSE (0x35).
/// Byte[0] (DD slot) carries the TPS-calibration-done flag.
/// </summary>
Task<CommandResult> WriteFirstUseAsync(byte[] fourBytes, CancellationToken ct = default);
// ── Diagnostics streaming ────────────────────────────────────────────────
/// <summary>
/// Observable stream of diagnostics frames (APP_MONITORING 0x70).
/// Emits continuously while diagnostics are running.
/// </summary>
IObservable<DiagnosticsFrame> DiagnosticsFrames { get; }
bool DiagnosticsRunning { get; }
/// <summary>Sends APP_MON_START and begins emitting DiagnosticsFrames.</summary>
Task StartDiagnosticsAsync(CancellationToken ct = default);
/// <summary>
/// Sends APP_MON_STOP and waits for silence before returning.
/// Safe to call even if diagnostics aren't running.
/// </summary>
Task StopDiagnosticsAsync(CancellationToken ct = default);
// ── Keepalive ────────────────────────────────────────────────────────────
/// <summary>
/// Called by the keepalive timer. Sends APP_READ_INFO if idle for > 15s.
/// Internally managed — exposed for test visibility only.
/// </summary>
void OnKeepaliveTimer();
}
+168
View File
@@ -0,0 +1,168 @@
namespace TuneBoss.Core.BLE;
/// <summary>
/// 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).
/// </summary>
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<ParsedPacket> _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<byte> _dataBuffer = new();
private readonly List<byte> _csBuffer = new();
private byte _currDlCommand;
private byte _currDlSeqCount;
private byte _currDlDWordCount;
private byte _currTlResp;
private byte _currTlCommand;
private byte _currTlLength;
public PacketParser(Action<ParsedPacket> 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];
}
}
+368
View File
@@ -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;
/// <summary>
/// A fully in-memory <see cref="IBleService"/> 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).
/// </summary>
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<BleConnectionState> _state = new(BleConnectionState.Disconnected);
private readonly Subject<DiagnosticsFrame> _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<BleConnectionState> ConnectionStateChanged => _state.AsObservable();
// ── Scan ──────────────────────────────────────────────────────────────────
public IObservable<BleDeviceInfo> StartScan() => Observable.Create<BleDeviceInfo>(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<bool> 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<EcuInfo?> ReadEcuInfoAsync(CancellationToken ct = default) =>
Task.FromResult<EcuInfo?>(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<CommandResult> UnlockAsync(string password, CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(Array.Empty<byte>()));
public Task<CommandResult> UnlockTunerAsync(string password, CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(Array.Empty<byte>()));
// ── 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<CommandResult> 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<CommandResult> WriteTable2DAsync(ushort address, byte[] data,
bool userTable = false, CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(data));
// ── 1D tables ─────────────────────────────────────────────────────────────
public Task<CommandResult> 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);
}
/// <summary>8-byte TPS abs-bounds block: [absMax, absMin, store2, store3, ...].</summary>
private static byte[] TpsAbsBounds()
=> new byte[] { 195, 5, 197, 199, 201, 203, 205, 207 };
public Task<CommandResult> WriteTable1DAsync(ushort address, byte[] data,
CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(data));
// ── Subtables ─────────────────────────────────────────────────────────────
public Task<CommandResult> ReadSubTableAsync(ushort address, CancellationToken ct = default)
=> OkFramed(CanonicalSub(), Commands.APP_MEMRD_SUBT);
public Task<CommandResult> WriteSubTableAsync(ushort address, byte[] data,
CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(data));
// ── Misc ──────────────────────────────────────────────────────────────────
public Task<CommandResult> ReadMiscAsync(ushort address, byte lengthBytes,
CancellationToken ct = default)
=> OkFramed(CanonicalMisc(lengthBytes), Commands.APP_MEMRD_MISC);
public Task<CommandResult> WriteMiscAsync(ushort address, byte[] data,
CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(data));
// ── Flash ─────────────────────────────────────────────────────────────────
public Task<CommandResult> FlashWriteAsync(CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(Array.Empty<byte>()));
// ── First-use settings ──────────────────────────────────────────────────────
public Task<CommandResult> WriteFirstUseAsync(byte[] fourBytes, CancellationToken ct = default)
{
if (fourBytes is { Length: >= 1 })
SimTpsCalibrated = fourBytes[0] == TpsCalibration.CalDoneFlag;
return Task.FromResult(CommandResult.Ok(Array.Empty<byte>()));
}
// ── Diagnostics (the moving part) ─────────────────────────────────────────
public IObservable<DiagnosticsFrame> 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 ────────────────────────────────────────────────────
/// <summary>228-byte 2D combined payload: smooth fuel surface, realistic axes.</summary>
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
}
/// <summary>24-byte 1D table: monotonic axis + ramp values, unscaled.</summary>
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
}
/// <summary>40-byte subtable body (4×6) with a monotonic RPM/load axis so it parses cleanly.</summary>
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;
}
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>Wraps a data block in the 4-byte response header (51 cmd len 00).</summary>
private static Task<CommandResult> 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();
}
}
+7
View File
@@ -0,0 +1,7 @@
namespace TuneBoss.Core
{
public class Class1
{
}
}
+470
View File
@@ -0,0 +1,470 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using TuneBoss.Core.Models;
namespace TuneBoss.Core.IO;
/// <summary>
/// Reader/writer for the TuneBoss <c>.fsr</c> 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.
/// </summary>
public static class FsrFile
{
public const int FormatVersion = 1;
// ── Public data structures ──────────────────────────────────────────────
public sealed class FsrDocument
{
public FsrHeader Header { get; set; } = new();
public List<FsrSection> 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";
/// <summary>Any header keys not recognised — preserved on round-trip.</summary>
public Dictionary<string, string> 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; }
/// <summary>Raw field lines for Unknown sections / unrecognised keys.</summary>
public Dictionary<string, string> Extra { get; } = new(StringComparer.OrdinalIgnoreCase);
}
// ════════════════════════════════════════════════════════════════════════
// WRITE
// ════════════════════════════════════════════════════════════════════════
/// <summary>Serialises a document to .fsr text (with an optional whole-body sha256).</summary>
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<string, string>(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<string, string> 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<string, string> 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<string, string> 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<string, string> 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<string, string> 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<byte>();
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<byte>();
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();
}
}
+54
View File
@@ -0,0 +1,54 @@
using System.Threading.Tasks;
using TuneBoss.Core.Models;
namespace TuneBoss.Core.IO;
/// <summary>
/// Serializes / parses the <c>data</c> section of a map file — the space- and
/// <c>__</c>-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.
/// </summary>
public interface IMapTableCodec
{
/// <summary>
/// Ensures any device-backed state required to serialize the given type is loaded,
/// re-reading tables whose models are not cached. Called before <see cref="Serialize"/>
/// 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.
/// </summary>
Task PrepareAsync(MapSaveType saveType, int cylinderCount) => Task.CompletedTask;
/// <summary>Runs an on-hardware diagnostic of the user-table read path and returns a report.</summary>
Task<string> DiagnoseAsync() => Task.FromResult(string.Empty);
/// <summary>Serializes the current in-app table state into a map <c>data</c> section.</summary>
string Serialize(MapSaveType saveType, int cylinderCount);
/// <summary>
/// Writes the currently-applied content for the given save type to the ECU,
/// optionally flashing at the end. Returns a human-readable summary.
/// </summary>
Task<string> WriteLoadedAsync(MapSaveType saveType, int cylinderCount, bool flash,
IProgress<string>? progress = null)
=> throw new NotImplementedException("Write-to-ECU on load is not wired for this codec.");
/// <summary>Parses a map <c>data</c> section and applies it to the in-app table state.</summary>
void Deserialize(string data, MapSaveType saveType, int cylinderCount);
/// <summary>Rebuilds the editor nav trees from the current session layout
/// (used after an offline file establishes a layout, so entries exist to populate).</summary>
void RebuildNavTrees() { }
/// <summary>
/// Builds an FSR document from the currently-loaded editors. Walks loaded entries
/// directly and skips anything not loaded (never throws "not loaded").
/// </summary>
FsrFile.FsrDocument BuildFsrFromEditors(Models.EcuInfo? info, MapTag? tag, int cylinderCount);
/// <summary>Applies a parsed FSR document into the editors.</summary>
void ApplyFsr(FsrFile.FsrDocument doc);
}
+44
View File
@@ -0,0 +1,44 @@
using TuneBoss.Core.Models;
namespace TuneBoss.Core.IO;
/// <summary>
/// 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.
/// </summary>
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)}.");
}
}
+77
View File
@@ -0,0 +1,77 @@
using System.Security.Cryptography;
using System.Text;
namespace TuneBoss.Core.IO;
/// <summary>
/// The on-disk envelope of a TuneBoss <c>.tst</c> map file:
///
/// MD5(tag)_____tag\nMD5(data)_____data
///
/// Two records separated by a newline; each record is <c>MD5hex_____payload</c>.
/// The MD5 is upper-case hex with no separators (matching the legacy
/// <c>BitConverter.ToString(...).Replace("-","")</c>). On load, both digests are
/// recomputed and must match or the file is rejected as corrupt/tampered.
/// </summary>
public static class MapFile
{
public const string Extension = ".tst";
public const string RecordSep = "_____";
/// <summary>Upper-case, separator-free MD5 hex of a UTF-8 string.</summary>
public static string Md5Hex(string s)
{
var hash = MD5.HashData(Encoding.UTF8.GetBytes(s));
return Convert.ToHexString(hash); // upper-case, no separators
}
/// <summary>Builds the full file text from a tag string and a data string.</summary>
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);
}
/// <summary>
/// Parses and integrity-checks a file's full text. Splits on <c>\r\n</c> or
/// <c>\n</c>, separates each record on <c>_____</c>, and verifies both MD5s.
/// </summary>
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)..]);
}
}
+139
View File
@@ -0,0 +1,139 @@
using System.Text;
using TuneBoss.Core.Models;
namespace TuneBoss.Core.IO;
/// <summary>
/// Byte-exact serializer / parser for the table sections inside a <c>.tst</c> map's
/// data string. Replicates the legacy helpers verbatim:
///
/// 2D : <c>label__data__load__rpm__max min mult sign ____</c>
/// AFR : <c>label__data__load__rpm____</c> (no modifiers)
/// Sub : <c>label__data____</c> (24 data bytes)
/// 1D : <c>label__&lt;24 wire bytes&gt;____</c>
///
/// Every value is its unsigned decimal followed by a single space; <c>__</c> separates
/// fields within a section, <c>____</c> 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 <c>populateSubTable</c>.
/// </summary>
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();
}
/// <summary>Parses a space-separated decimal list into bytes (empties skipped).</summary>
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;
/// <summary>Generic named byte block (used for the misc regions). <c>label__&lt;bytes&gt;____</c>.</summary>
public static string SectionBytes(string label, byte[] data) =>
label + FieldSep + Bytes(data) + SectionSep;
/// <summary>Parses a <see cref="SectionBytes"/> block back into its raw bytes.</summary>
public static byte[] ParseBytesSection(string section)
{
var f = Fields(section);
return f.Length > 1 ? ParseBytes(f[1]) : Array.Empty<byte>();
}
// ── Section splitting ───────────────────────────────────────────────────────
/// <summary>Splits a data string into its <c>____</c>-terminated sections (positional).</summary>
public static string[] SplitSections(string data) =>
data.Split(SectionSep, StringSplitOptions.None);
private static string[] Fields(string section) =>
section.Split(FieldSep, StringSplitOptions.None);
/// <summary>The label of a section (its first field), for sanity checks.</summary>
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),
};
}
/// <summary>
/// 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.
/// </summary>
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;
/// <summary>Returns an array of exactly <paramref name="n"/> bytes (pad/truncate).</summary>
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;
}
}
+100
View File
@@ -0,0 +1,100 @@
using System.Text;
namespace TuneBoss.Core.IO;
/// <summary>
/// Which tables a saved map contains. Values match the legacy save-type codes.
/// </summary>
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
}
/// <summary>
/// The metadata header of a TuneBoss map file — the legacy "tag", 16 fields joined
/// by <c>___</c>:
/// 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 <c>___</c>.
/// </summary>
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";
/// <summary>Serializes to the <c>___</c>-joined legacy string.</summary>
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();
}
/// <summary>Parses a <c>___</c>-joined tag string. Tolerates a short mod section.</summary>
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),
};
}
}
+221
View File
@@ -0,0 +1,221 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// 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.
/// </summary>
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 ───────────────────────────────────────────────────────
/// <summary>192 bytes, row-major [row * 24 + col]. Wire value = AFR × 10.</summary>
public byte[] Data { get; init; } = new byte[DataBytes];
/// <summary>8 bytes — load axis (0–110).</summary>
public byte[] LoadAxis { get; init; } = new byte[Rows];
/// <summary>24 bytes — RPM axis, each × 100 = display RPM.</summary>
public byte[] RpmAxis { get; init; } = new byte[Cols];
// ── Modifiers [224–227] ───────────────────────────────────────────────────
/// <summary>Wire: maxAFR × 10. E.g. byte 150 = AFR 15.0.</summary>
public byte MaxRaw { get; init; }
/// <summary>Wire: minAFR × 10. E.g. byte 0 = AFR 0.0.</summary>
public byte MinRaw { get; init; }
public byte Mult { get; init; }
public byte Sign { get; init; }
// ── Derived display values ────────────────────────────────────────────────
public bool IsSigned => Sign > 0;
/// <summary>Display AFR value for a cell (wire byte ÷ 10.0).</summary>
public double GetCell(int row, int col)
{
byte raw = Data[row * Cols + col];
return IsSigned
? unchecked((sbyte)raw) / 10.0
: raw / 10.0;
}
/// <summary>Max AFR display value.</summary>
public double MaxAfrDisplay => IsSigned
? unchecked((sbyte)MaxRaw) / 10.0
: MaxRaw / 10.0;
/// <summary>Min AFR display value.</summary>
public double MinAfrDisplay => IsSigned
? unchecked((sbyte)MinRaw) / 10.0
: MinRaw / 10.0;
/// <summary>RPM axis in display units (raw × 100).</summary>
public int[] RpmValues => RpmAxis.Select(r => r * 100).ToArray();
/// <summary>Load axis values (raw, 0–110).</summary>
public int[] LoadValues => LoadAxis.Select(l => (int)l).ToArray();
// ── Serialisation ─────────────────────────────────────────────────────────
/// <summary>
/// Builds the combined 228-byte write payload.
/// Matches prepareAllData() / writeBtn_Click() in TuningTablePanelAFR.cs.
/// Modifier bytes [224–225] are stored as AFR × 10.
/// </summary>
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 ───────────────────────────────────────────────────────
/// <summary>
/// Parses a combined 228-byte buffer from two split read responses.
/// Matches sendReadSplitTableToPanelThread (AFR path) in Form1_TableHandling.cs.
/// </summary>
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],
};
}
/// <summary>
/// Assembles from two raw device response buffers (data starts at offset 4).
/// </summary>
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 ──────────────────────────────────────────────────────────────
/// <summary>
/// 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.
/// </summary>
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 ──────────────────────────────────────────────────────────
/// <summary>
/// Returns modifier bytes as stored on wire.
/// MaxRaw/MinRaw are AFR × 10; Mult/Sign are unchanged.
/// </summary>
public byte[] ToModifierBytes() => new[]
{
MaxRaw, MinRaw, Mult, Sign
};
/// <summary>
/// Builds modifier bytes from display AFR values for writing.
/// Matches: modifiersInArray[0] = (byte)(maxRawVal * 10.0)
/// </summary>
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
};
}
+109
View File
@@ -0,0 +1,109 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// 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.
/// </summary>
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<byte, (string Make, Dictionary<int, string> 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 ───────────────────────────────────────────────────────────────
/// <summary>Returns the manufacturer name, or empty string if unknown.</summary>
public static string GetMake(byte makeCode)
=> _registry.TryGetValue(makeCode, out var entry) ? entry.Make : string.Empty;
/// <summary>Returns the model name, or empty string if unknown.</summary>
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;
}
/// <summary>Returns "Make — Model" display string, e.g. "Yamaha — Y15ZR 2019".</summary>
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}";
}
/// <summary>All registered manufacturers.</summary>
public static IEnumerable<(byte Code, string Name)> AllMakes
=> _registry.Select(kv => (kv.Key, kv.Value.Make));
/// <summary>All models for a given manufacturer code.</summary>
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)>();
}
+417
View File
@@ -0,0 +1,417 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// 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
/// </summary>
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;
/// <summary>Parsed error flags — ready to drive the 16-indicator error panel.</summary>
public ErrorFlags Errors => ErrorFlags.From(this);
// ── Parser ────────────────────────────────────────────────────────────────
/// <summary>
/// Parses a raw diagnostics frame payload.
/// <paramref name="data"/> is the full BLE packet payload starting at byte [0] = 0x70.
/// Byte indices in comments refer to the payload array as used in UpdateDiagLabel().
/// </summary>
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 ────────────────────────────────────────────────────────
/// <summary>
/// Returns a CSV log row matching the format in UpdateDiagLabel().
/// Columns match the .tbd log format used by TracBoss.
/// </summary>
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,
}
/// <summary>
/// Diagnostics tracker coordinates for highlighting the active cell
/// in a tuning table grid. Produced by getRpmToHighlight/getLoadToHighlight.
/// </summary>
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
/// <summary>
/// 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
/// </summary>
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;
/// <summary>All 16 error channels in display order (analog first, then output).</summary>
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;
}
}
/// <summary>
/// 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)
/// </summary>
public enum ErrorStatus
{
Clear,
Persistent,
Active,
}
+190
View File
@@ -0,0 +1,190 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// Parsed response from APP_READ_INFO (0x37).
/// Immutable — constructed once per successful read.
/// </summary>
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;
/// <summary>
/// Dual injector is a Stage 3 feature — the same nibble the Android app reads as
/// <c>Upgrade_Stage3</c>, so it follows the stage rather than being an independent flag.
/// </summary>
public bool IsDualInjectorUnlocked => Stage >= 3;
/// <summary>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.</summary>
public bool HasTpsCalibration => FirstUseInfo1 == TpsCalibration.CalDoneFlag;
/// <summary>
/// Legacy <c>Upgrade_Stage2</c> — high nibble of the shift/stage byte
/// (legacy <c>buf[offset+42] &amp; 0xF0</c>, whose low nibble is Shift Auto).
/// </summary>
public byte UpgradeStage2 => (byte)(UpgradeShiftAuto & 0xF0);
/// <summary>
/// Legacy <c>Upgrade_Stage3</c> — low nibble of the next byte
/// (legacy <c>buf[offset+43] &amp; 0x0F</c>; the WPF parser stores that byte
/// as <see cref="UpgradeLogImmo"/>).
/// </summary>
public byte UpgradeStage3 => (byte)(UpgradeLogImmo & 0x0F);
/// <summary>
/// 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).
/// </summary>
public int Stage =>
UpgradeStage3 > 0 ? 3 :
UpgradeStage2 > 0 ? 2 : 1;
/// <summary>True when the stage exposes the user 24×8 adjust tables (Stage 2+).</summary>
public bool HasUserAdjustTables => Stage >= 2;
// ── Parser ───────────────────────────────────────────────────────────────
/// <summary>
/// Parses a raw APP_READ_INFO response buffer.
/// Buffer[0] must be APP_CMD_SUCCESS (0x51); payload starts at byte 4.
/// </summary>
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}"));
}
+79
View File
@@ -0,0 +1,79 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// 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.
/// </summary>
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;
/// <summary>
/// True when the session has been fully loaded —
/// i.e. all tables available for this device have been read.
/// </summary>
public bool IsFullyLoaded { get; init; }
// ── Mutation helpers ──────────────────────────────────────────────────────
/// <summary>Returns a new session with Fuel_PulseWidth1 replaced.</summary>
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 };
}
}
+302
View File
@@ -0,0 +1,302 @@
using TuneBoss.Core.Protocol;
namespace TuneBoss.Core.Models;
/// <summary>
/// Describes a single memory region on the device — its address and read length.
/// </summary>
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 };
/// <summary>True if this region exists (address != 0x0000 or explicit availability flag).</summary>
public bool IsAvailable { get; init; } = true;
public static MemoryRegion Unavailable => new(0x0000, 0) { IsAvailable = false };
}
/// <summary>
/// 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
/// </summary>
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
// ════════════════════════════════════════════════════════════════════════
/// <summary>
/// Constructs the complete memory layout from parsed EcuInfo.
/// This is the single entry point — call once after ReadEcuInfoAsync().
/// </summary>
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 ──────────────────────────────────────────────────────────
/// <summary>
/// Returns all available 1D table regions in index order.
/// Skips Unavailable entries (FW-gated tables not present on this device).
/// </summary>
public IEnumerable<(int Index, MemoryRegion Region)> Available1DTables =>
OneDimTables
.Select((r, i) => (i, r))
.Where(x => x.r.IsAvailable);
}
+34
View File
@@ -0,0 +1,34 @@
namespace TuneBoss.Core.Models;
/// <summary>How a sub-field of a settings byte is edited.</summary>
public enum MiscEditorKind
{
Flag, // single bit → checkbox
Enum, // bit range → combo (Options indexed by value)
Number, // bit range → numeric 0..(mask>>shift)
}
/// <summary>
/// One sub-field occupying a contiguous bit range of a byte.
/// Value = (byte &amp; Mask) >> shift(Mask); written back masked.
/// </summary>
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
{
/// <summary>Human-readable label: underscores → spaces, shortforms expanded.</summary>
public string DisplayText => MiscDisplayText.For(Label);
}
/// <summary>
/// Decomposition of a single settings byte into bit sub-fields, plus optional
/// inter-bit constraints (bit indices 0..7).
/// </summary>
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
+228
View File
@@ -0,0 +1,228 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// 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).
/// </summary>
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<MiscByteSpec> 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),
}),
};
/// <summary>Lookup a spec by block + field label, or null.</summary>
public static MiscByteSpec? Find(MiscBlock block, string label)
{
foreach (var s in All)
if (s.Block == block && s.FieldLabel == label) return s;
return null;
}
}
+120
View File
@@ -0,0 +1,120 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// Converts raw config field identifiers into human-readable display text:
/// underscores become spaces, and engineering shortforms expand to their meaning
/// (e.g. <c>RPM_Limit_div100</c> → "RPM Limit (divided by 100)",
/// <c>Fuel_Max_PW_Mult</c> → "Fuel Max Pulse Width Multiplier").
/// Unknown tokens pass through unchanged, so new fields degrade gracefully.
/// </summary>
public static class MiscDisplayText
{
// Case-insensitive single-token expansions.
private static readonly Dictionary<string, string> 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<string, string> 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<string, string> Cache = new();
/// <summary>Display text for a raw field identifier.</summary>
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<string>(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;
}
}
+349
View File
@@ -0,0 +1,349 @@
namespace TuneBoss.Core.Models;
/// <summary>Which raw misc block a field lives in.</summary>
public enum MiscBlock { Core, LaunchFuel, LaunchFuel2, AuxOut, Extended }
/// <summary>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).</summary>
public sealed record MiscField(string Section, string Label, MiscBlock Block, int Index)
{
/// <summary>Human-readable label: underscores → spaces, shortforms expanded.</summary>
public string DisplayText => MiscDisplayText.For(Label);
}
public static class MiscFieldRegistry
{
public static readonly IReadOnlyList<MiscField> 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),
};
}
+482
View File
@@ -0,0 +1,482 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// 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.
/// </summary>
public sealed class MiscValues
{
// ── Raw memory regions ───────────────────────────────────────────────────
public byte[] Core { get; init; } = new byte[136];
public byte[] LaunchFuel { get; init; } = Array.Empty<byte>();
public byte[] LaunchFuel2 { get; init; } = Array.Empty<byte>();
public byte[] AuxOut { get; init; } = Array.Empty<byte>();
public byte[] Extended { get; init; } = Array.Empty<byte>();
// ════════════════════════════════════════════════════════════════════════
// 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<byte>();
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<byte>(),
};
}
/// <summary>
/// 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 &amp; 0x80) != 0 → full extended set (0x97 = 152 bytes)
/// otherwise → up to Ex(115) (0x73 = 116 bytes)
/// </summary>
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;
}
/// <summary>
/// Bike cylinder classification — determines Extended region size.
/// Derived from EcuInfo via TwoCylinderRegistry.
/// </summary>
public enum EcuVariant
{
SingleCylinder, // Y15, NVX etc. — Extended = 0x29
TwoCylinder, // R25, R3, MT25 — Extended = 0x73
TwoCylinderR15, // R15M, CBR250RR — Extended = 0x97
}
+39
View File
@@ -0,0 +1,39 @@
using System;
namespace TuneBoss.Core.Models
{
/// <summary>
/// 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).
/// </summary>
public static class OneDimDisplay
{
/// <summary>0/1 => 1; otherwise the multiplier itself.</summary>
public static int EffectiveMultiplier(int multiplier) => multiplier < 1 ? 1 : multiplier;
/// <summary>Raw byte value → displayed value.</summary>
public static long ToDisplay(int raw, int multiplier) =>
(long)raw * EffectiveMultiplier(multiplier);
/// <summary>
/// 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.
/// </summary>
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;
}
}
}
+127
View File
@@ -0,0 +1,127 @@
using System;
namespace TuneBoss.Core.Models
{
/// <summary>
/// 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.
/// </summary>
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];
}
/// <summary>Decode a 24-byte block (e.g. the data section of a 0x51 0x43 response).</summary>
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;
}
/// <summary>Produce the 24-byte data block to send with APP_MEMWR_1D.</summary>
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);
}
}
+102
View File
@@ -0,0 +1,102 @@
using System.Collections.Generic;
namespace TuneBoss.Core.Models
{
public enum OneDimGroup
{
SensorCalibration,
FuelCompensation,
SparkCompensation,
IdleControl,
TractionControl,
Quickshifter,
Nitrous,
OutputsAndHardware,
}
/// <summary>
/// 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.
/// </summary>
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<OneDimTableDefinition> 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"),
};
/// <summary>Nav-tree order for the groups.</summary>
public static readonly IReadOnlyList<OneDimGroup> 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(),
};
}
}
+182
View File
@@ -0,0 +1,182 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// 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()
/// </summary>
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 ───────────────────────────────────────────────────────
/// <summary>
/// 24 bytes — cell data, row-major [row * 6 + col].
/// Always signed sbyte on wire (stored as byte, interpreted as sbyte).
/// </summary>
public byte[] Data { get; init; } = new byte[DataBytes];
/// <summary>4 bytes — load axis values. Default: {5, 15, 40, 70}.</summary>
public byte[] LoadAxis { get; init; } = (byte[])DefaultLoadAxis.Clone();
/// <summary>
/// 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).
/// </summary>
public byte[] RpmAxis { get; init; } = new byte[RpmBytes];
// ── Derived display values ────────────────────────────────────────────────
/// <summary>
/// Gets the signed display value for a data cell.
/// SubTable cells are always sbyte — matches Convert.ToSByte() in the UI.
/// </summary>
public int GetCell(int row, int col) =>
unchecked((sbyte)Data[row * Cols + col]);
/// <summary>Low RPM bound for a column (display units).</summary>
public int GetRpmLo(int col) => RpmAxis[col * 2] * 100;
/// <summary>High RPM bound for a column (display units).</summary>
public int GetRpmHi(int col) => RpmAxis[col * 2 + 1] * 100;
/// <summary>Load axis value for a row (raw, 0–110).</summary>
public int GetLoad(int row) => LoadAxis[row];
// ── Deserialisation ───────────────────────────────────────────────────────
/// <summary>
/// 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
/// </summary>
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,
};
}
/// <summary>
/// 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.
/// </summary>
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 ─────────────────────────────────────────────────────────
/// <summary>
/// Returns the data-only write payload (24 bytes).
/// Matches writeSubTableFunctionThread: only dataOutArray is sent,
/// no RPM/load arrays on write.
/// </summary>
public byte[] ToWirePayload() => (byte[])Data.Clone();
/// <summary>
/// Full 40-byte payload including load and RPM axes.
/// Used when full round-trip serialisation is needed.
/// </summary>
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 ──────────────────────────────────────────────────────────────
/// <summary>
/// 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.
/// </summary>
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,
};
}
}
+158
View File
@@ -0,0 +1,158 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// 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);
/// </summary>
public static class TableTracker
{
/// <summary>
/// Finds the highlight and adjacent indices for a live value against an axis array.
/// </summary>
/// <param name="axis">The table axis (RPM ÷100 bytes or load bytes).</param>
/// <param name="value">The live sensor value in the same units as the axis.</param>
/// <returns>
/// (highlight, adjacent) where -1 means "out of range on that side".
/// </returns>
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);
}
}
/// <summary>
/// Produces a <see cref="DiagnosticsTracker"/> for a tuning table from live frame data.
/// </summary>
/// <param name="rpmAxis">Table RPM axis (raw bytes, each × 100 = RPM).</param>
/// <param name="loadAxis">Table load axis (raw bytes).</param>
/// <param name="rpmRaw">Live RPM raw value from DiagnosticsFrame.RPM_Raw.</param>
/// <param name="loadValue">Live load/TPS value — use frame.Load for main tables,
/// frame.TPS_Percent for user-adjust tables.</param>
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);
}
/// <summary>
/// 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.
/// </summary>
public static IReadOnlyDictionary<string, DiagnosticsTracker> CalculateAll(
EcuSession session,
DiagnosticsFrame frame)
{
var result = new Dictionary<string, DiagnosticsTracker>();
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 ───────────────────────────────────────────────────────────────
/// <summary>
/// Integer midpoint of two adjacent axis values.
/// Matches (rpmArrayRef[i] + rpmArrayRef[i+1]) / 2 in the original code.
/// Uses integer division — no rounding.
/// </summary>
private static byte Midpoint(byte[] axis, int i, int j)
=> (byte)((axis[i] + axis[j]) / 2);
}
+101
View File
@@ -0,0 +1,101 @@
using TuneBoss.Core.Protocol;
namespace TuneBoss.Core.Models;
/// <summary>
/// Throttle-position-sensor calibration rules, resolved verbatim from the legacy
/// WinForms (<c>saveUserReadInfo</c> / TPS page) and Android (<c>TpsCalPage</c> /
/// <c>BtApp.sendTpsCalWrite</c>) sources.
///
/// The calibration captures the raw TPS ADC (<see cref="DiagnosticsFrame.TPS_Raw"/>,
/// 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.
/// </summary>
public static class TpsCalibration
{
public readonly record struct Addresses(
ushort CalWrite,
ushort AbsBounds,
ushort AdvSettings,
bool AdvSupported);
/// <summary>Minimum firmware that exposes the advanced TPS settings byte.</summary>
public const int AdvMinFirmware = 152;
/// <summary>Number of full open/close sweeps the guide asks the tuner to perform.</summary>
public const int RequiredSweeps = 5;
/// <summary>
/// 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.
/// </summary>
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;
/// <summary>Resolves the calibration addresses for a generation + firmware.</summary>
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),
};
/// <summary>Convenience overload resolving the generation from <see cref="EcuInfo"/>.</summary>
public static Addresses For(EcuInfo info) =>
For((GenerationType)info.AppInfoVersion, info.FwVersion);
/// <summary>
/// Builds the 8-byte 1D calibration payload exactly as the legacy
/// <c>sendTpsCalWrite</c> 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.
/// </summary>
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
}
/// <summary>
/// Replicates the legacy acceptance test against the absolute bounds read from
/// <see cref="Addresses.AbsBounds"/> ([0] = absMax, [1] = absMin).
/// </summary>
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}.",
};
}
+232
View File
@@ -0,0 +1,232 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// 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)
/// </summary>
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 ───────────────────────────────────────────────────────
/// <summary>192 bytes, row-major [row * 24 + col].</summary>
public byte[] Data { get; init; } = new byte[DataBytes];
/// <summary>8 bytes — load axis values (0–110).</summary>
public byte[] LoadAxis { get; init; } = new byte[Rows];
/// <summary>24 bytes — RPM axis, each × 100 = actual RPM.</summary>
public byte[] RpmAxis { get; init; } = new byte[Cols];
// ── Modifiers (bytes 224–227) ─────────────────────────────────────────────
/// <summary>Raw max value from device (index [0] in modifiersInArray).</summary>
public byte MaxRaw { get; init; }
/// <summary>Raw min value from device (index [1] in modifiersInArray).</summary>
public byte MinRaw { get; init; }
/// <summary>Multiplier for display scaling (index [2]).</summary>
public byte Mult { get; init; }
/// <summary>Sign flag: 0 = unsigned byte, >0 = signed sbyte (index [3]).</summary>
public byte Sign { get; init; }
// ── Derived display values ────────────────────────────────────────────────
public bool IsSigned => Sign > 0;
/// <summary>Display min — sbyte if signed, byte if unsigned.</summary>
public int MinDataVal => IsSigned
? unchecked((sbyte)MinRaw)
: (int)MinRaw;
/// <summary>Display max — sbyte if signed, byte if unsigned.</summary>
public int MaxDataVal => IsSigned
? unchecked((sbyte)MaxRaw)
: (int)MaxRaw;
/// <summary>
/// Gets the display value for a cell.
/// Applies sign interpretation matching UpdateTable(readCmd=1) in TuningTablePanel.
/// </summary>
public int GetCell(int row, int col) =>
IsSigned
? unchecked((sbyte)Data[row * Cols + col])
: Data[row * Cols + col];
/// <summary>RPM axis values in display units (raw × 100).</summary>
public int[] RpmValues => RpmAxis.Select(r => r * 100).ToArray();
/// <summary>Load axis values (raw, 0–110 range).</summary>
public int[] LoadValues => LoadAxis.Select(l => (int)l).ToArray();
/// <summary>
/// 7-band color range thresholds, matching setDataValRange() in TuningTablePanel.
/// dataValRange[x] = minDataVal + (x * (maxDataVal - minDataVal)) / 7
/// </summary>
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) ────────────────────────────────────────────
/// <summary>
/// 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
/// </summary>
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;
}
/// <summary>First 128 bytes of the payload — sent as part 1 of split write.</summary>
public byte[] ToWirePayloadPart1() => ToWirePayload()[..( SplitFirstLength + 1)];
/// <summary>Remaining bytes — sent as part 2 of split write.</summary>
public byte[] ToWirePayloadPart2() => ToWirePayload()[(SplitFirstLength + 1)..];
// ── Deserialisation (read path) ───────────────────────────────────────────
/// <summary>
/// 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]
/// </summary>
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,
};
}
/// <summary>
/// Assembles the combined payload from the two raw device response buffers.
/// Each response buffer has a 4-byte header; data starts at offset 4.
/// </summary>
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) ────────────────────────────────
/// <summary>
/// Returns a new TuningTable with the cell at (row, col) adjusted by delta,
/// clamped to [MinDataVal, MaxDataVal].
/// </summary>
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,
};
}
}
@@ -0,0 +1,68 @@
using System.Xml.Linq;
namespace TuneBoss.Core.Models;
/// <summary>
/// Determines whether a bike is a two-cylinder model based on
/// manufacturer + model code, driven by twoCylModels.xml.
/// </summary>
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<byte, HashSet<uint>> _models = new();
private TwoCylinderRegistry() { }
/// <summary>
/// Loads from a twoCylModels.xml file path.
/// </summary>
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;
}
/// <summary>
/// Loads from an XML string (useful for embedding or testing).
/// </summary>
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;
}
}
+114
View File
@@ -0,0 +1,114 @@
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace TuneBoss.Core.Models;
/// <summary>
/// Which bike models have VVA (variable valve actuation), so the RPM Settings page can
/// gate the VVA RPM Trigger. Mirrors the legacy <c>vvaModels.xml</c> / <c>checkVvaModels</c>.
///
/// The list is loaded from an EDITABLE external file at
/// <c>%APPDATA%\TuneBoss\vvaModels.xml</c> 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): &lt;vvaModels&gt;&lt;ym&gt;14&lt;/ym&gt;…&lt;hn&gt;…&lt;/hn&gt;
/// &lt;su&gt;…&lt;/su&gt;&lt;kw&gt;…&lt;/kw&gt;&lt;/vvaModels&gt;.
/// Element → manufacturer code: ym=1 Yamaha, hn=2 Honda, kw=3 Kawasaki, su=6 Suzuki.
/// </summary>
public static class VvaModelRegistry
{
private static readonly object _lock = new();
private static Dictionary<byte, HashSet<byte>>? _map;
/// <summary>Editable list file. Sits beside settings.json in %APPDATA%\TuneBoss.</summary>
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<byte, HashSet<byte>> Defaults() => new()
{
[1] = new HashSet<byte> { 14, 17, 21, 22 },
};
/// <summary>True when the given make/model is known to have VVA.</summary>
public static bool IsVvaModel(byte manufacturer, byte model)
{
var map = EnsureLoaded();
return map.TryGetValue(manufacturer, out var models) && models.Contains(model);
}
/// <summary>Force a re-read of the file on the next lookup (call after editing it).</summary>
public static void Reload()
{
lock (_lock) { _map = null; }
}
private static Dictionary<byte, HashSet<byte>> 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<byte, HashSet<byte>> Parse(XDocument doc)
{
var map = new Dictionary<byte, HashSet<byte>>();
foreach (var (elem, mfr) in Makes)
{
var set = new HashSet<byte>();
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 */ }
}
}
+73
View File
@@ -0,0 +1,73 @@
namespace TuneBoss.Core.Protocol;
/// <summary>
/// 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.
/// </summary>
public static class ChecksumHelper
{
/// <summary>
/// Computes the DWord checksum over a byte span.
/// The span length must be a multiple of 4 (pad before calling if needed).
/// </summary>
public static uint GenChecksumDW(ReadOnlySpan<byte> 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
}
/// <summary>
/// Writes the 4-byte little-endian checksum into <paramref name="dest"/>.
/// </summary>
public static void WriteChecksumDW(ReadOnlySpan<byte> data, Span<byte> dest)
{
uint cs = GenChecksumDW(data);
dest[0] = (byte)(cs);
dest[1] = (byte)(cs >> 8);
dest[2] = (byte)(cs >> 16);
dest[3] = (byte)(cs >> 24);
}
/// <summary>
/// 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 ✓
/// </summary>
public static byte HeaderInverseSum(byte tlType, byte seqNum, byte dwCount)
=> unchecked((byte)(0xFF - (tlType + seqNum + dwCount)));
/// <summary>
/// Verifies an inbound packet's DWord checksum.
/// The last 4 bytes of <paramref name="payload"/> are the checksum;
/// the preceding bytes are the data.
/// </summary>
public static bool VerifyChecksumDW(ReadOnlySpan<byte> 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);
}
}
+78
View File
@@ -0,0 +1,78 @@
namespace TuneBoss.Core.Protocol;
/// <summary>
/// TuneBoss hardware command bytes.
/// </summary>
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;
}
+135
View File
@@ -0,0 +1,135 @@
namespace TuneBoss.Core.Protocol;
/// <summary>
/// Hardware/firmware generation, discriminated by App_Info_Version byte.
/// </summary>
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
}
/// <summary>
/// Per-generation command bytes and misc memory addresses resolved after
/// reading App_Info_Version from the device.
/// </summary>
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")
};
/// <summary>
/// Resolves generation from the App_Info_Version byte on the wire.
/// </summary>
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}")
};
}
+163
View File
@@ -0,0 +1,163 @@
namespace TuneBoss.Core.Protocol;
/// <summary>
/// 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)
/// </summary>
public static class PacketBuilder
{
private static readonly byte[] Preamble = { 0xFF, 0x00, 0xFF, 0x00 };
// ── Outbound ─────────────────────────────────────────────────────────────
/// <summary>
/// Builds a complete outbound packet.
/// </summary>
/// <param name="tlType">Transport layer type (TL_NONPOSTED, TL_STREAMING etc.)</param>
/// <param name="seqNum">Sequence number. Use 0 for streaming commands.</param>
/// <param name="data">Command payload. Will be zero-padded to DWord boundary.</param>
public static byte[] Build(byte tlType, byte seqNum, ReadOnlySpan<byte> 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;
}
/// <summary>
/// Convenience: builds a TL_NONPOSTED packet with a single command byte
/// and optional parameters, auto-padded.
/// </summary>
public static byte[] BuildNonPosted(byte seqNum, byte command, ReadOnlySpan<byte> parameters = default)
{
byte[] payload = new byte[1 + parameters.Length];
payload[0] = command;
parameters.CopyTo(payload.AsSpan(1));
return Build(Commands.TL_NONPOSTED, seqNum, payload);
}
/// <summary>
/// Convenience: builds a TL_STREAMING packet (always seq=0).
/// </summary>
public static byte[] BuildStreaming(byte command)
{
return Build(Commands.TL_STREAMING, seqNum: 0, data: new[] { command });
}
/// <summary>
/// Builds an APP_MON_START (0x71) streaming packet.
/// </summary>
public static byte[] BuildMonStart() => BuildStreaming(Commands.APP_MON_START);
/// <summary>
/// Builds an APP_MON_STOP (0x72) streaming packet.
/// </summary>
public static byte[] BuildMonStop() => BuildStreaming(Commands.APP_MON_STOP);
/// <summary>
/// Builds an APP_READ_INFO (0x37) request.
/// Data = [0x37, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] — 2 DWords.
/// Verified: log line 5–7.
/// </summary>
public static byte[] BuildReadInfo(byte seqNum)
=> BuildNonPosted(seqNum, Commands.APP_READ_INFO, new byte[7]);
// ── Inbound ──────────────────────────────────────────────────────────────
/// <summary>
/// Result of parsing an inbound packet.
/// </summary>
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<byte>(); // Full payload excl. checksum
public bool ChecksumValid { get; init; }
}
/// <summary>
/// Parses a raw inbound frame received over BLE.
/// Returns null if the preamble is missing or the frame is too short.
/// </summary>
public static InboundPacket? Parse(ReadOnlySpan<byte> 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 ──────────────────────────────────────────────────
/// <summary>
/// Returns true if a raw frame is a diagnostics streaming packet (0x70).
/// Fast check without full parse — used in the hot receive path.
/// </summary>
public static bool IsDiagnosticsFrame(ReadOnlySpan<byte> frame)
=> frame.Length >= 9
&& frame[4] == Commands.TL_STREAMING
&& frame[8] == Commands.APP_MONITORING;
}
+15
View File
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0-windows10.0.19041.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Reactive" Version="6.0.1" />
</ItemGroup>
<ItemGroup>
<Folder Include="BLE\" />
<Folder Include="Models\" />
<Folder Include="Protocol\" />
</ItemGroup>
</Project>
+4
View File
@@ -0,0 +1,4 @@
<Solution>
<Project Path="TuneBoss.Core/TuneBoss.Core.csproj" />
<Project Path="TuneBossPC/TuneBossPC.csproj" />
</Solution>
+22
View File
@@ -0,0 +1,22 @@
<Application
x:Class="TuneBossPC.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:conv="clr-namespace:TuneBossPC.Converters">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Assets/Styles/Colors.xaml" />
<ResourceDictionary Source="Assets/Styles/Typography.xaml" />
<ResourceDictionary Source="Assets/Styles/Controls.xaml" />
</ResourceDictionary.MergedDictionaries>
<!-- Global converters -->
<conv:ErrorStatusToBrushConverter x:Key="ErrToBrush" />
<conv:ErrorStatusToForegroundConverter x:Key="ErrToFg" />
<conv:CrankStateToBrushConverter x:Key="CrankToBrush" />
</ResourceDictionary>
</Application.Resources>
</Application>
+81
View File
@@ -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<IBleService, SimBleService>();
else
services.AddSingleton<IBleService, BleManager>();
services.AddSingleton<IAuthService, AuthService>();
services.AddSingleton<ISettingsService, SettingsService>();
services.AddSingleton<ISessionService, SessionService>();
services.AddSingleton<INavigationService, NavigationService>();
services.AddSingleton<ISnackbarService, SnackbarService>();
services.AddSingleton<MainWindow>();
services.AddSingleton<DiagnosticsStripViewModel>();
services.AddSingleton<MainWindowViewModel>();
services.AddTransient<ConnectView>();
services.AddTransient<ConnectViewModel>();
services.AddTransient<DiagnosticsView>();
services.AddTransient<DiagnosticsViewModel>();
services.AddSingleton<TuningTablesView>();
services.AddSingleton<TuningTablesViewModel>();
services.AddSingleton<MiscValuesView>();
services.AddSingleton<MiscValuesViewModel>();
services.AddSingleton<OneDimTablesView>();
services.AddSingleton<OneDimTablesViewModel>();
services.AddSingleton<RpmSettingsView>();
services.AddSingleton<RpmSettingsViewModel>();
services.AddTransient<TpsCalView>();
services.AddTransient<TpsCalViewModel>();
services.AddSingleton<FilesView>();
services.AddTransient<SettingsView>();
services.AddTransient<SettingsViewModel>();
services.AddSingleton<FilesViewModel>();
services.AddSingleton<TuneBoss.Core.IO.IMapTableCodec, MapTableCodec>();
}
protected override async void OnStartup(StartupEventArgs e)
{
await _host.StartAsync();
Wpf.Ui.Appearance.ApplicationThemeManager.Apply(
Wpf.Ui.Appearance.ApplicationTheme.Dark);
var mainWindow = _host.Services.GetRequiredService<MainWindow>();
mainWindow.Show();
base.OnStartup(e);
}
protected override async void OnExit(ExitEventArgs e)
{
await _host.StopAsync();
_host.Dispose();
base.OnExit(e);
}
public static T GetService<T>() where T : class
=> (Current as App)!._host.Services.GetRequiredService<T>();
}
+82
View File
@@ -0,0 +1,82 @@
using System.Reflection;
namespace TuneBossPC;
/// <summary>
/// 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 &lt;Version&gt;.
/// </summary>
public static class AppInfo
{
/// <summary>e.g. "v1.0.0.7" (ClickOnce publish) or "v2026.8.13" (assembly fallback).</summary>
public static string Version { get; } = ResolveVersion();
/// <summary>
/// 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
/// <c>-p:Dealer=true</c>, or a publish profile that sets &lt;Dealer&gt;true&lt;/Dealer&gt;)
/// to produce the dealer build; a normal build shows everything.
/// </summary>
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 <Version>).
var asm = Assembly.GetExecutingAssembly();
var info = asm.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.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
}
}
}
+10
View File
@@ -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)
)]
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+67
View File
@@ -0,0 +1,67 @@
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<!--
TuneBoss PC Color System
Dark instrument panel aesthetic — inspired by motorsport ECU software.
Base: deep charcoal (not pure black), accent: TuneBoss orange.
Contrast targets (vs Surface2 card bg): primary ≥ 14:1, secondary ≥ 7:1.
Tuned for legibility at arm's length in a workshop / dyno room.
-->
<!-- ── Surfaces ──────────────────────────────────────────────────────── -->
<Color x:Key="Surface0Color">#FF111416</Color> <!-- deepest bg — window -->
<Color x:Key="Surface1Color">#FF1A1D21</Color> <!-- panel bg -->
<Color x:Key="Surface2Color">#FF22262B</Color> <!-- card / groupbox bg -->
<Color x:Key="Surface3Color">#FF2C3036</Color> <!-- elevated / hover -->
<Color x:Key="BorderColor">#FF4A505A</Color> <!-- borders (raised for visibility) -->
<Color x:Key="InputBackgroundColor">#FF16191D</Color> <!-- text/combo wells -->
<!-- ── Brand accent ───────────────────────────────────────────────────── -->
<Color x:Key="AccentColor">#FFFF6B00</Color> <!-- TuneBoss orange -->
<Color x:Key="AccentDimColor">#FF994000</Color> <!-- dimmed / inactive -->
<Color x:Key="AccentGlowColor">#33FF6B00</Color> <!-- glow halo -->
<!-- ── Text ──────────────────────────────────────────────────────────── -->
<Color x:Key="TextPrimaryColor">#FFF4F6F8</Color> <!-- primary text -->
<Color x:Key="TextSecondaryColor">#FFB4BAC4</Color> <!-- labels, captions (was #8B9099) -->
<Color x:Key="TextDisabledColor">#FF6E7580</Color> <!-- disabled (was #4A5059) -->
<Color x:Key="TextAccentColor">#FFFF7D1F</Color> <!-- highlighted values -->
<!-- ── Status ─────────────────────────────────────────────────────────── -->
<Color x:Key="StatusGreenColor">#FF3DDC84</Color> <!-- connected / OK -->
<Color x:Key="StatusRedColor">#FFFF4D4D</Color> <!-- error / fault -->
<Color x:Key="StatusYellowColor">#FFFFD11A</Color> <!-- warning / persistent -->
<Color x:Key="StatusBlueColor">#FF4C90FF</Color> <!-- info -->
<!-- ── Heatmap (matches aracer-style: blue → cyan → green → yellow) ─── -->
<Color x:Key="HeatLow1">#FF0050B4</Color> <!-- cold — blue -->
<Color x:Key="HeatLow2">#FF0096C8</Color> <!-- blue-cyan -->
<Color x:Key="HeatMid1">#FF00C8C8</Color> <!-- cyan -->
<Color x:Key="HeatMid2">#FF50C850</Color> <!-- cyan-green -->
<Color x:Key="HeatHigh1">#FF96DC00</Color> <!-- yellow-green -->
<Color x:Key="HeatHigh2">#FFDCDC00</Color> <!-- yellow -->
<!-- ── Solid brushes ─────────────────────────────────────────────────── -->
<SolidColorBrush x:Key="Surface0Brush" Color="{StaticResource Surface0Color}" />
<SolidColorBrush x:Key="Surface1Brush" Color="{StaticResource Surface1Color}" />
<SolidColorBrush x:Key="Surface2Brush" Color="{StaticResource Surface2Color}" />
<SolidColorBrush x:Key="Surface3Brush" Color="{StaticResource Surface3Color}" />
<SolidColorBrush x:Key="BorderBrush" Color="{StaticResource BorderColor}" />
<SolidColorBrush x:Key="InputBackgroundBrush" Color="{StaticResource InputBackgroundColor}" />
<SolidColorBrush x:Key="AccentBrush" Color="{StaticResource AccentColor}" />
<SolidColorBrush x:Key="AccentDimBrush" Color="{StaticResource AccentDimColor}" />
<!-- Ghost-button hover fill: an accent-tinted grey that clearly lights up on hover. -->
<SolidColorBrush x:Key="HoverFillBrush" Color="#FF3D3126" />
<SolidColorBrush x:Key="TextPrimaryBrush" Color="{StaticResource TextPrimaryColor}" />
<SolidColorBrush x:Key="TextSecondaryBrush" Color="{StaticResource TextSecondaryColor}" />
<SolidColorBrush x:Key="TextDisabledBrush" Color="{StaticResource TextDisabledColor}" />
<SolidColorBrush x:Key="TextAccentBrush" Color="{StaticResource TextAccentColor}" />
<SolidColorBrush x:Key="StatusGreenBrush" Color="{StaticResource StatusGreenColor}" />
<SolidColorBrush x:Key="StatusRedBrush" Color="{StaticResource StatusRedColor}" />
<SolidColorBrush x:Key="StatusYellowBrush" Color="{StaticResource StatusYellowColor}" />
<SolidColorBrush x:Key="StatusBlueBrush" Color="{StaticResource StatusBlueColor}" />
</ResourceDictionary>
+615
View File
@@ -0,0 +1,615 @@
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ctrl="clr-namespace:TuneBossPC.Controls"
xmlns:conv="clr-namespace:TuneBossPC.Converters">
<conv:EqualityMultiConverter x:Key="PageEqualsConverter" />
<!--
Control styles.
Sizing rationale: this app is operated at a dyno / workbench, often while the
operator's attention is on the machine. Action buttons therefore use a 38px
minimum hit target, 13-14pt labels, and clearly separated destructive actions.
The implicit styles at the bottom (TextBox, ComboBox, CheckBox, PasswordBox,
ListBox, ToolTip, ScrollBar) exist so NO control ever renders stock white
Windows chrome on the dark theme. Controls that set their own Background
locally (e.g. heatmap grid cells) are unaffected — local values win.
-->
<!-- Card -->
<Style x:Key="Card" TargetType="Border">
<Setter Property="Background" Value="{StaticResource Surface2Brush}" />
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="6" />
<Setter Property="Padding" Value="12" />
</Style>
<!-- Primary button — the main affirmative action (WRITE, Connect, Save) -->
<Style x:Key="PrimaryButton" TargetType="Button">
<Setter Property="Background" Value="{StaticResource AccentBrush}" />
<Setter Property="Foreground" Value="White" />
<Setter Property="FontFamily" Value="{StaticResource UIFont}" />
<Setter Property="FontSize" Value="14" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Padding" Value="18,8" />
<Setter Property="MinHeight" Value="38" />
<Setter Property="MinWidth" Value="88" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="bg"
Background="{TemplateBinding Background}"
CornerRadius="4"
Padding="{TemplateBinding Padding}">
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="bg" Property="Background" Value="#FFFF8A2E" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="bg" Property="Background" Value="#FFD95B00" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="bg" Property="Background" Value="{StaticResource AccentDimBrush}" />
<Setter Property="Foreground" Value="{StaticResource TextDisabledBrush}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Ghost button — secondary actions. Primary-brightness text for legibility. -->
<Style x:Key="GhostButton" TargetType="Button">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}" />
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="FontFamily" Value="{StaticResource UIFont}" />
<Setter Property="FontSize" Value="13" />
<Setter Property="FontWeight" Value="Medium" />
<Setter Property="Padding" Value="14,7" />
<Setter Property="MinHeight" Value="38" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="bg"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="4"
Padding="{TemplateBinding Padding}">
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="bg" Property="Background" Value="{StaticResource HoverFillBrush}" />
<Setter TargetName="bg" Property="BorderBrush" Value="{StaticResource AccentBrush}" />
<Setter Property="Foreground" Value="{StaticResource TextAccentBrush}" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="bg" Property="Background" Value="{StaticResource Surface1Brush}" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="bg" Property="Background" Value="Transparent" />
<Setter TargetName="bg" Property="BorderBrush" Value="{StaticResource BorderBrush}" />
<Setter Property="Foreground" Value="{StaticResource TextDisabledBrush}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Danger button — destructive / permanent actions (FLASH). -->
<Style x:Key="DangerButton" TargetType="Button" BasedOn="{StaticResource GhostButton}">
<Setter Property="Foreground" Value="{StaticResource StatusRedBrush}" />
<Setter Property="BorderBrush" Value="{StaticResource StatusRedBrush}" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="bg"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="4"
Padding="{TemplateBinding Padding}">
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="bg" Property="Background" Value="#26FF4D4D" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="bg" Property="Background" Value="#40FF4D4D" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Foreground" Value="{StaticResource TextDisabledBrush}" />
<Setter TargetName="bg" Property="BorderBrush" Value="{StaticResource BorderBrush}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Hold-to-confirm FLASH button — fires only after a 1.2 s press-and-hold.
The PART_Fill bar sweeps left→right while held; early release shows "HOLD…". -->
<Style x:Key="HoldFlashButton" TargetType="ctrl:HoldToConfirmButton">
<Setter Property="Foreground" Value="{StaticResource StatusRedBrush}" />
<Setter Property="FontFamily" Value="{StaticResource UIFont}" />
<Setter Property="FontSize" Value="13" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="MinHeight" Value="38" />
<Setter Property="Padding" Value="14,7" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ctrl:HoldToConfirmButton">
<Border x:Name="bg"
Background="Transparent"
BorderBrush="{StaticResource StatusRedBrush}"
BorderThickness="1"
CornerRadius="4">
<Grid ClipToBounds="True">
<Border x:Name="PART_Fill" Background="#66FF4D4D" />
<Border x:Name="PART_Success"
Background="{StaticResource StatusGreenBrush}"
Opacity="0" />
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center"
Margin="{TemplateBinding Padding}" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="bg" Property="Background" Value="#1AFF4D4D" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Foreground" Value="{StaticResource TextDisabledBrush}" />
<Setter TargetName="bg" Property="BorderBrush" Value="{StaticResource BorderBrush}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Nav button — left rail -->
<Style x:Key="NavButton" TargetType="Button">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="{StaticResource TextSecondaryBrush}" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="FontFamily" Value="{StaticResource ConfigFont}" />
<Setter Property="FontSize" Value="{StaticResource ConfigValue}" />
<Setter Property="Padding" Value="12,11" />
<Setter Property="HorizontalContentAlignment" Value="Left" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="border"
Background="{TemplateBinding Background}"
CornerRadius="4"
Padding="{TemplateBinding Padding}"
Margin="0,1">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{StaticResource Surface3Brush}" />
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Foreground" Value="{StaticResource TextDisabledBrush}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<!-- Highlight the nav entry whose Tag equals the page being shown -->
<DataTrigger Value="True">
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource PageEqualsConverter}">
<Binding Path="DataContext.CurrentPageTag"
RelativeSource="{RelativeSource AncestorType=Window}" />
<Binding Path="Tag" RelativeSource="{RelativeSource Self}" />
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="Background" Value="{StaticResource Surface3Brush}" />
<Setter Property="Foreground" Value="{StaticResource AccentBrush}" />
<Setter Property="FontWeight" Value="SemiBold" />
</DataTrigger>
</Style.Triggers>
</Style>
<!-- Label text style -->
<Style x:Key="LabelText" TargetType="TextBlock">
<Setter Property="FontFamily" Value="{StaticResource UIFont}" />
<Setter Property="FontSize" Value="12" />
<Setter Property="Foreground" Value="{StaticResource TextSecondaryBrush}" />
</Style>
<!-- Value text style -->
<Style x:Key="ValueText" TargetType="TextBlock">
<Setter Property="FontFamily" Value="{StaticResource DataFont}" />
<Setter Property="FontSize" Value="14" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}" />
</Style>
<!-- Hash code entry box (used in password reset) -->
<Style x:Key="HashBox" TargetType="TextBox">
<Setter Property="Background" Value="{StaticResource Surface2Brush}" />
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}" />
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="FontFamily" Value="{StaticResource DataFont}" />
<Setter Property="FontSize" Value="11" />
<Setter Property="Padding" Value="4,4" />
<Setter Property="TextAlignment" Value="Center" />
<Setter Property="MaxLength" Value="8" />
<Setter Property="CaretBrush" Value="{StaticResource TextPrimaryBrush}" />
</Style>
<!-- Pill toggle (e.g. the "bits" switch on the Misc page) -->
<Style x:Key="PillToggle" TargetType="ToggleButton">
<Setter Property="Background" Value="{StaticResource Surface1Brush}" />
<Setter Property="Foreground" Value="{StaticResource TextSecondaryBrush}" />
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="FontFamily" Value="{StaticResource UIFont}" />
<Setter Property="FontSize" Value="12" />
<Setter Property="Padding" Value="10,4" />
<Setter Property="MinHeight" Value="28" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToggleButton">
<Border x:Name="bg"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="14"
Padding="{TemplateBinding Padding}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="bg" Property="Background" Value="{StaticResource AccentBrush}" />
<Setter TargetName="bg" Property="BorderBrush" Value="{StaticResource AccentBrush}" />
<Setter Property="Foreground" Value="White" />
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="bg" Property="BorderBrush" Value="{StaticResource AccentBrush}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- ══════════════════════════════════════════════════════════════════════
IMPLICIT STYLES — dark chrome for every stock control.
══════════════════════════════════════════════════════════════════════ -->
<!-- TextBox -->
<Style TargetType="TextBox">
<Setter Property="Background" Value="{StaticResource InputBackgroundBrush}" />
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}" />
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CaretBrush" Value="{StaticResource TextPrimaryBrush}" />
<Setter Property="SelectionBrush" Value="{StaticResource AccentBrush}" />
<Setter Property="FontFamily" Value="{StaticResource UIFont}" />
<Setter Property="FontSize" Value="13" />
<Setter Property="Padding" Value="6,4" />
<Setter Property="MinHeight" Value="30" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TextBox">
<Border x:Name="bg"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="4">
<ScrollViewer x:Name="PART_ContentHost"
Margin="{TemplateBinding Padding}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter TargetName="bg" Property="BorderBrush" Value="{StaticResource AccentBrush}" />
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="bg" Property="BorderBrush" Value="{StaticResource TextSecondaryBrush}" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Foreground" Value="{StaticResource TextDisabledBrush}" />
<Setter TargetName="bg" Property="Background" Value="{StaticResource Surface1Brush}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- PasswordBox -->
<Style TargetType="PasswordBox">
<Setter Property="Background" Value="{StaticResource InputBackgroundBrush}" />
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}" />
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CaretBrush" Value="{StaticResource TextPrimaryBrush}" />
<Setter Property="SelectionBrush" Value="{StaticResource AccentBrush}" />
<Setter Property="FontFamily" Value="{StaticResource UIFont}" />
<Setter Property="FontSize" Value="13" />
<Setter Property="Padding" Value="6,4" />
<Setter Property="MinHeight" Value="30" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="PasswordBox">
<Border x:Name="bg"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="4">
<ScrollViewer x:Name="PART_ContentHost"
Margin="{TemplateBinding Padding}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter TargetName="bg" Property="BorderBrush" Value="{StaticResource AccentBrush}" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Foreground" Value="{StaticResource TextDisabledBrush}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- ComboBox -->
<Style TargetType="ComboBoxItem">
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}" />
<Setter Property="Padding" Value="10,7" />
<Setter Property="FontFamily" Value="{StaticResource UIFont}" />
<Setter Property="FontSize" Value="13" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ComboBoxItem">
<Border x:Name="bg" Background="Transparent" Padding="{TemplateBinding Padding}">
<ContentPresenter VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsHighlighted" Value="True">
<Setter TargetName="bg" Property="Background" Value="{StaticResource Surface3Brush}" />
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="bg" Property="Background" Value="{StaticResource AccentDimBrush}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="ComboBox">
<Setter Property="Background" Value="{StaticResource InputBackgroundBrush}" />
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}" />
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="FontFamily" Value="{StaticResource UIFont}" />
<Setter Property="FontSize" Value="13" />
<Setter Property="Padding" Value="10,5" />
<Setter Property="MinHeight" Value="32" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ComboBox">
<Grid>
<ToggleButton x:Name="toggle"
Focusable="False"
ClickMode="Press"
IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}">
<ToggleButton.Template>
<ControlTemplate TargetType="ToggleButton">
<Border x:Name="bg"
Background="{Binding Background, RelativeSource={RelativeSource AncestorType=ComboBox}}"
BorderBrush="{Binding BorderBrush, RelativeSource={RelativeSource AncestorType=ComboBox}}"
BorderThickness="1"
CornerRadius="4">
<Path HorizontalAlignment="Right" VerticalAlignment="Center"
Margin="0,0,10,0"
Data="M 0 0 L 4 4 L 8 0"
Stroke="{StaticResource TextSecondaryBrush}"
StrokeThickness="1.6" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="bg" Property="BorderBrush" Value="{StaticResource AccentBrush}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ToggleButton.Template>
</ToggleButton>
<ContentPresenter Margin="{TemplateBinding Padding}"
HorizontalAlignment="Left" VerticalAlignment="Center"
Content="{TemplateBinding SelectionBoxItem}"
ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
IsHitTestVisible="False" />
<Popup x:Name="PART_Popup"
IsOpen="{TemplateBinding IsDropDownOpen}"
Placement="Bottom"
AllowsTransparency="True"
PopupAnimation="Fade"
StaysOpen="False">
<Border Background="{StaticResource Surface2Brush}"
BorderBrush="{StaticResource BorderBrush}"
BorderThickness="1" CornerRadius="4"
MinWidth="{TemplateBinding ActualWidth}"
MaxHeight="{TemplateBinding MaxDropDownHeight}"
Margin="0,2,0,0">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<ItemsPresenter />
</ScrollViewer>
</Border>
</Popup>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Foreground" Value="{StaticResource TextDisabledBrush}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- CheckBox -->
<Style TargetType="CheckBox">
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}" />
<Setter Property="FontFamily" Value="{StaticResource UIFont}" />
<Setter Property="FontSize" Value="13" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="CheckBox">
<StackPanel Orientation="Horizontal" Background="Transparent">
<Border x:Name="box" Width="18" Height="18" CornerRadius="3"
Background="{StaticResource InputBackgroundBrush}"
BorderBrush="{StaticResource BorderBrush}" BorderThickness="1.5"
VerticalAlignment="Center">
<Path x:Name="check"
Data="M 3 8 L 7 12 L 14 4"
Stroke="White" StrokeThickness="2"
Visibility="Collapsed" />
</Border>
<ContentPresenter Margin="8,0,0,0" VerticalAlignment="Center"
RecognizesAccessKey="True" />
</StackPanel>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="box" Property="Background" Value="{StaticResource AccentBrush}" />
<Setter TargetName="box" Property="BorderBrush" Value="{StaticResource AccentBrush}" />
<Setter TargetName="check" Property="Visibility" Value="Visible" />
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="box" Property="BorderBrush" Value="{StaticResource AccentBrush}" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Foreground" Value="{StaticResource TextDisabledBrush}" />
<Setter TargetName="box" Property="BorderBrush" Value="{StaticResource TextDisabledBrush}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- ListBox -->
<Style TargetType="ListBox">
<Setter Property="Background" Value="{StaticResource InputBackgroundBrush}" />
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}" />
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="FontFamily" Value="{StaticResource UIFont}" />
</Style>
<Style TargetType="ListBoxItem">
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}" />
<Setter Property="Padding" Value="10,7" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border x:Name="bg" Background="Transparent" Padding="{TemplateBinding Padding}">
<ContentPresenter VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="bg" Property="Background" Value="{StaticResource Surface3Brush}" />
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="bg" Property="Background" Value="{StaticResource AccentDimBrush}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- ToolTip -->
<Style TargetType="ToolTip">
<Setter Property="Background" Value="{StaticResource Surface3Brush}" />
<Setter Property="Foreground" Value="{StaticResource TextPrimaryBrush}" />
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="FontFamily" Value="{StaticResource UIFont}" />
<Setter Property="FontSize" Value="12" />
<Setter Property="Padding" Value="10,6" />
</Style>
<!-- ScrollBar — slim, dark, thumb-only -->
<Style TargetType="ScrollBar">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Width" Value="10" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ScrollBar">
<Grid Background="Transparent">
<Track x:Name="PART_Track" IsDirectionReversed="True">
<Track.DecreaseRepeatButton>
<RepeatButton Command="ScrollBar.PageUpCommand" Opacity="0" Focusable="False" />
</Track.DecreaseRepeatButton>
<Track.IncreaseRepeatButton>
<RepeatButton Command="ScrollBar.PageDownCommand" Opacity="0" Focusable="False" />
</Track.IncreaseRepeatButton>
<Track.Thumb>
<Thumb>
<Thumb.Template>
<ControlTemplate TargetType="Thumb">
<Border Background="{StaticResource Surface3Brush}"
BorderBrush="{StaticResource BorderBrush}"
BorderThickness="1"
CornerRadius="4" Margin="2,1" />
</ControlTemplate>
</Thumb.Template>
</Thumb>
</Track.Thumb>
</Track>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="Orientation" Value="Horizontal">
<Setter TargetName="PART_Track" Property="IsDirectionReversed" Value="False" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="Orientation" Value="Horizontal">
<Setter Property="Width" Value="Auto" />
<Setter Property="Height" Value="10" />
</Trigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
+22
View File
@@ -0,0 +1,22 @@
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib">
<FontFamily x:Key="DataFont">pack://application:,,,/Assets/Fonts/#Roboto Condensed</FontFamily>
<FontFamily x:Key="UIFont">pack://application:,,,/Assets/Fonts/#Roboto</FontFamily>
<!-- Config page uses the wider (non-condensed) face at a larger size so it reads
clearly on a large monitor / TV viewed from a distance. -->
<FontFamily x:Key="ConfigFont">pack://application:,,,/Assets/Fonts/#Roboto</FontFamily>
<system:Double x:Key="FontSM">11</system:Double>
<system:Double x:Key="FontMD">12</system:Double>
<system:Double x:Key="FontLG">14</system:Double>
<system:Double x:Key="FontXL">18</system:Double>
<system:Double x:Key="FontGauge">32</system:Double>
<!-- Config-page sizes (larger for distance viewing) -->
<system:Double x:Key="ConfigLabel">17</system:Double>
<system:Double x:Key="ConfigValue">18</system:Double>
<system:Double x:Key="ConfigHeader">22</system:Double>
</ResourceDictionary>
+208
View File
@@ -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;
/// <summary>
/// A button that fires its command only after being pressed and HELD for
/// <see cref="HoldDuration"/> 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.
/// </summary>
[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);
}
/// <summary>
/// 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.
/// </summary>
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);
}
/// <summary>Seconds the button must be held before the command fires.</summary>
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;
}
}
}
+407
View File
@@ -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;
/// <summary>
/// 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 <see cref="SetTracker"/>.
///
/// Interaction: left-drag orbits, mouse wheel zooms.
/// </summary>
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<string>();
private string[] _rowLabels = Array.Empty<string>();
// Overlay label pool
private readonly List<TextBlock> _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 ──────────────────────────────────────────────────────────────
/// <summary>
/// Updates the surface from a row-major value array (<c>values[row*cols+col]</c>)
/// plus axis tick label strings. Heights/colours normalise to the array's own
/// min/max so relief is always visible.
/// </summary>
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<string>();
_rowLabels = rowLabels ?? Array.Empty<string>();
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();
}
/// <summary>
/// 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.
/// </summary>
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();
}
}
/// <summary>Places the live tracker marker on a cell; pass -1,-1 to hide.</summary>
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();
}
/// <summary>
/// Lays out the axis tick labels: 3D anchor points on the camera-facing edges,
/// projected to 2D and positioned on the overlay canvas.
/// </summary>
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);
}
/// <summary>Projects a world point through the perspective camera to canvas pixels.</summary>
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;
}
/// <summary>Small octahedron used as the tracker marker.</summary>
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;
}
/// <summary>1-D heatmap gradient texture — mirrors the grid's colour ramp.</summary>
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 };
}
}
@@ -0,0 +1,15 @@
using System.Globalization;
using System.Windows.Data;
namespace TuneBossPC.Converters;
/// <summary>True when the two bound values are equal — used by the nav rail to
/// highlight the button whose Tag matches the currently displayed page.</summary>
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();
}
@@ -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;
/// <summary>
/// Converts ErrorStatus to a background brush:
/// Active → Red
/// Persistent → Yellow
/// Clear → Green
/// </summary>
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();
}
/// <summary>
/// Converts ErrorStatus to foreground text colour —
/// dark text on yellow, white on red/green.
/// </summary>
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();
}
/// <summary>
/// Converts CrankState int to background brush:
/// 6 → Green (running)
/// 5 → Yellow (near sync)
/// * → Red
/// </summary>
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();
}
+11
View File
@@ -0,0 +1,11 @@
{
"profiles": {
"TuneBossPC": {
"commandName": "Project"
},
"TuneBossPC Sim": {
"commandName": "Project",
"commandLineArgs": "--sim"
}
}
}
+137
View File
@@ -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;
/// <summary>
/// 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
/// </summary>
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<UnlockResult> 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<UnlockResult> 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<UnlockResult> RunUnlockLoopAsync(
string username,
Func<PasswordDialogViewModel, Task<TuneBoss.Core.BLE.CommandResult>> 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();
}
}
+45
View File
@@ -0,0 +1,45 @@
namespace TuneBossPC.Services;
/// <summary>
/// Result of an unlock attempt.
/// </summary>
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");
}
/// <summary>
/// Manages the ECU unlock/password flow.
/// Called after connect, before table population.
/// Two unlock domains: basic ECU and tuner tables.
/// </summary>
public interface IAuthService
{
/// <summary>
/// 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.
/// </summary>
Task<UnlockResult> EnsureUnlockedAsync(
string username,
CancellationToken ct = default);
/// <summary>
/// Runs the tuner unlock flow (APP_UNLOCK_TUNER).
/// Only needed for tuner-mode table access.
/// </summary>
Task<UnlockResult> EnsureTunerUnlockedAsync(
string username,
CancellationToken ct = default);
/// <summary>Last password successfully used — stored for auto-reconnect.</summary>
string? SavedPassword { get; }
/// <summary>Last tuner password successfully used.</summary>
string? SavedTunerPassword { get; }
}
+123
View File
@@ -0,0 +1,123 @@
using TuneBoss.Core.Models;
namespace TuneBossPC.Services;
/// <summary>
/// Holds the current connected device's session state —
/// EcuInfo, MemoryLayout, and variant. Populated on connect,
/// cleared on disconnect. Shared across all ViewModels.
/// </summary>
public interface ISessionService
{
EcuInfo? Info { get; }
MemoryLayout? Layout { get; }
EcuVariant Variant { get; }
/// <summary>True only when a real device is connected — gates all hardware comms.</summary>
bool IsActive { get; }
/// <summary>True when a layout is available to render tables — connected OR offline file view.</summary>
bool HasLayout { get; }
/// <summary>Raised whenever the session is established or cleared (connect / disconnect / offline load).</summary>
event Action? SessionChanged;
/// <summary>Builds and stores the session after a successful connect.</summary>
void Establish(EcuInfo info, EcuVariant variant);
/// <summary>
/// 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.
/// </summary>
void EstablishOffline(byte make, byte model, byte fw, int cylinderCount);
/// <summary>Clears the session on disconnect / closing an offline file.</summary>
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();
}
}
/// <summary>
/// Resolves the EcuVariant from bike manufacturer + model.
/// For now uses a simple lookup; extend with the two-cylinder registry as needed.
/// </summary>
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;
}
}
+589
View File
@@ -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;
/// <summary>
/// Real <see cref="IMapTableCodec"/> — maps the legacy <c>.tst</c> sections to the WPF
/// view-models.
///
/// <para><b>User</b> saves the adjust tables + their subtables (legacy-exact order).</para>
/// <para><b>Full Config</b> saves <i>every editable in the app</i>: 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.</para>
///
/// 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).
/// </summary>
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<Spec> 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<string> 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<string> WriteLoadedAsync(MapSaveType saveType, int cylinderCount, bool flash,
IProgress<string>? progress = null)
{
int tables, oneD = 0; bool misc = false;
List<string> 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 ───────────────────────────────────────────────────────────────
/// <summary>Rebuilds the tuning + 1D nav trees from the current layout so entries
/// exist to populate (needed after an offline file establishes a layout).</summary>
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<string, string>();
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<byte>();
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<string, string> map, string label) =>
map.TryGetValue(label, out var sec) ? MapTableFormat.ParseBytesSection(sec) : Array.Empty<byte>();
// ── Helpers ───────────────────────────────────────────────────────────────────
/// <summary>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.</summary>
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
// ════════════════════════════════════════════════════════════════════════
/// <summary>
/// Builds an <see cref="FsrFile.FsrDocument"/> 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.
/// </summary>
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,
};
/// <summary>Maps a tuning entry's display label to its stable FSR feature key.</summary>
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,
};
/// <summary>Applies a parsed FSR document into the editors (offline or connected view).</summary>
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<byte>();
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.");
}
+84
View File
@@ -0,0 +1,84 @@
using System.IO;
using System.Text.Json;
using CommunityToolkit.Mvvm.ComponentModel;
namespace TuneBossPC.Services;
/// <summary>
/// App-level behaviour settings (not hardware state). Observable so pages bind
/// directly; persisted automatically on every change.
/// </summary>
public sealed partial class AppSettings : ObservableObject
{
/// <summary>
/// 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.
/// </summary>
[ObservableProperty] private bool _trackerAutoSelect;
/// <summary>
/// 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.
/// </summary>
[ObservableProperty] private bool _autoWriteOnChange;
/// <summary>
/// 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.
/// </summary>
[ObservableProperty] private bool _flatMapNoContour;
/// <summary>The most recently used device password (stored so the user can pick
/// "use last password" on the next connection). Empty when none stored yet.</summary>
[ObservableProperty] private string _lastPassword = string.Empty;
}
public interface ISettingsService
{
AppSettings Settings { get; }
void Save();
}
/// <summary>
/// Loads settings from %APPDATA%\TuneBoss\settings.json at startup and saves on
/// every property change. Failures are non-fatal — defaults apply.
/// </summary>
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<AppSettings>(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 */ }
}
}
+44
View File
@@ -0,0 +1,44 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net9.0-windows10.0.19041.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UseWPF>true</UseWPF>
<RootNamespace>TuneBossPC</RootNamespace>
<!-- Build/version shown in the app (top-left, under the logo). Bump per build. -->
<Version>2026.8.13</Version>
<!-- Lets AppInfo read the ClickOnce publish version at runtime when installed. -->
<UseApplicationDeploymentApi>true</UseApplicationDeploymentApi>
</PropertyGroup>
<!-- Dealer release: publish with -p:Dealer=true (or set <Dealer>true</Dealer> in the
publish profile) to define the DEALER symbol, which hides the Config + 1D Tables
nav items. A normal build leaves Dealer unset and shows everything. -->
<PropertyGroup Condition="'$(Dealer)' == 'true'">
<DefineConstants>$(DefineConstants);DEALER</DefineConstants>
<!-- A DISTINCT assembly name gives the dealer build its own ClickOnce
application identity (output TuneBossPC.Dealer.exe →
TuneBossPC.Dealer.application). Without this, ClickOnce treats the
dealer and full builds as the SAME app — installing one from a
different URL than the other fails with "already installed from a
different location". RootNamespace stays TuneBossPC, so no code,
XAML, or resource path changes. -->
<AssemblyName>TuneBossPC.Dealer</AssemblyName>
<Product>TuneBoss PC (Dealer)</Product>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\TuneBoss.Core\TuneBoss.Core.csproj" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.3.2" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.0" />
<PackageReference Include="System.Reactive" Version="6.0.1" />
<PackageReference Include="WPF-UI" Version="4.3.0" />
</ItemGroup>
<ItemGroup>
<Resource Include="Assets\Fonts\**\*" />
</ItemGroup>
<ItemGroup>
<Folder Include="Assets\Fonts\" />
<Folder Include="Assets\Styles\" />
</ItemGroup>
</Project>
+263
View File
@@ -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<BleDeviceInfo> 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();
}
}
/// <summary>
/// Reads every available 2D table, 1D table, and misc block while a
/// non-cancellable modal progress dialog blocks the UI.
/// </summary>
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<string>(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();
}
}
@@ -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;
/// <summary>
/// Represents one slot in the 6-gauge persistent bottom strip.
/// </summary>
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);
}
}
/// <summary>
/// Available diagnostics channels that can be assigned to a gauge slot.
/// </summary>
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(),
_ => "—"
};
}
/// <summary>
/// ViewModel for the persistent 6-gauge bottom strip.
/// Lives in MainWindowViewModel — always active when diagnostics are running.
/// </summary>
public partial class DiagnosticsStripViewModel : ObservableObject, IDisposable
{
private readonly IBleService _ble;
private IDisposable? _diagSub;
[ObservableProperty] private bool _isRunning;
// The 6 configurable gauge slots
public ObservableCollection<GaugeSlotViewModel> 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<DiagChannel> AllChannels
=> Enum.GetValues<DiagChannel>();
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 ───────────────────────────────────────────────────────
/// <summary>Assigns a new channel to a slot by index (0–5).</summary>
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();
}
}
@@ -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();
}
@@ -0,0 +1,100 @@
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace TuneBossPC.ViewModels.Dialogs;
public enum PasswordDialogResult
{
Confirmed,
Cancelled,
}
/// <summary>How the user wants to supply the device password.</summary>
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;
/// <summary>The last successfully used password (from settings); empty if none.</summary>
[ObservableProperty] private string _lastPassword = string.Empty;
[NotifyPropertyChangedFor(nameof(IsEnterNew))]
[ObservableProperty] private PasswordChoice _choice = PasswordChoice.EnterNew;
/// <summary>True when a stored last password exists (enables that radio option).</summary>
public bool HasLastPassword => !string.IsNullOrEmpty(LastPassword);
/// <summary>True when the "enter new" option is selected (shows the password box).</summary>
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; }
}
+462
View File
@@ -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;
/// <summary>
/// Save / open TuneBoss map files (<c>.tst</c>).
///
/// 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.
/// </summary>
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<MapSaveType> 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;
/// <summary>Bumped on each confirmed flash — drives the flash button's green blink.</summary>
[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}";
}
}
/// <summary>Opens a .fsr file: parse, stash the doc, and surface a tag summary.</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);
/// <summary>
/// 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.
/// </summary>
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<string>(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();
}
}
@@ -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;
/// <summary>Build/version string shown under the logo.</summary>
public string AppVersion => TuneBossPC.AppInfo.Version;
/// <summary>False in the dealer build → the Config and 1D Tables nav items are hidden.</summary>
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",
};
/// <summary>Green when active (engine killed), amber while arming/restoring, red when inactive.</summary>
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;
/// <summary>The persistent diagnostics strip — always alive in the shell.</summary>
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);
}
/// <summary>Tag of the page currently shown — drives the nav-rail highlight.</summary>
[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();
}
}
@@ -0,0 +1,36 @@
using TuneBoss.Core.Models;
namespace TuneBossPC.ViewModels.Tables;
/// <summary>
/// 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.
/// </summary>
public partial class MiscValuesViewModel
{
/// <summary>The currently-loaded misc model (raw regions), or null if not read yet.</summary>
public MiscValues? CurrentMisc => _misc;
/// <summary>Reads the misc regions if they aren't loaded yet.</summary>
public async Task EnsureLoadedAsync()
{
if (_misc == null) await ReadAllAsync(null);
}
/// <summary>
/// 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.
/// </summary>
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();
}
}
@@ -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<MiscBitEditorViewModel> 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));
}
/// <summary>The underlying raw byte, read/written in place.</summary>
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();
}
/// <summary>Called after a bit edit: apply constraints, then resync siblings + raw value.</summary>
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<MiscFieldViewModel> Fields { get; } = new();
}
public partial class MiscBlockGroupViewModel : ObservableObject
{
public string Label { get; init; } = string.Empty;
[ObservableProperty] private bool _isExpanded = true;
public List<MiscSectionViewModel> 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<MiscBlockGroupViewModel> Groups { get; } = new();
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasSelection))]
private MiscSectionViewModel? _selectedSection;
public bool HasSelection => SelectedSection != null;
[ObservableProperty] private bool _isReading;
[ObservableProperty] private bool _isWriting;
/// <summary>Bumped on each confirmed flash — drives the FLASH button's green blink.</summary>
[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));
}
/// <summary>True when hardware comms are allowed — a live session. Offline is view-only.</summary>
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<string>? progress = null) => ReadAllAsync(progress);
[RelayCommand]
public Task ReadAsync() => ReadAllAsync(null);
/// <summary>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.</summary>
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<string>? 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<byte[]?> ReadBlock(MemoryRegion region, IProgress<string>? 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<bool> 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<MiscBlock, MiscBlockGroupViewModel>();
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<byte>(),
};
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() { }
}
@@ -0,0 +1,35 @@
namespace TuneBossPC.ViewModels.Tables;
/// <summary>
/// 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.
/// </summary>
public partial class OneDimTablesViewModel
{
/// <summary>Reads every available 1D table whose model isn't loaded. Best-effort.</summary>
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 */ }
}
}
}
/// <summary>Writes every loaded 1D table to the ECU from its model. Throws on first failure.</summary>
public async Task<int> WriteAllLoadedAsync(IProgress<string>? 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;
}
}
@@ -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;
/// <summary>Display-only unit labels (default from registry, editable in the UI).</summary>
[ObservableProperty] private string _axisUnit = string.Empty;
[ObservableProperty] private string _valueUnit = string.Empty;
[ObservableProperty] private bool _isSelected;
[ObservableProperty] private bool _isLoaded;
[ObservableProperty] private bool _isLoading;
/// <summary>Loaded model (null until first read).</summary>
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<OneDimEntryViewModel> 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<OneDimGroupViewModel> Groups { get; } = new();
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasSelectedTable))]
private OneDimEntryViewModel? _selectedEntry;
public bool HasSelectedTable => SelectedEntry != null;
// ── Grid (single value row + editable axis breakpoints) ───────────────────
public ObservableCollection<TuningTableCellViewModel> Cells { get; } = new();
[ObservableProperty] private ObservableCollection<AxisHeaderViewModel> _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;
/// <summary>Bumped on each confirmed flash — drives the FLASH button's green blink.</summary>
[ObservableProperty] private int _flashSuccessCount;
/// <summary>Raised when the curve needs redrawing (after populate or any value/axis edit).</summary>
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();
}
/// <summary>
/// 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.
/// </summary>
[ObservableProperty] private bool _showYMultiplied;
/// <summary>
/// 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.
/// </summary>
[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();
}
/// <summary>Effective value multiplier honouring the Y toggle (1 = unscaled).</summary>
private int DisplayConvMult => ShowYMultiplied ? EffConvMult : 1;
/// <summary>Value multiplier the curve axis labels should use (honours the Y toggle).</summary>
public int DisplayCurveMult => DisplayConvMult;
/// <summary>X-axis (breakpoint) multiplier — honours the independent X toggle
/// (1 = unscaled when unchecked).</summary>
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.
/// <summary>
/// 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.
/// </summary>
public sealed partial class MetaRow : ObservableObject
{
private readonly System.Func<string>? _read;
private readonly System.Action<string>? _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<string> read, System.Action<string> apply)
{
Label = label;
_read = read;
_apply = apply;
Value = read();
EditText = Value;
}
/// <summary>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.</summary>
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; }
}
}
/// <summary>True once the hidden 5-click gesture on the metadata header unlocks editing.</summary>
[ObservableProperty] private bool _metadataUnlocked;
private int _metaClickCount;
private System.DateTime _lastMetaClickUtc;
/// <summary>
/// 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.
/// </summary>
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<MetaRow> MetaRows
{
get
{
var t = SelectedEntry?.Table;
if (t == null) return System.Array.Empty<MetaRow>();
// Editable numeric row: parse as int, range-check to a byte/sbyte, assign.
MetaRow ByteRow(string label, System.Func<int> get, System.Action<int> 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),
};
}
}
/// <summary>
/// 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.
/// </summary>
private async Task ResumeDiagnosticsIfLiveAsync()
{
try { if (_strip.IsRunning) await _ble.StartDiagnosticsAsync(); }
catch { /* best-effort */ }
}
// ── Nav tree ──────────────────────────────────────────────────────────────
/// <summary>True when hardware comms are allowed — a live session. Offline is view-only.</summary>
public bool CanComms => _session.IsActive;
/// <summary>Rebuilds the nav tree from the current session layout. Call after connect.</summary>
public void RebuildNavTree()
{
OnPropertyChanged(nameof(CanComms));
Groups.Clear();
if (!_session.HasLayout || _session.Layout is null) return;
var layout = _session.Layout;
var entries = new List<OneDimEntryViewModel>();
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(); }
}
/// <summary>Reads all available 1D tables so they're cached for instant viewing. Mirrors the 2D init.</summary>
public async Task InitializeAllAsync(IProgress<string>? progress = null)
{
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<bool> 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);
}
/// <summary>Bulk nudge by whole RAW units (one press = ±1 raw = ±multiplier on the display).</summary>
private void AdjustSelected(int rawDelta)
{
if (SelectedEntry?.Table == null) return;
foreach (var c in BulkTargets()) SetCellValue(c, c.RawValue + rawDelta);
CurveInvalidated?.Invoke();
}
/// <summary>Set the selection from a DISPLAYED (scaled) value. Rejects non-multiples of the value multiplier.</summary>
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();
}
/// <summary>Stores the RAW value on the cell and shows raw × multiplier.</summary>
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<TuningTableCellViewModel> 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<int>(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<TuningTableCellViewModel> 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<TuningTableCellViewModel>();
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;
}
/// <summary>Strict monotonic check against immediate neighbours (direction auto-detected).</summary>
private static bool IsInSequence(IReadOnlyList<int> 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<int> 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() { }
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
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<RpmSettingItem, System.Threading.Tasks.Task> _setAsync;
public string Title { get; }
public bool HasMaximum { get; } // whether the "Maximum" row is shown (VVA hides it)
/// <summary>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).</summary>
public int RecoveryDelta { get; }
/// <summary>False when this setting isn't present on the connected unit (e.g. VVA on a non-VVA ECU).</summary>
[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<RpmSettingItem, System.Threading.Tasks.Task> setAsync)
{
Title = title;
HasMaximum = hasMaximum;
RecoveryDelta = recoveryDelta;
_setAsync = setAsync;
}
/// <summary>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.</summary>
public int Ceiling => MaxRpm > 0 ? System.Math.Min(MaxRpm, ByteMaxRpm) : ByteMaxRpm;
/// <summary>Apply a freshly-read current value and reset the pending New value to match.</summary>
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);
}
/// <summary>
/// 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.
/// </summary>
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(); }
}
/// <summary>
/// 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.
/// </summary>
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 */ }
}
}
@@ -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.";
}
}
+6
View File
@@ -0,0 +1,6 @@
using CommunityToolkit.Mvvm.ComponentModel;
namespace TuneBossPC.ViewModels;
// Stubs for pages not yet implemented
@@ -0,0 +1,26 @@
using CommunityToolkit.Mvvm.ComponentModel;
namespace TuneBossPC.ViewModels.Tables;
/// <summary>Which axis a header belongs to.</summary>
public enum AxisKind { Rpm, Load }
/// <summary>
/// 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.
/// </summary>
public partial class AxisHeaderViewModel : ObservableObject
{
/// <summary>Position along the axis (0..23 for RPM, 0..7 for Load).</summary>
public int Index { get; init; }
public AxisKind Kind { get; init; }
/// <summary>Numeric display value (RPM in rpm; Load in raw units).</summary>
public int Value { get; set; }
[ObservableProperty] private string _displayValue = "";
[ObservableProperty] private bool _isEditing;
[ObservableProperty] private string _editText = "";
}
@@ -0,0 +1,16 @@
using System.Globalization;
using System.Windows.Data;
namespace TuneBossPC.ViewModels.Tables;
/// <summary>Shows ▾ when expanded, ▸ when collapsed.</summary>
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();
}
@@ -0,0 +1,92 @@
using System.Windows.Media;
namespace TuneBossPC.ViewModels.Tables;
/// <summary>
/// Computes heatmap colours for tuning table cells.
/// 7-band gradient: blue → cyan → green → yellow-green → yellow
/// Matches setDataValRange() / updateCellBackgroundColors() in TuningTablePanel.cs.
/// </summary>
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)
};
/// <summary>
/// Gets background and foreground brushes for a cell value.
/// </summary>
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);
}
/// <summary>
/// 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.
/// </summary>
public static SolidColorBrush TrackerHighlight
=> new(Color.FromRgb(0xFF, 0xFF, 0xFF)); // white
/// <summary>
/// Gets the tracker adjacent colour — the three neighbouring cells.
/// </summary>
public static SolidColorBrush TrackerAdjacent
=> new(Color.FromRgb(0xD3, 0xD3, 0xD3)); // light grey
// ── Flat (no-contour) mode ───────────────────────────────────────────────
/// <summary>Flat cell fill when the contour heatmap is turned off — plain white.</summary>
public static SolidColorBrush FlatBackground
=> new(Color.FromRgb(0xFF, 0xFF, 0xFF)); // white
/// <summary>Tracker exact-position colour in flat mode — orange (white would vanish).</summary>
public static SolidColorBrush FlatTrackerHighlight
=> new(Color.FromRgb(0xFF, 0x80, 0x00)); // orange
/// <summary>Tracker neighbour colour in flat mode — a PALE yellow. Kept light so
/// the orange active cell clearly stands out from its three neighbours.</summary>
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));
}
@@ -0,0 +1,134 @@
using CommunityToolkit.Mvvm.ComponentModel;
using TuneBoss.Core.Models;
namespace TuneBossPC.ViewModels.Tables;
/// <summary>
/// Type of table entry in the nav tree.
/// </summary>
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)
}
/// <summary>Icon shown beside a 2D table's big title.</summary>
public enum TableIconKind
{
None,
Fuel, // droplet — fuel tables
Spark, // lightning — spark/ignition tables
Angle, // injection angle
Afr, // AFR target
}
/// <summary>
/// A single entry in the tuning table nav tree.
/// Carries the address, label, type, and loaded data.
/// </summary>
public partial class TableEntryViewModel : ObservableObject
{
public string Label { get; init; } = string.Empty;
/// <summary>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.</summary>
public string? DisplayNameRaw { get; init; }
public string DisplayName => string.IsNullOrEmpty(DisplayNameRaw) ? Label : DisplayNameRaw!;
/// <summary>Hidden from the nav (still constructed so lookups/writes are unaffected).</summary>
public bool IsHidden { get; init; }
/// <summary>Which icon to show beside the big table title.</summary>
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; }
/// <summary>Optional subtable that lives below this table on the same view.</summary>
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)
/// <summary>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.</summary>
[ObservableProperty] private bool _isStageUnlocked = true;
/// <summary>True for a standalone Stage-1 subtable entry (renders the 4×6 grid only).</summary>
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;
/// <summary>Emoji/symbol glyph shown beside the big table title.</summary>
public string IconGlyph => IconKind switch
{
TableIconKind.Fuel => "💧",
TableIconKind.Spark => "⚡",
TableIconKind.Angle => "📐",
TableIconKind.Afr => "🎯",
_ => string.Empty,
};
/// <summary>
/// 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.
/// </summary>
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));
}
}
/// <summary>
/// A group in the nav tree (Base Tables / User Tables).
/// </summary>
public partial class TableGroupViewModel : ObservableObject
{
public string Label { get; init; } = string.Empty;
/// <summary>Minimum ECU stage that unlocks this group (1/2/3). 0 = always on.</summary>
public int RequiredStage { get; init; }
[ObservableProperty] private bool _isExpanded = true;
/// <summary>False when the connected ECU is below <see cref="RequiredStage"/>.
/// Entries stay selectable/viewable (read-only); comms actions are disabled.</summary>
[ObservableProperty] private bool _isStageUnlocked = true;
public List<TableEntryViewModel> Entries { get; } = new();
}
@@ -0,0 +1,23 @@
using System;
namespace TuneBossPC.ViewModels.Tables;
/// <summary>
/// One row in the tuning table for binding: the editable Load breakpoint header
/// plus the 24 cell view-models.
/// </summary>
public sealed class TableRowViewModel
{
public AxisHeaderViewModel LoadHeader { get; init; } = new();
public TuningTableCellViewModel[] Cells { get; init; } = Array.Empty<TuningTableCellViewModel>();
}
/// <summary>
/// One row in the subtable. Its load header stays a plain label (subtable axis
/// editing is out of scope for now).
/// </summary>
public sealed class SubTableRowViewModel
{
public string LoadHeader { get; init; } = string.Empty;
public TuningTableCellViewModel[] Cells { get; init; } = Array.Empty<TuningTableCellViewModel>();
}
@@ -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; }
}
@@ -0,0 +1,257 @@
using TuneBoss.Core.BLE;
using TuneBoss.Core.Models;
using TuneBoss.Core.Protocol;
namespace TuneBossPC.ViewModels.Tables;
/// <summary>
/// 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.
/// </summary>
public partial class TuningTablesViewModel
{
/// <summary>
/// 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.
/// </summary>
public async Task EnsureLoadedAsync(IEnumerable<string> 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 */ }
}
}
}
/// <summary>
/// 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).
/// </summary>
public async Task<string> 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 ?? "-"}";
}
/// <summary>
/// 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.
/// </summary>
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,
};
}
/// <summary>Fallback typical RPM axis (×100 ⇒ 1500…13000 rpm) when no base table is loaded.</summary>
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;
}
/// <summary>
/// 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.
/// </summary>
public async Task<(int Written, List<string> LockedLabels)> WriteEntriesFromModelsAsync(
IEnumerable<string> labels, IProgress<string>? progress = null)
{
int written = 0;
var locked = new List<string>();
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);
}
/// <summary>Public wrapper so services can resume the live stream after bulk writes.</summary>
public Task ResumeStreamIfLiveAsync() => ResumeDiagnosticsIfLiveAsync();
}
File diff suppressed because it is too large Load Diff
+258
View File
@@ -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;
/// <summary>
/// Throttle-position-sensor calibration page.
///
/// Faithful port of the legacy Android <c>TpsCalPage</c> 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 (<see cref="DiagnosticsFrame.TPS_Raw"/>) 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.
/// </summary>
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 ─────────────────────────────────────────────────────────────
/// <summary>Called when the page is shown. Reads the absolute bounds.</summary>
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();
}
}
/// <summary>
/// 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.
/// </summary>
private static byte[] FirstUseFlagBytes() =>
new byte[] { 0x00, TpsCalibration.CalDoneFlag, 0x00, 0x00 };
private void RaiseCanExecute()
{
StartCommand.NotifyCanExecuteChanged();
FinishCommand.NotifyCanExecuteChanged();
CancelCommand.NotifyCanExecuteChanged();
}
public void Dispose() => StopCapture();
}
+177
View File
@@ -0,0 +1,177 @@
<UserControl
x:Class="TuneBossPC.Views.ConnectView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Background="{StaticResource Surface0Brush}">
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVis" />
</UserControl.Resources>
<Grid Margin="32">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MaxWidth="520" />
<ColumnDefinition Width="24" />
<ColumnDefinition Width="*" MaxWidth="360" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="20" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!-- Header -->
<StackPanel Grid.Row="0" Grid.ColumnSpan="3">
<TextBlock Text="CONNECT"
FontFamily="{StaticResource DataFont}"
FontSize="11" FontWeight="Medium"
Foreground="{StaticResource TextSecondaryBrush}" />
<TextBlock Text="Select a TuneBoss device"
Margin="0,4,0,0"
FontFamily="{StaticResource DataFont}"
FontSize="22" FontWeight="SemiBold"
Foreground="{StaticResource TextPrimaryBrush}" />
</StackPanel>
<!-- Device list card -->
<Border Grid.Row="2" Grid.Column="0" Style="{StaticResource Card}">
<DockPanel>
<!-- List header -->
<DockPanel DockPanel.Dock="Top" Margin="0,0,0,12">
<Button DockPanel.Dock="Right"
Content="{Binding ScanButtonText}"
Command="{Binding ToggleScanCommand}"
Style="{StaticResource GhostButton}"
Padding="10,4" FontSize="11" />
<TextBlock Text="Nearby Devices"
Style="{StaticResource LabelText}"
VerticalAlignment="Center" />
</DockPanel>
<!-- Scanning indicator -->
<ProgressBar DockPanel.Dock="Top"
IsIndeterminate="True"
Height="2" Margin="0,0,0,12"
Visibility="{Binding IsScanning, Converter={StaticResource BoolToVis}}" />
<!-- Device list -->
<ListView ItemsSource="{Binding Devices}"
SelectedItem="{Binding SelectedDevice, Mode=TwoWay}"
Background="{StaticResource Surface1Brush}"
Foreground="{StaticResource TextPrimaryBrush}"
BorderThickness="0">
<ListView.Template>
<!-- Explicit dark template: the stock ListView template's
ScrollViewer chrome shows the (previously white) window
through its empty area. -->
<ControlTemplate TargetType="ListView">
<Border Background="{StaticResource Surface1Brush}"
BorderThickness="0" SnapsToDevicePixels="True">
<ScrollViewer Focusable="False" Padding="0">
<ItemsPresenter SnapsToDevicePixels="True" />
</ScrollViewer>
</Border>
</ControlTemplate>
</ListView.Template>
<ListView.ItemTemplate>
<DataTemplate>
<Border Padding="8,10" CornerRadius="4" Margin="0,1">
<DockPanel>
<TextBlock DockPanel.Dock="Right"
Text="{Binding Rssi, StringFormat='{}{0} dBm'}"
Style="{StaticResource LabelText}"
VerticalAlignment="Center" />
<StackPanel>
<TextBlock Text="{Binding Name}"
FontFamily="{StaticResource DataFont}"
FontSize="13" FontWeight="SemiBold"
Foreground="{StaticResource TextPrimaryBrush}" />
<TextBlock Text="{Binding MacAddress}"
Margin="0,2,0,0"
Style="{StaticResource LabelText}" />
</StackPanel>
</DockPanel>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="Padding" Value="0" />
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Cursor" Value="Hand" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
</DockPanel>
</Border>
<!-- Right panel -->
<StackPanel Grid.Row="2" Grid.Column="2">
<Button Content="Connect"
Command="{Binding ConnectCommand}"
Style="{StaticResource PrimaryButton}"
HorizontalAlignment="Stretch"
Height="44" />
<Button Content="Disconnect"
Command="{Binding DisconnectCommand}"
Style="{StaticResource GhostButton}"
HorizontalAlignment="Stretch"
Height="38" Margin="0,8,0,0"
IsEnabled="{Binding IsConnected}" />
<!-- Status message -->
<Border Style="{StaticResource Card}" Margin="0,12,0,0"
Padding="12,10"
Visibility="{Binding HasStatusMessage, Converter={StaticResource BoolToVis}}">
<TextBlock Text="{Binding StatusMessage}"
Style="{StaticResource LabelText}"
TextWrapping="Wrap" />
</Border>
<!-- ECU info -->
<Border Style="{StaticResource Card}" Margin="0,12,0,0"
Visibility="{Binding IsConnected, Converter={StaticResource BoolToVis}}">
<StackPanel>
<TextBlock Text="DEVICE INFO"
FontFamily="{StaticResource DataFont}"
FontSize="10" FontWeight="Medium"
Foreground="{StaticResource TextSecondaryBrush}" />
<Grid Margin="0,8,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="Username" Style="{StaticResource LabelText}" />
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding EcuUsername}" Foreground="{StaticResource TextPrimaryBrush}" FontSize="12" />
<TextBlock Grid.Row="1" Grid.Column="0" Text="FW Version" Style="{StaticResource LabelText}" Margin="0,6,0,0" />
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding EcuFwVersion}" Foreground="{StaticResource TextPrimaryBrush}" FontSize="12" Margin="0,6,0,0" />
<TextBlock Grid.Row="2" Grid.Column="0" Text="HW Version" Style="{StaticResource LabelText}" Margin="0,6,0,0" />
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding EcuHwVersion}" Foreground="{StaticResource TextPrimaryBrush}" FontSize="12" Margin="0,6,0,0" />
<TextBlock Grid.Row="3" Grid.Column="0" Text="RPM Limit" Style="{StaticResource LabelText}" Margin="0,6,0,0" />
<TextBlock Grid.Row="3" Grid.Column="1" Text="{Binding EcuRpmLimit}" Foreground="{StaticResource TextAccentBrush}" FontSize="12" Margin="0,6,0,0" />
<TextBlock Grid.Row="4" Grid.Column="0" Text="Flash Writes" Style="{StaticResource LabelText}" Margin="0,6,0,0" />
<TextBlock Grid.Row="4" Grid.Column="1" Text="{Binding EcuFlashWrites}" Foreground="{StaticResource TextPrimaryBrush}" FontSize="12" Margin="0,6,0,0" />
</Grid>
</StackPanel>
</Border>
</StackPanel>
</Grid>
</UserControl>
+14
View File
@@ -0,0 +1,14 @@
using System.Windows.Controls;
using TuneBossPC.ViewModels;
namespace TuneBossPC.Views;
public partial class ConnectView : UserControl
{
public ConnectView(ConnectViewModel vm)
{
DataContext = vm;
InitializeComponent();
vm.StartScan();
}
}
+142
View File
@@ -0,0 +1,142 @@
<UserControl
x:Class="TuneBossPC.Views.DiagnosticsStrip"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:TuneBossPC.ViewModels">
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVis" />
</UserControl.Resources>
<Border Background="{StaticResource Surface1Brush}"
BorderBrush="{StaticResource BorderBrush}"
BorderThickness="0,1,0,0">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" /> <!-- start/stop button -->
<ColumnDefinition Width="1" /> <!-- divider -->
<ColumnDefinition Width="*" /> <!-- gauges -->
</Grid.ColumnDefinitions>
<!-- Start/Stop diagnostics button -->
<Button Grid.Column="0"
Width="110"
BorderThickness="0"
Background="Transparent"
Padding="0"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Stretch"
Cursor="Hand"
Command="{Binding ToggleCommand}"
ToolTip="Start / Stop diagnostics">
<Grid>
<!-- Pulses gently while diagnostics is streaming -->
<Border CornerRadius="0" Margin="0">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Background" Value="{StaticResource StatusGreenBrush}" />
<Setter Property="Opacity" Value="0" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsRunning}" Value="True">
<DataTrigger.EnterActions>
<BeginStoryboard x:Name="BlinkSb">
<Storyboard RepeatBehavior="Forever" AutoReverse="True">
<DoubleAnimation Storyboard.TargetProperty="Opacity"
From="0.08" To="0.40"
Duration="0:0:0.75" />
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<StopStoryboard BeginStoryboardName="BlinkSb" />
</DataTrigger.ExitActions>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" IsHitTestVisible="False">
<Ellipse Width="11" Height="11" HorizontalAlignment="Center" Margin="0,0,0,4">
<Ellipse.Style>
<Style TargetType="Ellipse">
<Setter Property="Fill" Value="{StaticResource TextDisabledBrush}" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsRunning}" Value="True">
<Setter Property="Fill" Value="{StaticResource StatusGreenBrush}" />
</DataTrigger>
</Style.Triggers>
</Style>
</Ellipse.Style>
</Ellipse>
<TextBlock HorizontalAlignment="Center"
FontFamily="{StaticResource DataFont}"
FontSize="12">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Text" Value="START" />
<Setter Property="Foreground" Value="{StaticResource TextSecondaryBrush}" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsRunning}" Value="True">
<Setter Property="Text" Value="STOP" />
<Setter Property="Foreground" Value="{StaticResource StatusGreenBrush}" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</StackPanel>
</Grid>
</Button>
<!-- Vertical divider -->
<Border Grid.Column="1"
Background="{StaticResource BorderBrush}" />
<!-- 6 gauge slots -->
<ItemsControl Grid.Column="2"
ItemsSource="{Binding Slots}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="1" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type vm:GaugeSlotViewModel}">
<Border BorderBrush="{StaticResource BorderBrush}"
BorderThickness="0,0,1,0">
<!-- Right-click to change channel -->
<Border.ContextMenu>
<ContextMenu Tag="{Binding}">
<MenuItem Header="Change channel..."
Click="ChangeChannel_Click"
Tag="{Binding}" />
</ContextMenu>
</Border.ContextMenu>
<StackPanel VerticalAlignment="Center"
HorizontalAlignment="Center"
Margin="4,2">
<TextBlock Text="{Binding Label}"
Style="{StaticResource LabelText}"
FontSize="15"
HorizontalAlignment="Center"
Margin="0,0,0,3" />
<StackPanel Orientation="Horizontal"
HorizontalAlignment="Center">
<TextBlock Text="{Binding Value}"
FontFamily="{StaticResource DataFont}"
FontSize="46" FontWeight="Bold"
Foreground="{StaticResource AccentBrush}" />
<TextBlock Text="{Binding Unit}"
Style="{StaticResource LabelText}"
FontSize="15"
VerticalAlignment="Bottom"
Margin="4,0,0,2" />
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Border>
</UserControl>
+32
View File
@@ -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);
}
}

Some files were not shown because too many files have changed in this diff Show More