418 lines
21 KiB
C#
418 lines
21 KiB
C#
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,
|
||
}
|