Initial Commit
This commit is contained in:
@@ -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
|
||||
};
|
||||
}
|
||||
@@ -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)>();
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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] & 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] & 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}"));
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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 & 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
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
@@ -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 & 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
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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}.",
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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): <vvaModels><ym>14</ym>…<hn>…</hn>
|
||||
/// <su>…</su><kw>…</kw></vvaModels>.
|
||||
/// Element → manufacturer code: ym=1 Yamaha, hn=2 Honda, kw=3 Kawasaki, su=6 Suzuki.
|
||||
/// </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 */ }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user