Initial Commit

This commit is contained in:
2026-09-28 16:55:31 +08:00
commit 14f8706198
128 changed files with 19860 additions and 0 deletions
+668
View File
@@ -0,0 +1,668 @@
using System.Collections.Concurrent;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.Advertisement;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Storage.Streams;
using TuneBoss.Core.Models;
using TuneBoss.Core.Protocol;
using System.Runtime.InteropServices.WindowsRuntime;
namespace TuneBoss.Core.BLE;
/// <summary>
/// Windows WinRT BLE implementation of IBleService.
/// Uses Nordic UART Service (NUS) over a single bidirectional characteristic.
/// </summary>
public sealed class BleManager : IBleService
{
// ── NUS UUIDs ────────────────────────────────────────────────────────────
private static readonly Guid NusServiceUuid = new("0000f0f0-0000-1000-8000-00805f9b34fb");
private static readonly Guid NusCharUuid = new("0000f0f1-0000-1000-8000-00805f9b34fb");
// ── Config ───────────────────────────────────────────────────────────────
private const int CommandTimeoutMs = 3000; // 3s default timeout
private const int SilenceWindowMs = 300; // diag silence detection window
private const int MaxSilenceWaitMs = 5000; // max wait for diagnostics drain
private const int KeepaliveIdleMs = 15000; // send keepalive after 15s idle
// ── GATT resources ───────────────────────────────────────────────────────
private BluetoothLEDevice? _device;
private GattDeviceService? _nusService;
private GattCharacteristic? _nusChar;
// ── State ────────────────────────────────────────────────────────────────
private BleConnectionState _connectionState = BleConnectionState.Disconnected;
private GenerationConfig? _genConfig;
private byte _seqNum = 1;
// ── Rx processing ────────────────────────────────────────────────────────
private readonly ConcurrentQueue<byte[]> _bleQueue = new();
private readonly SemaphoreSlim _bleSignal = new(0);
private CancellationTokenSource? _loopCts;
// ── Packet parser state ──────────────────────────────────────────────────
private readonly PacketParser _parser;
// ── Response rendezvous ──────────────────────────────────────────────────
// The BLE receive loop sets this when a non-streaming packet arrives.
private readonly SemaphoreSlim _responseReady = new(0);
private volatile byte[]? _responsePayload;
private readonly object _responseLock = new();
// ── Diagnostics ──────────────────────────────────────────────────────────
private readonly Subject<DiagnosticsFrame> _diagSubject = new();
private volatile bool _diagnosticsRunning;
private long _lastDiagTickUtc;
// ── Observables ──────────────────────────────────────────────────────────
private readonly BehaviorSubject<BleConnectionState> _connSubject =
new(BleConnectionState.Disconnected);
private readonly Subject<BleDeviceInfo> _scanSubject = new();
private BluetoothLEAdvertisementWatcher? _watcher;
// ── Keepalive ────────────────────────────────────────────────────────────
private long _lastCommandTickUtc;
// ────────────────────────────────────────────────────────────────────────
// Constructor
// ────────────────────────────────────────────────────────────────────────
public BleManager()
{
_parser = new PacketParser(OnFullPacketReceived);
}
// ── IBleService: State ───────────────────────────────────────────────────
public BleConnectionState ConnectionState => _connectionState;
public bool IsConnected => _connectionState == BleConnectionState.Connected;
public IObservable<BleConnectionState> ConnectionStateChanged => _connSubject.AsObservable();
public IObservable<DiagnosticsFrame> DiagnosticsFrames => _diagSubject.AsObservable();
public bool DiagnosticsRunning => _diagnosticsRunning;
// ────────────────────────────────────────────────────────────────────────
// SCANNING
// ────────────────────────────────────────────────────────────────────────
public IObservable<BleDeviceInfo> StartScan()
{
var seen = new Dictionary<ulong, string>();
_watcher = new BluetoothLEAdvertisementWatcher
{
ScanningMode = BluetoothLEScanningMode.Active
};
_watcher.SignalStrengthFilter.InRangeThresholdInDBm = -127;
_watcher.SignalStrengthFilter.OutOfRangeThresholdInDBm = -127;
_watcher.SignalStrengthFilter.OutOfRangeTimeout = null;
_watcher.Received += (_, args) =>
{
ulong addr = args.BluetoothAddress;
string name = args.Advertisement.LocalName?.Trim() ?? string.Empty;
bool hasName = !string.IsNullOrWhiteSpace(name);
lock (seen)
{
if (!seen.ContainsKey(addr))
{
seen[addr] = hasName ? name : $"Unknown [{new BleDeviceInfo(addr, "", 0).MacAddress}]";
_scanSubject.OnNext(new BleDeviceInfo(addr, seen[addr], args.RawSignalStrengthInDBm));
}
else if (hasName && seen[addr].StartsWith("Unknown"))
{
seen[addr] = name;
_scanSubject.OnNext(new BleDeviceInfo(addr, name, args.RawSignalStrengthInDBm));
}
}
};
_watcher.Start();
return _scanSubject.AsObservable();
}
public void StopScan()
{
_watcher?.Stop();
_watcher = null;
}
// ────────────────────────────────────────────────────────────────────────
// CONNECTION
// ────────────────────────────────────────────────────────────────────────
public async Task<bool> ConnectAsync(BleDeviceInfo device, CancellationToken ct = default)
{
SetState(BleConnectionState.Connecting);
try
{
// Step 1: Resolve device
_device = await BluetoothLEDevice.FromBluetoothAddressAsync(device.Address);
if (_device == null) return Fail("Could not resolve device from address.");
_device.ConnectionStatusChanged += OnDeviceConnectionStatusChanged;
// Step 2: Open GATT channel with retry
if (!await OpenGattChannelAsync(ct)) return Fail("Could not open GATT channel.");
// Step 3: Stabilize
await Task.Delay(1500, ct);
// Step 4: Get NUS service
_nusService = await GetServiceAsync(NusServiceUuid, ct);
if (_nusService == null) return Fail("NUS service not found.");
// Step 5: Get characteristic
_nusChar = await GetCharacteristicAsync(_nusService, NusCharUuid, ct);
if (_nusChar == null) return Fail("NUS characteristic not found.");
// Step 6: Enable notifications
_nusChar.ValueChanged += OnCharValueChanged;
await _nusChar.WriteClientCharacteristicConfigurationDescriptorAsync(
GattClientCharacteristicConfigurationDescriptorValue.Notify);
// Step 7: Start BLE processing loop
StartProcessingLoop();
SetState(BleConnectionState.Connected);
return true;
}
catch (OperationCanceledException) { return Fail("Connection cancelled."); }
catch (Exception ex) { return Fail($"Connection error: {ex.Message}"); }
}
public async Task DisconnectAsync()
{
SetState(BleConnectionState.Disconnecting);
if (_diagnosticsRunning)
await StopDiagnosticsAsync();
StopProcessingLoop();
if (_nusChar != null)
{
_nusChar.ValueChanged -= OnCharValueChanged;
try { await _nusChar.WriteClientCharacteristicConfigurationDescriptorAsync(
GattClientCharacteristicConfigurationDescriptorValue.None); } catch { }
}
_nusChar = null;
_nusService?.Dispose();
_nusService = null;
if (_device != null)
{
_device.ConnectionStatusChanged -= OnDeviceConnectionStatusChanged;
_device.Dispose();
_device = null;
}
SetState(BleConnectionState.Disconnected);
}
// ────────────────────────────────────────────────────────────────────────
// DEVICE INFO
// ────────────────────────────────────────────────────────────────────────
public async Task<EcuInfo?> ReadEcuInfoAsync(CancellationToken ct = default)
{
var frame = PacketBuilder.BuildReadInfo(NextSeq());
var result = await SendAndWaitAsync(frame, ct);
if (!result.Success) return null;
var info = EcuInfo.Parse(result.Payload);
// Store generation config for subsequent table operations
var gen = GenerationConfig.ResolveGeneration(info.AppInfoVersion);
_genConfig = GenerationConfig.For(gen);
return info;
}
// ────────────────────────────────────────────────────────────────────────
// AUTH
// ────────────────────────────────────────────────────────────────────────
public async Task<CommandResult> UnlockAsync(string password, CancellationToken ct = default)
{
var payload = BuildUnlockPayload(_genConfig?.UnlockCmd ?? Commands.APP_UNLOCK, password, isReset: false);
var frame = PacketBuilder.Build(Commands.TL_NONPOSTED, NextSeq(), payload);
return await SendAndWaitAsync(frame, ct);
}
public async Task<CommandResult> UnlockTunerAsync(string password, CancellationToken ct = default)
{
var payload = BuildUnlockPayload(Commands.APP_UNLOCK_TUNER, password, isReset: false);
var frame = PacketBuilder.Build(Commands.TL_NONPOSTED, NextSeq(), payload);
return await SendAndWaitAsync(frame, ct);
}
// ────────────────────────────────────────────────────────────────────────
// TABLE OPERATIONS
// ────────────────────────────────────────────────────────────────────────
public Task<CommandResult> ReadTable2DAsync(ushort address, byte lengthBytes, bool userTable = false, CancellationToken ct = default)
=> ReadTableAsync(
userTable ? (_genConfig?.ReadCmd2DUser ?? Commands.APP_MEMRD_2D_USER)
: (_genConfig?.ReadCmd2D ?? Commands.APP_MEMRD_2D),
address, lengthBytes, ct);
public Task<CommandResult> WriteTable2DAsync(ushort address, byte[] data, bool userTable = false, CancellationToken ct = default)
=> WriteTableAsync(
userTable ? (_genConfig?.WriteCmd2DUser ?? Commands.APP_MEMWR_2D_USER)
: (_genConfig?.WriteCmd2D ?? Commands.APP_MEMWR_2D),
address, data, ct);
public Task<CommandResult> ReadTable1DAsync(ushort address, byte lengthBytes, CancellationToken ct = default)
=> ReadTableAsync(_genConfig?.ReadCmd1D ?? Commands.APP_MEMRD_1D, address, lengthBytes, ct);
public Task<CommandResult> WriteTable1DAsync(ushort address, byte[] data, CancellationToken ct = default)
=> WriteTableAsync(_genConfig?.WriteCmd1D ?? Commands.APP_MEMWR_1D, address, data, ct);
public Task<CommandResult> ReadSubTableAsync(ushort address, CancellationToken ct = default)
=> ReadTableAsync(_genConfig?.ReadCmdSubT ?? Commands.APP_MEMRD_SUBT, address,
(byte)TuneBoss.Core.Models.SubTable.TotalBytes, ct);
public Task<CommandResult> WriteSubTableAsync(ushort address, byte[] data, CancellationToken ct = default)
=> WriteTableAsync(_genConfig?.WriteCmdSubT ?? Commands.APP_MEMWR_SUBT, address, data, ct);
public Task<CommandResult> ReadMiscAsync(ushort address, byte lengthBytes, CancellationToken ct = default)
=> ReadTableAsync(_genConfig?.ReadCmdMisc ?? Commands.APP_MEMRD_MISC, address, lengthBytes, ct);
public Task<CommandResult> WriteMiscAsync(ushort address, byte[] data, CancellationToken ct = default)
=> WriteTableAsync(_genConfig?.WriteCmdMisc ?? Commands.APP_MEMWR_MISC, address, data, ct);
// ────────────────────────────────────────────────────────────────────────
// FLASH WRITE
// ────────────────────────────────────────────────────────────────────────
public async Task<CommandResult> FlashWriteAsync(CancellationToken ct = default)
{
await StopDiagnosticsIfRunningAsync(ct);
var now = DateTime.Now;
var payload = new byte[]
{
Commands.APP_FLASH_WR,
(byte)'F', (byte)'S', (byte)'R',
(byte)now.Day,
(byte)now.Month,
(byte)(now.Year % 100),
0x00
};
var frame = PacketBuilder.Build(Commands.TL_NONPOSTED, NextSeq(), payload);
var result = await SendAndWaitAsync(frame, ct);
await RestartDiagnosticsIfStoppedAsync(ct);
return result;
}
// ────────────────────────────────────────────────────────────────────────
// FIRST-USE SETTINGS (APP_FIRSTUSE)
// ────────────────────────────────────────────────────────────────────────
public async Task<CommandResult> WriteFirstUseAsync(byte[] fourBytes, CancellationToken ct = default)
{
if (fourBytes is null || fourBytes.Length < 4)
return CommandResult.Fail(0x00, "First-use payload must be 4 bytes.");
// Legacy updateFirstUseSettings layout: [APP_FIRSTUSE, 0x00, 0x00, 0x00, b0, b1, b2, b3]
var payload = new byte[]
{
Commands.APP_FIRSTUSE, 0x00, 0x00, 0x00,
fourBytes[0], fourBytes[1], fourBytes[2], fourBytes[3],
};
var frame = PacketBuilder.Build(Commands.TL_NONPOSTED, NextSeq(), payload);
return await SendAndWaitAsync(frame, ct);
}
// ────────────────────────────────────────────────────────────────────────
// DIAGNOSTICS
// ────────────────────────────────────────────────────────────────────────
public async Task StartDiagnosticsAsync(CancellationToken ct = default)
{
if (_diagnosticsRunning) return;
_diagnosticsRunning = true;
Interlocked.Exchange(ref _lastDiagTickUtc, DateTime.UtcNow.Ticks);
await SendRawAsync(PacketBuilder.BuildMonStart());
}
public async Task StopDiagnosticsAsync(CancellationToken ct = default)
{
if (!_diagnosticsRunning) return;
_diagnosticsRunning = false;
await SendRawAsync(PacketBuilder.BuildMonStop());
// Wait for silence — device keeps sending 0x70s for a while after STOP
Interlocked.Exchange(ref _lastDiagTickUtc, DateTime.UtcNow.Ticks);
int waited = 0;
while (waited < MaxSilenceWaitMs)
{
await Task.Delay(100, ct);
waited += 100;
long elapsed = (DateTime.UtcNow.Ticks - Interlocked.Read(ref _lastDiagTickUtc))
/ TimeSpan.TicksPerMillisecond;
if (elapsed >= SilenceWindowMs) break;
}
// Flush residual 0x70 packets
_parser.Reset();
while (_bleQueue.TryDequeue(out byte[]? _)) { }
}
// ────────────────────────────────────────────────────────────────────────
// KEEPALIVE
// ────────────────────────────────────────────────────────────────────────
public void OnKeepaliveTimer()
{
if (!IsConnected) return;
long idleMs = (DateTime.UtcNow.Ticks - Interlocked.Read(ref _lastCommandTickUtc))
/ TimeSpan.TicksPerMillisecond;
if (idleMs >= KeepaliveIdleMs)
_ = SendRawAsync(PacketBuilder.BuildReadInfo(NextSeq()));
}
// ────────────────────────────────────────────────────────────────────────
// PRIVATE: Table helpers
// ────────────────────────────────────────────────────────────────────────
private async Task<CommandResult> ReadTableAsync(
byte cmd, ushort address, byte lengthBytes, CancellationToken ct)
{
await StopDiagnosticsIfRunningAsync(ct);
var addrBytes = BitConverter.GetBytes(address); // little-endian
var payload = new byte[] { cmd, lengthBytes, addrBytes[0], addrBytes[1] };
var frame = PacketBuilder.Build(Commands.TL_NONPOSTED, NextSeq(), payload);
// Flush residual diagnostic packets before sending
_parser.Reset();
while (_bleQueue.TryDequeue(out byte[]? _)) { }
var result = await SendAndWaitAsync(frame, ct);
await RestartDiagnosticsIfStoppedAsync(ct);
return result;
}
private async Task<CommandResult> WriteTableAsync(
byte cmd, ushort address, byte[] data, CancellationToken ct)
{
await StopDiagnosticsIfRunningAsync(ct);
var addrBytes = BitConverter.GetBytes(address);
var payload = new byte[4 + data.Length];
payload[0] = cmd;
// The length byte is the LAST inclusive offset the device writes (offset 0..N),
// exactly like the read commands — so N = data.Length - 1. Sending the raw count
// wrote one byte past the region and returned 0x54 (APP_MEMADDR_INV) — seen on the
// tightly-packed 1D tables and on 2D part-2 writes (100-byte tail region).
payload[1] = (byte)(data.Length - 1);
payload[2] = addrBytes[0];
payload[3] = addrBytes[1];
data.CopyTo(payload, 4);
var frame = PacketBuilder.Build(Commands.TL_NONPOSTED, NextSeq(), payload);
var result = await SendAndWaitAsync(frame, ct);
await RestartDiagnosticsIfStoppedAsync(ct);
return result;
}
private async Task StopDiagnosticsIfRunningAsync(CancellationToken ct)
{
if (_diagnosticsRunning)
await StopDiagnosticsAsync(ct);
}
private async Task RestartDiagnosticsIfStoppedAsync(CancellationToken ct)
{
// Intentionally does NOT auto-restart here. Resume is driven by the ViewModel
// layer (ResumeDiagnosticsIfLiveAsync) which knows whether the strip should be
// live. Restarting here as well caused a double MON_START and a frame storm that
// disrupted the next command's response matching (froze edits / writes).
}
// ────────────────────────────────────────────────────────────────────────
// PRIVATE: Send and wait for response
// ────────────────────────────────────────────────────────────────────────
private async Task<CommandResult> SendAndWaitAsync(byte[] frame, CancellationToken ct)
{
lock (_responseLock)
{
_responsePayload = null;
// drain any stale ready signal
while (_responseReady.CurrentCount > 0)
_responseReady.Wait(0);
}
await SendRawAsync(frame);
Interlocked.Exchange(ref _lastCommandTickUtc, DateTime.UtcNow.Ticks);
using var timeout = new CancellationTokenSource(CommandTimeoutMs);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeout.Token);
try
{
await _responseReady.WaitAsync(linked.Token);
}
catch (OperationCanceledException)
{
return timeout.IsCancellationRequested
? CommandResult.Timeout()
: CommandResult.Fail(0x00, "Cancelled");
}
var payload = _responsePayload;
if (payload == null || payload.Length == 0)
return CommandResult.Fail(0x00, "Empty response");
return payload[0] == 0x51
? CommandResult.Ok(payload)
: CommandResult.Fail(payload[0], $"Device returned 0x{payload[0]:X2}");
}
private async Task SendRawAsync(byte[] frame)
{
if (_nusChar == null) return;
var writer = new DataWriter();
writer.WriteBytes(frame);
var writeOption = _nusChar.CharacteristicProperties
.HasFlag(GattCharacteristicProperties.WriteWithoutResponse)
? GattWriteOption.WriteWithoutResponse
: GattWriteOption.WriteWithResponse;
await _nusChar.WriteValueAsync(writer.DetachBuffer(), writeOption);
}
// ────────────────────────────────────────────────────────────────────────
// PRIVATE: BLE receive path
// ────────────────────────────────────────────────────────────────────────
private void OnCharValueChanged(GattCharacteristic _, GattValueChangedEventArgs args)
{
try
{
var chunk = args.CharacteristicValue.ToArray();
if (chunk.Length == 0) return;
_bleQueue.Enqueue(chunk);
_bleSignal.Release();
}
catch { /* non-critical */ }
}
private void StartProcessingLoop()
{
_loopCts = new CancellationTokenSource();
var token = _loopCts.Token;
Task.Run(async () =>
{
while (!token.IsCancellationRequested)
{
await _bleSignal.WaitAsync(token);
while (_bleQueue.TryDequeue(out byte[]? chunk))
{
foreach (byte b in chunk)
_parser.ProcessByte(b);
}
}
}, token);
}
private void StopProcessingLoop()
{
_loopCts?.Cancel();
_loopCts?.Dispose();
_loopCts = null;
}
// ────────────────────────────────────────────────────────────────────────
// PRIVATE: Packet dispatch
// ────────────────────────────────────────────────────────────────────────
private void OnFullPacketReceived(PacketParser.ParsedPacket packet)
{
// ── Diagnostics frame ────────────────────────────────────────────────
if (packet.TlResponse == Commands.APP_MONITORING)
{
Interlocked.Exchange(ref _lastDiagTickUtc, DateTime.UtcNow.Ticks);
if (_diagnosticsRunning)
{
try
{
var frame = DiagnosticsFrame.Parse(packet.Payload, packet.SeqNum, DateTime.UtcNow);
_diagSubject.OnNext(frame);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[DIAG] Parse error: {ex.Message}");
}
}
return;
}
// ── Non-posted response ──────────────────────────────────────────────
lock (_responseLock)
{
_responsePayload = packet.Payload;
}
_responseReady.Release();
}
// ────────────────────────────────────────────────────────────────────────
// PRIVATE: GATT helpers
// ────────────────────────────────────────────────────────────────────────
private async Task<bool> OpenGattChannelAsync(CancellationToken ct, int maxAttempts = 6)
{
for (int i = 1; i <= maxAttempts; i++)
{
try
{
var result = await _device!.GetGattServicesAsync(BluetoothCacheMode.Uncached);
if (result.Status == GattCommunicationStatus.Success) return true;
if (result.Status == GattCommunicationStatus.AccessDenied)
await TrySilentPairAsync();
}
catch { }
if (i < maxAttempts) await Task.Delay(2000, ct);
}
return false;
}
private async Task<GattDeviceService?> GetServiceAsync(Guid uuid, CancellationToken ct, int maxAttempts = 4)
{
for (int i = 1; i <= maxAttempts; i++)
{
var result = await _device!.GetGattServicesAsync(BluetoothCacheMode.Uncached);
if (result.Status == GattCommunicationStatus.Success)
{
var svc = result.Services.FirstOrDefault(s => s.Uuid == uuid);
if (svc != null) return svc;
}
if (i < maxAttempts) await Task.Delay(1500, ct);
}
return null;
}
private async Task<GattCharacteristic?> GetCharacteristicAsync(
GattDeviceService service, Guid uuid, CancellationToken ct, int maxAttempts = 3)
{
for (int i = 1; i <= maxAttempts; i++)
{
var result = await service.GetCharacteristicsForUuidAsync(uuid, BluetoothCacheMode.Uncached);
if (result.Status == GattCommunicationStatus.Success && result.Characteristics.Count > 0)
return result.Characteristics[0];
if (i < maxAttempts) await Task.Delay(1000, ct);
}
return null;
}
private async Task TrySilentPairAsync()
{
var pairing = _device!.DeviceInformation.Pairing;
if (pairing.IsPaired || !pairing.CanPair) return;
await pairing.PairAsync(Windows.Devices.Enumeration.DevicePairingProtectionLevel.None);
await Task.Delay(800);
}
private void OnDeviceConnectionStatusChanged(BluetoothLEDevice sender, object _)
{
if (sender.ConnectionStatus == BluetoothConnectionStatus.Disconnected && IsConnected)
{
_diagnosticsRunning = false;
_parser.Reset();
while (_bleQueue.TryDequeue(out byte[]? _)) { }
SetState(BleConnectionState.Disconnected);
}
}
// ────────────────────────────────────────────────────────────────────────
// PRIVATE: Misc helpers
// ────────────────────────────────────────────────────────────────────────
private void SetState(BleConnectionState state)
{
_connectionState = state;
_connSubject.OnNext(state);
}
private bool Fail(string _) { SetState(BleConnectionState.Disconnected); return false; }
private byte NextSeq() => _seqNum == 0xFF ? (_seqNum = 1) : _seqNum++;
private static byte[] BuildUnlockPayload(byte unlockCmd, string password, bool isReset)
{
var now = DateTime.Now;
var pwd = System.Text.Encoding.ASCII.GetBytes(password.Trim());
var data = new List<byte>
{
unlockCmd, 0x00, 0x00, 0x00
};
// 16-byte password field (null-padded)
for (int i = 0; i < 16; i++)
data.Add(i < pwd.Length ? pwd[i] : (byte)0x00);
data.Add((byte)now.Day);
data.Add((byte)now.Month);
data.Add((byte)(now.Year % 100));
data.Add(0x00); // reserved
// Sentinel bytes matching original
data.AddRange(new byte[] { 0xF3, 0xF3, 0xF3, 0xF3 });
return data.ToArray();
}
public void Dispose()
{
StopProcessingLoop();
_nusService?.Dispose();
_device?.Dispose();
_diagSubject.Dispose();
_connSubject.Dispose();
_responseReady.Dispose();
_bleSignal.Dispose();
}
}
+196
View File
@@ -0,0 +1,196 @@
using TuneBoss.Core.Models;
using TuneBoss.Core.Protocol;
namespace TuneBoss.Core.BLE;
/// <summary>
/// Represents a discovered BLE device before connection.
/// </summary>
public sealed record BleDeviceInfo(
ulong Address,
string Name,
short Rssi)
{
public string MacAddress => FormatMac(Address);
private static string FormatMac(ulong a)
{
var b = BitConverter.GetBytes(a);
return $"{b[5]:X2}:{b[4]:X2}:{b[3]:X2}:{b[2]:X2}:{b[1]:X2}:{b[0]:X2}";
}
public override string ToString() => $"{Name} | {MacAddress} | {Rssi} dBm";
}
/// <summary>
/// Connection state published to observers.
/// </summary>
public enum BleConnectionState
{
Disconnected,
Connecting,
Connected,
Disconnecting,
}
/// <summary>
/// Result of a command sent to the device.
/// </summary>
public sealed record CommandResult(
bool Success,
byte ResponseCode, // 0x51 = success, 0x52 = fail, etc.
byte[] Payload,
string? ErrorMessage = null)
{
public static CommandResult Ok(byte[] payload) =>
new(true, 0x51, payload);
public static CommandResult Fail(byte responseCode, string message) =>
new(false, responseCode, Array.Empty<byte>(), message);
public static CommandResult Timeout() =>
new(false, 0x00, Array.Empty<byte>(), "Command timed out");
}
/// <summary>
/// The primary BLE service contract.
/// All table and device operations go through this interface.
/// The UI layer never touches BLE APIs directly.
/// </summary>
public interface IBleService : IDisposable
{
// ── State ────────────────────────────────────────────────────────────────
BleConnectionState ConnectionState { get; }
bool IsConnected { get; }
/// <summary>Observable connection state changes.</summary>
IObservable<BleConnectionState> ConnectionStateChanged { get; }
// ── Scanning ─────────────────────────────────────────────────────────────
/// <summary>Starts BLE advertisement scanning. Emits discovered devices.</summary>
IObservable<BleDeviceInfo> StartScan();
/// <summary>Stops active scan.</summary>
void StopScan();
// ── Connection ───────────────────────────────────────────────────────────
/// <summary>
/// Connects to a device. Handles GATT channel opening, NUS service
/// discovery, notification subscription, and the post-connect APP_READ_INFO.
/// </summary>
Task<bool> ConnectAsync(BleDeviceInfo device, CancellationToken ct = default);
/// <summary>Gracefully disconnects, stops diagnostics, cleans up GATT resources.</summary>
Task DisconnectAsync();
// ── Device info ──────────────────────────────────────────────────────────
/// <summary>
/// Reads ECU info (APP_READ_INFO). Returns null on timeout or failure.
/// Also sets the active GenerationConfig internally.
/// </summary>
Task<EcuInfo?> ReadEcuInfoAsync(CancellationToken ct = default);
// ── Auth ─────────────────────────────────────────────────────────────────
/// <summary>Sends unlock command with password and current date.</summary>
Task<CommandResult> UnlockAsync(string password, CancellationToken ct = default);
/// <summary>Sends tuner unlock command.</summary>
Task<CommandResult> UnlockTunerAsync(string password, CancellationToken ct = default);
// ── Table operations ─────────────────────────────────────────────────────
/// <summary>
/// Reads a 2D table (split read: two halves, with diagnostics pause/resume).
/// Returns the raw combined payload.
/// </summary>
Task<CommandResult> ReadTable2DAsync(
ushort address,
byte lengthBytes,
bool userTable = false,
CancellationToken ct = default);
/// <summary>Writes a 2D table (split write).</summary>
Task<CommandResult> WriteTable2DAsync(
ushort address,
byte[] data,
bool userTable = false,
CancellationToken ct = default);
/// <summary>Reads a 1D table.</summary>
Task<CommandResult> ReadTable1DAsync(
ushort address,
byte lengthBytes,
CancellationToken ct = default);
/// <summary>Writes a 1D table.</summary>
Task<CommandResult> WriteTable1DAsync(
ushort address,
byte[] data,
CancellationToken ct = default);
/// <summary>Reads a subtable.</summary>
Task<CommandResult> ReadSubTableAsync(
ushort address,
CancellationToken ct = default);
/// <summary>Writes a subtable.</summary>
Task<CommandResult> WriteSubTableAsync(
ushort address,
byte[] data,
CancellationToken ct = default);
/// <summary>Reads misc values block.</summary>
Task<CommandResult> ReadMiscAsync(
ushort address,
byte lengthBytes,
CancellationToken ct = default);
/// <summary>Writes misc values block.</summary>
Task<CommandResult> WriteMiscAsync(
ushort address,
byte[] data,
CancellationToken ct = default);
// ── Flash ────────────────────────────────────────────────────────────────
/// <summary>Sends APP_FLASH_WR to persist all writes to ECU flash.</summary>
Task<CommandResult> FlashWriteAsync(CancellationToken ct = default);
/// <summary>
/// Writes the 4-byte first-use settings block via APP_FIRSTUSE (0x35).
/// Byte[0] (DD slot) carries the TPS-calibration-done flag.
/// </summary>
Task<CommandResult> WriteFirstUseAsync(byte[] fourBytes, CancellationToken ct = default);
// ── Diagnostics streaming ────────────────────────────────────────────────
/// <summary>
/// Observable stream of diagnostics frames (APP_MONITORING 0x70).
/// Emits continuously while diagnostics are running.
/// </summary>
IObservable<DiagnosticsFrame> DiagnosticsFrames { get; }
bool DiagnosticsRunning { get; }
/// <summary>Sends APP_MON_START and begins emitting DiagnosticsFrames.</summary>
Task StartDiagnosticsAsync(CancellationToken ct = default);
/// <summary>
/// Sends APP_MON_STOP and waits for silence before returning.
/// Safe to call even if diagnostics aren't running.
/// </summary>
Task StopDiagnosticsAsync(CancellationToken ct = default);
// ── Keepalive ────────────────────────────────────────────────────────────
/// <summary>
/// Called by the keepalive timer. Sends APP_READ_INFO if idle for > 15s.
/// Internally managed — exposed for test visibility only.
/// </summary>
void OnKeepaliveTimer();
}
+168
View File
@@ -0,0 +1,168 @@
namespace TuneBoss.Core.BLE;
/// <summary>
/// Stateful byte-stream parser for TuneBoss BLE packets.
/// Extracted from Form1_BLEhelper.cs ProcessByte() / OnFullPacketReceived().
/// Thread-safe only when all calls are serialized (BLE processing loop does this).
/// </summary>
public sealed class PacketParser
{
public sealed record ParsedPacket(
byte DlCommand,
byte SeqNum,
byte DwCount,
byte TlResponse,
byte TlCommand,
byte TlLength,
byte[] Payload);
private readonly Action<ParsedPacket> _onPacketReceived;
// ── Parser state ─────────────────────────────────────────────────────────
private int _byteCycle;
private int _startSeqCycle;
private int _packetHeaderCycle;
private int _dWordByteTrack;
private int _dWordCheckSumTrack;
private readonly byte[] _startSeq = new byte[4];
private readonly byte[] _packetHeader = new byte[4];
private readonly List<byte> _dataBuffer = new();
private readonly List<byte> _csBuffer = new();
private byte _currDlCommand;
private byte _currDlSeqCount;
private byte _currDlDWordCount;
private byte _currTlResp;
private byte _currTlCommand;
private byte _currTlLength;
public PacketParser(Action<ParsedPacket> onPacketReceived)
{
_onPacketReceived = onPacketReceived;
}
public void Reset()
{
_byteCycle = 0;
_startSeqCycle = 0;
_packetHeaderCycle = 0;
_dWordByteTrack = 0;
_dWordCheckSumTrack = 0;
_dataBuffer.Clear();
_csBuffer.Clear();
_currDlCommand = 0;
_currDlSeqCount = 0;
_currDlDWordCount = 0;
_currTlResp = 0;
_currTlCommand = 0;
_currTlLength = 0;
}
public void ProcessByte(byte b)
{
// ── Zone 1: bytes 0–3 — preamble FF 00 FF 00 ─────────────────────
if (_byteCycle <= 3)
{
_startSeq[_startSeqCycle] = b;
if (_startSeqCycle == 3)
{
bool valid = _startSeq[0] == 0xFF && _startSeq[1] == 0x00
&& _startSeq[2] == 0xFF && _startSeq[3] == 0x00;
if (!valid) { Reset(); return; }
}
_startSeqCycle++;
_byteCycle++;
return;
}
// ── Zone 2: bytes 4–7 — packet header ────────────────────────────
if (_byteCycle <= 7)
{
_packetHeader[_packetHeaderCycle] = b;
if (_packetHeaderCycle == 3)
{
if (!HeaderIntegrityOk(_packetHeader)) { Reset(); return; }
_currDlCommand = _packetHeader[0];
_currDlSeqCount = _packetHeader[1];
_currDlDWordCount = _packetHeader[2];
}
_packetHeaderCycle++;
_byteCycle++;
return;
}
// ── Zone 3: no payload ────────────────────────────────────────────
if (_currDlDWordCount == 0) { Reset(); return; }
// ── Zone 4: bytes 8–11 — TL header (first DWord of payload) ──────
if (_byteCycle <= 11)
{
switch (_byteCycle)
{
case 8: _currTlResp = b; break;
case 9: _currTlCommand = b; break;
case 10: _currTlLength = b; break;
}
_dataBuffer.Add(b);
_byteCycle++;
return;
}
// ── Zone 5: bytes 12+ — payload bytes + checksum ─────────────────
_byteCycle++;
int payloadBytes = 4 * (_currDlDWordCount - 1); // DWords after the TL header
if (_dWordByteTrack < payloadBytes)
{
_dataBuffer.Add(b);
_dWordByteTrack++;
}
else if (_dWordCheckSumTrack < 4)
{
_csBuffer.Add(b);
_dWordCheckSumTrack++;
if (_dWordCheckSumTrack == 4)
OnFullPacketReceived();
}
}
private void OnFullPacketReceived()
{
byte[] data = _dataBuffer.ToArray();
byte[] cs = _csBuffer.ToArray();
// Verify checksum
var expected = Protocol.ChecksumHelper.GenChecksumDW(data);
var receivedCs = (uint)(cs[0] | (cs[1] << 8) | (cs[2] << 16) | (cs[3] << 24));
if (expected != receivedCs) { Reset(); return; }
var packet = new ParsedPacket(
DlCommand: _currDlCommand,
SeqNum: _currDlSeqCount,
DwCount: _currDlDWordCount,
TlResponse: _currTlResp,
TlCommand: _currTlCommand,
TlLength: _currTlLength,
Payload: data);
Reset();
_onPacketReceived(packet);
}
private static bool HeaderIntegrityOk(byte[] h)
{
byte sum = unchecked((byte)(h[0] + h[1] + h[2]));
byte invSum = unchecked((byte)~sum);
return invSum == h[3];
}
}
+368
View File
@@ -0,0 +1,368 @@
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using TuneBoss.Core.Models;
using TuneBoss.Core.Protocol;
namespace TuneBoss.Core.BLE;
/// <summary>
/// A fully in-memory <see cref="IBleService"/> for hardware-free testing.
///
/// • Scan/connect/unlock succeed instantly.
/// • Reads synthesize correctly-framed wire payloads (4-byte header, data at offset 4,
/// the device len+1 convention, and the 2D split-read halves) so every table,
/// misc block and 1D table populates in the real UI.
/// • Diagnostics stream a LIVE, moving RPM + load (sine sweep, ~20 Hz) so the 2D
/// tuning-table tracker visibly walks across the grid. The six gauge channels
/// move with it (MAP follows load, ETemp warms up, AFR wobbles, spark advances).
///
/// Swap it in via DI (see the App.xaml.cs snippet in SimBleService_DI_README).
/// </summary>
public sealed class SimBleService : IBleService
{
// ── Tunables (change before connecting to exercise different cases) ────────
public byte SimAppInfoVersion { get; set; } = 2; // 2=Gen3, 1=Gen2, 245=Gen1
public byte SimFwVersion { get; set; } = 193; // try 70 / 100 / 150 to see FW gating
public bool SimTpsCalibrated { get; set; } = false; // false => connect warns + jumps to TPS cal
public byte SimRpmMax { get; set; } = 130; // ×100 = 13000 rpm limit
public double SweepSeconds { get; set; } = 6.0; // one full idle→redline→idle cycle
public int EmitHz { get; set; } = 20; // diagnostics frames per second
// ── Plumbing ──────────────────────────────────────────────────────────────
private readonly BehaviorSubject<BleConnectionState> _state = new(BleConnectionState.Disconnected);
private readonly Subject<DiagnosticsFrame> _diag = new();
private CancellationTokenSource? _diagCts;
private byte _seq;
private readonly Random _rng = new(1234);
public BleConnectionState ConnectionState => _state.Value;
public bool IsConnected => _state.Value == BleConnectionState.Connected;
public IObservable<BleConnectionState> ConnectionStateChanged => _state.AsObservable();
// ── Scan ──────────────────────────────────────────────────────────────────
public IObservable<BleDeviceInfo> StartScan() => Observable.Create<BleDeviceInfo>(o =>
{
o.OnNext(new BleDeviceInfo(0xAABBCCDDEEFF, "B_SIM-PG1", -42));
o.OnNext(new BleDeviceInfo(0x0011223344556, "B_SIM-R15", -57));
return Disposable.Empty; // stay "scanning" (no completion)
});
public void StopScan() { }
// ── Connect ───────────────────────────────────────────────────────────────
public async Task<bool> ConnectAsync(BleDeviceInfo device, CancellationToken ct = default)
{
_state.OnNext(BleConnectionState.Connecting);
await Task.Delay(120, ct);
_state.OnNext(BleConnectionState.Connected);
// Auto-start the live stream so the persistent gauge strip + table tracker
// come alive immediately. Idempotent — a later StartDiagnosticsAsync() is a no-op.
await StartDiagnosticsAsync(ct);
return true;
}
public async Task DisconnectAsync()
{
await StopDiagnosticsAsync();
_state.OnNext(BleConnectionState.Disconnecting);
_state.OnNext(BleConnectionState.Disconnected);
}
// ── Device info ───────────────────────────────────────────────────────────
public Task<EcuInfo?> ReadEcuInfoAsync(CancellationToken ct = default) =>
Task.FromResult<EcuInfo?>(new EcuInfo
{
Username = "SIM-RIDER",
UniqueId = "51A0-0000-0000-0001",
AppInfoVersion = SimAppInfoVersion,
FwVersion = SimFwVersion,
HwVersion = 10,
UpgradeRpmMax = SimRpmMax,
BikeManufacturer = 1, // Yamaha
UpgradeLogImmo = 0x0F, // dual-injector unlocked
FirstUseInfo0 = SimTpsCalibrated ? TpsCalibration.CalDoneFlag : (byte)0,
});
// ── Auth ──────────────────────────────────────────────────────────────────
public Task<CommandResult> UnlockAsync(string password, CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(Array.Empty<byte>()));
public Task<CommandResult> UnlockTunerAsync(string password, CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(Array.Empty<byte>()));
// ── 2D tables (split read) ────────────────────────────────────────────────
// The VM reads part 1 with len = SplitFirstLength (0x7F) at the base address,
// then part 2 (len = 100) at base+128. FromSplitResponses copies from offset 4
// of each. We branch on the requested length. Tuning + AFR share this layout.
public Task<CommandResult> ReadTable2DAsync(ushort address, byte lengthBytes,
bool userTable = false, CancellationToken ct = default)
{
var combined = Canonical2D(); // 228 bytes
const int firstCount = TuningTable.SplitFirstLength + 1; // 128
if (lengthBytes == TuningTable.SplitFirstLength)
return OkFramed(Slice(combined, 0, firstCount), Commands.APP_MEMRD_2D);
int secondCount = TuningTable.TotalPayloadBytes - firstCount; // 100
return OkFramed(Slice(combined, firstCount, secondCount), Commands.APP_MEMRD_2D);
}
public Task<CommandResult> WriteTable2DAsync(ushort address, byte[] data,
bool userTable = false, CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(data));
// ── 1D tables ─────────────────────────────────────────────────────────────
public Task<CommandResult> ReadTable1DAsync(ushort address, byte lengthBytes,
CancellationToken ct = default)
{
// TPS absolute bounds live at a fixed address; return [max, min, ...] so the
// calibration page validates a full sweep successfully.
var addr = TpsCalibration.For((GenerationType)SimAppInfoVersion, SimFwVersion);
if (address == addr.AbsBounds)
return OkFramed(TpsAbsBounds(), Commands.APP_MEMRD_1D);
return OkFramed(Canonical1D(), Commands.APP_MEMRD_1D);
}
/// <summary>8-byte TPS abs-bounds block: [absMax, absMin, store2, store3, ...].</summary>
private static byte[] TpsAbsBounds()
=> new byte[] { 195, 5, 197, 199, 201, 203, 205, 207 };
public Task<CommandResult> WriteTable1DAsync(ushort address, byte[] data,
CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(data));
// ── Subtables ─────────────────────────────────────────────────────────────
public Task<CommandResult> ReadSubTableAsync(ushort address, CancellationToken ct = default)
=> OkFramed(CanonicalSub(), Commands.APP_MEMRD_SUBT);
public Task<CommandResult> WriteSubTableAsync(ushort address, byte[] data,
CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(data));
// ── Misc ──────────────────────────────────────────────────────────────────
public Task<CommandResult> ReadMiscAsync(ushort address, byte lengthBytes,
CancellationToken ct = default)
=> OkFramed(CanonicalMisc(lengthBytes), Commands.APP_MEMRD_MISC);
public Task<CommandResult> WriteMiscAsync(ushort address, byte[] data,
CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(data));
// ── Flash ─────────────────────────────────────────────────────────────────
public Task<CommandResult> FlashWriteAsync(CancellationToken ct = default)
=> Task.FromResult(CommandResult.Ok(Array.Empty<byte>()));
// ── First-use settings ──────────────────────────────────────────────────────
public Task<CommandResult> WriteFirstUseAsync(byte[] fourBytes, CancellationToken ct = default)
{
if (fourBytes is { Length: >= 1 })
SimTpsCalibrated = fourBytes[0] == TpsCalibration.CalDoneFlag;
return Task.FromResult(CommandResult.Ok(Array.Empty<byte>()));
}
// ── Diagnostics (the moving part) ─────────────────────────────────────────
public IObservable<DiagnosticsFrame> DiagnosticsFrames => _diag.AsObservable();
public bool DiagnosticsRunning => _diagCts is not null;
public Task StartDiagnosticsAsync(CancellationToken ct = default)
{
if (_diagCts is not null) return Task.CompletedTask;
_diagCts = new CancellationTokenSource();
_ = RunDiagnosticsLoop(_diagCts.Token);
return Task.CompletedTask;
}
public Task StopDiagnosticsAsync(CancellationToken ct = default)
{
_diagCts?.Cancel();
_diagCts?.Dispose();
_diagCts = null;
return Task.CompletedTask;
}
public void OnKeepaliveTimer() { /* no-op in sim */ }
private async Task RunDiagnosticsLoop(CancellationToken ct)
{
var period = TimeSpan.FromMilliseconds(1000.0 / Math.Max(1, EmitHz));
using var timer = new PeriodicTimer(period);
var start = DateTime.UtcNow;
// RPM raw sweep range — must sit inside the canonical RpmAxis (10..217)
const double rpmIdle = 12, rpmRedline = 205;
const double loadLo = 22, loadHi = 95;
try
{
while (await timer.WaitForNextTickAsync(ct))
{
double tSec = (DateTime.UtcNow - start).TotalSeconds;
double phase = tSec / Math.Max(0.5, SweepSeconds) * 2 * Math.PI;
double s = (Math.Sin(phase) + 1) / 2; // 0..1
bool rising = Math.Cos(phase) >= 0;
byte rpmRaw = (byte)Math.Round(rpmIdle + s * (rpmRedline - rpmIdle));
byte load = (byte)Math.Round(loadLo + s * (loadHi - loadLo) + Noise(2));
byte tps = (byte)Math.Clamp(Math.Round(s * 100 + Noise(2)), 0, 100);
byte map = (byte)Math.Clamp(load + Noise(2), 0, 255);
byte etemp = (byte)Math.Clamp(40 + tSec * 3, 40, 92); // warm-up ramp
byte afrx10 = (byte)Math.Clamp(Math.Round(145 + Noise(8)), 120, 170);
_diag.OnNext(new DiagnosticsFrame
{
SeqNum = _seq++,
ReceivedAt = DateTime.UtcNow,
// tracker channels
Load = load,
RPM_Raw = rpmRaw,
TPS_Percent = tps,
TPS_Raw = (byte)Math.Clamp(Math.Round(10 + s * 178), 0, 255),
// gauges
Baro_kPa = 101,
Baro_Dynamic = 101,
VBAT_deciV = (byte)(138 - (int)(s * 6)), // sags under load
ETEMP_DegC = etemp,
IAT_DegC = 32,
MAP_kPa = map,
MAP_Lo_Avg = (byte)Math.Max(0, map - 4),
MAP_Hi_Avg_Raw = (byte)Math.Clamp(s * 120, 0, 255), // doubles as meter speed
O2_AFR_x10 = afrx10,
FuelStartAngle1_Raw = (byte)Math.Clamp(20 + s * 30, 0, 255),
FuelStartAngle2_Raw = (byte)Math.Clamp(20 + s * 30, 0, 255),
FuelPulseWidth1 = (int)(1500 + s * 6000),
FuelEndAngle = (int)(s * 360),
SparkAngle1 = (sbyte)Math.Clamp(5 + s * 30, -30, 60),
SparkAngle2 = (sbyte)Math.Clamp(5 + s * 30, -30, 60),
SparkPulseWidth = 25,
CrankSyncLostCounter = 0,
// packed state bytes
CrankState_Raw = 0x06, // 6 = RUNNING (low nibble), TC_Mode 0 (high)
UMState_Packed = 0x33, // UMState 3 = RUN, gear 3 (high nibble)
ThrottleState_Packed = (byte)(rising ? 0x01 : 0x02), // Accel / Decel
RPMState_Packed = (byte)((rising ? 0x02 : 0x01) | 0x80), // Accel/Decel + StayTuned
// no faults
ErrorsFatal = 0,
AnalogError_Current = 0, AnalogError_Persistent = 0,
OutputError_Current = 0, OutputError_Persistent = 0,
});
}
}
catch (OperationCanceledException) { /* normal stop */ }
}
private double Noise(double amp) => (_rng.NextDouble() - 0.5) * 2 * amp;
// ── Canonical payloads ────────────────────────────────────────────────────
/// <summary>228-byte 2D combined payload: smooth fuel surface, realistic axes.</summary>
private static byte[] Canonical2D()
{
var data = new byte[TuningTable.DataBytes]; // 24 cols × 8 rows
for (int r = 0; r < TuningTable.Rows; r++)
for (int c = 0; c < TuningTable.Cols; c++)
data[r * TuningTable.Cols + c] = (byte)Math.Clamp(30 + c * 8 + r * 3, 0, 255);
var loadAxis = new byte[TuningTable.Rows];
for (int r = 0; r < TuningTable.Rows; r++) loadAxis[r] = (byte)(20 + r * 10); // 20..90
var rpmAxis = new byte[TuningTable.Cols];
for (int c = 0; c < TuningTable.Cols; c++) rpmAxis[c] = (byte)(10 + c * 9); // 10..217 (×100)
var t = new TuningTable
{
Data = data, LoadAxis = loadAxis, RpmAxis = rpmAxis,
MaxRaw = 255, MinRaw = 0, Mult = 1, Sign = 0,
};
return t.ToWirePayload(); // 228 bytes
}
/// <summary>24-byte 1D table: monotonic axis + ramp values, unscaled.</summary>
private static byte[] Canonical1D()
{
var t = new OneDimTable
{
MaxRaw = 255, MinRaw = 0,
RawSignedFlag = 0, ConvSignedFlag = 0,
RawMultiplier = 1, ConvMultiplier = 1, RawRounding = 0, ConvOffset = 0,
};
for (int i = 0; i < OneDimTable.PointCount; i++)
{
t.RawAxis[i] = i * 10; // 0,10,...,70
t.ConvValues[i] = 20 + i * 6; // gentle ramp
}
return t.ToWirePayload(); // 24 bytes
}
/// <summary>40-byte subtable body (4×6) with a monotonic RPM/load axis so it parses cleanly.</summary>
private static byte[] CanonicalSub()
{
var buf = new byte[SubTable.TotalBytes]; // 40
for (int i = 0; i < SubTable.DataBytes; i++) buf[i] = (byte)(40 + i);
// load axis (4)
var lo = SubTable.DefaultLoadAxis;
for (int i = 0; i < SubTable.LoadBytes; i++) buf[SubTable.DataBytes + i] = lo[i];
// rpm axis (12 = 6 lo/hi pairs)
for (int c = 0; c < SubTable.Cols; c++)
{
buf[SubTable.DataBytes + SubTable.LoadBytes + c * 2] = (byte)(15 + c * 20);
buf[SubTable.DataBytes + SubTable.LoadBytes + c * 2 + 1] = (byte)(20 + c * 20);
}
return buf;
}
/// <summary>
/// Misc block sized for the request (returns len+1 bytes, mimicking the device
/// off-by-one). The 136-byte core block gets a few representative settings bytes
/// set so the bit-editors show real state.
/// </summary>
private byte[] CanonicalMisc(byte lengthBytes)
{
var data = new byte[lengthBytes + 1]; // device returns len+1
if (lengthBytes >= MemoryLayout.LenMiscCore) // core block (0x88 = 136)
{
data[8] = 131; // Crank_CamSync_Config
data[25] = 0x05; // Fuel_Settings2 (a couple of flags)
data[31] = 0x12; // Spark_Settings
data[33] = 0x01; // O2_Autotune_Enable
data[84] = 0x0F; // ShiftBoss_Enable = enable + both DIN bits
data[88] = 35; // ShiftBoss_Spark_Retard_deg
}
return data;
}
// ── Framing helpers ───────────────────────────────────────────────────────
private static byte[] Slice(byte[] src, int start, int count)
{
var b = new byte[count];
Buffer.BlockCopy(src, start, b, 0, count);
return b;
}
/// <summary>Wraps a data block in the 4-byte response header (51 cmd len 00).</summary>
private static Task<CommandResult> OkFramed(byte[] data, byte cmd)
{
var buf = new byte[4 + data.Length];
buf[0] = 0x51;
buf[1] = cmd;
buf[2] = (byte)data.Length;
buf[3] = 0x00;
Buffer.BlockCopy(data, 0, buf, 4, data.Length);
return Task.FromResult(CommandResult.Ok(buf));
}
public void Dispose()
{
_diagCts?.Cancel();
_diagCts?.Dispose();
_diag.Dispose();
_state.Dispose();
}
}
+7
View File
@@ -0,0 +1,7 @@
namespace TuneBoss.Core
{
public class Class1
{
}
}
+470
View File
@@ -0,0 +1,470 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using TuneBoss.Core.Models;
namespace TuneBoss.Core.IO;
/// <summary>
/// Reader/writer for the TuneBoss <c>.fsr</c> configuration format (v1) — a
/// text-based, self-describing container for a full ECU tuning configuration.
/// See FSR_FORMAT_SPEC.md for the authoritative specification.
///
/// This type is model-based and standalone: it (de)serialises the actual table
/// models, so it does not depend on the app's nav-tree/codec plumbing.
/// </summary>
public static class FsrFile
{
public const int FormatVersion = 1;
// ── Public data structures ──────────────────────────────────────────────
public sealed class FsrDocument
{
public FsrHeader Header { get; set; } = new();
public List<FsrSection> Sections { get; } = new();
public FsrSection? Find(string name) =>
Sections.FirstOrDefault(s => string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase));
}
public sealed class FsrHeader
{
public int FsrVersion { get; set; } = FormatVersion;
public string Generator { get; set; } = "";
public string CreatedUtc { get; set; } = "";
public string CreatorId { get; set; } = "";
public int FwVersion { get; set; }
public int HwVersion { get; set; }
public int Make { get; set; }
public int Model { get; set; }
public int Cylinders { get; set; } = 1;
public int Generation { get; set; } = 3;
public string SaveType { get; set; } = "full_config";
public string Note { get; set; } = "none";
// Modification tags
public string ModEngineBlock { get; set; } = "none";
public string ModCamshaft { get; set; } = "none";
public string ModExhaust { get; set; } = "none";
public string ModAirFilter { get; set; } = "none";
public string ModCylinderHead { get; set; } = "none";
public string ModInjector { get; set; } = "none";
public string ModThrottleBody { get; set; } = "none";
public string ModJackRod { get; set; } = "none";
/// <summary>Any header keys not recognised — preserved on round-trip.</summary>
public Dictionary<string, string> Extra { get; } = new(StringComparer.OrdinalIgnoreCase);
}
public enum SectionType { Table2D, Table1D, SubTable, Afr, Misc, Unknown }
public sealed class FsrSection
{
public SectionType Type { get; set; }
public string TypeToken { get; set; } = ""; // raw token, preserves Unknown
public string Name { get; set; } = ""; // stable feature key
public string Label { get; set; } = "";
public ushort Addr { get; set; }
public byte Length { get; set; } // last-inclusive-offset (bytes-1)
public int Gen { get; set; }
// Exactly one of these is populated depending on Type.
public TuningTable? Table2D { get; set; }
public AfrTable? Afr { get; set; }
public OneDimTable? Table1D { get; set; }
public SubTable? Sub { get; set; }
public byte[]? MiscBytes { get; set; }
/// <summary>Raw field lines for Unknown sections / unrecognised keys.</summary>
public Dictionary<string, string> Extra { get; } = new(StringComparer.OrdinalIgnoreCase);
}
// ════════════════════════════════════════════════════════════════════════
// WRITE
// ════════════════════════════════════════════════════════════════════════
/// <summary>Serialises a document to .fsr text (with an optional whole-body sha256).</summary>
public static string Write(FsrDocument doc, bool includeSha256 = true)
{
var body = new StringBuilder();
WriteHeader(body, doc.Header);
body.Append('\n');
foreach (var s in doc.Sections)
WriteSection(body, s);
if (!includeSha256)
return body.ToString();
// sha256 covers everything after the sha256 line — write header line first.
string bodyText = body.ToString();
string hash = Sha256Hex(bodyText);
return $"# integrity\nsha256 = {hash}\n{bodyText}";
}
private static void WriteHeader(StringBuilder sb, FsrHeader h)
{
sb.Append("# TuneBoss configuration — .fsr v").Append(h.FsrVersion).Append('\n');
void F(string k, object v) => sb.Append(k).Append(" = ").Append(v).Append('\n');
F("fsr_version", h.FsrVersion);
if (!string.IsNullOrEmpty(h.Generator)) F("generator", h.Generator);
if (!string.IsNullOrEmpty(h.CreatedUtc)) F("created_utc", h.CreatedUtc);
F("creator_id", h.CreatorId);
F("fw_version", h.FwVersion);
F("hw_version", h.HwVersion);
F("make", h.Make);
F("model", h.Model);
F("cylinders", h.Cylinders);
F("generation", h.Generation);
F("save_type", h.SaveType);
F("mod_engine_block", h.ModEngineBlock);
F("mod_camshaft", h.ModCamshaft);
F("mod_exhaust", h.ModExhaust);
F("mod_air_filter", h.ModAirFilter);
F("mod_cylinder_head", h.ModCylinderHead);
F("mod_injector", h.ModInjector);
F("mod_throttle_body", h.ModThrottleBody);
F("mod_jack_rod", h.ModJackRod);
F("note", h.Note);
foreach (var kv in h.Extra) F(kv.Key, kv.Value);
}
private static void WriteSection(StringBuilder sb, FsrSection s)
{
string typeToken = s.Type switch
{
SectionType.Table2D => "TABLE2D",
SectionType.Afr => "AFR",
SectionType.Table1D => "TABLE1D",
SectionType.SubTable => "SUBTABLE",
SectionType.Misc => "MISC",
_ => s.TypeToken,
};
sb.Append('[').Append(typeToken).Append(' ').Append(s.Name).Append("]\n");
void F(string k, object v) => sb.Append(k).Append(" = ").Append(v).Append('\n');
F("label", s.Label);
F("addr", Hex16(s.Addr));
F("length", Hex8(s.Length));
if (s.Gen != 0) F("gen", s.Gen);
switch (s.Type)
{
case SectionType.Table2D when s.Table2D is { } t: Write2D(sb, t.Data, t.RpmAxis, t.LoadAxis, t.Sign, t.MaxRaw, t.MinRaw, t.Mult); break;
case SectionType.Afr when s.Afr is { } a: Write2D(sb, a.Data, a.RpmAxis, a.LoadAxis, a.Sign, a.MaxRaw, a.MinRaw, a.Mult); break;
case SectionType.Table1D when s.Table1D is { } o: Write1D(sb, o); break;
case SectionType.SubTable when s.Sub is { } sub: WriteSub(sb, sub); break;
case SectionType.Misc when s.MiscBytes is { } b: WriteBytes(sb, b); break;
default:
foreach (var kv in s.Extra) F(kv.Key, kv.Value);
break;
}
sb.Append('\n');
}
private static void Write2D(StringBuilder sb, byte[] data, byte[] rpm, byte[] load, byte sign, byte maxRaw, byte minRaw, byte mult)
{
sb.Append("signed = ").Append(sign > 0 ? 1 : 0).Append('\n');
sb.Append("mult = ").Append(mult).Append('\n');
sb.Append("max_raw = ").Append(maxRaw).Append('\n');
sb.Append("min_raw = ").Append(minRaw).Append('\n');
sb.Append("rpm_axis = ").Append(HexBytes(rpm)).Append('\n');
sb.Append("load_axis = ").Append(HexBytes(load)).Append('\n');
for (int r = 0; r < TuningTable.Rows; r++)
{
sb.Append("row").Append(r).Append(" = ");
for (int c = 0; c < TuningTable.Cols; c++)
{
if (c > 0) sb.Append(' ');
sb.Append(Hex8(data[r * TuningTable.Cols + c]));
}
sb.Append('\n');
}
}
private static void Write1D(StringBuilder sb, OneDimTable o)
{
sb.Append("raw_signed = ").Append(o.RawSignedFlag > 0 ? 1 : 0).Append('\n');
sb.Append("conv_signed = ").Append(o.ConvSignedFlag > 0 ? 1 : 0).Append('\n');
sb.Append("raw_mult = ").Append(o.RawMultiplier).Append('\n');
sb.Append("conv_mult = ").Append(o.ConvMultiplier).Append('\n');
sb.Append("raw_round = ").Append(o.RawRounding).Append('\n');
sb.Append("conv_offset = ").Append((int)o.ConvOffset).Append('\n');
sb.Append("max_raw = ").Append(o.MaxRaw).Append('\n');
sb.Append("min_raw = ").Append(o.MinRaw).Append('\n');
for (int i = 0; i < OneDimTable.PointCount; i++)
sb.Append('p').Append(i).Append(" = ").Append(o.RawAxis[i]).Append(", ").Append(o.ConvValues[i]).Append('\n');
}
private static void WriteSub(StringBuilder sb, SubTable sub)
{
for (int r = 0; r < SubTable.Rows; r++)
{
sb.Append("row").Append(r).Append(" = ");
for (int c = 0; c < SubTable.Cols; c++)
{
if (c > 0) sb.Append(", ");
sb.Append((int)unchecked((sbyte)sub.Data[r * SubTable.Cols + c]));
}
sb.Append('\n');
}
}
private static void WriteBytes(StringBuilder sb, byte[] bytes)
{
const int perLine = 32;
for (int off = 0; off < bytes.Length; off += perLine)
{
int n = Math.Min(perLine, bytes.Length - off);
sb.Append("bytes = ");
for (int i = 0; i < n; i++)
{
if (i > 0) sb.Append(' ');
sb.Append(Hex8(bytes[off + i]));
}
sb.Append('\n');
}
}
// ════════════════════════════════════════════════════════════════════════
// READ
// ════════════════════════════════════════════════════════════════════════
public static FsrDocument Read(string text)
{
var doc = new FsrDocument();
FsrSection? cur = null;
var secFields = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var rowLines = new List<(string key, string val)>();
void Flush()
{
if (cur == null) return;
BuildSection(cur, secFields, rowLines);
doc.Sections.Add(cur);
secFields = new(StringComparer.OrdinalIgnoreCase);
rowLines = new();
}
foreach (var raw in text.Split('\n'))
{
var line = raw.TrimEnd('\r');
var t = line.TrimStart();
if (t.Length == 0 || t[0] == '#') continue;
if (t[0] == '[')
{
Flush();
int close = t.IndexOf(']');
var inner = (close > 0 ? t[1..close] : t[1..]).Trim();
int sp = inner.IndexOf(' ');
string typeTok = sp > 0 ? inner[..sp] : inner;
string name = sp > 0 ? inner[(sp + 1)..].Trim() : "";
cur = new FsrSection { TypeToken = typeTok, Type = ParseType(typeTok), Name = name };
continue;
}
int eq = line.IndexOf('=');
if (eq < 0) continue;
string key = line[..eq].Trim();
string val = line[(eq + 1)..].Trim();
if (cur == null) { ApplyHeader(doc.Header, key, val); continue; }
// Row-style keys accumulate (rowN, pN, bytes); everything else is a field.
if (IsRowKey(key)) rowLines.Add((key, val));
else secFields[key] = val;
}
Flush();
return doc;
}
private static bool IsRowKey(string k) =>
k.StartsWith("row", StringComparison.OrdinalIgnoreCase) ||
(k.Length >= 2 && (k[0] == 'p' || k[0] == 'P') && char.IsDigit(k[1])) ||
k.Equals("bytes", StringComparison.OrdinalIgnoreCase);
private static SectionType ParseType(string tok) => tok.ToUpperInvariant() switch
{
"TABLE2D" => SectionType.Table2D,
"AFR" => SectionType.Afr,
"TABLE1D" => SectionType.Table1D,
"SUBTABLE" => SectionType.SubTable,
"MISC" => SectionType.Misc,
_ => SectionType.Unknown,
};
private static void ApplyHeader(FsrHeader h, string key, string val)
{
switch (key.ToLowerInvariant())
{
case "fsr_version": h.FsrVersion = ParseInt(val); break;
case "generator": h.Generator = val; break;
case "created_utc": h.CreatedUtc = val; break;
case "creator_id": h.CreatorId = val; break;
case "fw_version": h.FwVersion = ParseInt(val); break;
case "hw_version": h.HwVersion = ParseInt(val); break;
case "make": h.Make = ParseInt(val); break;
case "model": h.Model = ParseInt(val); break;
case "cylinders": h.Cylinders = ParseInt(val); break;
case "generation": h.Generation = ParseInt(val); break;
case "save_type": h.SaveType = val; break;
case "note": h.Note = val; break;
case "mod_engine_block": h.ModEngineBlock = val; break;
case "mod_camshaft": h.ModCamshaft = val; break;
case "mod_exhaust": h.ModExhaust = val; break;
case "mod_air_filter": h.ModAirFilter = val; break;
case "mod_cylinder_head": h.ModCylinderHead = val; break;
case "mod_injector": h.ModInjector = val; break;
case "mod_throttle_body": h.ModThrottleBody = val; break;
case "mod_jack_rod": h.ModJackRod = val; break;
case "sha256": break; // integrity only; not structural
default: h.Extra[key] = val; break; // forward-compat
}
}
private static void BuildSection(FsrSection s, Dictionary<string, string> f, List<(string key, string val)> rows)
{
s.Label = f.GetValueOrDefault("label", s.Name);
s.Addr = (ushort)ParseInt(f.GetValueOrDefault("addr", "0"));
s.Length = (byte)ParseInt(f.GetValueOrDefault("length", "0"));
s.Gen = ParseInt(f.GetValueOrDefault("gen", "0"));
switch (s.Type)
{
case SectionType.Table2D: s.Table2D = Build2D(f, rows); break;
case SectionType.Afr: s.Afr = BuildAfr(f, rows); break;
case SectionType.Table1D: s.Table1D = Build1D(f, rows); break;
case SectionType.SubTable:s.Sub = BuildSub(rows); break;
case SectionType.Misc: s.MiscBytes = BuildBytes(rows); break;
default:
foreach (var kv in f) s.Extra[kv.Key] = kv.Value;
break;
}
}
private static (byte[] data, byte[] rpm, byte[] load, byte sign, byte maxRaw, byte minRaw, byte mult) Read2DCore(
Dictionary<string, string> f, List<(string key, string val)> rows)
{
var rpm = ParseHexBytes(f.GetValueOrDefault("rpm_axis", ""));
var load = ParseHexBytes(f.GetValueOrDefault("load_axis", ""));
byte sign = (byte)(ParseInt(f.GetValueOrDefault("signed", "0")) > 0 ? 1 : 0);
byte maxRaw = (byte)ParseInt(f.GetValueOrDefault("max_raw", "0"));
byte minRaw = (byte)ParseInt(f.GetValueOrDefault("min_raw", "0"));
byte mult = (byte)ParseInt(f.GetValueOrDefault("mult", "1"));
var data = new byte[TuningTable.DataBytes];
foreach (var (key, val) in rows)
{
if (!key.StartsWith("row", StringComparison.OrdinalIgnoreCase)) continue;
int r = ParseInt(key[3..]);
var cells = ParseHexBytes(val);
for (int c = 0; c < cells.Length && c < TuningTable.Cols; c++)
data[r * TuningTable.Cols + c] = cells[c];
}
return (data, rpm, load, sign, maxRaw, minRaw, mult);
}
private static TuningTable Build2D(Dictionary<string, string> f, List<(string, string)> rows)
{
var (data, rpm, load, sign, maxRaw, minRaw, mult) = Read2DCore(f, rows);
return new TuningTable { Data = data, RpmAxis = rpm, LoadAxis = load, Sign = sign, MaxRaw = maxRaw, MinRaw = minRaw, Mult = mult };
}
private static AfrTable BuildAfr(Dictionary<string, string> f, List<(string, string)> rows)
{
var (data, rpm, load, sign, maxRaw, minRaw, mult) = Read2DCore(f, rows);
return new AfrTable { Data = data, RpmAxis = rpm, LoadAxis = load, Sign = sign, MaxRaw = maxRaw, MinRaw = minRaw, Mult = mult };
}
private static OneDimTable Build1D(Dictionary<string, string> f, List<(string key, string val)> rows)
{
var o = new OneDimTable
{
RawSignedFlag = (byte)(ParseInt(f.GetValueOrDefault("raw_signed", "0")) > 0 ? 1 : 0),
ConvSignedFlag = (byte)(ParseInt(f.GetValueOrDefault("conv_signed", "0")) > 0 ? 1 : 0),
RawMultiplier = (byte)ParseInt(f.GetValueOrDefault("raw_mult", "1")),
ConvMultiplier = (byte)ParseInt(f.GetValueOrDefault("conv_mult", "1")),
RawRounding = (byte)ParseInt(f.GetValueOrDefault("raw_round", "0")),
ConvOffset = (sbyte)ParseInt(f.GetValueOrDefault("conv_offset", "0")),
MaxRaw = ParseInt(f.GetValueOrDefault("max_raw", "0")),
MinRaw = ParseInt(f.GetValueOrDefault("min_raw", "0")),
};
foreach (var (key, val) in rows)
{
if (key.Length < 2 || (key[0] != 'p' && key[0] != 'P')) continue;
int i = ParseInt(key[1..]);
if (i < 0 || i >= OneDimTable.PointCount) continue;
var parts = val.Split(',');
if (parts.Length >= 1) o.RawAxis[i] = ParseInt(parts[0].Trim());
if (parts.Length >= 2) o.ConvValues[i] = ParseInt(parts[1].Trim());
}
return o;
}
private static SubTable BuildSub(List<(string key, string val)> rows)
{
var data = new byte[SubTable.DataBytes];
foreach (var (key, val) in rows)
{
if (!key.StartsWith("row", StringComparison.OrdinalIgnoreCase)) continue;
int r = ParseInt(key[3..]);
var parts = val.Split(',');
for (int c = 0; c < parts.Length && c < SubTable.Cols; c++)
data[r * SubTable.Cols + c] = unchecked((byte)(sbyte)ParseInt(parts[c].Trim()));
}
return new SubTable { Data = data };
}
private static byte[] BuildBytes(List<(string key, string val)> rows)
{
var all = new List<byte>();
foreach (var (key, val) in rows)
if (key.Equals("bytes", StringComparison.OrdinalIgnoreCase))
all.AddRange(ParseHexBytes(val));
return all.ToArray();
}
// ── Helpers ─────────────────────────────────────────────────────────────
private static string Hex8(byte b) => "0x" + b.ToString("X2", CultureInfo.InvariantCulture);
private static string Hex16(ushort v) => "0x" + v.ToString("X4", CultureInfo.InvariantCulture);
private static string HexBytes(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 3);
for (int i = 0; i < bytes.Length; i++)
{
if (i > 0) sb.Append(' ');
sb.Append(bytes[i].ToString("X2", CultureInfo.InvariantCulture));
}
return sb.ToString();
}
private static byte[] ParseHexBytes(string s)
{
if (string.IsNullOrWhiteSpace(s)) return Array.Empty<byte>();
var toks = s.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
var outp = new byte[toks.Length];
for (int i = 0; i < toks.Length; i++)
{
var tok = toks[i];
if (tok.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) tok = tok[2..];
outp[i] = byte.Parse(tok, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
return outp;
}
private static int ParseInt(string s)
{
s = s.Trim();
if (s.Length == 0) return 0;
if (s.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
return int.Parse(s[2..], NumberStyles.HexNumber, CultureInfo.InvariantCulture);
return int.Parse(s, NumberStyles.Integer | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture);
}
private static string Sha256Hex(string body)
{
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(body));
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes) sb.Append(b.ToString("x2", CultureInfo.InvariantCulture));
return sb.ToString();
}
}
+54
View File
@@ -0,0 +1,54 @@
using System.Threading.Tasks;
using TuneBoss.Core.Models;
namespace TuneBoss.Core.IO;
/// <summary>
/// Serializes / parses the <c>data</c> section of a map file — the space- and
/// <c>__</c>-delimited table dump. Kept behind an interface because its exact
/// table ordering is interop-critical and is filled once the format (legacy-exact
/// vs. new) and the included save-types are confirmed.
///
/// Implementations live in the app layer, where they can read and write the
/// table view-models that hold the current ECU state.
/// </summary>
public interface IMapTableCodec
{
/// <summary>
/// Ensures any device-backed state required to serialize the given type is loaded,
/// re-reading tables whose models are not cached. Called before <see cref="Serialize"/>
/// so a save works even if the user reached this page before a full table load
/// finished (or a table read was missed). Default: nothing to do.
/// </summary>
Task PrepareAsync(MapSaveType saveType, int cylinderCount) => Task.CompletedTask;
/// <summary>Runs an on-hardware diagnostic of the user-table read path and returns a report.</summary>
Task<string> DiagnoseAsync() => Task.FromResult(string.Empty);
/// <summary>Serializes the current in-app table state into a map <c>data</c> section.</summary>
string Serialize(MapSaveType saveType, int cylinderCount);
/// <summary>
/// Writes the currently-applied content for the given save type to the ECU,
/// optionally flashing at the end. Returns a human-readable summary.
/// </summary>
Task<string> WriteLoadedAsync(MapSaveType saveType, int cylinderCount, bool flash,
IProgress<string>? progress = null)
=> throw new NotImplementedException("Write-to-ECU on load is not wired for this codec.");
/// <summary>Parses a map <c>data</c> section and applies it to the in-app table state.</summary>
void Deserialize(string data, MapSaveType saveType, int cylinderCount);
/// <summary>Rebuilds the editor nav trees from the current session layout
/// (used after an offline file establishes a layout, so entries exist to populate).</summary>
void RebuildNavTrees() { }
/// <summary>
/// Builds an FSR document from the currently-loaded editors. Walks loaded entries
/// directly and skips anything not loaded (never throws "not loaded").
/// </summary>
FsrFile.FsrDocument BuildFsrFromEditors(Models.EcuInfo? info, MapTag? tag, int cylinderCount);
/// <summary>Applies a parsed FSR document into the editors.</summary>
void ApplyFsr(FsrFile.FsrDocument doc);
}
+44
View File
@@ -0,0 +1,44 @@
using TuneBoss.Core.Models;
namespace TuneBoss.Core.IO;
/// <summary>
/// Checks whether a loaded map's tag matches the connected ECU. Mirrors the legacy
/// open-time check, which warns (but doesn't hard-block) on make/model mismatch.
/// </summary>
public static class MapCompatibility
{
public enum Result
{
Match,
ModelMismatch,
MakeMismatch,
CylinderMismatch,
}
public readonly record struct Report(Result Result, string Message)
{
public bool IsMatch => Result == Result.Match;
}
public static Report Check(MapTag tag, EcuInfo ecu, int connectedCylinders)
{
if (tag.Make != ecu.BikeManufacturer)
return new Report(Result.MakeMismatch,
$"This map is for {BikeRegistry.GetMake((byte)tag.Make)} but the connected unit is " +
$"{BikeRegistry.GetMake(ecu.BikeManufacturer)}. Loading it is not recommended.");
if (tag.Model != ecu.BikeModel)
return new Report(Result.ModelMismatch,
$"This map is for {BikeRegistry.GetDisplayName((byte)tag.Make, tag.Model)} but the connected unit is " +
$"{BikeRegistry.GetDisplayName(ecu.BikeManufacturer, ecu.BikeModel)}. Loading it is not recommended.");
if (connectedCylinders > 0 && tag.CylinderCount != connectedCylinders)
return new Report(Result.CylinderMismatch,
$"This map is for a {tag.CylinderCount}-cylinder layout but the connected unit is " +
$"{connectedCylinders}-cylinder.");
return new Report(Result.Match,
$"Map matches the connected {BikeRegistry.GetDisplayName(ecu.BikeManufacturer, ecu.BikeModel)}.");
}
}
+77
View File
@@ -0,0 +1,77 @@
using System.Security.Cryptography;
using System.Text;
namespace TuneBoss.Core.IO;
/// <summary>
/// The on-disk envelope of a TuneBoss <c>.tst</c> map file:
///
/// MD5(tag)_____tag\nMD5(data)_____data
///
/// Two records separated by a newline; each record is <c>MD5hex_____payload</c>.
/// The MD5 is upper-case hex with no separators (matching the legacy
/// <c>BitConverter.ToString(...).Replace("-","")</c>). On load, both digests are
/// recomputed and must match or the file is rejected as corrupt/tampered.
/// </summary>
public static class MapFile
{
public const string Extension = ".tst";
public const string RecordSep = "_____";
/// <summary>Upper-case, separator-free MD5 hex of a UTF-8 string.</summary>
public static string Md5Hex(string s)
{
var hash = MD5.HashData(Encoding.UTF8.GetBytes(s));
return Convert.ToHexString(hash); // upper-case, no separators
}
/// <summary>Builds the full file text from a tag string and a data string.</summary>
public static string BuildEnvelope(string tag, string data)
=> $"{Md5Hex(tag)}{RecordSep}{tag}\n{Md5Hex(data)}{RecordSep}{data}";
public readonly record struct ParseResult(
bool Ok,
string Tag,
string Data,
string? Error)
{
public static ParseResult Fail(string error) => new(false, "", "", error);
public static ParseResult Success(string tag, string data) => new(true, tag, data, null);
}
/// <summary>
/// Parses and integrity-checks a file's full text. Splits on <c>\r\n</c> or
/// <c>\n</c>, separates each record on <c>_____</c>, and verifies both MD5s.
/// </summary>
public static ParseResult TryParse(string fileText)
{
if (string.IsNullOrEmpty(fileText))
return ParseResult.Fail("File is empty.");
var lines = fileText.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None);
if (lines.Length < 2)
return ParseResult.Fail("File is not a valid TuneBoss map (missing data record).");
var tagRec = SplitOnce(lines[0]);
var dataRec = SplitOnce(lines[1]);
if (tagRec is null || dataRec is null)
return ParseResult.Fail("File is not a valid TuneBoss map (bad record format).");
var (tagHash, tag) = tagRec.Value;
var (dataHash, data) = dataRec.Value;
if (!string.Equals(tagHash, Md5Hex(tag), StringComparison.OrdinalIgnoreCase))
return ParseResult.Fail("Tag checksum mismatch — the file may be corrupt or edited.");
if (!string.Equals(dataHash, Md5Hex(data), StringComparison.OrdinalIgnoreCase))
return ParseResult.Fail("Data checksum mismatch — the file may be corrupt or edited.");
return ParseResult.Success(tag, data);
}
private static (string Hash, string Payload)? SplitOnce(string record)
{
int i = record.IndexOf(RecordSep, StringComparison.Ordinal);
if (i < 0) return null;
return (record[..i], record[(i + RecordSep.Length)..]);
}
}
+139
View File
@@ -0,0 +1,139 @@
using System.Text;
using TuneBoss.Core.Models;
namespace TuneBoss.Core.IO;
/// <summary>
/// Byte-exact serializer / parser for the table sections inside a <c>.tst</c> map's
/// data string. Replicates the legacy helpers verbatim:
///
/// 2D : <c>label__data__load__rpm__max min mult sign ____</c>
/// AFR : <c>label__data__load__rpm____</c> (no modifiers)
/// Sub : <c>label__data____</c> (24 data bytes)
/// 1D : <c>label__&lt;24 wire bytes&gt;____</c>
///
/// Every value is its unsigned decimal followed by a single space; <c>__</c> separates
/// fields within a section, <c>____</c> terminates each section. Subtable RPM axes are
/// not stored — on load they are derived from the parent 2D table's RPM axis (every
/// 4th breakpoint), matching legacy <c>populateSubTable</c>.
/// </summary>
public static class MapTableFormat
{
public const string SectionSep = "____";
public const string FieldSep = "__";
// ── Value lists ─────────────────────────────────────────────────────────────
private static string Bytes(byte[] a)
{
var sb = new StringBuilder(a.Length * 4);
foreach (var b in a) sb.Append((int)b).Append(' '); // "v v v "
return sb.ToString();
}
/// <summary>Parses a space-separated decimal list into bytes (empties skipped).</summary>
public static byte[] ParseBytes(string s)
{
var parts = s.Split(' ', StringSplitOptions.RemoveEmptyEntries);
var r = new byte[parts.Length];
for (int i = 0; i < parts.Length; i++)
r[i] = (byte)(int.Parse(parts[i]) & 0xFF);
return r;
}
// ── Serialize ───────────────────────────────────────────────────────────────
public static string Section2D(string label, TuningTable t) =>
label + FieldSep + Bytes(t.Data) + FieldSep + Bytes(t.LoadAxis) + FieldSep + Bytes(t.RpmAxis) +
FieldSep + $"{t.MaxRaw} {t.MinRaw} {t.Mult} {t.Sign} " + SectionSep;
public static string SectionAfr(string label, AfrTable t) =>
label + FieldSep + Bytes(t.Data) + FieldSep + Bytes(t.LoadAxis) + FieldSep + Bytes(t.RpmAxis) + SectionSep;
public static string SectionSub(string label, SubTable t) =>
label + FieldSep + Bytes(t.Data) + SectionSep;
public static string Section1D(string label, OneDimTable t) =>
label + FieldSep + Bytes(t.ToWirePayload()) + SectionSep;
/// <summary>Generic named byte block (used for the misc regions). <c>label__&lt;bytes&gt;____</c>.</summary>
public static string SectionBytes(string label, byte[] data) =>
label + FieldSep + Bytes(data) + SectionSep;
/// <summary>Parses a <see cref="SectionBytes"/> block back into its raw bytes.</summary>
public static byte[] ParseBytesSection(string section)
{
var f = Fields(section);
return f.Length > 1 ? ParseBytes(f[1]) : Array.Empty<byte>();
}
// ── Section splitting ───────────────────────────────────────────────────────
/// <summary>Splits a data string into its <c>____</c>-terminated sections (positional).</summary>
public static string[] SplitSections(string data) =>
data.Split(SectionSep, StringSplitOptions.None);
private static string[] Fields(string section) =>
section.Split(FieldSep, StringSplitOptions.None);
/// <summary>The label of a section (its first field), for sanity checks.</summary>
public static string LabelOf(string section) => Fields(section)[0];
// ── Parse ───────────────────────────────────────────────────────────────────
public static TuningTable Parse2D(string section)
{
var f = Fields(section);
var data = Fit(ParseBytes(f[1]), TuningTable.DataBytes);
var load = Fit(ParseBytes(f[2]), TuningTable.Rows);
var rpm = Fit(ParseBytes(f[3]), TuningTable.Cols);
var mod = ParseBytes(f.Length > 4 ? f[4] : "");
return new TuningTable
{
Data = data, LoadAxis = load, RpmAxis = rpm,
MaxRaw = At(mod, 0), MinRaw = At(mod, 1), Mult = At(mod, 2), Sign = At(mod, 3),
};
}
public static AfrTable ParseAfr(string section)
{
var f = Fields(section);
return new AfrTable
{
Data = Fit(ParseBytes(f[1]), AfrTable.DataBytes),
LoadAxis = Fit(ParseBytes(f[2]), AfrTable.Rows),
RpmAxis = Fit(ParseBytes(f[3]), AfrTable.Cols),
};
}
/// <summary>
/// Parses a subtable section. The 12-byte RPM axis is derived from the parent 2D
/// table's 24-byte RPM axis: 6 (lo,hi) pairs taken from indices 4·x and 4·x+3.
/// </summary>
public static SubTable ParseSub(string section, byte[] parentRpm)
{
var f = Fields(section);
var sub = new SubTable { Data = Fit(ParseBytes(f[1]), SubTable.DataBytes) };
for (int x = 0; x < SubTable.Cols; x++)
{
sub.RpmAxis[x * 2] = At(parentRpm, x * 4);
sub.RpmAxis[x * 2 + 1] = At(parentRpm, x * 4 + 3);
}
return sub;
}
public static OneDimTable Parse1D(string section)
{
var f = Fields(section);
var wire = Fit(ParseBytes(f[1]), OneDimTable.WireLength);
return OneDimTable.FromWire(wire, 0);
}
// ── Helpers ─────────────────────────────────────────────────────────────────
private static byte At(byte[] a, int i) => i < a.Length ? a[i] : (byte)0;
/// <summary>Returns an array of exactly <paramref name="n"/> bytes (pad/truncate).</summary>
private static byte[] Fit(byte[] src, int n)
{
if (src.Length == n) return src;
var r = new byte[n];
Array.Copy(src, r, Math.Min(src.Length, n));
return r;
}
}
+100
View File
@@ -0,0 +1,100 @@
using System.Text;
namespace TuneBoss.Core.IO;
/// <summary>
/// Which tables a saved map contains. Values match the legacy save-type codes.
/// </summary>
public enum MapSaveType
{
User = 1, // user adjust tables (+ their subtables)
FullTables = 2, // all base + user 2D tables, AFR, subtables, 1D
FullConfig = 4, // FullTables plus the misc / extended config blocks
}
/// <summary>
/// The metadata header of a TuneBoss map file — the legacy "tag", 16 fields joined
/// by <c>___</c>:
/// creatorID, FW, HW, make, model, cyl, saveType,
/// engineBlock, camshaft, exhaust, airFilter, cylinderHead, injector, throttleBody, jackRod,
/// miscNote
///
/// The trailing note carries no separator; every other field is followed by <c>___</c>.
/// </summary>
public sealed record MapTag
{
public const string FieldSep = "___";
public const int FieldCount = 16;
public string CreatorId { get; init; } = "";
public int FwVersion { get; init; }
public int HwVersion { get; init; }
public int Make { get; init; }
public int Model { get; init; }
public int CylinderCount { get; init; } = 1;
public MapSaveType SaveType { get; init; } = MapSaveType.FullConfig;
public string EngineBlock { get; init; } = "none";
public string Camshaft { get; init; } = "none";
public string Exhaust { get; init; } = "none";
public string AirFilter { get; init; } = "none";
public string CylinderHead { get; init; } = "none";
public string Injector { get; init; } = "none";
public string ThrottleBody { get; init; } = "none";
public string JackRod { get; init; } = "none";
public string MiscNote { get; init; } = "none";
/// <summary>Serializes to the <c>___</c>-joined legacy string.</summary>
public string Build()
{
var sb = new StringBuilder();
void F(string v) => sb.Append(v).Append(FieldSep);
F(CreatorId);
F(FwVersion.ToString());
F(HwVersion.ToString());
F(Make.ToString());
F(Model.ToString());
F(CylinderCount.ToString());
F(((int)SaveType).ToString());
F(EngineBlock);
F(Camshaft);
F(Exhaust);
F(AirFilter);
F(CylinderHead);
F(Injector);
F(ThrottleBody);
F(JackRod);
sb.Append(MiscNote); // no trailing separator
return sb.ToString();
}
/// <summary>Parses a <c>___</c>-joined tag string. Tolerates a short mod section.</summary>
public static MapTag Parse(string tag)
{
var f = tag.Split(FieldSep);
string At(int i) => i < f.Length ? f[i] : "";
int AtInt(int i) => int.TryParse(At(i), out var v) ? v : 0;
return new MapTag
{
CreatorId = At(0),
FwVersion = AtInt(1),
HwVersion = AtInt(2),
Make = AtInt(3),
Model = AtInt(4),
CylinderCount = AtInt(5) is var c && c > 0 ? c : 1,
SaveType = (MapSaveType)AtInt(6),
EngineBlock = At(7),
Camshaft = At(8),
Exhaust = At(9),
AirFilter = At(10),
CylinderHead = At(11),
Injector = At(12),
ThrottleBody = At(13),
JackRod = At(14),
MiscNote = At(15),
};
}
}
+221
View File
@@ -0,0 +1,221 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// Data model for an AFR Target table (AFR_Target1, AFR_Target2).
///
/// Structurally identical to TuningTable (24 cols × 8 rows, same split read/write,
/// same wire layout) but with a critical difference in value encoding:
///
/// ── Fixed-point ×10 encoding ─────────────────────────────────────────────────
/// All cell values are stored as byte × 10 on the wire.
/// Wire byte 145 = AFR 14.5, byte 137 = AFR 13.7, etc.
/// Display range set by caller: minDataVal=0.0, maxDataVal=15.0 (from populateInitTables)
///
/// ── Modifier encoding ─────────────────────────────────────────────────────────
/// MaxRaw / MinRaw are also stored ×10 on wire:
/// modifiersInArray[0] = (byte)(maxRawVal * 10.0)
/// modifiersInArray[1] = (byte)(minRawVal * 10.0)
/// modifiersInArray[2] = (byte)multRawVal (same as TuningTable)
/// modifiersInArray[3] = (byte)signRawVal (same as TuningTable)
/// Confirmed from writeBtn_Click and prepareAllData() in TuningTablePanelAFR.cs.
///
/// ── Button increments ────────────────────────────────────────────────────────
/// +/- large = 5.0 AFR (minusFive_Click / plusFive_Click)
/// +/- small = 0.1 AFR (minusOne_Click / plusOne_Click) ← different from TuningTable
/// Validated as double, displayed as "N1" (1 decimal place).
///
/// ── Wire format ──────────────────────────────────────────────────────────────
/// Identical layout to TuningTable (228 bytes, split at 0x7F):
/// [0..191] Data — 192 bytes, row-major, each byte = AFR × 10
/// [192..199] Load — 8 bytes
/// [200..223] RPM — 24 bytes, each × 100 = display RPM
/// [224] MaxRaw — stored as byte = maxAFR × 10
/// [225] MinRaw — stored as byte = minAFR × 10
/// [226] Mult
/// [227] Sign
///
/// Read length from populateInitTables: 0xEF (239) — larger than TuningTable's 0xE3.
/// </summary>
public sealed record AfrTable
{
public const int Cols = 24;
public const int Rows = 8;
public const int DataBytes = Cols * Rows; // 192
public const int SplitFirstLength = 0x7F; // 127 — same as TuningTable
public const int TotalPayloadBytes = DataBytes + Rows + Cols + 4; // 228
public const byte ReadLength = 0xEF; // 239 — from populateInitTables
// ── Raw wire arrays ───────────────────────────────────────────────────────
/// <summary>192 bytes, row-major [row * 24 + col]. Wire value = AFR × 10.</summary>
public byte[] Data { get; init; } = new byte[DataBytes];
/// <summary>8 bytes — load axis (0–110).</summary>
public byte[] LoadAxis { get; init; } = new byte[Rows];
/// <summary>24 bytes — RPM axis, each × 100 = display RPM.</summary>
public byte[] RpmAxis { get; init; } = new byte[Cols];
// ── Modifiers [224–227] ───────────────────────────────────────────────────
/// <summary>Wire: maxAFR × 10. E.g. byte 150 = AFR 15.0.</summary>
public byte MaxRaw { get; init; }
/// <summary>Wire: minAFR × 10. E.g. byte 0 = AFR 0.0.</summary>
public byte MinRaw { get; init; }
public byte Mult { get; init; }
public byte Sign { get; init; }
// ── Derived display values ────────────────────────────────────────────────
public bool IsSigned => Sign > 0;
/// <summary>Display AFR value for a cell (wire byte ÷ 10.0).</summary>
public double GetCell(int row, int col)
{
byte raw = Data[row * Cols + col];
return IsSigned
? unchecked((sbyte)raw) / 10.0
: raw / 10.0;
}
/// <summary>Max AFR display value.</summary>
public double MaxAfrDisplay => IsSigned
? unchecked((sbyte)MaxRaw) / 10.0
: MaxRaw / 10.0;
/// <summary>Min AFR display value.</summary>
public double MinAfrDisplay => IsSigned
? unchecked((sbyte)MinRaw) / 10.0
: MinRaw / 10.0;
/// <summary>RPM axis in display units (raw × 100).</summary>
public int[] RpmValues => RpmAxis.Select(r => r * 100).ToArray();
/// <summary>Load axis values (raw, 0–110).</summary>
public int[] LoadValues => LoadAxis.Select(l => (int)l).ToArray();
// ── Serialisation ─────────────────────────────────────────────────────────
/// <summary>
/// Builds the combined 228-byte write payload.
/// Matches prepareAllData() / writeBtn_Click() in TuningTablePanelAFR.cs.
/// Modifier bytes [224–225] are stored as AFR × 10.
/// </summary>
public byte[] ToWirePayload()
{
var buf = new byte[TotalPayloadBytes];
Buffer.BlockCopy(Data, 0, buf, 0, DataBytes);
Buffer.BlockCopy(LoadAxis,0, buf, DataBytes, Rows);
Buffer.BlockCopy(RpmAxis, 0, buf, DataBytes + Rows, Cols);
buf[DataBytes + Rows + Cols] = MaxRaw;
buf[DataBytes + Rows + Cols + 1] = MinRaw;
buf[DataBytes + Rows + Cols + 2] = Mult;
buf[DataBytes + Rows + Cols + 3] = Sign;
return buf;
}
public byte[] ToWirePayloadPart1() => ToWirePayload()[..(SplitFirstLength + 1)];
public byte[] ToWirePayloadPart2() => ToWirePayload()[(SplitFirstLength + 1)..];
// ── Deserialisation ───────────────────────────────────────────────────────
/// <summary>
/// Parses a combined 228-byte buffer from two split read responses.
/// Matches sendReadSplitTableToPanelThread (AFR path) in Form1_TableHandling.cs.
/// </summary>
public static AfrTable FromWirePayload(byte[] combined)
{
if (combined.Length < TotalPayloadBytes)
throw new ArgumentException(
$"Expected {TotalPayloadBytes} bytes, got {combined.Length}.", nameof(combined));
var data = new byte[DataBytes];
var loadAxis = new byte[Rows];
var rpmAxis = new byte[Cols];
Buffer.BlockCopy(combined, 0, data, 0, DataBytes);
Buffer.BlockCopy(combined, DataBytes, loadAxis,0, Rows);
Buffer.BlockCopy(combined, DataBytes + Rows, rpmAxis, 0, Cols);
int modBase = DataBytes + Rows + Cols;
return new AfrTable
{
Data = data,
LoadAxis = loadAxis,
RpmAxis = rpmAxis,
MaxRaw = combined[modBase],
MinRaw = combined[modBase + 1],
Mult = combined[modBase + 2],
Sign = combined[modBase + 3],
};
}
/// <summary>
/// Assembles from two raw device response buffers (data starts at offset 4).
/// </summary>
public static AfrTable FromSplitResponses(byte[] part1Response, byte[] part2Response)
{
var combined = new byte[TotalPayloadBytes];
Buffer.BlockCopy(part1Response, 4, combined, 0, SplitFirstLength + 1);
int part2Len = TotalPayloadBytes - (SplitFirstLength + 1);
Buffer.BlockCopy(part2Response, 4, combined, SplitFirstLength + 1, part2Len);
return FromWirePayload(combined);
}
// ── Mutation ──────────────────────────────────────────────────────────────
/// <summary>
/// Returns a new AfrTable with cell (row, col) adjusted by delta (in AFR units, e.g. 0.1).
/// Delta is converted to wire units (×10) before clamping.
/// Matches minusButton/addButton in TuningTablePanelAFR.cs.
/// </summary>
public AfrTable WithCellAdjusted(int row, int col, double deltaAfr,
double minAfr = 0.0, double maxAfr = 15.0)
{
var newData = (byte[])Data.Clone();
int idx = row * Cols + col;
double current = GetCell(row, col);
double adjusted = Math.Clamp(current + deltaAfr, minAfr, maxAfr);
// Round to 1 decimal place then encode ×10
double rounded = Math.Round(adjusted, 1, MidpointRounding.AwayFromZero);
newData[idx] = IsSigned
? unchecked((byte)(sbyte)(rounded * 10.0))
: (byte)(rounded * 10.0);
return new AfrTable
{
Data = newData,
LoadAxis = LoadAxis,
RpmAxis = RpmAxis,
MaxRaw = MaxRaw,
MinRaw = MinRaw,
Mult = Mult,
Sign = Sign,
};
}
// ── Convenience ──────────────────────────────────────────────────────────
/// <summary>
/// Returns modifier bytes as stored on wire.
/// MaxRaw/MinRaw are AFR × 10; Mult/Sign are unchanged.
/// </summary>
public byte[] ToModifierBytes() => new[]
{
MaxRaw, MinRaw, Mult, Sign
};
/// <summary>
/// Builds modifier bytes from display AFR values for writing.
/// Matches: modifiersInArray[0] = (byte)(maxRawVal * 10.0)
/// </summary>
public static byte[] BuildModifierBytes(double maxAfr, double minAfr,
byte mult = 1, byte sign = 0) => new[]
{
(byte)(maxAfr * 10.0),
(byte)(minAfr * 10.0),
mult,
sign
};
}
+109
View File
@@ -0,0 +1,109 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// Bike manufacturer and model registry.
/// To add a new make: add a new entry to Manufacturers.
/// To add a new model: add a new entry to the Models list for that make.
/// </summary>
public static class BikeRegistry
{
// ── Manufacturer codes ────────────────────────────────────────────────────
public const byte Yamaha = 1;
public const byte Honda = 2;
public const byte Modenas = 5;
public const byte Suzuki = 6;
// ── Registry ──────────────────────────────────────────────────────────────
private static readonly Dictionary<byte, (string Make, Dictionary<int, string> Models)> _registry
= new()
{
[Yamaha] = ("Yamaha", new()
{
[1] = "FZ150i (2008–2013)",
[2] = "Lagenda 115z EFi",
[3] = "FZ150i (2014)",
[4] = "YZF R15 (2008–2013)",
[5] = "YZF R15 (2014)",
[6] = "Y15ZR / Exciter 150 / MX King 150",
[7] = "FZ150i / YZF R15",
[8] = "FZ150i (2016)",
[9] = "MSLAZ 2015",
[10] = "YZF R25 2018",
[11] = "YZF R3 2015",
[13] = "YZF R15 2015",
[14] = "NMAX",
[15] = "NVX",
[16] = "Y15ZR 2019",
[17] = "Y16ZR",
[18] = "135LC Fi",
[19] = "XMAX",
[20] = "XMAX V2",
[21] = "R15M 2022",
[22] = "MT15 2022",
[23] = "EGO AVANTIZ",
[24] = "R125 2019",
[25] = "R25 2019",
[26] = "R3 2019",
[27] = "R125 2008",
[28] = "XMAX V3",
[29] = "NVX V1",
[30] = "PG1 / EZ115",
}),
[Honda] = ("Honda", new()
{
[1] = "Dream110 / Wave110 / Wave125 / MSX125",
[2] = "PCX",
[3] = "RS150R / Winner150",
[4] = "CBR250",
[5] = "CRF250L (2013)",
[6] = "CRF250L (2017)",
[7] = "EX5",
[8] = "RSX",
}),
[Modenas] = ("Modenas", new()
{
[1] = "VF3i",
}),
[Suzuki] = ("Suzuki", new()
{
[1] = "Raider R150",
}),
};
// ── Lookups ───────────────────────────────────────────────────────────────
/// <summary>Returns the manufacturer name, or empty string if unknown.</summary>
public static string GetMake(byte makeCode)
=> _registry.TryGetValue(makeCode, out var entry) ? entry.Make : string.Empty;
/// <summary>Returns the model name, or empty string if unknown.</summary>
public static string GetModel(byte makeCode, int modelCode)
{
if (!_registry.TryGetValue(makeCode, out var entry)) return string.Empty;
return entry.Models.TryGetValue(modelCode, out var name) ? name : string.Empty;
}
/// <summary>Returns "Make — Model" display string, e.g. "Yamaha — Y15ZR 2019".</summary>
public static string GetDisplayName(byte makeCode, int modelCode)
{
string make = GetMake(makeCode);
string model = GetModel(makeCode, modelCode);
if (string.IsNullOrEmpty(make)) return $"Unknown ({makeCode}/{modelCode})";
if (string.IsNullOrEmpty(model)) return $"{make} — Unknown model ({modelCode})";
return $"{make} — {model}";
}
/// <summary>All registered manufacturers.</summary>
public static IEnumerable<(byte Code, string Name)> AllMakes
=> _registry.Select(kv => (kv.Key, kv.Value.Make));
/// <summary>All models for a given manufacturer code.</summary>
public static IEnumerable<(int Code, string Name)> ModelsFor(byte makeCode)
=> _registry.TryGetValue(makeCode, out var entry)
? entry.Models.Select(kv => (kv.Key, kv.Value))
: Enumerable.Empty<(int, string)>();
}
+417
View File
@@ -0,0 +1,417 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// Parsed APP_MONITORING (0x70) streaming diagnostics frame.
///
/// ── Wire layout — 36 bytes (value[0..35]) ────────────────────────────────────
/// Sourced from UpdateDiagLabel() and label assignment logic in the WinForms app.
/// Column mapping confirmed from tableLayoutPanel1 Designer.cs:
/// col 0/2 = definition label (static text)
/// col 1/3 = value label (updated each frame)
///
/// Byte Channel Notes / Display
/// ───── ───────────────────────── ──────────────────────────────────────────
/// [0] (TL command = 0x70) Packet type, not a data channel
/// [1] (reserved / seq)
/// [2] (reserved)
/// [3] (reserved)
/// [4] Load Raw load value
/// [5] RPM_raw × 100 = display RPM
/// [6] Baro_kPa Barometric pressure kPa
/// [7] VBAT_deciV Battery voltage (decivolts)
/// [8] FuelStartAngle1_raw × 3 = display degrees (label71)
/// [9] FuelStartAngle2_raw × 3 = display degrees (label71a)
/// [10] FuelPW1_lo Combined: [10] + 256×[11] = fuel PW 1
/// [11] FuelPW1_hi
/// [12] SparkAngle1 unchecked sbyte
/// [13] SparkAngle2 unchecked sbyte
/// [14] CrankSyncLostCounter
/// [15] SparkPulseWidth
/// [16] FuelEndAngle_lo Combined: [16] + 256×[17]
/// [17] FuelEndAngle_hi
/// [18] TPS_Raw Raw TPS value (label78 = "TPS Raw")
/// [19] CrankState_packed [19] & 0x0F = CrankState, [19] & 0xF0 >> 4 = TC_Mode
/// [20] ETEMP_DegC Engine temperature °C
/// [21] IAT_DegC Intake air temperature °C
/// [22] TPS_Percent TPS as percentage (used for gauge + tracker)
/// [23] MAP_kPa Manifold absolute pressure kPa
/// [24] O2_AirFuel_x10 AFR × 10 (e.g. 145 = 14.5 AFR)
/// [25] MAP_Lo_Avg_kPa
/// [26] MAP_Hi_Avg_kPa + ([29] & 0x10) × 16 = extra speed bit (2026/04/06)
/// [27] Baro_Dynamic
/// [28] ThrottleState_packed [28] & 0x0F = ThrottleState, [28] & 0x10 = FuelPW_Limit
/// [29] RPMState_packed [29] & 0x0F = RPMState, [29] & 0x80 = StayTuned,
/// [29] & 0x20 = Mode, [29] & 0x10 = extra speed bit
/// [30] UMState_packed [30] & 0x0F = UMState, [30] & 0xF0 >> 4 = GearRatio
/// [31] ErrorState1 Bit-packed analog errors (current)
/// [32] ErrorState2 Bit-packed output errors (current)
/// [33] ErrorState1_Persistent Bit-packed analog errors (persistent)
/// [34] ErrorState2_Persistent Bit-packed output errors (persistent) (also captureError arg 3)
/// [35] ErrorState_Extra Bit-packed output errors persistent (captureError arg 4)
///
/// ── Tracker channels ──────────────────────────────────────────────────────────
/// Load tracker : uses value[4] (Load)
/// RPM tracker : uses value[5] (RPM_raw)
/// TPS tracker : uses value[22] (TPS_Percent) ← for user-adjust tables (diag4/5/10/11/12)
///
/// ── CrankState display values ─────────────────────────────────────────────────
/// 5 = Yellow (near-sync), 6 = Green (running), other = Red (lost/searching)
///
/// ── UMState display values ────────────────────────────────────────────────────
/// 0=INIT, 1=STOP, 2=START, 3=RUN, 4=CUT, 5=SAFEMODE_RUN, 6=SAFEMODE_CUT,
/// 7=LAUNCHBOSS, 8=LAUNCHBOSS_CUT
/// </summary>
public sealed class DiagnosticsFrame
{
public const int FrameBytes = 36;
// ── Identity ─────────────────────────────────────────────────────────────
public byte SeqNum { get; init; }
public DateTime ReceivedAt { get; init; }
// ── Primary channels ─────────────────────────────────────────────────────
public byte Load { get; init; } // [4]
public byte RPM_Raw { get; init; } // [5] × 100 = RPM
public byte Baro_kPa { get; init; } // [6]
public byte VBAT_deciV { get; init; } // [7]
// ── Fuel channels ────────────────────────────────────────────────────────
public byte FuelStartAngle1_Raw { get; init; } // [8] × 3 = degrees
public byte FuelStartAngle2_Raw { get; init; } // [9] × 3 = degrees
public int FuelPulseWidth1 { get; init; } // [10] + 256×[11]
public int FuelEndAngle { get; init; } // [16] + 256×[17]
// ── Spark channels ────────────────────────────────────────────────────────
public sbyte SparkAngle1 { get; init; } // [12] sbyte
public sbyte SparkAngle2 { get; init; } // [13] sbyte
public byte SparkPulseWidth { get; init; } // [15]
// ── Crank ────────────────────────────────────────────────────────────────
public byte CrankSyncLostCounter { get; init; } // [14]
public byte CrankState_Raw { get; init; } // [19] raw packed byte
public byte TPS_Raw { get; init; } // [18]
// ── Sensor channels ──────────────────────────────────────────────────────
public byte ETEMP_DegC { get; init; } // [20]
public byte IAT_DegC { get; init; } // [21]
public byte TPS_Percent { get; init; } // [22]
public byte MAP_kPa { get; init; } // [23]
public byte O2_AFR_x10 { get; init; } // [24] ÷ 10 = AFR
public byte MAP_Lo_Avg { get; init; } // [25]
public byte MAP_Hi_Avg_Raw{ get; init; } // [26] raw (extra bit in [29])
public byte Baro_Dynamic { get; init; } // [27]
// ── State packed bytes ────────────────────────────────────────────────────
public byte ThrottleState_Packed { get; init; } // [28]
public byte RPMState_Packed { get; init; } // [29]
public byte UMState_Packed { get; init; } // [30]
// ── Error bytes ──────────────────────────────────────────────────────────
// captureError(value[32], value[33], value[34], value[35])
// = captureError(analogError, analogErrorP, outputError, outputErrorP)
public byte ErrorsFatal { get; init; } // [31] raw display only (label91)
public byte AnalogError_Current { get; init; } // [32] analogError
public byte AnalogError_Persistent { get; init; } // [33] analogErrorP
public byte OutputError_Current { get; init; } // [34] outputError
public byte OutputError_Persistent { get; init; } // [35] outputErrorP
// ── Derived display values ────────────────────────────────────────────────
public int RPM => RPM_Raw * 100;
public int FuelStartAngle1_Deg => FuelStartAngle1_Raw * 3;
public int FuelStartAngle2_Deg => FuelStartAngle2_Raw * 3;
public double O2_AFR => O2_AFR_x10 / 10.0;
public double VBAT_Volts => VBAT_deciV / 10.0;
// [19] CrankState nibbles
public int CrankState => CrankState_Raw & 0x0F;
public int TC_Mode => (CrankState_Raw & 0xF0) >> 4;
// [28] ThrottleState
public ThrottleStateValue ThrottleState => (ThrottleStateValue)(ThrottleState_Packed & 0x0F);
public bool FuelPW_LimitActive => (ThrottleState_Packed & 0x10) != 0;
// [29] RPM State
public RPMStateValue RPMState => (RPMStateValue)(RPMState_Packed & 0x0F);
public bool StayTunedRunning => (RPMState_Packed & 0x80) != 0;
public bool ModeSelected => (RPMState_Packed & 0x20) != 0;
public bool SpeedExtraBit => (RPMState_Packed & 0x10) != 0;
// [26] Meter speed with extra bit from [29] (added 2026/04/06)
public int MeterSpeed => MAP_Hi_Avg_Raw + (SpeedExtraBit ? 0x10 * 16 : 0);
// [30] UM State
public UMStateValue UMState => (UMStateValue)(UMState_Packed & 0x0F);
public int GearRatio => (UMState_Packed & 0xF0) >> 4;
// ── Error flags ───────────────────────────────────────────────────────────
public bool[] AnalogErrors_Current => UnpackBits(AnalogError_Current);
public bool[] OutputErrors_Current => UnpackBits(OutputError_Current);
public bool[] AnalogErrors_Persistent => UnpackBits(AnalogError_Persistent);
public bool[] OutputErrors_Persistent => UnpackBits(OutputError_Persistent);
public bool HasActiveError =>
AnalogError_Current != 0 || OutputError_Current != 0;
/// <summary>Parsed error flags — ready to drive the 16-indicator error panel.</summary>
public ErrorFlags Errors => ErrorFlags.From(this);
// ── Parser ────────────────────────────────────────────────────────────────
/// <summary>
/// Parses a raw diagnostics frame payload.
/// <paramref name="data"/> is the full BLE packet payload starting at byte [0] = 0x70.
/// Byte indices in comments refer to the payload array as used in UpdateDiagLabel().
/// </summary>
public static DiagnosticsFrame Parse(byte[] data, byte seqNum, DateTime? receivedAt = null)
{
if (data.Length < FrameBytes)
throw new ArgumentException(
$"Expected at least {FrameBytes} bytes, got {data.Length}.", nameof(data));
return new DiagnosticsFrame
{
SeqNum = seqNum,
ReceivedAt = receivedAt ?? DateTime.UtcNow,
Load = data[4],
RPM_Raw = data[5],
Baro_kPa = data[6],
VBAT_deciV = data[7],
FuelStartAngle1_Raw = data[8],
FuelStartAngle2_Raw = data[9],
FuelPulseWidth1 = data[10] + (256 * data[11]),
SparkAngle1 = unchecked((sbyte)data[12]),
SparkAngle2 = unchecked((sbyte)data[13]),
CrankSyncLostCounter = data[14],
SparkPulseWidth = data[15],
FuelEndAngle = data[16] + (256 * data[17]),
TPS_Raw = data[18],
CrankState_Raw = data[19],
ETEMP_DegC = data[20],
IAT_DegC = data[21],
TPS_Percent = data[22],
MAP_kPa = data[23],
O2_AFR_x10 = data[24],
MAP_Lo_Avg = data[25],
MAP_Hi_Avg_Raw = data[26],
Baro_Dynamic = data[27],
ThrottleState_Packed = data[28],
RPMState_Packed = data[29],
UMState_Packed = data[30],
ErrorsFatal = data[31],
AnalogError_Current = data[32],
AnalogError_Persistent = data[33],
OutputError_Current = data[34],
OutputError_Persistent = data[35],
};
}
// ── CSV log format ────────────────────────────────────────────────────────
/// <summary>
/// Returns a CSV log row matching the format in UpdateDiagLabel().
/// Columns match the .tbd log format used by TracBoss.
/// </summary>
public string ToCsvRow(string timestamp) =>
$"{timestamp}," +
$"{Load}," +
$"{RPM}," +
$"{Baro_kPa}," +
$"{VBAT_deciV}," +
$"{FuelPulseWidth1}," +
$"{FuelEndAngle}," +
$"{SparkAngle1}," +
$"{SparkAngle2}," +
$"{CrankSyncLostCounter}," +
$"{SparkPulseWidth}," +
$"{FuelEndAngle}," +
$"{TPS_Raw}," +
$"{CrankState_Raw}," +
$"{ETEMP_DegC}," +
$"{IAT_DegC}," +
$"{TPS_Percent}," +
$"{MAP_kPa}," +
$"{O2_AFR_x10}," +
$"{MAP_Lo_Avg}," +
$"{MAP_Hi_Avg_Raw}," +
$"{Baro_Dynamic}," +
$"{ThrottleState_Packed}," +
$"{RPMState_Packed}," +
$"{UMState_Packed}," +
$"{AnalogError_Current}," +
$"{OutputError_Current}," +
$"{AnalogError_Persistent}," +
$"{OutputError_Persistent},";
// ── Helpers ───────────────────────────────────────────────────────────────
private static bool[] UnpackBits(byte b) =>
Enumerable.Range(0, 8).Select(i => (b & (1 << i)) != 0).ToArray();
}
// ── State enums ───────────────────────────────────────────────────────────────
public enum ThrottleStateValue : byte
{
Steady = 0,
Accel = 1,
Decel = 2,
}
public enum RPMStateValue : byte
{
Steady = 0,
Decel = 1,
Accel = 2,
}
public enum UMStateValue : byte
{
Init = 0,
Stop = 1,
Start = 2,
Run = 3,
Cut = 4,
SafeMode_Run = 5,
SafeMode_Cut = 6,
LaunchBoss = 7,
LaunchBoss_Cut = 8,
}
/// <summary>
/// Diagnostics tracker coordinates for highlighting the active cell
/// in a tuning table grid. Produced by getRpmToHighlight/getLoadToHighlight.
/// </summary>
public sealed record DiagnosticsTracker(
int ColHighlight, // exact RPM column
int ColLowlight, // next RPM column
int RowHighlight, // exact load/TPS row
int RowLowlight); // next load/TPS row
/// <summary>
/// Parsed error flags from the four error bytes in a DiagnosticsFrame.
///
/// Call site (UpdateDiagLabel): captureError(value[32], value[33], value[34], value[35])
/// analogError = [32] AnalogError_Current
/// analogErrorP = [33] AnalogError_Persistent
/// outputError = [34] OutputError_Current
/// outputErrorP = [35] OutputError_Persistent
///
/// Display: Red = active now, Yellow = persistent (ever triggered), Green = clear
///
/// ── Analog errors (err1–err8) bit map ────────────────────────────────────────
/// Bit 0 err1 Throttle Position Sensor
/// Bit 1 err2 Manifold Air Pressure Sensor
/// Bit 2 err3 Intake Air Temperature Sensor
/// Bit 3 err4 Vehicle Down Sensor
/// Bit 4 err5 Engine Temperature Sensor
/// Bit 5 err6 Oxygen Sensor
/// Bit 6 err7 Battery Voltage
/// Bit 7 err8 Aux
///
/// ── Output errors (err9o–err16o) bit map ─────────────────────────────────────
/// Bit 0 err9o Injector 1
/// Bit 1 err10o Injector 2 / Idle Solenoid
/// Bit 2 err11o Fuel Pump
/// Bit 3 err12o Radiator Fan
/// Bit 4 err13o Spark Ignition 1
/// Bit 5 err14o Spark Ignition 2
/// Bit 6 err15o 5V PSU
/// Bit 7 err16o O2H
/// </summary>
public sealed class ErrorFlags
{
// ── Raw bytes ─────────────────────────────────────────────────────────────
public byte AnalogCurrent { get; init; } // value[32]
public byte AnalogPersistent { get; init; } // value[33]
public byte OutputCurrent { get; init; } // value[34]
public byte OutputPersistent { get; init; } // value[35]
// ── Analog error channels ─────────────────────────────────────────────────
public ErrorStatus TPS => Get(AnalogCurrent, AnalogPersistent, 0);
public ErrorStatus MAP => Get(AnalogCurrent, AnalogPersistent, 1);
public ErrorStatus IAT => Get(AnalogCurrent, AnalogPersistent, 2);
public ErrorStatus VehicleDown => Get(AnalogCurrent, AnalogPersistent, 3);
public ErrorStatus ETemp => Get(AnalogCurrent, AnalogPersistent, 4);
public ErrorStatus OxygenSensor=> Get(AnalogCurrent, AnalogPersistent, 5);
public ErrorStatus BattVoltage => Get(AnalogCurrent, AnalogPersistent, 6);
public ErrorStatus Aux => Get(AnalogCurrent, AnalogPersistent, 7);
// ── Output error channels ─────────────────────────────────────────────────
public ErrorStatus Injector1 => Get(OutputCurrent, OutputPersistent, 0);
public ErrorStatus Injector2_IdleSol => Get(OutputCurrent, OutputPersistent, 1);
public ErrorStatus FuelPump => Get(OutputCurrent, OutputPersistent, 2);
public ErrorStatus RadiatorFan => Get(OutputCurrent, OutputPersistent, 3);
public ErrorStatus SparkIgnition1 => Get(OutputCurrent, OutputPersistent, 4);
public ErrorStatus SparkIgnition2 => Get(OutputCurrent, OutputPersistent, 5);
public ErrorStatus PSU_5V => Get(OutputCurrent, OutputPersistent, 6);
public ErrorStatus O2Heater => Get(OutputCurrent, OutputPersistent, 7);
// ── Summary ───────────────────────────────────────────────────────────────
public bool HasActiveError =>
AnalogCurrent != 0 || OutputCurrent != 0;
/// <summary>All 16 error channels in display order (analog first, then output).</summary>
public IEnumerable<(string Name, ErrorStatus Status)> AllErrors()
{
yield return ("Throttle Position Sensor", TPS);
yield return ("Manifold Air Pressure Sensor", MAP);
yield return ("Intake Air Temperature Sensor", IAT);
yield return ("Vehicle Down Sensor", VehicleDown);
yield return ("Engine Temperature Sensor", ETemp);
yield return ("Oxygen Sensor", OxygenSensor);
yield return ("Battery Voltage", BattVoltage);
yield return ("Aux", Aux);
yield return ("Injector 1", Injector1);
yield return ("Injector 2 / Idle Solenoid", Injector2_IdleSol);
yield return ("Fuel Pump", FuelPump);
yield return ("Radiator Fan", RadiatorFan);
yield return ("Spark Ignition 1", SparkIgnition1);
yield return ("Spark Ignition 2", SparkIgnition2);
yield return ("5V PSU", PSU_5V);
yield return ("O2 Heater", O2Heater);
}
// ── Factory ───────────────────────────────────────────────────────────────
public static ErrorFlags From(DiagnosticsFrame frame) => new()
{
AnalogCurrent = frame.AnalogError_Current,
AnalogPersistent = frame.AnalogError_Persistent,
OutputCurrent = frame.OutputError_Current,
OutputPersistent = frame.OutputError_Persistent,
};
public static ErrorFlags Clear => new()
{
AnalogCurrent = 0, AnalogPersistent = 0,
OutputCurrent = 0, OutputPersistent = 0,
};
// ── Helper ────────────────────────────────────────────────────────────────
private static ErrorStatus Get(byte current, byte persistent, int bit)
{
bool isActive = (current & (1 << bit)) != 0;
bool wasPersistent= (persistent & (1 << bit)) != 0;
if (isActive) return ErrorStatus.Active;
if (wasPersistent) return ErrorStatus.Persistent;
return ErrorStatus.Clear;
}
}
/// <summary>
/// Three-state error status matching the traffic-light display:
/// Active = Red (currently faulted)
/// Persistent = Yellow (was faulted this session, now cleared)
/// Clear = Green (no fault)
/// </summary>
public enum ErrorStatus
{
Clear,
Persistent,
Active,
}
+190
View File
@@ -0,0 +1,190 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// Parsed response from APP_READ_INFO (0x37).
/// Immutable — constructed once per successful read.
/// </summary>
public sealed class EcuInfo
{
// ── Identity ─────────────────────────────────────────────────────────────
public string Username { get; init; } = string.Empty;
public string UniqueId { get; init; } = string.Empty; // "AABBCCDD-EEFF0011-..."
// ── Version ──────────────────────────────────────────────────────────────
public byte FwVersion { get; init; }
public byte HwVersion { get; init; }
public byte FwVersion2 { get; init; } // Only present if buffer > 68
public byte FwSubVersion2 { get; init; }
public byte TableVersion { get; init; }
public byte HwComponentVersion { get; init; }
public byte AppInfoVersion { get; init; } // Generation discriminator
// ── Bike identity ────────────────────────────────────────────────────────
public byte BikeManufacturer { get; init; } // 1=Yamaha 2=Honda 3=Kawasaki 6=Suzuki
public byte BikeModel { get; init; }
// ── Usage counters ───────────────────────────────────────────────────────
public uint FlashWriteCount { get; init; }
public uint SwitchToggleCount { get; init; }
public byte PwdResetCount { get; init; }
// ── Dates ────────────────────────────────────────────────────────────────
public DateOnly? ProgrammingDate { get; init; }
public DateOnly? FirstUseDate { get; init; }
public byte FirstUseInfo0 { get; init; } // raw buf[32] (FirstUseDate DD)
public byte FirstUseInfo1 { get; init; } // raw buf[33] — TPS cal-done flag (Android UIfirstUseDate[1])
public DateOnly? FirstFlashDate { get; init; }
// ── Upgrade flags ────────────────────────────────────────────────────────
public byte UpgradeRpmMax { get; init; } // × 100 = actual RPM limit
public byte UpgradeShiftAuto { get; init; }
public byte UpgradeLogImmo { get; init; } // low nibble = legacy Upgrade_Stage3 (see Stage)
public byte UpgradeFuture12 { get; init; }
public byte UpgradeFuture2 { get; init; } // only if buffer > 68
// ── Derived ──────────────────────────────────────────────────────────────
public int RpmLimit => UpgradeRpmMax * 100;
/// <summary>
/// Dual injector is a Stage 3 feature — the same nibble the Android app reads as
/// <c>Upgrade_Stage3</c>, so it follows the stage rather than being an independent flag.
/// </summary>
public bool IsDualInjectorUnlocked => Stage >= 3;
/// <summary>True once the throttle (TPS) calibration has been completed on this unit.
/// The firmware/Android app stores the flag in the second first-use byte
/// (UIfirstUseDate[1] = buf[33]), not the first.</summary>
public bool HasTpsCalibration => FirstUseInfo1 == TpsCalibration.CalDoneFlag;
/// <summary>
/// Legacy <c>Upgrade_Stage2</c> — high nibble of the shift/stage byte
/// (legacy <c>buf[offset+42] &amp; 0xF0</c>, whose low nibble is Shift Auto).
/// </summary>
public byte UpgradeStage2 => (byte)(UpgradeShiftAuto & 0xF0);
/// <summary>
/// Legacy <c>Upgrade_Stage3</c> — low nibble of the next byte
/// (legacy <c>buf[offset+43] &amp; 0x0F</c>; the WPF parser stores that byte
/// as <see cref="UpgradeLogImmo"/>).
/// </summary>
public byte UpgradeStage3 => (byte)(UpgradeLogImmo & 0x0F);
/// <summary>
/// ECU stage — 1, 2 or 3. Mirrors the Android app's precedence exactly:
/// Stage 3 wins if its nibble is set, else Stage 2, else Stage 1.
/// Stage 1 does not expose the user 24×8 adjust tables (only the subtables).
/// </summary>
public int Stage =>
UpgradeStage3 > 0 ? 3 :
UpgradeStage2 > 0 ? 2 : 1;
/// <summary>True when the stage exposes the user 24×8 adjust tables (Stage 2+).</summary>
public bool HasUserAdjustTables => Stage >= 2;
// ── Parser ───────────────────────────────────────────────────────────────
/// <summary>
/// Parses a raw APP_READ_INFO response buffer.
/// Buffer[0] must be APP_CMD_SUCCESS (0x51); payload starts at byte 4.
/// </summary>
public static EcuInfo Parse(byte[] buf)
{
if (buf[0] != 0x51)
throw new InvalidOperationException($"Expected APP_CMD_SUCCESS (0x51), got 0x{buf[0]:X2}");
const int payloadStart = 4;
const int fieldStart = payloadStart + 16; // after 16-byte username
// Username (16 bytes, null-terminated ASCII)
var username = System.Text.Encoding.ASCII
.GetString(buf, payloadStart, 16)
.TrimEnd('\0');
// Little-endian uint32 helper
uint ReadU32(int offset) =>
buf[offset] |
((uint)buf[offset + 1] << 8) |
((uint)buf[offset + 2] << 16) |
((uint)buf[offset + 3] << 24);
var flashWriteCount = ReadU32(fieldStart);
var switchToggleCount = ReadU32(fieldStart + 4);
// Dates — DD=0 means "Never"
// Day/Month/Year(+2000) as raw bytes. DD==0 means "Never". Some units carry
// uninitialised or garbage bytes in unused date slots (e.g. month 0 or 14,
// day 31 in a 30-day month); those must NOT throw and abort the whole info
// read — treat any non-calendar value as "not set" (null).
DateOnly? ParseDate(int offset)
{
int day = buf[offset], month = buf[offset + 1], year = 2000 + buf[offset + 2];
if (day == 0) return null;
if (month < 1 || month > 12) return null;
if (day > DateTime.DaysInMonth(year, month)) return null;
return new DateOnly(year, month, day);
}
var progDate = ParseDate(fieldStart + 8);
var firstUseDate = ParseDate(fieldStart + 12);
var firstUseInfo0 = buf[fieldStart + 12]; // DD slot (first-use date day)
var firstUseInfo1 = buf[fieldStart + 13]; // MM slot — doubles as the TPS cal-done flag
var firstFlashDate = ParseDate(fieldStart + 16);
// UniqueID — 16 bytes formatted as 4×4 hex groups
var uid = buf.Skip(fieldStart + 20).Take(16).ToArray();
var uniqueId = $"{Hex(uid, 0, 4)}-{Hex(uid, 4, 4)}-{Hex(uid, 8, 4)}-{Hex(uid, 12, 4)}";
int o = fieldStart + 36; // after UniqueID
var fwVersion = buf[o];
var hwVersion = buf[o + 1];
var bikeMfr = buf[o + 2];
var bikeModel = buf[o + 3];
var upgradeRpmMax = buf[o + 4];
var upgradeShift = buf[o + 5];
var upgradeLogImmo = buf[o + 6];
var upgradeFuture12 = buf[o + 7];
byte upgradeFuture2 = 0, fw2 = 0, fw2sub = 0, tableVer = 0, hwComp = 0;
if (buf.Length > 68)
{
upgradeFuture2 = buf[o + 8];
fw2 = buf[o + 9];
fw2sub = buf[o + 10];
tableVer = buf[o + 11];
hwComp = buf[o + 12];
}
var appInfoVersion = buf[^1]; // last byte
var pwdRstCount = buf[^5]; // 4 bytes from end
return new EcuInfo
{
Username = username,
UniqueId = uniqueId,
FwVersion = fwVersion,
HwVersion = hwVersion,
FwVersion2 = fw2,
FwSubVersion2 = fw2sub,
TableVersion = tableVer,
HwComponentVersion = hwComp,
AppInfoVersion = appInfoVersion,
BikeManufacturer = bikeMfr,
BikeModel = bikeModel,
FlashWriteCount = flashWriteCount,
SwitchToggleCount = switchToggleCount,
PwdResetCount = pwdRstCount,
ProgrammingDate = progDate,
FirstUseDate = firstUseDate,
FirstUseInfo0 = firstUseInfo0,
FirstUseInfo1 = firstUseInfo1,
FirstFlashDate = firstFlashDate,
UpgradeRpmMax = upgradeRpmMax,
UpgradeShiftAuto = upgradeShift,
UpgradeLogImmo = upgradeLogImmo,
UpgradeFuture12 = upgradeFuture12,
UpgradeFuture2 = upgradeFuture2,
};
}
private static string Hex(byte[] src, int start, int count) =>
string.Concat(src.Skip(start).Take(count).Select(b => $"{b:X2}"));
}
+79
View File
@@ -0,0 +1,79 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// Holds all table data loaded from a connected TuneBoss device.
/// Constructed after a successful populateInitTables sequence.
///
/// Acts as the single source of truth for the current session.
/// ViewModels bind to properties on this object.
/// Immutable by convention — table updates produce new instances.
/// </summary>
public sealed record EcuSession
{
// ── Device identity ───────────────────────────────────────────────────────
public EcuInfo Info { get; init; } = null!;
public MemoryLayout Layout { get; init; } = null!;
public EcuVariant Variant { get; init; }
// ── 2D tuning tables — cylinder 1 ────────────────────────────────────────
public TuningTable? Fuel_PulseWidth1 { get; init; }
public TuningTable? Spark_Angle1 { get; init; }
public TuningTable? Fuel_Angle2D { get; init; }
public TuningTable? Secondary_Load_Conversion { get; init; }
public TuningTable? Fuel_PulseWidth_Adjust1 { get; init; }
public TuningTable? Spark_Angle_Adjust1 { get; init; }
public AfrTable? AFR_Target1 { get; init; }
// ── Subtables — cylinder 1 ────────────────────────────────────────────────
public SubTable? AFR_Target1_SubTable { get; init; }
public SubTable? Fuel_PulseWidth_Adjust1_SubTable { get; init; }
public SubTable? Spark_Angle_Adjust1_SubTable { get; init; }
// ── 2D tuning tables — cylinder 2 (isTwoCylinder only) ───────────────────
public TuningTable? Fuel_PulseWidth2 { get; init; }
public TuningTable? Spark_Angle2 { get; init; }
public TuningTable? Fuel_Angle2D_2 { get; init; }
public TuningTable? Fuel_PulseWidth_Adjust2 { get; init; }
public TuningTable? Spark_Angle_Adjust2 { get; init; }
public AfrTable? AFR_Target2 { get; init; }
// ── Subtables — cylinder 2 ────────────────────────────────────────────────
public SubTable? AFR_Target2_SubTable { get; init; }
public SubTable? Fuel_PulseWidth_Adjust2_SubTable { get; init; }
public SubTable? Spark_Angle_Adjust2_SubTable { get; init; }
// ── 1D tables (up to 37, null = not available on this FW version) ─────────
public OneDimTable?[] OneDimTables { get; init; } = new OneDimTable?[37];
// ── Misc values ───────────────────────────────────────────────────────────
public MiscValues? Misc { get; init; }
// ── Derived ──────────────────────────────────────────────────────────────
public bool IsTwoCylinder => Variant != EcuVariant.SingleCylinder;
public bool HasExtendedMisc => Info.FwVersion >= 150;
/// <summary>
/// True when the session has been fully loaded —
/// i.e. all tables available for this device have been read.
/// </summary>
public bool IsFullyLoaded { get; init; }
// ── Mutation helpers ──────────────────────────────────────────────────────
/// <summary>Returns a new session with Fuel_PulseWidth1 replaced.</summary>
public EcuSession WithFuel1(TuningTable t) => this with { Fuel_PulseWidth1 = t };
public EcuSession WithSpark1(TuningTable t) => this with { Spark_Angle1 = t };
public EcuSession WithFuelAdjust1(TuningTable t) => this with { Fuel_PulseWidth_Adjust1 = t };
public EcuSession WithSparkAdjust1(TuningTable t) => this with { Spark_Angle_Adjust1 = t };
public EcuSession WithFuelAngle(TuningTable t) => this with { Fuel_Angle2D = t };
public EcuSession WithAfr1(AfrTable t) => this with { AFR_Target1 = t };
public EcuSession WithMisc(MiscValues m) => this with { Misc = m };
public EcuSession WithOneDimTable(int index, OneDimTable t)
{
var arr = (OneDimTable?[])OneDimTables.Clone();
arr[index] = t;
return this with { OneDimTables = arr };
}
}
+302
View File
@@ -0,0 +1,302 @@
using TuneBoss.Core.Protocol;
namespace TuneBoss.Core.Models;
/// <summary>
/// Describes a single memory region on the device — its address and read length.
/// </summary>
public sealed record MemoryRegion(ushort Address, byte Length)
{
public byte AddrLo => (byte)(Address & 0xFF);
public byte AddrHi => (byte)(Address >> 8);
public byte[] AddrBytes => new[] { AddrLo, AddrHi };
/// <summary>True if this region exists (address != 0x0000 or explicit availability flag).</summary>
public bool IsAvailable { get; init; } = true;
public static MemoryRegion Unavailable => new(0x0000, 0) { IsAvailable = false };
}
/// <summary>
/// Complete memory address map for a connected TuneBoss device.
/// Constructed once after EcuInfo is parsed; replaces the static memAddress class.
///
/// ── Generation mapping ────────────────────────────────────────────────────────
/// Gen1 (AppInfoVersion=245): legacy addresses, APP_MEMRD_SEQ for all ops
/// Gen2 (AppInfoVersion=1) : dedicated read commands, single-cylinder layout
/// Gen3 (AppInfoVersion=2) : same as Gen2 + separate 2D_USER address space
///
/// ── 1D table FW gates (from populateInitTables) ───────────────────────────────
/// Tables 1–18 : always (base set)
/// Tables 19–24 : FW_Version >= 80
/// Tables 25–26 : FW_Version >= 83
/// Tables 27–34 : FW_Version >= 90
/// Tables 35–37 : FW_Version >= 130
///
/// ── Misc FW gates ─────────────────────────────────────────────────────────────
/// Core (136B) : always
/// LaunchFuel (12B) : FW_Version >= 150
/// LaunchFuel2 (12B) : FW_Version >= 150
/// AuxOut (12B) : FW_Version >= 150
/// Extended (var B) : FW_Version >= 150, size from EcuVariant
/// </summary>
public sealed record MemoryLayout
{
// ── 2D main tuning tables ─────────────────────────────────────────────────
public MemoryRegion Fuel_PulseWidth1 { get; init; } = MemoryRegion.Unavailable;
public MemoryRegion Spark_Angle1 { get; init; } = MemoryRegion.Unavailable;
public MemoryRegion AFR_Target1 { get; init; } = MemoryRegion.Unavailable;
public MemoryRegion Fuel_Angle2D { get; init; } = MemoryRegion.Unavailable;
public MemoryRegion Secondary_Load_Conversion { get; init; } = MemoryRegion.Unavailable;
// ── 2D user-adjustable tables (cyl1) ─────────────────────────────────────
public MemoryRegion Fuel_PulseWidth_Adjust1 { get; init; } = MemoryRegion.Unavailable;
public MemoryRegion Spark_Angle_Adjust1 { get; init; } = MemoryRegion.Unavailable;
// ── Subtables (cyl1) ─────────────────────────────────────────────────────
public MemoryRegion AFR_Target1_SubTable { get; init; } = MemoryRegion.Unavailable;
public MemoryRegion Fuel_PulseWidth_Adjust1_SubTable { get; init; } = MemoryRegion.Unavailable;
public MemoryRegion Spark_Angle_Adjust1_SubTable { get; init; } = MemoryRegion.Unavailable;
// ── 2D tables cyl2 (isTwoCylinder only) ──────────────────────────────────
public MemoryRegion Fuel_PulseWidth2 { get; init; } = MemoryRegion.Unavailable;
public MemoryRegion Spark_Angle2 { get; init; } = MemoryRegion.Unavailable;
public MemoryRegion AFR_Target2 { get; init; } = MemoryRegion.Unavailable;
public MemoryRegion Fuel_Angle2D_2 { get; init; } = MemoryRegion.Unavailable;
public MemoryRegion Fuel_PulseWidth_Adjust2 { get; init; } = MemoryRegion.Unavailable;
public MemoryRegion Spark_Angle_Adjust2 { get; init; } = MemoryRegion.Unavailable;
// ── Subtables cyl2 ───────────────────────────────────────────────────────
public MemoryRegion AFR_Target2_SubTable { get; init; } = MemoryRegion.Unavailable;
public MemoryRegion Fuel_PulseWidth_Adjust2_SubTable { get; init; } = MemoryRegion.Unavailable;
public MemoryRegion Spark_Angle_Adjust2_SubTable { get; init; } = MemoryRegion.Unavailable;
// ── 1D tables (up to 37 depending on FW_Version) ─────────────────────────
// Index 0-based: OneDimTables[0] = table 1, OneDimTables[36] = table 37
// Unavailable entries have IsAvailable=false and are skipped by the service layer.
public MemoryRegion[] OneDimTables { get; init; } = new MemoryRegion[37];
// ── Misc regions ─────────────────────────────────────────────────────────
public MemoryRegion MiscCore { get; init; } = MemoryRegion.Unavailable; // 136 bytes, always
public MemoryRegion MiscLaunchFuel { get; init; } = MemoryRegion.Unavailable; // 12B, FW>=150
public MemoryRegion MiscLaunchFuel2 { get; init; } = MemoryRegion.Unavailable; // 12B, FW>=150
public MemoryRegion MiscAuxOut { get; init; } = MemoryRegion.Unavailable; // 12B, FW>=150
public MemoryRegion MiscExtended { get; init; } = MemoryRegion.Unavailable; // var, FW>=150
// ── RPM limit misc address ────────────────────────────────────────────────
public MemoryRegion RpmLimitMisc { get; init; } = MemoryRegion.Unavailable; // 0x63 length
// ── Read lengths (fixed from populateInitTables) ──────────────────────────
public const byte Len2DTable = 0xE3; // 227 — split read
public const byte LenAFRTable = 0xEF; // 239 — AFR split read
public const byte Len1DTable = 0x17; // 23 — single read
public const byte LenSubTable = 0x17; // 23 — single read
public const byte LenMiscCore = 0x88; // 136
public const byte LenMiscExt12 = 0x0B; // 11 (12 bytes incl [0])
public const byte LenRpmCheck = 0x63; // 99
// ════════════════════════════════════════════════════════════════════════
// FACTORY
// ════════════════════════════════════════════════════════════════════════
/// <summary>
/// Constructs the complete memory layout from parsed EcuInfo.
/// This is the single entry point — call once after ReadEcuInfoAsync().
/// </summary>
public static MemoryLayout For(EcuInfo info, EcuVariant variant)
{
var gen = GenerationConfig.ResolveGeneration(info.AppInfoVersion);
byte fw = info.FwVersion;
byte fw2sub = info.FwSubVersion2;
return gen switch
{
GenerationType.Gen1 => BuildGen1(fw, variant),
GenerationType.Gen2 => BuildGen2(fw, variant, fw2sub),
GenerationType.Gen3 => BuildGen3(fw, variant, fw2sub),
_ => throw new InvalidOperationException($"Unknown generation for AppInfoVersion {info.AppInfoVersion}")
};
}
// ════════════════════════════════════════════════════════════════════════
// GEN1 — legacy, APP_MEMRD_SEQ for all
// ════════════════════════════════════════════════════════════════════════
private static MemoryLayout BuildGen1(byte fw, EcuVariant variant)
{
static MemoryRegion R(ushort addr, byte len) => new(addr, len);
var layout = new MemoryLayout
{
// 2D tables at fixed GEN1 addresses
Fuel_PulseWidth1 = R(0x0000, Len2DTable),
Spark_Angle1 = R(0x00E4, Len2DTable),
AFR_Target1 = R(0x01C8, LenAFRTable),
Fuel_Angle2D = R(0x02AC, Len2DTable),
Secondary_Load_Conversion = R(0x0390, Len2DTable),
Fuel_PulseWidth_Adjust1 = R(0x048C, Len2DTable),
Spark_Angle_Adjust1 = R(0x0588, Len2DTable),
// Subtables
AFR_Target1_SubTable = R(0x02AC, LenSubTable),
Fuel_PulseWidth_Adjust1_SubTable = R(0x0570, LenSubTable),
Spark_Angle_Adjust1_SubTable = R(0x066C, LenSubTable),
// Misc
MiscCore = R(0x0834, LenMiscCore),
RpmLimitMisc = R(0x0840, LenRpmCheck),
// GEN1 has no extended misc regions
MiscLaunchFuel = MemoryRegion.Unavailable,
MiscLaunchFuel2 = MemoryRegion.Unavailable,
MiscAuxOut = MemoryRegion.Unavailable,
MiscExtended = MemoryRegion.Unavailable,
OneDimTables = Build1DTables_Gen1(fw),
};
return layout;
}
// ════════════════════════════════════════════════════════════════════════
// GEN2 — dedicated read commands, single/dual cylinder
// ════════════════════════════════════════════════════════════════════════
private static MemoryLayout BuildGen2(byte fw, EcuVariant variant, byte fw2sub = 0)
{
static MemoryRegion R(ushort addr, byte len) => new(addr, len);
bool isTwoCyl = variant != EcuVariant.SingleCylinder;
return new MemoryLayout
{
// Cyl1 2D
Fuel_PulseWidth1 = R(0x0000, Len2DTable),
Spark_Angle1 = R(0x00E4, Len2DTable),
AFR_Target1 = R(0x01C8, LenAFRTable),
Fuel_Angle2D = R(0x02AC, Len2DTable),
Secondary_Load_Conversion = R(0x0390, Len2DTable),
Fuel_PulseWidth_Adjust1 = R(0x0474, Len2DTable),
Spark_Angle_Adjust1 = R(0x0558, Len2DTable),
// Cyl1 subtables
AFR_Target1_SubTable = R(0x0000, LenSubTable),
Fuel_PulseWidth_Adjust1_SubTable = R(0x0018, LenSubTable),
Spark_Angle_Adjust1_SubTable = R(0x0030, LenSubTable),
// Cyl2 2D (zero/unavailable for single cylinder)
Fuel_PulseWidth2 = isTwoCyl ? R(0x063C, Len2DTable) : MemoryRegion.Unavailable,
AFR_Target2 = isTwoCyl ? R(0x0720, LenAFRTable) : MemoryRegion.Unavailable,
Fuel_Angle2D_2 = isTwoCyl ? R(0x0804, Len2DTable) : MemoryRegion.Unavailable,
Spark_Angle2 = isTwoCyl ? R(0x08E8, Len2DTable) : MemoryRegion.Unavailable,
Fuel_PulseWidth_Adjust2 = isTwoCyl ? R(0x09CC, Len2DTable) : MemoryRegion.Unavailable,
Spark_Angle_Adjust2 = isTwoCyl ? R(0x0AB0, Len2DTable) : MemoryRegion.Unavailable,
// Cyl2 subtables
AFR_Target2_SubTable = isTwoCyl ? R(0x0048, LenSubTable) : MemoryRegion.Unavailable,
Fuel_PulseWidth_Adjust2_SubTable = isTwoCyl ? R(0x0060, LenSubTable) : MemoryRegion.Unavailable,
Spark_Angle_Adjust2_SubTable = isTwoCyl ? R(0x0078, LenSubTable) : MemoryRegion.Unavailable,
// Misc core
MiscCore = R(0x0000, LenMiscCore),
RpmLimitMisc = R(0x000C, LenRpmCheck),
// Extended misc — FW >= 150
MiscLaunchFuel = fw >= 150 ? R(0x0088, LenMiscExt12) : MemoryRegion.Unavailable,
MiscLaunchFuel2 = fw >= 150 ? R(0x0094, LenMiscExt12) : MemoryRegion.Unavailable,
MiscAuxOut = fw >= 150 ? R(0x00A0, LenMiscExt12) : MemoryRegion.Unavailable,
MiscExtended = fw >= 150
? R(0x00AC, MiscValues.ExtendedLengthFor(fw2sub))
: MemoryRegion.Unavailable,
OneDimTables = Build1DTables_Gen2(fw),
};
}
// ════════════════════════════════════════════════════════════════════════
// GEN3 — same as Gen2 but 2D_USER in separate address space
// ════════════════════════════════════════════════════════════════════════
private static MemoryLayout BuildGen3(byte fw, EcuVariant variant, byte fw2sub = 0)
{
// GEN3 user-adjust tables live in a separate address space:
// Fuel_PulseWidth_Adjust1 = 0x0000, Spark_Angle_Adjust1 = 0x00E4
// etc. (addressed via APP_MEMRD_2D_USER not APP_MEMRD_2D)
var base2 = BuildGen2(fw, variant, fw2sub);
bool isTwoCyl = variant != EcuVariant.SingleCylinder;
static MemoryRegion R(ushort addr, byte len) => new(addr, len);
return base2 with
{
// Override user-adjust addresses for GEN3
Fuel_PulseWidth_Adjust1 = R(0x0000, Len2DTable),
Spark_Angle_Adjust1 = R(0x00E4, Len2DTable),
Fuel_PulseWidth_Adjust2 = isTwoCyl ? R(0x01C8, Len2DTable) : MemoryRegion.Unavailable,
Spark_Angle_Adjust2 = isTwoCyl ? R(0x02AC, Len2DTable) : MemoryRegion.Unavailable,
};
}
// ════════════════════════════════════════════════════════════════════════
// 1D TABLE ADDRESS BUILDERS
// Note the deliberate addr17→panel19, addr18→panel20 swap observed in
// populateInitTables — preserved here in array order.
// ════════════════════════════════════════════════════════════════════════
private static MemoryRegion[] Build1DTables_Gen1(byte fw)
{
var t = Enumerable.Repeat(MemoryRegion.Unavailable, 37).ToArray();
static MemoryRegion R(ushort a) => new(a, Len1DTable);
// Base 18 (addr 0x0684 onwards, 0x18 = 24 byte stride)
t[0] = R(0x0684); t[1] = R(0x069C); t[2] = R(0x06B4);
t[3] = R(0x06CC); t[4] = R(0x06E4); t[5] = R(0x06FC);
t[6] = R(0x0714); t[7] = R(0x072C); t[8] = R(0x0744);
t[9] = R(0x075C); t[10] = R(0x0774); t[11] = R(0x078C);
t[12] = R(0x07A4); t[13] = R(0x07BC); t[14] = R(0x07D4);
t[15] = R(0x07EC); t[16] = R(0x0804); t[17] = R(0x081C);
return t;
}
private static MemoryRegion[] Build1DTables_Gen2(byte fw)
{
var t = Enumerable.Repeat(MemoryRegion.Unavailable, 37).ToArray();
static MemoryRegion R(ushort a) => new(a, Len1DTable);
// Base 18 — always
t[0] = R(0x0000); t[1] = R(0x0018); t[2] = R(0x0030);
t[3] = R(0x0048); t[4] = R(0x0060); t[5] = R(0x0078);
t[6] = R(0x0090); t[7] = R(0x00A8); t[8] = R(0x00C0);
t[9] = R(0x00D8); t[10] = R(0x00F0); t[11] = R(0x0108);
t[12] = R(0x0120); t[13] = R(0x0138); t[14] = R(0x0150);
t[15] = R(0x0168); t[16] = R(0x0180); t[17] = R(0x0198);
if (fw >= 80)
{
t[18] = R(0x01B0); t[19] = R(0x01C8); t[20] = R(0x01E0);
t[21] = R(0x01F8); t[22] = R(0x0210); t[23] = R(0x0228);
}
if (fw >= 83)
{
// Slots 25-26 (Speed Fuel/Spark Comp) ship in FW 83, not 80 —
// populateInitTables gates these in a nested FW>=83 check.
t[24] = R(0x0240); t[25] = R(0x0258);
}
if (fw >= 90)
{
t[26] = R(0x0270); t[27] = R(0x0288); t[28] = R(0x02A0);
t[29] = R(0x02B8); t[30] = R(0x02D0); t[31] = R(0x02E8);
t[32] = R(0x0300); t[33] = R(0x0318);
}
if (fw >= 130)
{
t[34] = R(0x0330); t[35] = R(0x0348); t[36] = R(0x0360);
}
return t;
}
// ── Convenience ──────────────────────────────────────────────────────────
/// <summary>
/// Returns all available 1D table regions in index order.
/// Skips Unavailable entries (FW-gated tables not present on this device).
/// </summary>
public IEnumerable<(int Index, MemoryRegion Region)> Available1DTables =>
OneDimTables
.Select((r, i) => (i, r))
.Where(x => x.r.IsAvailable);
}
+34
View File
@@ -0,0 +1,34 @@
namespace TuneBoss.Core.Models;
/// <summary>How a sub-field of a settings byte is edited.</summary>
public enum MiscEditorKind
{
Flag, // single bit → checkbox
Enum, // bit range → combo (Options indexed by value)
Number, // bit range → numeric 0..(mask>>shift)
}
/// <summary>
/// One sub-field occupying a contiguous bit range of a byte.
/// Value = (byte &amp; Mask) >> shift(Mask); written back masked.
/// </summary>
public sealed record MiscBitField(
string Label,
int Mask, // e.g. 0x01 (flag), 0xF0 (high nibble), 0x7F (7-bit value)
MiscEditorKind Kind = MiscEditorKind.Flag,
string[]? Options = null) // Enum only: option labels indexed by value
{
/// <summary>Human-readable label: underscores → spaces, shortforms expanded.</summary>
public string DisplayText => MiscDisplayText.For(Label);
}
/// <summary>
/// Decomposition of a single settings byte into bit sub-fields, plus optional
/// inter-bit constraints (bit indices 0..7).
/// </summary>
public sealed record MiscByteSpec(
MiscBlock Block,
string FieldLabel, // must match a MiscField.Label in MiscFieldRegistry
MiscBitField[] Fields,
(int A, int B)[]? MutualExclusive = null, // checking one clears the other
(int A, int B)[]? Linked = null); // toggling one toggles the other
+228
View File
@@ -0,0 +1,228 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// Per-byte bit decompositions for the misc "settings" bytes.
/// Labels are taken verbatim from the legacy Form1.Designer.cs CheckedListBox /
/// ComboBox item strings (TuneBossPCAppBLE2026), so bit order is authoritative.
///
/// KEYING: each spec attaches by (Block, FieldLabel); FieldLabel matches a MiscField.Label
/// in MiscFieldRegistry. Keys were resolved against the legacy core write-map
/// (returnBytes[N] = textBox(N+1)), so byte indices are exact. The flag bytes your model
/// left unnamed map to the raw placeholders: Core_8 (CamSync), Core_25 (Fuel_Settings2),
/// Core_31 (Spark_Settings), Core_33 (O2_Autotune_Enable), Core_120 (TPS_Accel_Type).
///
/// MODEL FIX NEEDED — ShiftBoss Enable: byte 84 is the enable flags byte (legacy value
/// 15 = 0x0F), but MiscValues.cs currently names Core[84] "ShiftBoss_Retard_Degrees".
/// Rename that accessor (and its MiscFieldRegistry entry) to "ShiftBoss_Enable" so this
/// spec attaches. The real retard degrees is the low 7 bits of byte 88 (ShiftBoss_Spark_Retard_deg).
/// </summary>
public static class MiscBitSpecRegistry
{
private static MiscBitField Flag(string label, int mask) => new(label, mask, MiscEditorKind.Flag);
private static MiscBitField Num (string label, int mask) => new(label, mask, MiscEditorKind.Number);
private static MiscBitField Enum(string label, int mask, params string[] opts) => new(label, mask, MiscEditorKind.Enum, opts);
// VRS combo option labels (index = nibble value 0..15), from the designer.
private static readonly string[] VrsMilliVolt = { "10","14","20","28","40","56","80","110","150","215","300","425","600","850","1210","1715" };
private static readonly string[] VrsBlanking = { "0","3.12","6.25","9.37","12.5","15.62","18.75","21.87","25","28.1","31.3","34.4","37.5","40.6","43.8","46.9" };
public static readonly IReadOnlyList<MiscByteSpec> All = new[]
{
// ── Crank CamSync Config — raw byte Core_8 (value 131 on test device) (rename Core_8 → Crank_CamSync_Config)
new MiscByteSpec(MiscBlock.Core, "Crank_CamSync_Config", new[]
{
Flag("MAP Sync - Enable", 0x01),
Flag("Rotation Sync - whole rotation compare", 0x02),
Flag("Rotation Sync - No min RPM", 0x04),
Flag("Rotation Sync - Disable", 0x08),
Flag("MAP Sync - sync TPS < 50pct", 0x10),
Flag("MAP Sync - disable min RPM", 0x20),
Flag("Unused [2025/03/06]", 0x40),
Flag("Startup Fixed Spark Trigger Tooth", 0x80),
}),
// ── O2 Autotune Enable
new MiscByteSpec(MiscBlock.Core, "O2_Autotune_Enable", new[]
{
Flag("Enable Autotune", 0x01),
Flag("Average with current table value", 0x02),
Flag("Write to Fuel Table", 0x04),
Flag("Read initial value from Fuel Table", 0x08),
Flag("Ignore TPS State", 0x10),
Flag("Ignore RPM State", 0x20),
Flag("Unused [2025/04/24]", 0x40),
Flag("Enable Autotune in all conditions", 0x80),
}),
// ── ShiftBoss Enable ─ bit2<->bit3 linked (DIN)
new MiscByteSpec(MiscBlock.Core, "ShiftBoss_Enable", new[]
{
Flag("Enable ShiftBoss", 0x01),
Flag("Unused [2025/04/25]", 0x02),
Flag("Enable DIN (uncheck for Analog)", 0x04),
Flag("Enable DIN (uncheck for Analog)", 0x08),
Flag("Enable AutoTrigger RPM", 0x10),
Flag("Use Fuel Cut 1D Table", 0x20),
Flag("Use Spark Cut 1D Table", 0x40),
Flag("Use Spark Retard 1D Table", 0x80),
},
Linked: new[] { (2, 3) }),
// ── ShiftBoss Spark Retard deg
new MiscByteSpec(MiscBlock.Core, "ShiftBoss_Spark_Retard_deg", new[]
{
Num ("Retard Degrees (0-127)", 0x7F),
Flag("Retard reference = Current Spark Angle", 0x80),
}),
// ── ShiftBoss Input Active High
new MiscByteSpec(MiscBlock.Core, "ShiftBoss_Input_Active_High", new[]
{
Flag("Input Active High", 0x01),
}),
// ── ShiftBoss Input Debounce ms
new MiscByteSpec(MiscBlock.Core, "ShiftBoss_Input_Debounce_ms", new[]
{
Num ("Debounce ms (0-63)", 0x3F),
Flag("Input Display - Engine Light", 0x40),
Flag("Input Display - Overheat Light", 0x80),
}),
// ── MAP Settings
new MiscByteSpec(MiscBlock.Core, "MAP_Settings", new[]
{
Flag("Auto Temperature Correction", 0x01),
Flag("Baro Compensation Static", 0x02),
Flag("Static Error Detect", 0x04),
Flag("UNUSED", 0x08),
Flag("CamSync on MAP Hi->Lo transition", 0x10),
Flag("Cam sync use MAP tooth average", 0x20),
Flag("MAP Avg use tooth average", 0x40),
Flag("Unsync use Lowest MAP_Lo_Avg reading across 2 cycles", 0x80),
}),
// ── TPS Accel Type
new MiscByteSpec(MiscBlock.Core, "TPS_Accel_Type", new[]
{
Enum("TPS source", 0x01, "TPS Raw", "TPS Percent"),
Enum("1D Table Raw", 0x02, "Start_Value", "Diff"),
Flag("Unused [2025/05/16]", 0x04),
Enum("1D Table Conv", 0x08, "Absolute PW", "% Table"),
Flag("Unused [2025/05/16] (0x10)", 0x10),
Flag("Unused [2025/05/16] (0x20)", 0x20),
Flag("Unused [2025/05/16] (0x40)", 0x40),
Flag("Unused [2025/05/16] (0x80)", 0x80),
}),
// ── Fuel Settings
new MiscByteSpec(MiscBlock.Core, "Fuel_Settings", new[]
{
Enum("Reference Angle", 0x01, "End Angle", "Start Angle"),
Flag("2nd Injector Enable (see 0x80)", 0x02),
Flag("1D Fuel Idle Table - Enable", 0x04),
Flag("Unused [2025/07/04]", 0x08),
Flag("Combine Fuel Base Tables", 0x10),
Flag("Combine Fuel Adjustment Tables", 0x20),
Flag("Combine Fuel Angle Tables", 0x40),
Flag("AFR Table change to 2nd Injector Table (see 0x02)", 0x80),
}),
// ── Fuel Settings 2 ─ bits1-2 form a MAP-source mode
new MiscByteSpec(MiscBlock.Core, "Fuel_Settings2", new[]
{
Flag("1D idle table MAP scaling factor (see 0x02)", 0x01),
Enum("Idle MAP source", 0x06, "MAP Avg", "Baro Static", "Map Lo Avg", "(reserved)"),
Flag("Unused [2025/07/04] (0x08)", 0x08),
Flag("Unused [2025/07/04] (0x10)", 0x10),
Flag("Unused [2025/07/04] (0x20)", 0x20),
Flag("Unused [2025/07/04] (0x40)", 0x40),
Flag("Enable Baro/Map scaling for 1D idle table", 0x80),
}),
// ── Spark Settings
new MiscByteSpec(MiscBlock.Core, "Spark_Settings", new[]
{
Flag("Spark cut when fuel cut", 0x01),
Flag("Max dwell time clamping - Enable", 0x02),
Flag("OverCurrent dwell AutoClamp - Enable", 0x04),
Flag("Spark end time recalc - Enable", 0x08),
Flag("Combine Spark Base Tables", 0x10),
Flag("Combine Spark Adjust Tables", 0x20),
Enum("VBAT Table axis", 0x40, "RPM", "RawVal"),
Enum("Spark Table units", 0x80, "Degrees", "Timer ticks"),
}),
// ── MC33814 VRS Misc Params
new MiscByteSpec(MiscBlock.Core, "MC33814_VRS_Misc_Params", new[]
{
Flag("Disable 2.5V reference", 0x01),
Flag("Swap VRSN & VRSP", 0x02),
Flag("Single ended mode (VRSN=GND)", 0x04),
Flag("De-glitch enable", 0x08),
Enum("Blanking time calc ref", 0x10, "High PW", "Low PW"),
Flag("reserved", 0x20),
Flag("Disable VRS", 0x40),
Flag("Automatic Mode VRS", 0x80),
}),
// ── VRS Manual Control (Running): hi nibble = mV, lo nibble = blanking%
new MiscByteSpec(MiscBlock.Core, "MC33814_Cfg_VRS_Manual_Control", new[]
{
Enum("Running blanking %", 0x0F, VrsBlanking),
Enum("Running miliVolt", 0xF0, VrsMilliVolt),
}),
// ── VRS Conditioner (Cranking): hi nibble = mV, lo nibble = blanking%
new MiscByteSpec(MiscBlock.Core, "MC33814_Ctrl_VRS_Conditioner", new[]
{
Enum("Cranking blanking %", 0x0F, VrsBlanking),
Enum("Cranking miliVolt", 0xF0, VrsMilliVolt),
}),
// ── ISM Settings 1 (Extended/R25 block) ─ bit0/bit1 mutually exclusive (Mode)
new MiscByteSpec(MiscBlock.Extended, "ISM_Settings1", new[]
{
Flag("Mode - Test", 0x01),
Flag("Mode - Normal", 0x02),
Flag("Mode - Unused [2025/03/19]", 0x04),
Flag("Mode - Unused [2025/03/19]", 0x08),
Flag("Off Throttle ISM - Enable", 0x10),
Flag("OffThrottle ISM - Ignore TPS", 0x20),
Flag("Fixed position for Engine Start", 0x40),
Flag("ISM Auto target RPM", 0x80),
},
MutualExclusive: new[] { (0, 1) }),
// ── ISM PID Config (Extended block)
new MiscByteSpec(MiscBlock.Extended, "ISM_PID_Config", new[]
{
Flag("Init use stored target step", 0x01),
Flag("Clutch Input for stored tgt step", 0x02),
Flag("Speed Input for stored tgt step", 0x04),
Flag("Always enable stored tgt step", 0x08),
Flag("RPM ramp down detect", 0x10),
Flag("Reduce tgt step when > table val", 0x20),
Flag("Increase tgt step when < table val", 0x40),
Flag("Unused", 0x80),
}),
// ── Mode Switch Settings (low nibble flags; high nibble = input selection 0-15)
new MiscByteSpec(MiscBlock.Extended, "Mode_Switch_Settings", new[]
{
Flag("Enable Mode Switch", 0x01),
Flag("Invert Input", 0x02),
Flag("Unused (0x04)", 0x04),
Flag("Unused (0x08)", 0x08),
Num ("Input selection (0-15)", 0xF0),
}),
};
/// <summary>Lookup a spec by block + field label, or null.</summary>
public static MiscByteSpec? Find(MiscBlock block, string label)
{
foreach (var s in All)
if (s.Block == block && s.FieldLabel == label) return s;
return null;
}
}
+120
View File
@@ -0,0 +1,120 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// Converts raw config field identifiers into human-readable display text:
/// underscores become spaces, and engineering shortforms expand to their meaning
/// (e.g. <c>RPM_Limit_div100</c> → "RPM Limit (divided by 100)",
/// <c>Fuel_Max_PW_Mult</c> → "Fuel Max Pulse Width Multiplier").
/// Unknown tokens pass through unchanged, so new fields degrade gracefully.
/// </summary>
public static class MiscDisplayText
{
// Case-insensitive single-token expansions.
private static readonly Dictionary<string, string> Map = new(StringComparer.OrdinalIgnoreCase)
{
// scaling / units
["div100"] = "(divided by 100)",
["div10"] = "(divided by 10)",
["div5"] = "(divided by 5)",
["x10"] = "(times 10)",
["x100"] = "(times 100)",
["ms"] = "(in milliseconds)",
["5ms"] = "(in 5 ms steps)",
["10ms"] = "(in 10 ms steps)",
["100ms"] = "(in 100 ms steps)",
["us"] = "(in microseconds)",
["degC"] = "(in Celsius degrees)",
["deg"] = "(in degrees)",
["kph"] = "(in km/h)",
["kmh"] = "(in km/h)",
["pct"] = "Percent",
["raw"] = "(raw)",
// engineering shortforms
["PW"] = "Pulse Width",
["Decel"] = "Deceleration",
["Accel"] = "Acceleration",
["Etemp"] = "Engine Temperature",
["VBAT"] = "Battery Voltage",
["IAT"] = "Intake Air Temperature",
["BARO"] = "Barometric",
["NOS"] = "Nitrous",
["ISM"] = "Idle Stepper Motor",
["AIS"] = "Air Induction System",
["O2H"] = "O2 Heater",
["FC"] = "Fuel Consumption",
["PerSec"] = "Per Second",
["Hi"] = "High",
["Lo"] = "Low",
["Neg"] = "Negative",
["Pos"] = "Positive",
["Mult"] = "Multiplier",
["Div"] = "Divider",
["Num"] = "Number",
["Init"] = "Initial",
["Cfg"] = "Config",
["Ctrl"] = "Control",
["Rsvd"] = "Reserved",
["Isol"] = "Idle Solenoid",
["Ref"] = "Reference",
["Retard"] = "Retard",
["Solenoid"] = "Solenoid",
["Samplepoint"] = "Sample Point",
};
// Case-SENSITIVE tokens (too dangerous to match loosely).
private static readonly Dictionary<string, string> ExactMap = new(StringComparer.Ordinal)
{
["s"] = "(in seconds)",
};
// Multi-token sequences consumed together (checked before single tokens).
private static readonly (string A, string B, string Text)[] Pairs =
{
("ms", "div5", "(in milliseconds, divided by 5)"),
("ms", "div10", "(in milliseconds, divided by 10)"),
};
private static readonly Dictionary<string, string> Cache = new();
/// <summary>Display text for a raw field identifier.</summary>
public static string For(string raw)
{
if (string.IsNullOrEmpty(raw)) return raw;
lock (Cache)
{
if (Cache.TryGetValue(raw, out var hit)) return hit;
}
var tokens = raw.Split('_', StringSplitOptions.RemoveEmptyEntries);
var outParts = new List<string>(tokens.Length);
for (int i = 0; i < tokens.Length; i++)
{
bool paired = false;
if (i + 1 < tokens.Length)
{
foreach (var (a, b, text) in Pairs)
{
if (tokens[i].Equals(a, StringComparison.OrdinalIgnoreCase) &&
tokens[i + 1].Equals(b, StringComparison.OrdinalIgnoreCase))
{
outParts.Add(text);
i++; // consume both
paired = true;
break;
}
}
}
if (paired) continue;
if (ExactMap.TryGetValue(tokens[i], out var exact)) outParts.Add(exact);
else if (Map.TryGetValue(tokens[i], out var mapped)) outParts.Add(mapped);
else outParts.Add(tokens[i]);
}
var result = string.Join(" ", outParts);
lock (Cache) { Cache[raw] = result; }
return result;
}
}
+349
View File
@@ -0,0 +1,349 @@
namespace TuneBoss.Core.Models;
/// <summary>Which raw misc block a field lives in.</summary>
public enum MiscBlock { Core, LaunchFuel, LaunchFuel2, AuxOut, Extended }
/// <summary>One editable misc setting: a single raw byte in a block.
/// Generated from MiscValues.cs accessor map; unnamed bytes are exposed as
/// raw placeholders (rename in this file later).</summary>
public sealed record MiscField(string Section, string Label, MiscBlock Block, int Index)
{
/// <summary>Human-readable label: underscores → spaces, shortforms expanded.</summary>
public string DisplayText => MiscDisplayText.For(Label);
}
public static class MiscFieldRegistry
{
public static readonly IReadOnlyList<MiscField> All = new MiscField[]
{
// ── Core ──
new("Crank", "Crank_Teeth", MiscBlock.Core, 0),
new("Crank", "Crank_Missing_Teeth", MiscBlock.Core, 1),
new("Crank", "Crank_Detect_Edge", MiscBlock.Core, 2),
new("Crank", "CrankTooth_Positive_Period_Pct", MiscBlock.Core, 3),
new("Crank", "CrankTooth_Negative_Period_Pct", MiscBlock.Core, 4),
new("Crank", "Crank_Timeout_Pct", MiscBlock.Core, 5),
new("Crank", "Crank_CamSync_Detect_Method", MiscBlock.Core, 6),
new("Crank", "Crank_CamSync_Detect_Cycle", MiscBlock.Core, 7),
new("Crank", "Crank_CamSync_Config", MiscBlock.Core, 8),
new("Crank", "Crank_CamSync_MAP_Detect_Cycle", MiscBlock.Core, 9),
new("Crank", "Crank_CamSync_Rotation_Tooth", MiscBlock.Core, 10),
new("Crank", "Crank_CamSync_Num_Fast_Rotations", MiscBlock.Core, 11),
new("RPM", "RPM_Limit_div100", MiscBlock.Core, 12),
new("RPM", "RPM_Limit_Recovery_div100", MiscBlock.Core, 13),
new("RPM", "RPM_Limit_Failsafe_div100", MiscBlock.Core, 14),
new("RPM", "RPM_Limit_Failsafe_Recovery_div100", MiscBlock.Core, 15),
new("RPM", "RPM_Detect_Min_div100", MiscBlock.Core, 16),
new("RPM", "RPM_Detect_Min_Recovery_div100", MiscBlock.Core, 17),
new("RPM", "RPM_Stall_div100", MiscBlock.Core, 18),
new("RPM", "RPM_Stall_Recovery_div100", MiscBlock.Core, 19),
new("RPM", "RPM_Decel_Threshold_PerSec_div100", MiscBlock.Core, 20),
new("RPM", "RPM_Accel_Threshold_PerSec_div100", MiscBlock.Core, 21),
new("RPM", "RPM_Meter_Divider", MiscBlock.Core, 22),
new("Fuel", "Fuel_Settings", MiscBlock.Core, 23),
new("Fuel", "Fuel_Max_PW_Mult", MiscBlock.Core, 24),
new("Fuel", "Fuel_Settings2", MiscBlock.Core, 25),
new("Fuel", "Fuel_Cut_Min_LOAD", MiscBlock.Core, 26),
new("Fuel", "Fuel_Cut_Min_TPS_pct", MiscBlock.Core, 27),
new("Fuel", "Fuel_Cut_Min_RPM_div100", MiscBlock.Core, 28),
new("Fuel", "Fuel_Cut_Disable_LOAD", MiscBlock.Core, 29),
new("Fuel", "Fuel_Cut_Min_Etemp_degC", MiscBlock.Core, 30),
new("Fuel", "Spark_Settings", MiscBlock.Core, 31),
new("Fuel", "VBAT_Trim_deciV", MiscBlock.Core, 32),
new("Fuel", "O2_Autotune_Enable", MiscBlock.Core, 33),
new("O2 Sensor / Autotune", "O2_Sensor_Sample_Rate_ms", MiscBlock.Core, 34),
new("O2 Sensor / Autotune", "O2_Sensor_Delay_ms_div5", MiscBlock.Core, 35),
new("O2 Sensor / Autotune", "O2_Fuel_Max_Add_Pct", MiscBlock.Core, 36),
new("O2 Sensor / Autotune", "O2_Fuel_Max_Sub_Pct", MiscBlock.Core, 37),
new("O2 Sensor / Autotune", "O2_Autotune_Max_RPM_div100", MiscBlock.Core, 38),
new("O2 Sensor / Autotune", "O2_Autotune_Min_RPM_div100", MiscBlock.Core, 39),
new("O2 Sensor / Autotune", "O2_Autotune_Max_Load", MiscBlock.Core, 40),
new("O2 Sensor / Autotune", "O2_Autotune_Min_Load", MiscBlock.Core, 41),
new("O2 Sensor / Autotune", "O2_Autotune_StepUp_Pct", MiscBlock.Core, 42),
new("O2 Sensor / Autotune", "O2_Autotune_Average_Weight", MiscBlock.Core, 43),
new("O2 Sensor / Autotune", "O2_Autotune_AFR_x10_Diff", MiscBlock.Core, 44),
new("O2 Sensor / Autotune", "O2_Autotune_Start_Delay_s", MiscBlock.Core, 45),
new("O2 Sensor / Autotune", "O2_Autotune_Min_ETemp", MiscBlock.Core, 46),
new("O2 Sensor / Autotune", "O2_Autotune_Max_ETemp", MiscBlock.Core, 47),
new("TPS", "TPS_Accel_Threshold_PctPer100ms", MiscBlock.Core, 48),
new("TPS", "TPS_Decel_Threshold_PctPer100ms", MiscBlock.Core, 49),
new("TPS", "TPS_Threshold_10ms_sample_gap", MiscBlock.Core, 50),
new("TPS", "TPS_Accel_Fuel_Adjust_Hold_Time_10ms", MiscBlock.Core, 51),
new("TPS", "TPS_Accel_Fuel_Adjust_Decay_Time_10ms", MiscBlock.Core, 52),
new("TPS", "TPS_Accel_Spark_Adjust_Hold_Time_10ms", MiscBlock.Core, 53),
new("TPS", "TPS_Accel_Spark_Adjust_Decay_Time_10ms", MiscBlock.Core, 54),
new("TPS", "TPS_Steady_State_Delay_Time_10ms", MiscBlock.Core, 55),
new("MAP", "MAP_Settings", MiscBlock.Core, 56),
new("MAP", "MAP_Lo_Hyst_Mult", MiscBlock.Core, 57),
new("MAP", "MAP_Ref_Temp_DegC", MiscBlock.Core, 58),
new("MAP", "MAP_Intake_Tooth_End", MiscBlock.Core, 59),
new("MAP", "MAP_Intake_Num_Teeth", MiscBlock.Core, 60),
new("MAP", "MAP_Baro_Tooth_End", MiscBlock.Core, 61),
new("MAP", "MAP_Baro_Num_Teeth", MiscBlock.Core, 62),
new("MAP", "MAP_Baro_RPM_div100_Limit", MiscBlock.Core, 63),
new("MAP", "MAP_Baro_TPS_Limit", MiscBlock.Core, 64),
new("MAP", "MAP_Baro_Static_Delay_10ms", MiscBlock.Core, 65),
new("MAP", "MAP_Settings2", MiscBlock.Core, 66),
new("Radiator / Overheat", "RadFan_On_Temp_DegC", MiscBlock.Core, 67),
new("Radiator / Overheat", "RadFan_Off_Temp_DegC", MiscBlock.Core, 68),
new("Radiator / Overheat", "Etemp_Overheat_On_Temp_DegC", MiscBlock.Core, 69),
new("Radiator / Overheat", "Etemp_Overheat_Off_Temp_DegC", MiscBlock.Core, 70),
new("Radiator / Overheat", "Etemp_Sensor_Error_Temp", MiscBlock.Core, 71),
new("Bluetooth / MC33814", "Bluetooth_PowerOn_Timeout_s", MiscBlock.Core, 72),
new("Bluetooth / MC33814", "MC33814_Init_Delay_10ms", MiscBlock.Core, 73),
new("Bluetooth / MC33814", "MC33814_Tacho_Control", MiscBlock.Core, 74),
new("Bluetooth / MC33814", "MC33814_VRS_Misc_Params", MiscBlock.Core, 75),
new("Bluetooth / MC33814", "MC33814_Cfg_VRS_Manual_Control", MiscBlock.Core, 76),
new("Bluetooth / MC33814", "MC33814_Ctrl_VRS_Conditioner", MiscBlock.Core, 77),
new("Fuel Pump / Solenoid", "Fuel_Pump_Timeout_100ms", MiscBlock.Core, 78),
new("Fuel Pump / Solenoid", "Idle_Solenoid_Off_Tooth", MiscBlock.Core, 79),
new("Fuel Pump / Solenoid", "Idle_Solenoid_Reset_RPM_div100", MiscBlock.Core, 80),
new("Fuel Pump / Solenoid", "Idle_Solenoid_Step_Down", MiscBlock.Core, 81),
new("Fuel Pump / Solenoid", "Idle_Solenoid_PID_Kp", MiscBlock.Core, 82),
new("Fuel Pump / Solenoid", "Idle_Solenoid_Min_Open_Angle_deg", MiscBlock.Core, 83),
new("ShiftBoss", "ShiftBoss_Enable", MiscBlock.Core, 84),
new("ShiftBoss", "ShiftBoss_Fuel_Cut_ms", MiscBlock.Core, 85),
new("ShiftBoss", "ShiftBoss_Spark_Cut_ms", MiscBlock.Core, 86),
new("ShiftBoss", "ShiftBoss_Spark_Retard_ms", MiscBlock.Core, 87),
new("ShiftBoss", "ShiftBoss_Spark_Retard_deg", MiscBlock.Core, 88),
new("ShiftBoss", "ShiftBoss_Interval_Time_10ms", MiscBlock.Core, 89),
new("ShiftBoss", "ShiftBoss_Min_RPM_div100", MiscBlock.Core, 90),
new("ShiftBoss", "ShiftBoss_Input_Active_High", MiscBlock.Core, 91),
new("ShiftBoss", "ShiftBoss_Input_Debounce_ms", MiscBlock.Core, 92),
new("ShiftBoss", "ShiftBoss_Autotrigger_RPM_div100", MiscBlock.Core, 93),
new("Load selection", "Load_Primary_Select", MiscBlock.Core, 94),
new("Load selection", "Load_Fuel_PulseWidth1_Select", MiscBlock.Core, 95),
new("Load selection", "Load_Spark_Angle1_Select", MiscBlock.Core, 96),
new("Load selection", "Load_AFR_Target1_Select", MiscBlock.Core, 97),
new("Load selection", "Load_Fuel_Angle2D_Select", MiscBlock.Core, 98),
new("Load selection", "Load_Fuel_PulseWidth_Adjust1_Select", MiscBlock.Core, 99),
new("Load selection", "Load_Spark_Angle_Adjust1_Select", MiscBlock.Core, 100),
new("Extended config", "VBAT_Min_deciV", MiscBlock.Core, 101),
new("Extended config", "VBAT_Max_deciV", MiscBlock.Core, 102),
new("Extended config", "O2_Sensor_Present", MiscBlock.Core, 103),
new("Extended config", "VDS_Present", MiscBlock.Core, 104),
new("Extended config", "TPS_Accel_Taper_Start_RPM_div100", MiscBlock.Core, 105),
new("Extended config", "TPS_Accel_Taper_End_RPM_div100", MiscBlock.Core, 106),
new("Extended config", "Error_Check_Startup_Delay", MiscBlock.Core, 107),
new("Extended config", "ErrorLog_Recording_Delay", MiscBlock.Core, 108),
new("Extended config", "ShiftLight_On_RPM_div100", MiscBlock.Core, 109),
new("Extended config", "ShiftLight_Off_RPM_div100", MiscBlock.Core, 110),
new("Extended config", "ShiftLight_Output_Select", MiscBlock.Core, 111),
new("Extended config", "MC33814_Lamp_Config", MiscBlock.Core, 112),
new("Extended config", "MC33814_O2H_Config", MiscBlock.Core, 113),
new("Extended config", "VBAT_Longterm_Min_DeciV", MiscBlock.Core, 114),
new("Extended config", "ErrorLog_MC33814_Mask_Lo", MiscBlock.Core, 115),
new("Extended config", "ErrorLog_MC33814_Mask_Hi", MiscBlock.Core, 116),
new("Extended config", "ErrorLog_MC33814_EngineOff_Enable", MiscBlock.Core, 117),
new("Extended config", "ErrorLog_MC33814_OL_Hysteresis", MiscBlock.Core, 118),
new("Extended config", "ErrorLog_MC33814_Killswitch_Mask", MiscBlock.Core, 119),
new("Extended config", "TPS_Accel_Type", MiscBlock.Core, 120),
new("Extended config", "TPS_Accel_Fuel_TempComp", MiscBlock.Core, 121),
new("Extended config", "TPS_Accel_Threshold_Fast_PctPer100ms", MiscBlock.Core, 122),
new("Extended config", "TPS_Decel_Fuel_Adjust_Pct", MiscBlock.Core, 123),
new("Extended config", "TPS_Accel_Modifier_Cyclecount", MiscBlock.Core, 124),
new("Extended config", "TPS_Accel_Threshold_SuperFast_PctPer100ms", MiscBlock.Core, 125),
new("Extended config", "VBAT_longterm_min_DeciV", MiscBlock.Core, 126),
new("Extended config", "ErrorLog_MC33814_SafeMode_Trigger_Lo", MiscBlock.Core, 127),
new("Extended config", "ErrorLog_MC33814_SafeMode_Trigger_Hi", MiscBlock.Core, 128),
new("Extended config", "VDS_Time_Delay_100ms", MiscBlock.Core, 129),
new("Extended config", "UM_Stop_Timer_Delay_100ms", MiscBlock.Core, 130),
new("Extended config", "Start_Fuel_Enrichment_Hold_100ms", MiscBlock.Core, 131),
new("Extended config", "Start_Fuel_Enrichment_Decay_100ms", MiscBlock.Core, 132),
new("Extended config", "TPS_Accel_Recursive_Accel", MiscBlock.Core, 133),
new("Extended config", "Idle_Solenoid_Reset_Timeout_100ms", MiscBlock.Core, 134),
new("Extended config", "Speed_Adjust_Percent", MiscBlock.Core, 135),
// ── LaunchFuel (spark/fuel reference angles + init) ──
new("Timing", "RPM_Table_2Samplepoint_div100", MiscBlock.LaunchFuel, 0),
new("Timing", "Fuel_Init_Cycles", MiscBlock.LaunchFuel, 1),
new("Timing", "Idle_Solenoid_Settings", MiscBlock.LaunchFuel, 2),
new("Timing", "Spark_Ref_Angle_Lo", MiscBlock.LaunchFuel, 3),
new("Timing", "Spark_Ref_Angle_Hi", MiscBlock.LaunchFuel, 4),
new("Timing", "Fuel_Ref_Angle_Lo", MiscBlock.LaunchFuel, 5),
new("Timing", "Fuel_Ref_Angle_Hi", MiscBlock.LaunchFuel, 6),
new("Timing", "Fuel_Base_PW_ms_x10", MiscBlock.LaunchFuel, 7),
new("Timing", "Spark2_Ref_Angle_Lo", MiscBlock.LaunchFuel, 8),
new("Timing", "Spark2_Ref_Angle_Hi", MiscBlock.LaunchFuel, 9),
new("Timing", "Fuel2_Ref_Angle_Lo", MiscBlock.LaunchFuel, 10),
new("Timing", "Fuel2_Ref_Angle_Hi", MiscBlock.LaunchFuel, 11),
// ── LaunchFuel2 (launch control + rad fan) ──
new("Launch Control", "TBD_Unused", MiscBlock.LaunchFuel2, 0),
new("Launch Control", "LaunchBoss_Enable", MiscBlock.LaunchFuel2, 1),
new("Launch Control", "LaunchBoss_Settings", MiscBlock.LaunchFuel2, 2),
new("Launch Control", "LaunchBoss_RPM_Limit_Start_div100", MiscBlock.LaunchFuel2, 3),
new("Launch Control", "LaunchBoss_RPM_Limit_End_div100", MiscBlock.LaunchFuel2, 4),
new("Launch Control", "LaunchBoss_RPM_Persec_Up_Rate_div100", MiscBlock.LaunchFuel2, 5),
new("Launch Control", "LaunchBoss_RPM_Up_Speed_Start_kph", MiscBlock.LaunchFuel2, 6),
new("Launch Control", "LaunchBoss_Speed_End_kph", MiscBlock.LaunchFuel2, 7),
new("Launch Control", "LaunchBoss_Spark_Retard_deg", MiscBlock.LaunchFuel2, 8),
new("Launch Control", "RadFan_Settings", MiscBlock.LaunchFuel2, 9),
new("Launch Control", "RadFan_PWM_Width_100ms", MiscBlock.LaunchFuel2, 10),
new("Launch Control", "Analog_Safe_Mode_Trigger", MiscBlock.LaunchFuel2, 11),
// ── AuxOut ──
new("General", "AuxOut_Control", MiscBlock.AuxOut, 0),
new("General", "AuxOut_Control2", MiscBlock.AuxOut, 1),
new("General", "RadFan_On_Temp_NOS_RPM", MiscBlock.AuxOut, 2),
new("General", "RadFan_Off_Temp_NOS_TPS", MiscBlock.AuxOut, 3),
new("General", "NOS_Speed", MiscBlock.AuxOut, 4),
new("General", "AuxOut_Ref_Value2_Off", MiscBlock.AuxOut, 5),
new("General", "AuxOut_Delay1_10ms", MiscBlock.AuxOut, 6),
new("General", "AuxOut_Delay2_10ms", MiscBlock.AuxOut, 7),
new("General", "Idle_Threshold_TPS", MiscBlock.AuxOut, 8),
new("General", "Idle_Threshold_RPM_div100", MiscBlock.AuxOut, 9),
new("General", "Spark_Dwell_Max_100us", MiscBlock.AuxOut, 10),
new("General", "Spark_Dwell_Min_100us", MiscBlock.AuxOut, 11),
// ── Extended ──
new("Spark tab", "Spark_Dwell_Reduction_10us", MiscBlock.Extended, 0),
new("Spark tab", "Spark_Dwell_Min_Deg", MiscBlock.Extended, 1),
new("Spark tab", "Spark_Dwell_Max_Deg_div4", MiscBlock.Extended, 2),
new("Spark tab", "Spark_Dwell_Reserved1", MiscBlock.Extended, 3),
new("Spark tab", "Crank_MissingTooth2_Pos_Period_Mult", MiscBlock.Extended, 4),
new("Spark tab", "Crank_MissingTooth2_Neg_Period_Mult", MiscBlock.Extended, 5),
new("Spark tab", "Crank_MissingTooth_Pos_Period_Mult", MiscBlock.Extended, 6),
new("Spark tab", "Crank_MissingTooth_Neg_Period_Mult", MiscBlock.Extended, 7),
new("Spark tab", "VRS_Threshold_Lo_RPM_div100", MiscBlock.Extended, 8),
new("Spark tab", "VRS_Threshold_Hi_RPM_div100", MiscBlock.Extended, 9),
new("Spark tab", "Spark_Cut_Retard1_RPM_Gap_div100", MiscBlock.Extended, 10),
new("Spark tab", "Spark_Cut_Retard2_RPM_Gap_div100", MiscBlock.Extended, 11),
new("Spark tab", "Spark_Cut_Retard1", MiscBlock.Extended, 12),
new("Spark tab", "Spark_Cut_Retard2", MiscBlock.Extended, 13),
new("Spark tab", "CrankTooth_Pos_Period_Mult_Run", MiscBlock.Extended, 14),
new("Spark tab", "CrankTooth_Neg_Period_Mult_Run", MiscBlock.Extended, 15),
new("Spark tab", "Gear_Ratio_Hysteresis_Count", MiscBlock.Extended, 16),
new("Spark tab", "Gear_Ratio_min_RPM_div100", MiscBlock.Extended, 17),
new("TC tab", "TC_Settings1", MiscBlock.Extended, 18),
new("TC tab", "TC_Settings2", MiscBlock.Extended, 19),
new("TC tab", "TC_Rpm_Min_div100", MiscBlock.Extended, 20),
new("TC tab", "TC_Rpm_Max_div100", MiscBlock.Extended, 21),
new("TC tab", "TC_TPS_Min", MiscBlock.Extended, 22),
new("TC tab", "TC_TPS_Max", MiscBlock.Extended, 23),
new("TC tab", "TC_Speed_Min", MiscBlock.Extended, 24),
new("TC tab", "TC_Speed_Max", MiscBlock.Extended, 25),
new("TC tab", "TC_Consecutive_Error_Trigger", MiscBlock.Extended, 26),
new("TC tab", "TC_Retard_Off_Ramp_deg_per100ms", MiscBlock.Extended, 27),
new("TC tab", "TC_Table_Input_Selection", MiscBlock.Extended, 28),
new("TC tab", "TC_Sample_Rate_ms", MiscBlock.Extended, 29),
new("TC tab", "TC_Speed_Tooth_Skip", MiscBlock.Extended, 30),
new("TC tab", "TC_Tooth_Average_Count", MiscBlock.Extended, 31),
new("TC tab", "TC_Tooth_Compare_Count", MiscBlock.Extended, 32),
new("TC tab", "TC_Gear_Max", MiscBlock.Extended, 33),
new("TC tab", "TC_Button_Modes", MiscBlock.Extended, 34),
new("TC tab", "TC_Button_Sensitivity_Modifier", MiscBlock.Extended, 35),
new("TC tab", "TC_Button_Delay_100ms", MiscBlock.Extended, 36),
new("TC tab", "TC_Tooth_Undriven_Count", MiscBlock.Extended, 37),
new("TC tab", "TC_Reserved6", MiscBlock.Extended, 38),
new("TC tab", "Offthrottle_Threshold_TPS", MiscBlock.Extended, 39),
new("TC tab", "Idle_Rumble_Min_Rpm_div100", MiscBlock.Extended, 40),
new("TC tab", "Speed_Settings1", MiscBlock.Extended, 41),
new("ISM tab", "ISM_Settings1", MiscBlock.Extended, 42),
new("ISM tab", "ISM_Startup_Delay_10ms", MiscBlock.Extended, 43),
new("ISM tab", "ISM_Max_Steps_Lo", MiscBlock.Extended, 44),
new("ISM tab", "ISM_Max_Steps_Hi", MiscBlock.Extended, 45),
new("ISM tab", "ISM_CR0_Init", MiscBlock.Extended, 46),
new("ISM tab", "ISM_CR1_Init", MiscBlock.Extended, 47),
new("ISM tab", "ISM_CR2_Init", MiscBlock.Extended, 48),
new("ISM tab", "ISM_Test_Step_Lo", MiscBlock.Extended, 49),
new("ISM tab", "ISM_Test_Step_Hi", MiscBlock.Extended, 50),
new("ISM tab", "ISM_Off_Delay_10ms", MiscBlock.Extended, 51),
new("ISM tab", "ISM_Max_Open_Steps_Per_Cycle", MiscBlock.Extended, 52),
new("ISM tab", "ISM_Max_Close_Steps_Per_Cycle", MiscBlock.Extended, 53),
new("ISM tab", "ISM_CR0_Run", MiscBlock.Extended, 54),
new("ISM tab", "ISM_CR0_Hold", MiscBlock.Extended, 55),
new("ISM tab", "ISM_Calibrate_Overshoot_Steps", MiscBlock.Extended, 56),
new("ISM tab", "ISM_PID_Delay_5ms", MiscBlock.Extended, 57),
new("ISM tab", "ISM_PID_Kp_lo", MiscBlock.Extended, 58),
new("ISM tab", "ISM_PID_Kp_hi", MiscBlock.Extended, 59),
new("ISM tab", "ISM_PID_Ki_lo", MiscBlock.Extended, 60),
new("ISM tab", "ISM_PID_Ki_hi", MiscBlock.Extended, 61),
new("ISM tab", "ISM_PID_Kd_lo", MiscBlock.Extended, 62),
new("ISM tab", "ISM_PID_Kd_hi", MiscBlock.Extended, 63),
new("ISM tab", "ISM_PID_Error_Threshold", MiscBlock.Extended, 64),
new("ISM tab", "ISM_PID_Config", MiscBlock.Extended, 65),
new("ISM tab", "ISM_Start_Boost_Step_raw", MiscBlock.Extended, 66),
new("ISM tab", "ISM_Stall_Boost_Step_raw", MiscBlock.Extended, 67),
new("ISM tab", "ISM_Start_Boost_Step_Delay_100ms", MiscBlock.Extended, 68),
new("ISM tab", "ISM_Stall_Boost_Step_Delay_100ms", MiscBlock.Extended, 69),
new("ISM tab", "ISM_Stall_Boost_RPM_div100", MiscBlock.Extended, 70),
new("ISM tab", "ISM_Boost_Step_Mult", MiscBlock.Extended, 71),
new("ISM tab", "ISM_PID_Gain_Mult", MiscBlock.Extended, 72),
new("ISM tab", "ISM_PID_Gain_Div_ShiftRight", MiscBlock.Extended, 73),
new("ISM tab", "ISM_PID_RPM_Rampdown_Rate", MiscBlock.Extended, 74),
new("ISM tab", "ISM_Rsvd22", MiscBlock.Extended, 75),
new("AIS tab", "AIS_Settings1", MiscBlock.Extended, 76),
new("AIS tab", "AIS_Settings2", MiscBlock.Extended, 77),
new("AIS tab", "AIS_RPM_Threshold1", MiscBlock.Extended, 78),
new("AIS tab", "AIS_TPS_Threshold1", MiscBlock.Extended, 79),
new("AIS tab", "AIS_RPM_Threshold2", MiscBlock.Extended, 80),
new("AIS tab", "AIS_TPS_Threshold2", MiscBlock.Extended, 81),
new("AIS tab", "AIS_RPM_Threshold3", MiscBlock.Extended, 82),
new("AIS tab", "AIS_TPS_Threshold3", MiscBlock.Extended, 83),
new("O2Heater tab", "AIS_Delay1_10ms", MiscBlock.Extended, 84),
new("O2Heater tab", "AIS_Settings10", MiscBlock.Extended, 85),
new("O2Heater tab", "ETEMP_Sensor_Sample_Rate_ms", MiscBlock.Extended, 86),
new("O2Heater tab", "IAT_Sensor_Sample_Rate_ms", MiscBlock.Extended, 87),
new("O2Heater tab", "O2Heater_Settings1", MiscBlock.Extended, 88),
new("O2Heater tab", "O2Heater_Settings2", MiscBlock.Extended, 89),
new("O2Heater tab", "O2Heater_Delay1_10ms", MiscBlock.Extended, 90),
new("O2Heater tab", "O2Heater_Settings4", MiscBlock.Extended, 91),
new("O2Heater tab", "O2Heater_Settings5", MiscBlock.Extended, 92),
new("O2Heater tab", "O2Heater_Settings6", MiscBlock.Extended, 93),
new("O2Heater tab", "ShiftBoss_Spark_RampDown_ms", MiscBlock.Extended, 94),
new("O2Heater tab", "ShiftBoss_Spark_RampUp_ms", MiscBlock.Extended, 95),
new("O2Heater tab", "VBAT_UVReset_DeciV", MiscBlock.Extended, 96),
new("O2Heater tab", "O2Heater_Settings10", MiscBlock.Extended, 97),
new("O2Heater tab", "LaunchBoss_Settings3", MiscBlock.Extended, 98),
new("O2Heater tab", "LaunchBoss_RPM_Limit_Fixed_div100", MiscBlock.Extended, 99),
new("O2Autotune tab", "O2_Autotune_Settings2", MiscBlock.Extended, 100),
new("O2Autotune tab", "O2_Autotune_Cylinder_Correct", MiscBlock.Extended, 101),
new("O2Autotune tab", "O2_Autotune_Cylinder_Write", MiscBlock.Extended, 102),
new("O2Autotune tab", "O2_Autotune_Settings5", MiscBlock.Extended, 103),
new("O2Autotune tab", "VRS_Settings1", MiscBlock.Extended, 104),
new("O2Autotune tab", "MC33814_VRS_MaxVolt_Val", MiscBlock.Extended, 105),
new("O2Autotune tab", "MC33814_Relay1_Config", MiscBlock.Extended, 106),
new("O2Autotune tab", "MC33814_Relay2_Config", MiscBlock.Extended, 107),
new("MCU Tacho tab", "MCU_Tacho_Settings1", MiscBlock.Extended, 108),
new("MCU Tacho tab", "MCU_Tacho_Divider", MiscBlock.Extended, 109),
new("MCU Tacho tab", "MCU_Tacho_Settings3", MiscBlock.Extended, 110),
new("MCU Tacho tab", "MCU_Tacho_Settings4", MiscBlock.Extended, 111),
new("MCU Tacho tab", "Meter_Speed_Mult", MiscBlock.Extended, 112),
new("MCU Tacho tab", "Meter_Speed_Div", MiscBlock.Extended, 113),
new("MCU Tacho tab", "Meter_Speed_Test", MiscBlock.Extended, 114),
new("MCU Tacho tab", "Meter_FC_Mult", MiscBlock.Extended, 115),
new("VVA tab", "VVA_Settings1", MiscBlock.Extended, 116),
new("VVA tab", "VVA_Settings2", MiscBlock.Extended, 117),
new("VVA tab", "VVA_Settings3", MiscBlock.Extended, 118),
new("VVA tab", "VVA_Settings4", MiscBlock.Extended, 119),
new("VVA tab", "VVA_Etemp_HiVal", MiscBlock.Extended, 120),
new("VVA tab", "VVA_Etemp_LoVal", MiscBlock.Extended, 121),
new("VVA tab", "VVA_EngineOn_Delay1_100ms", MiscBlock.Extended, 122),
new("VVA tab", "VVA_EngineOn_Delay2_10ms", MiscBlock.Extended, 123),
new("VVA tab", "VVA_On_RPM_div100", MiscBlock.Extended, 124),
new("VVA tab", "VVA_Off_RPM_div100", MiscBlock.Extended, 125),
new("VVA tab", "VVA_On_TPS_pct", MiscBlock.Extended, 126),
new("VVA tab", "VVA_Off_TPS_pct", MiscBlock.Extended, 127),
new("VVA tab", "VVA_On_Stage1_PWM_Pct", MiscBlock.Extended, 128),
new("VVA tab", "VVA_On_Stage1_Delay_10ms", MiscBlock.Extended, 129),
new("VVA tab", "VVA_On_Stage2_PWM_Pct", MiscBlock.Extended, 130),
new("VVA tab", "VVA_On_Stage2_Delay_10ms", MiscBlock.Extended, 131),
new("VVA tab", "VVA_On_Stage3_PWM_Pct", MiscBlock.Extended, 132),
new("VVA tab", "VVA_On_Stage3_Delay_10ms", MiscBlock.Extended, 133),
new("VVA tab", "VVA_On_Stage4_PWM_Pct", MiscBlock.Extended, 134),
new("VVA tab", "VVA_On_Stage4_Delay_10ms", MiscBlock.Extended, 135),
new("VVA tab", "VVA_On_TableSwap_Delay_ms_lo", MiscBlock.Extended, 136),
new("VVA tab", "VVA_On_TableSwap_Delay_ms_hi", MiscBlock.Extended, 137),
new("VVA tab", "VVA_Off_TableSwap_Delay_ms_lo", MiscBlock.Extended, 138),
new("VVA tab", "VVA_Off_TableSwap_Delay_ms_hi", MiscBlock.Extended, 139),
new("VVA tab", "VVA_On_Tooth", MiscBlock.Extended, 140),
new("VVA tab", "VVA_Off_Tooth", MiscBlock.Extended, 141),
new("VVA tab", "VVA_HiSide_Toggle_Gap_Rpm_div100", MiscBlock.Extended, 142),
new("VVA tab", "VVA_ErrorCheck_Delay_10ms", MiscBlock.Extended, 143),
new("VVA tab", "VVA_Rsvd9", MiscBlock.Extended, 144),
new("VVA tab", "VVA_Rsvd10", MiscBlock.Extended, 145),
new("VVA tab", "VVA_Rsvd11", MiscBlock.Extended, 146),
new("VVA tab", "VVA_Rsvd12", MiscBlock.Extended, 147),
new("VVA tab", "MAP_Error_Value_Fixed", MiscBlock.Extended, 148),
new("VVA tab", "TPS_Error_Value_Fixed", MiscBlock.Extended, 149),
new("VVA tab", "Digital_Input_Mask", MiscBlock.Extended, 150),
new("VVA tab", "Mode_Switch_Settings", MiscBlock.Extended, 151),
};
}
+482
View File
@@ -0,0 +1,482 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// All ECU configuration parameters outside the 2D/1D tuning tables.
///
/// Five memory regions, each read via APP_MEMRD_MISC. Addresses from
/// GenerationConfig; regions beyond Core gated on EcuInfo.FwVersion >= 150.
///
/// Region Address field Size FW gate
/// ──────────── ───────────────────────── ─────── ────────
/// Core miscValStartAddress 136 B always
/// LaunchFuel extraPaddingStartAddress 12 B FW >= 150
/// LaunchFuel2 extraPaddingStartAddress2 12 B FW >= 150
/// AuxOut extraPaddingStartAddress3 12 B FW >= 150
/// Extended extraPaddingStartAddress4 var B FW >= 150
/// (FW2_SubVersion & 0x80) == 0 → 0x73 (116 B, up to Ex(115))
/// (FW2_SubVersion & 0x80) != 0 → 0x97 (152 B, full set)
///
/// Extended label map is authoritative — derived from:
/// READ: UpdateMiscValuesExtraPadding4New() in Form1_Utils.cs
/// WRITE: getMiscValByteArrayExtraPadding4New() in Form1_TableHandling.cs
/// LABELS: Designer.cs parsed per inner tab of tabControl14 (Spark/TC/ISM/
/// AIS/O2Heater/O2Autotune/MCU Tacho/VVA) inside tabPage93.
/// Each inner tab parsed independently to avoid cross-column pollution.
/// </summary>
public sealed class MiscValues
{
// ── Raw memory regions ───────────────────────────────────────────────────
public byte[] Core { get; init; } = new byte[136];
public byte[] LaunchFuel { get; init; } = Array.Empty<byte>();
public byte[] LaunchFuel2 { get; init; } = Array.Empty<byte>();
public byte[] AuxOut { get; init; } = Array.Empty<byte>();
public byte[] Extended { get; init; } = Array.Empty<byte>();
// ════════════════════════════════════════════════════════════════════════
// CORE — 136 bytes (tabControl4, tabPage3 through tabPage2)
// ════════════════════════════════════════════════════════════════════════
// ── Crank [0–11] ─────────────────────────────────────────────────────────
public byte Crank_Teeth => Core[0];
public byte Crank_Missing_Teeth => Core[1];
public byte Crank_Detect_Edge => Core[2];
public byte CrankTooth_Positive_Period_Pct => Core[3];
public byte CrankTooth_Negative_Period_Pct => Core[4];
public byte Crank_Timeout_Pct => Core[5];
public byte Crank_CamSync_Detect_Method => Core[6];
public byte Crank_CamSync_Detect_Cycle => Core[7];
// [8] reserved
public byte Crank_CamSync_MAP_Detect_Cycle => Core[9];
public byte Crank_CamSync_Rotation_Tooth => Core[10];
public byte Crank_CamSync_Num_Fast_Rotations => Core[11];
// ── RPM [12–22] ──────────────────────────────────────────────────────────
public byte RPM_Limit_div100 => Core[12];
public byte RPM_Limit_Recovery_div100 => Core[13];
public byte RPM_Limit_Failsafe_div100 => Core[14];
public byte RPM_Limit_Failsafe_Recovery_div100 => Core[15];
public byte RPM_Detect_Min_div100 => Core[16];
public byte RPM_Detect_Min_Recovery_div100 => Core[17];
public byte RPM_Stall_div100 => Core[18];
public byte RPM_Stall_Recovery_div100 => Core[19];
public byte RPM_Decel_Threshold_PerSec_div100 => Core[20];
public byte RPM_Accel_Threshold_PerSec_div100 => Core[21];
public byte RPM_Meter_Divider => Core[22];
public int RPM_Limit => RPM_Limit_div100 * 100;
// ── Fuel [23–32] ─────────────────────────────────────────────────────────
public byte Fuel_Settings => Core[23];
public byte Fuel_Max_PW_Mult => Core[24];
// [25] reserved
public byte Fuel_Cut_Min_LOAD => Core[26];
public byte Fuel_Cut_Min_TPS_pct => Core[27];
public byte Fuel_Cut_Min_RPM_div100 => Core[28];
public byte Fuel_Cut_Disable_LOAD => Core[29];
public byte Fuel_Cut_Min_Etemp_degC => Core[30];
// [31] reserved
public byte VBAT_Trim_deciV => Core[32];
// ── O2 Sensor / Autotune [33–47] ─────────────────────────────────────────
// [33] reserved
public byte O2_Sensor_Sample_Rate_ms => Core[34];
public byte O2_Sensor_Delay_ms_div5 => Core[35];
public byte O2_Fuel_Max_Add_Pct => Core[36];
public byte O2_Fuel_Max_Sub_Pct => Core[37];
public byte O2_Autotune_Max_RPM_div100 => Core[38];
public byte O2_Autotune_Min_RPM_div100 => Core[39];
public byte O2_Autotune_Max_Load => Core[40];
public byte O2_Autotune_Min_Load => Core[41];
public byte O2_Autotune_StepUp_Pct => Core[42];
public byte O2_Autotune_Average_Weight => Core[43];
public byte O2_Autotune_AFR_x10_Diff => Core[44];
public byte O2_Autotune_Start_Delay_s => Core[45];
public byte O2_Autotune_Min_ETemp => Core[46];
public byte O2_Autotune_Max_ETemp => Core[47];
// ── TPS [48–55] ──────────────────────────────────────────────────────────
public byte TPS_Accel_Threshold_PctPer100ms => Core[48];
public byte TPS_Decel_Threshold_PctPer100ms => Core[49];
public byte TPS_Threshold_10ms_sample_gap => Core[50];
public byte TPS_Accel_Fuel_Adjust_Hold_Time_10ms => Core[51];
public byte TPS_Accel_Fuel_Adjust_Decay_Time_10ms => Core[52];
public byte TPS_Accel_Spark_Adjust_Hold_Time_10ms => Core[53];
public byte TPS_Accel_Spark_Adjust_Decay_Time_10ms => Core[54];
public byte TPS_Steady_State_Delay_Time_10ms => Core[55];
// ── MAP [56–66] ──────────────────────────────────────────────────────────
public byte MAP_Settings => Core[56];
public byte MAP_Lo_Hyst_Mult => Core[57];
public byte MAP_Ref_Temp_DegC => Core[58];
public byte MAP_Intake_Tooth_End => Core[59];
public byte MAP_Intake_Num_Teeth => Core[60];
public byte MAP_Baro_Tooth_End => Core[61];
public byte MAP_Baro_Num_Teeth => Core[62];
public byte MAP_Baro_RPM_div100_Limit => Core[63];
public byte MAP_Baro_TPS_Limit => Core[64];
public byte MAP_Baro_Static_Delay_10ms => Core[65];
public byte MAP_Settings2 => Core[66];
// ── Radiator / Overheat [67–71] ──────────────────────────────────────────
public byte RadFan_On_Temp_DegC => Core[67];
public byte RadFan_Off_Temp_DegC => Core[68];
public byte Etemp_Overheat_On_Temp_DegC => Core[69];
public byte Etemp_Overheat_Off_Temp_DegC => Core[70];
public byte Etemp_Sensor_Error_Temp => Core[71];
// ── Bluetooth / MC33814 [72–77] ──────────────────────────────────────────
public byte Bluetooth_PowerOn_Timeout_s => Core[72];
public byte MC33814_Init_Delay_10ms => Core[73];
public byte MC33814_Tacho_Control => Core[74];
public byte MC33814_VRS_Misc_Params => Core[75];
public byte MC33814_Cfg_VRS_Manual_Control => Core[76];
public byte MC33814_Ctrl_VRS_Conditioner => Core[77];
// ── Fuel Pump / Solenoid [78–83] ─────────────────────────────────────────
public byte Fuel_Pump_Timeout_100ms => Core[78];
public byte Idle_Solenoid_Off_Tooth => Core[79];
public byte Idle_Solenoid_Reset_RPM_div100 => Core[80];
public byte Idle_Solenoid_Step_Down => Core[81];
public byte Idle_Solenoid_PID_Kp => Core[82];
public byte Idle_Solenoid_Min_Open_Angle_deg => Core[83];
// ── ShiftBoss [84–93] ────────────────────────────────────────────────────
public byte ShiftBoss_Enable => Core[84]; // byte 84 = enable flags (see MiscBitSpecRegistry); real retard deg = ShiftBoss_Spark_Retard_deg & 0x7F
public byte ShiftBoss_Fuel_Cut_ms => Core[85];
public byte ShiftBoss_Spark_Cut_ms => Core[86];
public byte ShiftBoss_Spark_Retard_ms => Core[87];
public byte ShiftBoss_Spark_Retard_deg => Core[88];
public byte ShiftBoss_Interval_Time_10ms => Core[89];
public byte ShiftBoss_Min_RPM_div100 => Core[90];
public byte ShiftBoss_Input_Active_High => Core[91];
public byte ShiftBoss_Input_Debounce_ms => Core[92];
public byte ShiftBoss_Autotrigger_RPM_div100 => Core[93];
// ── Load selection [94–100] ──────────────────────────────────────────────
public byte Load_Primary_Select => Core[94];
public byte Load_Fuel_PulseWidth1_Select => Core[95];
public byte Load_Spark_Angle1_Select => Core[96];
public byte Load_AFR_Target1_Select => Core[97];
public byte Load_Fuel_Angle2D_Select => Core[98];
public byte Load_Fuel_PulseWidth_Adjust1_Select => Core[99];
public byte Load_Spark_Angle_Adjust1_Select => Core[100];
// ── Extended config [101–135] ─────────────────────────────────────────────
public byte VBAT_Min_deciV => Core[101];
public byte VBAT_Max_deciV => Core[102];
public byte O2_Sensor_Present => Core[103];
public byte VDS_Present => Core[104];
public byte TPS_Accel_Taper_Start_RPM_div100 => Core[105];
public byte TPS_Accel_Taper_End_RPM_div100 => Core[106];
public byte Error_Check_Startup_Delay => Core[107];
public byte ErrorLog_Recording_Delay => Core[108];
public byte ShiftLight_On_RPM_div100 => Core[109];
public byte ShiftLight_Off_RPM_div100 => Core[110];
public byte ShiftLight_Output_Select => Core[111];
public byte MC33814_Lamp_Config => Core[112];
public byte MC33814_O2H_Config => Core[113];
public byte VBAT_Longterm_Min_DeciV => Core[114];
public byte ErrorLog_MC33814_Mask_Lo => Core[115];
public byte ErrorLog_MC33814_Mask_Hi => Core[116];
public byte ErrorLog_MC33814_EngineOff_Enable => Core[117];
public byte ErrorLog_MC33814_OL_Hysteresis => Core[118];
public byte ErrorLog_MC33814_Killswitch_Mask => Core[119];
// [120] reserved
public byte TPS_Accel_Fuel_TempComp => Core[121];
public byte TPS_Accel_Threshold_Fast_PctPer100ms => Core[122];
public byte TPS_Decel_Fuel_Adjust_Pct => Core[123];
public byte TPS_Accel_Modifier_Cyclecount => Core[124];
public byte TPS_Accel_Threshold_SuperFast_PctPer100ms => Core[125];
// [120, 126–131] distinct settings/log bytes — named via MiscFieldRegistry, bound raw in the VM
public byte Start_Fuel_Enrichment_Decay_100ms => Core[132];
public byte TPS_Accel_Recursive_Accel => Core[133];
public byte Idle_Solenoid_Reset_Timeout_100ms => Core[134];
public byte Speed_Adjust_Percent => Core[135];
public int ShiftLight_On_RPM => ShiftLight_On_RPM_div100 * 100;
public int ShiftLight_Off_RPM => ShiftLight_Off_RPM_div100 * 100;
// ════════════════════════════════════════════════════════════════════════
// LAUNCHFUEL — 12 bytes (spark/fuel reference angles + init)
// ════════════════════════════════════════════════════════════════════════
public byte? RPM_Table_2Samplepoint_div100 => Lf(0);
public byte? Fuel_Init_Cycles => Lf(1);
public byte? Idle_Solenoid_Settings => Lf(2);
public byte? Spark_Ref_Angle_Lo => Lf(3);
public byte? Spark_Ref_Angle_Hi => Lf(4);
public byte? Fuel_Ref_Angle_Lo => Lf(5);
public byte? Fuel_Ref_Angle_Hi => Lf(6);
public byte? Fuel_Base_PW_ms_x10 => Lf(7);
public byte? Spark2_Ref_Angle_Lo => Lf(8);
public byte? Spark2_Ref_Angle_Hi => Lf(9);
public byte? Fuel2_Ref_Angle_Lo => Lf(10);
public byte? Fuel2_Ref_Angle_Hi => Lf(11);
// ════════════════════════════════════════════════════════════════════════
// LAUNCHFUEL2 — 12 bytes (launch control + rad fan)
// ════════════════════════════════════════════════════════════════════════
public byte? LF2_TBD_Unused => Lf2(0);
public byte? LaunchBoss_Enable => Lf2(1);
public byte? LaunchBoss_Settings => Lf2(2);
public byte? LaunchBoss_RPM_Limit_Start_div100 => Lf2(3);
public byte? LaunchBoss_RPM_Limit_End_div100 => Lf2(4);
public byte? LaunchBoss_RPM_Persec_Up_Rate_div100 => Lf2(5);
public byte? LaunchBoss_RPM_Up_Speed_Start_kph => Lf2(6);
public byte? LaunchBoss_Speed_End_kph => Lf2(7);
public byte? LaunchBoss_Spark_Retard_deg => Lf2(8);
public byte? LF2_RadFan_Settings => Lf2(9);
public byte? LF2_RadFan_PWM_Width_100ms => Lf2(10);
public byte? Analog_Safe_Mode_Trigger => Lf2(11);
// ════════════════════════════════════════════════════════════════════════
// AUXOUT — 12 bytes
// ════════════════════════════════════════════════════════════════════════
public byte? AuxOut_Control => Ao(0);
public byte? AuxOut_Control2 => Ao(1);
public byte? RadFan_On_Temp_NOS_RPM => Ao(2);
public byte? RadFan_Off_Temp_NOS_TPS => Ao(3);
public byte? NOS_Speed => Ao(4);
public byte? AuxOut_Ref_Value2_Off => Ao(5);
public byte? AuxOut_Delay1_10ms => Ao(6);
public byte? AuxOut_Delay2_10ms => Ao(7);
public byte? Idle_Threshold_TPS => Ao(8);
public byte? Idle_Threshold_RPM_div100 => Ao(9);
public byte? Spark_Dwell_Max_100us => Ao(10);
public byte? Spark_Dwell_Min_100us => Ao(11);
public int? AuxOut_Mode_Index => AuxOut_Control is byte b && b <= 3 ? (int?)b : null;
// ════════════════════════════════════════════════════════════════════════
// EXTENDED — variable size
//
// Buffer index → textbox → label, sourced from:
// READ: UpdateMiscValuesExtraPadding4New() (Form1_Utils.cs)
// WRITE: getMiscValByteArrayExtraPadding4New() (Form1_TableHandling.cs)
// LABELS: Designer.cs per-inner-tab parsing of tabControl14 inside tabPage93
//
// Y15 [0–41] — always present when Extended is non-empty
// R25 [42–115] — EcuVariant >= TwoCylinder
// R15 [116–151]— EcuVariant == TwoCylinderR15
// ════════════════════════════════════════════════════════════════════════
// ── Y15: Spark tab [0–17] ────────────────────────────────────────────────
public byte? Spark_Dwell_Reduction_10us => Ex(0); // textBox261
public byte? Spark_Dwell_Min_Deg => Ex(1); // textBox262
public byte? Spark_Dwell_Max_Deg_div4 => Ex(2); // textBox263
public byte? Spark_Dwell_Reserved1 => Ex(3); // textBox264
public byte? Crank_MissingTooth2_Pos_Period_Mult => Ex(4); // textBox265
public byte? Crank_MissingTooth2_Neg_Period_Mult => Ex(5); // textBox266
public byte? Crank_MissingTooth_Pos_Period_Mult => Ex(6); // textBox267
public byte? Crank_MissingTooth_Neg_Period_Mult => Ex(7); // textBox268
public byte? VRS_Threshold_Lo_RPM_div100 => Ex(8); // textBox269
public byte? VRS_Threshold_Hi_RPM_div100 => Ex(9); // textBox270
public byte? Spark_Cut_Retard1_RPM_Gap_div100 => Ex(10); // textBox271
public byte? Spark_Cut_Retard2_RPM_Gap_div100 => Ex(11); // textBox272
public byte? Spark_Cut_Retard1 => Ex(12); // textBox273
public byte? Spark_Cut_Retard2 => Ex(13); // textBox274
public byte? CrankTooth_Pos_Period_Mult_Run => Ex(14); // textBox275
public byte? CrankTooth_Neg_Period_Mult_Run => Ex(15); // textBox276
public byte? Gear_Ratio_Hysteresis_Count => Ex(16); // textBox277
public byte? Gear_Ratio_min_RPM_div100 => Ex(17); // textBox278
// ── Y15: TC tab [18–41] ──────────────────────────────────────────────────
public byte? TC_Settings1 => Ex(18); // textBox279
public byte? TC_Settings2 => Ex(19); // textBox280
public byte? TC_Rpm_Min_div100 => Ex(20); // textBox281
public byte? TC_Rpm_Max_div100 => Ex(21); // textBox282
public byte? TC_TPS_Min => Ex(22); // textBox283
public byte? TC_TPS_Max => Ex(23); // textBox284
public byte? TC_Speed_Min => Ex(24); // textBox285
public byte? TC_Speed_Max => Ex(25); // textBox286
public byte? TC_Consecutive_Error_Trigger => Ex(26); // textBox287
public byte? TC_Retard_Off_Ramp_deg_per100ms => Ex(27); // textBox288
public byte? TC_Table_Input_Selection => Ex(28); // textBox289
public byte? TC_Sample_Rate_ms => Ex(29); // textBox290
public byte? TC_Speed_Tooth_Skip => Ex(30); // textBox291
public byte? TC_Tooth_Average_Count => Ex(31); // textBox292
public byte? TC_Tooth_Compare_Count => Ex(32); // textBox293
public byte? TC_Gear_Max => Ex(33); // textBox294
public byte? TC_Button_Modes => Ex(34); // textBox295
public byte? TC_Button_Sensitivity_Modifier => Ex(35); // textBox296
public byte? TC_Button_Delay_100ms => Ex(36); // textBox297
public byte? TC_Tooth_Undriven_Count => Ex(37); // textBox298
public byte? TC_Reserved6 => Ex(38); // textBox299
public byte? Offthrottle_Threshold_TPS => Ex(39); // textBox300
public byte? Idle_Rumble_Min_Rpm_div100 => Ex(40); // textBox301
public byte? Speed_Settings1 => Ex(41); // textBox302
// ── R25: ISM tab [42–75] ─────────────────────────────────────────────────
public byte? ISM_Settings1 => Ex(42); // textBox303
public byte? ISM_Startup_Delay_10ms => Ex(43); // textBox304 ✓
public byte? ISM_Max_Steps_Lo => Ex(44); // textBox305
public byte? ISM_Max_Steps_Hi => Ex(45); // textBox306
public byte? ISM_CR0_Init => Ex(46); // textBox307
public byte? ISM_CR1_Init => Ex(47); // textBox308
public byte? ISM_CR2_Init => Ex(48); // textBox309
public byte? ISM_Test_Step_Lo => Ex(49); // textBox310 ✓
public byte? ISM_Test_Step_Hi => Ex(50); // textBox311
public byte? ISM_Off_Delay_10ms => Ex(51); // textBox312
public byte? ISM_Max_Open_Steps_Per_Cycle => Ex(52); // textBox313
public byte? ISM_Max_Close_Steps_Per_Cycle => Ex(53); // textBox314
public byte? ISM_CR0_Run => Ex(54); // textBox315
public byte? ISM_CR0_Hold => Ex(55); // textBox316
public byte? ISM_Calibrate_Overshoot_Steps => Ex(56); // textBox317
public byte? ISM_PID_Delay_5ms => Ex(57); // textBox318
public byte? ISM_PID_Kp_lo => Ex(58); // textBox319
public byte? ISM_PID_Kp_hi => Ex(59); // textBox320
public byte? ISM_PID_Ki_lo => Ex(60); // textBox321
public byte? ISM_PID_Ki_hi => Ex(61); // textBox322
public byte? ISM_PID_Kd_lo => Ex(62); // textBox323
public byte? ISM_PID_Kd_hi => Ex(63); // textBox324
public byte? ISM_PID_Error_Threshold => Ex(64); // textBox325
public byte? ISM_PID_Config => Ex(65); // textBox326
public byte? ISM_Start_Boost_Step_raw => Ex(66); // textBox327
public byte? ISM_Stall_Boost_Step_raw => Ex(67); // textBox328
public byte? ISM_Start_Boost_Step_Delay_100ms => Ex(68); // textBox329
public byte? ISM_Stall_Boost_Step_Delay_100ms => Ex(69); // textBox330
public byte? ISM_Stall_Boost_RPM_div100 => Ex(70); // textBox331
public byte? ISM_Boost_Step_Mult => Ex(71); // textBox332
public byte? ISM_PID_Gain_Mult => Ex(72); // textBox333
public byte? ISM_PID_Gain_Div_ShiftRight => Ex(73); // textBox334
public byte? ISM_PID_RPM_Rampdown_Rate => Ex(74); // textBox335
public byte? ISM_Rsvd22 => Ex(75); // textBox336
// ── R25: AIS tab [76–83] ─────────────────────────────────────────────────
public byte? AIS_Settings1 => Ex(76); // textBox337
public byte? AIS_Settings2 => Ex(77); // textBox338
public byte? AIS_RPM_Threshold1 => Ex(78); // textBox339
public byte? AIS_TPS_Threshold1 => Ex(79); // textBox340
public byte? AIS_RPM_Threshold2 => Ex(80); // textBox341
public byte? AIS_TPS_Threshold2 => Ex(81); // textBox342
public byte? AIS_RPM_Threshold3 => Ex(82); // textBox343
public byte? AIS_TPS_Threshold3 => Ex(83); // textBox344
// ── R25: O2Heater tab [84–99] ────────────────────────────────────────────
public byte? AIS_Delay1_10ms => Ex(84); // textBox345
public byte? AIS_Settings10 => Ex(85); // textBox346
public byte? ETEMP_Sensor_Sample_Rate_ms => Ex(86); // textBox347
public byte? IAT_Sensor_Sample_Rate_ms => Ex(87); // textBox348
public byte? O2Heater_Settings1 => Ex(88); // textBox349
public byte? O2Heater_Settings2 => Ex(89); // textBox350
public byte? O2Heater_Delay1_10ms => Ex(90); // textBox351
public byte? O2Heater_Settings4 => Ex(91); // textBox352
public byte? O2Heater_Settings5 => Ex(92); // textBox353
public byte? O2Heater_Settings6 => Ex(93); // textBox354
public byte? ShiftBoss_Spark_RampDown_ms => Ex(94); // textBox355
public byte? ShiftBoss_Spark_RampUp_ms => Ex(95); // textBox356
public byte? VBAT_UVReset_DeciV => Ex(96); // textBox357
public byte? O2Heater_Settings10 => Ex(97); // textBox358
public byte? LaunchBoss_Settings3 => Ex(98); // textBox359
public byte? LaunchBoss_RPM_Limit_Fixed_div100 => Ex(99); // textBox360
// ── R25: O2Autotune tab [100–107] ────────────────────────────────────────
public byte? O2_Autotune_Settings2 => Ex(100); // textBox361
public byte? O2_Autotune_Cylinder_Correct => Ex(101); // textBox362
public byte? O2_Autotune_Cylinder_Write => Ex(102); // textBox363
public byte? O2_Autotune_Settings5 => Ex(103); // textBox364
public byte? VRS_Settings1 => Ex(104); // textBox365
public byte? MC33814_VRS_MaxVolt_Val => Ex(105); // textBox366
public byte? MC33814_Relay1_Config => Ex(106); // textBox367
public byte? MC33814_Relay2_Config => Ex(107); // textBox368
// ── R25: MCU Tacho tab [108–115] ─────────────────────────────────────────
public byte? MCU_Tacho_Settings1 => Ex(108); // textBox369
public byte? MCU_Tacho_Divider => Ex(109); // textBox370
public byte? MCU_Tacho_Settings3 => Ex(110); // textBox371
public byte? MCU_Tacho_Settings4 => Ex(111); // textBox372
public byte? Meter_Speed_Mult => Ex(112); // textBox373
public byte? Meter_Speed_Div => Ex(113); // textBox374
public byte? Meter_Speed_Test => Ex(114); // textBox375
public byte? Meter_FC_Mult => Ex(115); // textBox376
// ── R15: VVA tab [116–151] ───────────────────────────────────────────────
public byte? VVA_Settings1 => Ex(116); // textBox377
public byte? VVA_Settings2 => Ex(117); // textBox378
public byte? VVA_Settings3 => Ex(118); // textBox379
public byte? VVA_Settings4 => Ex(119); // textBox380
public byte? VVA_Etemp_HiVal => Ex(120); // textBox381
public byte? VVA_Etemp_LoVal => Ex(121); // textBox382
public byte? VVA_EngineOn_Delay1_100ms => Ex(122); // textBox383
public byte? VVA_EngineOn_Delay2_10ms => Ex(123); // textBox384
public byte? VVA_On_RPM_div100 => Ex(124); // textBox385
public byte? VVA_Off_RPM_div100 => Ex(125); // textBox386
public byte? VVA_On_TPS_pct => Ex(126); // textBox387
public byte? VVA_Off_TPS_pct => Ex(127); // textBox388
public byte? VVA_On_Stage1_PWM_Pct => Ex(128); // textBox389
public byte? VVA_On_Stage1_Delay_10ms => Ex(129); // textBox390
public byte? VVA_On_Stage2_PWM_Pct => Ex(130); // textBox391
public byte? VVA_On_Stage2_Delay_10ms => Ex(131); // textBox392
public byte? VVA_On_Stage3_PWM_Pct => Ex(132); // textBox393
public byte? VVA_On_Stage3_Delay_10ms => Ex(133); // textBox394
public byte? VVA_On_Stage4_PWM_Pct => Ex(134); // textBox395
public byte? VVA_On_Stage4_Delay_10ms => Ex(135); // textBox396
public byte? VVA_On_TableSwap_Delay_ms_lo => Ex(136); // textBox397
public byte? VVA_On_TableSwap_Delay_ms_hi => Ex(137); // textBox398
public byte? VVA_Off_TableSwap_Delay_ms_lo => Ex(138); // textBox399
public byte? VVA_Off_TableSwap_Delay_ms_hi => Ex(139); // textBox400
public byte? VVA_On_Tooth => Ex(140); // textBox401
public byte? VVA_Off_Tooth => Ex(141); // textBox402
public byte? VVA_HiSide_Toggle_Gap_Rpm_div100 => Ex(142); // textBox403
public byte? VVA_ErrorCheck_Delay_10ms => Ex(143); // textBox404
public byte? VVA_Rsvd9 => Ex(144); // textBox405
public byte? VVA_Rsvd10 => Ex(145); // textBox406
public byte? VVA_Rsvd11 => Ex(146); // textBox407
public byte? VVA_Rsvd12 => Ex(147); // textBox408
public byte? MAP_Error_Value_Fixed => Ex(148); // textBox409
public byte? TPS_Error_Value_Fixed => Ex(149); // textBox410
public byte? Digital_Input_Mask => Ex(150); // textBox411
public byte? Mode_Switch_Settings => Ex(151); // textBox412
// ════════════════════════════════════════════════════════════════════════
// FACTORY
// ════════════════════════════════════════════════════════════════════════
public static MiscValues FromPayloads(
byte[] corePayload,
byte[]? launchFuelPayload = null,
byte[]? launchFuel2Payload = null,
byte[]? auxOutPayload = null,
byte[]? extendedPayload = null)
{
static byte[] Slice(byte[]? payload, int size)
{
if (payload == null || payload.Length < 4 + size) return Array.Empty<byte>();
var buf = new byte[size];
Buffer.BlockCopy(payload, 4, buf, 0, size);
return buf;
}
int extSize = extendedPayload != null ? Math.Max(0, extendedPayload.Length - 4) : 0;
return new MiscValues
{
Core = Slice(corePayload, 136),
LaunchFuel = Slice(launchFuelPayload, 12),
LaunchFuel2 = Slice(launchFuel2Payload, 12),
AuxOut = Slice(auxOutPayload, 12),
Extended = extendedPayload != null && extSize > 0
? Slice(extendedPayload, extSize)
: Array.Empty<byte>(),
};
}
/// <summary>
/// Extended region byte count to request. Per the legacy firmware, this is gated by
/// bit 7 of FW2_SubVersion, NOT by bike model:
/// (FW2_SubVersion &amp; 0x80) != 0 → full extended set (0x97 = 152 bytes)
/// otherwise → up to Ex(115) (0x73 = 116 bytes)
/// </summary>
public static byte ExtendedLengthFor(byte fw2SubVersion)
=> (fw2SubVersion & 0x80) != 0 ? (byte)0x97 : (byte)0x73;
private byte? Lf(int i) => i < LaunchFuel.Length ? LaunchFuel[i] : null;
private byte? Lf2(int i) => i < LaunchFuel2.Length ? LaunchFuel2[i] : null;
private byte? Ao(int i) => i < AuxOut.Length ? AuxOut[i] : null;
private byte? Ex(int i) => i < Extended.Length ? Extended[i] : null;
}
/// <summary>
/// Bike cylinder classification — determines Extended region size.
/// Derived from EcuInfo via TwoCylinderRegistry.
/// </summary>
public enum EcuVariant
{
SingleCylinder, // Y15, NVX etc. — Extended = 0x29
TwoCylinder, // R25, R3, MT25 — Extended = 0x73
TwoCylinderR15, // R15M, CBR250RR — Extended = 0x97
}
+39
View File
@@ -0,0 +1,39 @@
using System;
namespace TuneBoss.Core.Models
{
/// <summary>
/// Display scaling for 1D tables: displayed value = raw × multiplier.
/// A multiplier of 0 or 1 means unscaled (×1). Editing is done in displayed units
/// and must land on a multiple of the multiplier.
///
/// This is the single source of truth for the rules the 1D view-model applies
/// (OneDimTablesViewModel can delegate to it so the UI and tests can't drift).
/// </summary>
public static class OneDimDisplay
{
/// <summary>0/1 => 1; otherwise the multiplier itself.</summary>
public static int EffectiveMultiplier(int multiplier) => multiplier < 1 ? 1 : multiplier;
/// <summary>Raw byte value → displayed value.</summary>
public static long ToDisplay(int raw, int multiplier) =>
(long)raw * EffectiveMultiplier(multiplier);
/// <summary>
/// Displayed value → raw. Returns false if the displayed value is not an exact
/// multiple of the (effective) multiplier, so the caller can reject the edit.
/// </summary>
public static bool TryFromDisplay(double display, int multiplier, out int raw)
{
int m = EffectiveMultiplier(multiplier);
double q = display / m;
if (Math.Abs(q - Math.Round(q)) > 1e-6)
{
raw = 0;
return false;
}
raw = (int)Math.Round(q);
return true;
}
}
}
+127
View File
@@ -0,0 +1,127 @@
using System;
namespace TuneBoss.Core.Models
{
/// <summary>
/// A 1D lookup table as stored on the ECU: 8 raw-axis breakpoints mapped to
/// 8 conversion (output) values, plus 8 metadata bytes (scaling / sign / clamp).
///
/// Fixed 24-byte wire layout:
/// [0..7] raw axis breakpoints (signed when RawSignedFlag > 0)
/// [8..15] conversion/output vals (signed when ConvSignedFlag > 0)
/// [16] MaxRaw (follows raw sign)
/// [17] MinRaw (follows raw sign)
/// [18] RawSignedFlag (> 0 => axis bytes are signed)
/// [19] ConvSignedFlag (> 0 => value bytes are signed)
/// [20] RawMultiplier (firmware-side display scaling)
/// [21] ConvMultiplier
/// [22] RawRounding
/// [23] ConvOffset (ALWAYS signed)
///
/// Read with APP_MEMRD_1D (0x43), written with APP_MEMWR_1D (0x4B).
/// The sign flags and the four scaling bytes are round-tripped VERBATIM so a
/// write never disturbs metadata the firmware relies on.
/// </summary>
public sealed class OneDimTable
{
public const int PointCount = 8;
public const int WireLength = 24;
public int[] RawAxis { get; }
public int[] ConvValues { get; }
// metadata (bytes 16..23)
public int MaxRaw { get; set; }
public int MinRaw { get; set; }
public byte RawSignedFlag { get; set; }
public byte ConvSignedFlag { get; set; }
public byte RawMultiplier { get; set; }
public byte ConvMultiplier { get; set; }
public byte RawRounding { get; set; }
public sbyte ConvOffset { get; set; }
public bool IsRawSigned => RawSignedFlag > 0;
public bool IsConvSigned => ConvSignedFlag > 0;
public OneDimTable()
{
RawAxis = new int[PointCount];
ConvValues = new int[PointCount];
}
/// <summary>Decode a 24-byte block (e.g. the data section of a 0x51 0x43 response).</summary>
public static OneDimTable FromWire(byte[] data, int offset = 0)
{
if (data is null) throw new ArgumentNullException(nameof(data));
if (data.Length - offset < WireLength)
throw new ArgumentException($"1D payload needs {WireLength} bytes from offset {offset}.", nameof(data));
var t = new OneDimTable
{
RawSignedFlag = data[offset + 18],
ConvSignedFlag = data[offset + 19],
RawMultiplier = data[offset + 20],
ConvMultiplier = data[offset + 21],
RawRounding = data[offset + 22],
ConvOffset = unchecked((sbyte)data[offset + 23]),
};
bool rawSigned = t.RawSignedFlag > 0;
bool convSigned = t.ConvSignedFlag > 0;
for (int i = 0; i < PointCount; i++)
{
t.RawAxis[i] = Decode(data[offset + i], rawSigned);
t.ConvValues[i] = Decode(data[offset + 8 + i], convSigned);
}
t.MaxRaw = Decode(data[offset + 16], rawSigned);
t.MinRaw = Decode(data[offset + 17], rawSigned);
return t;
}
/// <summary>Produce the 24-byte data block to send with APP_MEMWR_1D.</summary>
public byte[] ToWirePayload()
{
var d = new byte[WireLength];
bool rawSigned = IsRawSigned;
bool convSigned = IsConvSigned;
for (int i = 0; i < PointCount; i++)
{
d[i] = Encode(RawAxis[i], rawSigned);
d[8 + i] = Encode(ConvValues[i], convSigned);
}
d[16] = Encode(MaxRaw, rawSigned);
d[17] = Encode(MinRaw, rawSigned);
d[18] = RawSignedFlag;
d[19] = ConvSignedFlag;
d[20] = RawMultiplier;
d[21] = ConvMultiplier;
d[22] = RawRounding;
d[23] = unchecked((byte)ConvOffset);
return d;
}
public OneDimTable Clone()
{
var c = new OneDimTable
{
MaxRaw = MaxRaw, MinRaw = MinRaw,
RawSignedFlag = RawSignedFlag, ConvSignedFlag = ConvSignedFlag,
RawMultiplier = RawMultiplier, ConvMultiplier = ConvMultiplier,
RawRounding = RawRounding, ConvOffset = ConvOffset,
};
Array.Copy(RawAxis, c.RawAxis, PointCount);
Array.Copy(ConvValues, c.ConvValues, PointCount);
return c;
}
private static int Decode(byte b, bool signed) => signed ? unchecked((sbyte)b) : b;
private static byte Encode(int v, bool signed) => signed
? unchecked((byte)(sbyte)Math.Clamp(v, sbyte.MinValue, sbyte.MaxValue))
: (byte)Math.Clamp(v, byte.MinValue, byte.MaxValue);
}
}
+102
View File
@@ -0,0 +1,102 @@
using System.Collections.Generic;
namespace TuneBoss.Core.Models
{
public enum OneDimGroup
{
SensorCalibration,
FuelCompensation,
SparkCompensation,
IdleControl,
TractionControl,
Quickshifter,
Nitrous,
OutputsAndHardware,
}
/// <summary>
/// Stable identity of a 1D table slot. The ECU ADDRESS is generation-dependent and
/// is resolved at connect time (see MemoryLayout) — it is intentionally NOT stored
/// here. Slot is the 1-based ECU read order.
///
/// AxisUnit / ValueUnit are display-only labels (proposed defaults — editable in the
/// UI per table). They never affect the wire format.
/// </summary>
public sealed record OneDimTableDefinition(
int Slot,
string Label,
OneDimGroup Group,
int MinFirmware, // 0 = base; otherwise 80 / 83 / 90 / 130
string AxisUnit = "",
string ValueUnit = "");
public static class OneDimTableRegistry
{
public static readonly IReadOnlyList<OneDimTableDefinition> All = new[]
{
new OneDimTableDefinition( 1, "Spark Dwell Time", OneDimGroup.OutputsAndHardware, 0, "V", "ms"),
new OneDimTableDefinition( 2, "O2 Sensor", OneDimGroup.SensorCalibration, 0, "mV", "AFR"),
new OneDimTableDefinition( 3, "Intake Air Temperature", OneDimGroup.SensorCalibration, 0, "raw", "\u00B0C"),
new OneDimTableDefinition( 4, "Engine Temperature", OneDimGroup.SensorCalibration, 0, "raw", "\u00B0C"),
new OneDimTableDefinition( 5, "Manifold Air Pressure", OneDimGroup.SensorCalibration, 0, "raw", "kPa"),
new OneDimTableDefinition( 6, "Throttle Position", OneDimGroup.SensorCalibration, 0, "raw", "%"),
new OneDimTableDefinition( 7, "Fuel \u00B7 Engine Temp", OneDimGroup.FuelCompensation, 0, "\u00B0C", "%"),
new OneDimTableDefinition( 8, "Spark \u00B7 Engine Temp", OneDimGroup.SparkCompensation, 0, "\u00B0C", "\u00B0"),
new OneDimTableDefinition( 9, "Fuel \u00B7 Barometer", OneDimGroup.FuelCompensation, 0, "kPa", "%"),
new OneDimTableDefinition(10, "AUX Conversion", OneDimGroup.OutputsAndHardware, 0, "raw", "raw"),
new OneDimTableDefinition(11, "Fuel \u00B7 Intake Air Temp", OneDimGroup.FuelCompensation, 0, "\u00B0C", "%"),
new OneDimTableDefinition(12, "Spark \u00B7 Intake Air Temp", OneDimGroup.SparkCompensation, 0, "\u00B0C", "\u00B0"),
new OneDimTableDefinition(13, "Fuel \u00B7 TPS Accel", OneDimGroup.FuelCompensation, 0, "%", "%"),
new OneDimTableDefinition(14, "Spark \u00B7 TPS Accel", OneDimGroup.SparkCompensation, 0, "%", "\u00B0"),
new OneDimTableDefinition(15, "Battery V / Injector Opening", OneDimGroup.OutputsAndHardware, 0, "V", "\u00B5s"),
new OneDimTableDefinition(16, "TPS / MAP Percentage", OneDimGroup.SensorCalibration, 0, "raw", "%"),
new OneDimTableDefinition(17, "Idle Solenoid Ctrl Pct", OneDimGroup.IdleControl, 0, "RPM", "%"),
new OneDimTableDefinition(18, "Startup Fuel Comp", OneDimGroup.FuelCompensation, 0, "\u00B0C", "%"),
new OneDimTableDefinition(19, "Injector 2 Pct", OneDimGroup.OutputsAndHardware, 80, "RPM", "%"),
new OneDimTableDefinition(20, "RadFan PWM", OneDimGroup.OutputsAndHardware, 80, "\u00B0C", "%"),
new OneDimTableDefinition(21, "Idle Spark Rumble", OneDimGroup.Nitrous, 80, "RPM", "\u00B0"),
new OneDimTableDefinition(22, "Antilag Spark Control", OneDimGroup.Nitrous, 80, "RPM", "\u00B0"),
new OneDimTableDefinition(23, "Idle Fuel Pulse Width", OneDimGroup.IdleControl, 80, "\u00B0C", "\u00B5s"),
new OneDimTableDefinition(24, "Off-Throttle Isol Control", OneDimGroup.OutputsAndHardware, 80, "RPM", "%"),
new OneDimTableDefinition(25, "Speed Fuel Comp", OneDimGroup.FuelCompensation, 83, "km/h", "%"),
new OneDimTableDefinition(26, "Speed Spark Comp", OneDimGroup.SparkCompensation, 83, "km/h", "\u00B0"),
new OneDimTableDefinition(27, "ShiftBoss Fuel Cut", OneDimGroup.Quickshifter, 90, "RPM", "%"),
new OneDimTableDefinition(28, "ShiftBoss Spark Cut", OneDimGroup.Quickshifter, 90, "RPM", "%"),
new OneDimTableDefinition(29, "ShiftBoss Spark Retard", OneDimGroup.Quickshifter, 90, "RPM", "\u00B0"),
new OneDimTableDefinition(30, "TC Sensitivity", OneDimGroup.TractionControl, 90, "RPM", "%"),
new OneDimTableDefinition(31, "TC Spark Retard Degrees", OneDimGroup.TractionControl, 90, "%", "\u00B0"),
new OneDimTableDefinition(32, "TC Spark Retard Duration", OneDimGroup.TractionControl, 90, "%", "ms"),
new OneDimTableDefinition(33, "Gear Ratio Detection", OneDimGroup.TractionControl, 90, "gear", "ratio"),
new OneDimTableDefinition(34, "AUX PWM", OneDimGroup.OutputsAndHardware, 90, "raw", "%"),
new OneDimTableDefinition(35, "Idle Solenoid Control Steps", OneDimGroup.IdleControl, 130, "\u00B0C", "steps"),
new OneDimTableDefinition(36, "BARO Spark Comp", OneDimGroup.SparkCompensation, 130, "kPa", "\u00B0"),
new OneDimTableDefinition(37, "Idle Spark Compensation", OneDimGroup.IdleControl, 130, "RPM", "\u00B0"),
};
/// <summary>Nav-tree order for the groups.</summary>
public static readonly IReadOnlyList<OneDimGroup> GroupOrder = new[]
{
OneDimGroup.SensorCalibration,
OneDimGroup.FuelCompensation,
OneDimGroup.SparkCompensation,
OneDimGroup.IdleControl,
OneDimGroup.TractionControl,
OneDimGroup.Quickshifter,
OneDimGroup.Nitrous,
OneDimGroup.OutputsAndHardware,
};
public static string DisplayName(OneDimGroup g) => g switch
{
OneDimGroup.SensorCalibration => "Sensor Calibration",
OneDimGroup.FuelCompensation => "Fuel Compensation",
OneDimGroup.SparkCompensation => "Spark Compensation",
OneDimGroup.IdleControl => "Idle Control",
OneDimGroup.TractionControl => "Traction Control",
OneDimGroup.Quickshifter => "Quickshifter",
OneDimGroup.Nitrous => "Rumble & Antilag",
OneDimGroup.OutputsAndHardware => "Outputs & Hardware",
_ => g.ToString(),
};
}
}
+182
View File
@@ -0,0 +1,182 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// Data model for a subtable (AFR_Target_SubTable, Fuel_PulseWidth_Adjust_SubTable,
/// Spark_Angle_Adjust_SubTable — one per cylinder pair).
///
/// A subtable is a small 2D correction grid: 4 load rows × 6 RPM columns,
/// always signed sbyte values. It provides a secondary axis multiplier on
/// top of the main 2D table, keyed by RPM range pairs rather than absolute RPM.
///
/// ── Wire format — single read/write, no split ─────────────────────────────────
///
/// Field Size Notes
/// ─────────── ────── ────────────────────────────────────────────────────
/// Data cells 24 B sbyte[4 rows × 6 cols], row-major, always signed
/// Load axis 4 B byte[4] — fixed default {5, 15, 40, 70}
/// RPM axis 12 B byte[12] — pairs: [lo÷100, hi÷100] × 6 columns
///
/// Total 40 B = dataInArray(24) + loadInArray(4) + rpmInArray(12)
///
/// ── Key differences from TuningTable ─────────────────────────────────────────
/// - Always signed sbyte (no sign flag — hard-coded in the UI's Convert.ToSByte)
/// - Smaller grid: 4 rows × 6 cols vs 8 rows × 24 cols
/// - RPM axis uses pairs (low/high range per column), not single values
/// Each RPM cell displays as "loRPM\nhiRPM" (two lines)
/// - No modifier bytes (no MaxRaw/MinRaw/Mult/Sign trailer)
/// - Write sends only dataOutArray (no RPM/load arrays on write)
/// confirmed from writeSubTableFunctionThread: userDataArrayFromTable = sttp.dataOutArray
/// - Read response length comes from _tableMemReadBuffer[2] (Fix 1 in CheckNPreturn)
///
/// ── Default load axis ─────────────────────────────────────────────────────────
/// Fixed at {5, 15, 40, 70} — hardcoded in SubTuningTablePanel.InitializeTable()
/// </summary>
public sealed record SubTable
{
public const int Rows = 4;
public const int Cols = 6;
public const int DataBytes = Rows * Cols; // 24
public const int LoadBytes = Rows; // 4
public const int RpmBytes = Cols * 2; // 12 (lo+hi pair per column)
public const int TotalBytes = DataBytes + LoadBytes + RpmBytes; // 40
// ── Default axis values ───────────────────────────────────────────────────
public static readonly byte[] DefaultLoadAxis = { 5, 15, 40, 70 };
// ── Raw wire arrays ───────────────────────────────────────────────────────
/// <summary>
/// 24 bytes — cell data, row-major [row * 6 + col].
/// Always signed sbyte on wire (stored as byte, interpreted as sbyte).
/// </summary>
public byte[] Data { get; init; } = new byte[DataBytes];
/// <summary>4 bytes — load axis values. Default: {5, 15, 40, 70}.</summary>
public byte[] LoadAxis { get; init; } = (byte[])DefaultLoadAxis.Clone();
/// <summary>
/// 12 bytes — RPM axis pairs, [lo÷100, hi÷100] interleaved.
/// rpmInArray[col*2] = lo RPM ÷ 100, rpmInArray[col*2+1] = hi RPM ÷ 100.
/// Display: "loRPM\nhiRPM" (two lines per cell in the UI).
/// </summary>
public byte[] RpmAxis { get; init; } = new byte[RpmBytes];
// ── Derived display values ────────────────────────────────────────────────
/// <summary>
/// Gets the signed display value for a data cell.
/// SubTable cells are always sbyte — matches Convert.ToSByte() in the UI.
/// </summary>
public int GetCell(int row, int col) =>
unchecked((sbyte)Data[row * Cols + col]);
/// <summary>Low RPM bound for a column (display units).</summary>
public int GetRpmLo(int col) => RpmAxis[col * 2] * 100;
/// <summary>High RPM bound for a column (display units).</summary>
public int GetRpmHi(int col) => RpmAxis[col * 2 + 1] * 100;
/// <summary>Load axis value for a row (raw, 0–110).</summary>
public int GetLoad(int row) => LoadAxis[row];
// ── Deserialisation ───────────────────────────────────────────────────────
/// <summary>
/// Parses the device response for a subtable read.
/// The response payload starts at byte offset 4 (after the 4-byte header).
/// Response length is given by _tableMemReadBuffer[2] per CheckNPreturn Fix 1.
///
/// Layout matches sendReadSplitTableToPanelThread (subtable path):
/// response[4 .. 4+DataBytes-1] → Data
/// response[4+DataBytes .. 4+DataBytes+3] → LoadAxis
/// response[4+DataBytes+4 .. 4+TotalBytes-1] → RpmAxis
/// </summary>
public static SubTable FromPayload(byte[] payload)
{
int expectedMin = 4 + TotalBytes;
if (payload.Length < expectedMin)
throw new ArgumentException(
$"Expected at least {expectedMin} bytes, got {payload.Length}.", nameof(payload));
const int o = 4;
var data = payload[o..(o + DataBytes)];
var loadAxis = payload[(o + DataBytes)..(o + DataBytes + LoadBytes)];
var rpmAxis = payload[(o + DataBytes + LoadBytes)..(o + TotalBytes)];
return new SubTable
{
Data = data,
LoadAxis = loadAxis,
RpmAxis = rpmAxis,
};
}
/// <summary>
/// Parses when only the data segment length is known from the response header.
/// Matches the CheckNPreturn Fix 1 pattern:
/// sttp.dataInArray = new byte[_tableMemReadBuffer[2]]
/// BlockCopy from _tableMemReadBuffer[4]
/// Load/RPM axes use defaults when not included in the response.
/// </summary>
public static SubTable FromDataOnlyPayload(byte[] payload, int dataLength)
{
if (payload.Length < 4 + dataLength)
throw new ArgumentException(
$"Payload too short for {dataLength} data bytes.", nameof(payload));
var data = new byte[dataLength];
Buffer.BlockCopy(payload, 4, data, 0, dataLength);
return new SubTable
{
Data = data,
LoadAxis = (byte[])DefaultLoadAxis.Clone(),
RpmAxis = new byte[RpmBytes],
};
}
// ── Serialisation ─────────────────────────────────────────────────────────
/// <summary>
/// Returns the data-only write payload (24 bytes).
/// Matches writeSubTableFunctionThread: only dataOutArray is sent,
/// no RPM/load arrays on write.
/// </summary>
public byte[] ToWirePayload() => (byte[])Data.Clone();
/// <summary>
/// Full 40-byte payload including load and RPM axes.
/// Used when full round-trip serialisation is needed.
/// </summary>
public byte[] ToFullPayload()
{
var buf = new byte[TotalBytes];
Buffer.BlockCopy(Data, 0, buf, 0, DataBytes);
Buffer.BlockCopy(LoadAxis, 0, buf, DataBytes, LoadBytes);
Buffer.BlockCopy(RpmAxis, 0, buf, DataBytes + LoadBytes, RpmBytes);
return buf;
}
// ── Mutation ──────────────────────────────────────────────────────────────
/// <summary>
/// Returns a new SubTable with cell (row, col) adjusted by delta,
/// clamped to the signed sbyte range [-128, 127].
/// Matches minusButton/addButton in SubTuningTablePanel using Convert.ToSByte.
/// </summary>
public SubTable WithCellAdjusted(int row, int col, int delta,
int minVal = -128, int maxVal = 127)
{
var newData = (byte[])Data.Clone();
int idx = row * Cols + col;
int current = unchecked((sbyte)newData[idx]);
int adjusted = Math.Clamp(current + delta, minVal, maxVal);
newData[idx] = unchecked((byte)(sbyte)adjusted);
return new SubTable
{
Data = newData,
LoadAxis = LoadAxis,
RpmAxis = RpmAxis,
};
}
}
+158
View File
@@ -0,0 +1,158 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// Calculates which table cells to highlight during live diagnostics.
///
/// Given a live sensor value and a table's axis array, returns two indices:
/// [0] = the primary (exact) cell — the bracket the value falls into
/// [1] = the adjacent cell — either the previous or next bracket
/// (-1 means "before first" or "after last" — no secondary highlight)
///
/// ── Algorithm ────────────────────────────────────────────────────────────────
/// For each pair of adjacent axis values, the midpoint defines the boundary
/// between brackets. The live value is assigned to the bracket whose midpoint
/// boundary it falls within, then the adjacent bracket is the one whose axis
/// value is closest to the live value.
///
/// Reverse-engineered from getRpmToHighlight() and getLoadToHighlight() in the
/// WinForms app. Both functions are identical in structure — only the axis
/// length differs (24 for RPM, 8 for Load/TPS).
///
/// ── Usage ────────────────────────────────────────────────────────────────────
/// var (col, adjCol) = TableTracker.FindIndex(table.RpmAxis, frame.RPM_Raw);
/// var (row, adjRow) = TableTracker.FindIndex(table.LoadAxis, frame.Load);
///
/// // TPS-keyed tables (user-adjust: diag4/5/10/11/12)
/// var (row, adjRow) = TableTracker.FindIndex(table.LoadAxis, frame.TPS_Percent);
/// </summary>
public static class TableTracker
{
/// <summary>
/// Finds the highlight and adjacent indices for a live value against an axis array.
/// </summary>
/// <param name="axis">The table axis (RPM ÷100 bytes or load bytes).</param>
/// <param name="value">The live sensor value in the same units as the axis.</param>
/// <returns>
/// (highlight, adjacent) where -1 means "out of range on that side".
/// </returns>
public static (int Highlight, int Adjacent) FindIndex(byte[] axis, byte value)
{
int n = axis.Length;
if (n == 0) return (0, -1);
if (n == 1) return (0, -1);
// Below first midpoint → bracket 0
if (value < Midpoint(axis, 0, 1))
{
int adj = value < axis[0] ? -1 : 1;
return (0, adj);
}
// Middle brackets
for (int i = 1; i < n - 1; i++)
{
int lo = Midpoint(axis, i - 1, i);
int hi = Midpoint(axis, i, i + 1);
if (lo <= value && value < hi)
{
int adj = value < axis[i] ? i - 1 : i + 1;
return (i, adj);
}
}
// Above last midpoint → bracket n-1
{
int adj = value < axis[n - 1] ? n - 2 : -1;
return (n - 1, adj);
}
}
/// <summary>
/// Produces a <see cref="DiagnosticsTracker"/> for a tuning table from live frame data.
/// </summary>
/// <param name="rpmAxis">Table RPM axis (raw bytes, each × 100 = RPM).</param>
/// <param name="loadAxis">Table load axis (raw bytes).</param>
/// <param name="rpmRaw">Live RPM raw value from DiagnosticsFrame.RPM_Raw.</param>
/// <param name="loadValue">Live load/TPS value — use frame.Load for main tables,
/// frame.TPS_Percent for user-adjust tables.</param>
public static DiagnosticsTracker Calculate(
byte[] rpmAxis,
byte[] loadAxis,
byte rpmRaw,
byte loadValue)
{
var (col, adjCol) = FindIndex(rpmAxis, rpmRaw);
var (row, adjRow) = FindIndex(loadAxis, loadValue);
return new DiagnosticsTracker(
ColHighlight: col,
ColLowlight: adjCol,
RowHighlight: row,
RowLowlight: adjRow);
}
/// <summary>
/// Calculates trackers for all loaded tables in a session from one frame.
/// Returns a dictionary keyed by table name.
/// Only includes tables whose axes are loaded.
/// </summary>
public static IReadOnlyDictionary<string, DiagnosticsTracker> CalculateAll(
EcuSession session,
DiagnosticsFrame frame)
{
var result = new Dictionary<string, DiagnosticsTracker>();
byte rpm = frame.RPM_Raw;
byte load = frame.Load;
byte tps = frame.TPS_Percent;
void Add(string name, TuningTable? t, byte axisValue)
{
if (t == null) return;
result[name] = Calculate(t.RpmAxis, t.LoadAxis, rpm, axisValue);
}
void AddAfr(string name, AfrTable? t, byte axisValue)
{
if (t == null) return;
result[name] = Calculate(t.RpmAxis, t.LoadAxis, rpm, axisValue);
}
// Cyl1 main tables — load-keyed
Add("Fuel_PulseWidth1", session.Fuel_PulseWidth1, load);
Add("Spark_Angle1", session.Spark_Angle1, load);
Add("Fuel_Angle2D", session.Fuel_Angle2D, load);
Add("Secondary_Load_Conversion", session.Secondary_Load_Conversion, load);
AddAfr("AFR_Target1", session.AFR_Target1, load);
// Cyl1 user-adjust — TPS-keyed
Add("Fuel_PulseWidth_Adjust1", session.Fuel_PulseWidth_Adjust1, tps);
Add("Spark_Angle_Adjust1", session.Spark_Angle_Adjust1, tps);
if (session.IsTwoCylinder)
{
// Cyl2 main tables — load-keyed
Add("Fuel_PulseWidth2", session.Fuel_PulseWidth2, load);
Add("Spark_Angle2", session.Spark_Angle2, load);
Add("Fuel_Angle2D_2", session.Fuel_Angle2D_2, load);
AddAfr("AFR_Target2", session.AFR_Target2, load);
// Cyl2 user-adjust — TPS-keyed
Add("Fuel_PulseWidth_Adjust2", session.Fuel_PulseWidth_Adjust2, tps);
Add("Spark_Angle_Adjust2", session.Spark_Angle_Adjust2, tps);
}
return result;
}
// ── Helpers ───────────────────────────────────────────────────────────────
/// <summary>
/// Integer midpoint of two adjacent axis values.
/// Matches (rpmArrayRef[i] + rpmArrayRef[i+1]) / 2 in the original code.
/// Uses integer division — no rounding.
/// </summary>
private static byte Midpoint(byte[] axis, int i, int j)
=> (byte)((axis[i] + axis[j]) / 2);
}
+101
View File
@@ -0,0 +1,101 @@
using TuneBoss.Core.Protocol;
namespace TuneBoss.Core.Models;
/// <summary>
/// Throttle-position-sensor calibration rules, resolved verbatim from the legacy
/// WinForms (<c>saveUserReadInfo</c> / TPS page) and Android (<c>TpsCalPage</c> /
/// <c>BtApp.sendTpsCalWrite</c>) sources.
///
/// The calibration captures the raw TPS ADC (<see cref="DiagnosticsFrame.TPS_Raw"/>,
/// channel [18]) at closed and wide-open throttle over several sweeps, validates the
/// captured min/max against the per-unit absolute bounds, then writes an 8-byte 1D
/// block and sets the first-use flag.
///
/// ── Generation addressing (absolute ECU addresses) ───────────────────────────
/// Gen2 / Gen3 (small-address layout — PG1/EZ115 is Gen3):
/// CalWrite = 0x0078 (120) ← 8-byte calibration block
/// AbsBounds = 0x0088 (136) ← [max, min, store2, store3] sanity bounds
/// AdvSettings = 0x0094 (148) ← advanced TPS toggle (FW ≥ 152)
/// Gen1 (legacy ~1788 range): CalWrite = 0x06FC, AbsBounds = 0x070C, no adv.
/// </summary>
public static class TpsCalibration
{
public readonly record struct Addresses(
ushort CalWrite,
ushort AbsBounds,
ushort AdvSettings,
bool AdvSupported);
/// <summary>Minimum firmware that exposes the advanced TPS settings byte.</summary>
public const int AdvMinFirmware = 152;
/// <summary>Number of full open/close sweeps the guide asks the tuner to perform.</summary>
public const int RequiredSweeps = 5;
/// <summary>
/// FirstUseInfo[0] sentinel (READ_INFO buf[32], the DD slot, overloaded as a flag
/// on Gen2/Gen3). The unit is considered calibrated iff this byte == 1.
/// </summary>
public const byte CalDoneFlag = 1;
// Absolute-bounds editor limits (legacy long-press editor ranges).
public const byte AbsMaxFloor = 180, AbsMaxCeil = 198;
public const byte AbsMinFloor = 2, AbsMinCeil = 10;
/// <summary>Resolves the calibration addresses for a generation + firmware.</summary>
public static Addresses For(GenerationType generation, byte fwVersion) => generation switch
{
GenerationType.Gen1 => new Addresses(0x06FC, 0x070C, 0x0000, AdvSupported: false),
_ => new Addresses(0x0078, 0x0088, 0x0094, AdvSupported: fwVersion >= AdvMinFirmware),
};
/// <summary>Convenience overload resolving the generation from <see cref="EcuInfo"/>.</summary>
public static Addresses For(EcuInfo info) =>
For((GenerationType)info.AppInfoVersion, info.FwVersion);
/// <summary>
/// Builds the 8-byte 1D calibration payload exactly as the legacy
/// <c>sendTpsCalWrite</c> does: [min, max, max+2, max+4, max+6, max+8, max+10, max+12].
/// The trailing ramp defines the TPS% curve above wide-open throttle.
/// </summary>
public static byte[] BuildCalWritePayload(int minRaw, int maxRaw)
{
byte m = (byte)(maxRaw & 0xFF);
return new[]
{
(byte)(minRaw & 0xFF),
m,
(byte)(m + 2), (byte)(m + 4), (byte)(m + 6),
(byte)(m + 8), (byte)(m + 10), (byte)(m + 12),
};
}
public enum Validation
{
Ok,
MinBelowFloor, // captured closed-throttle raw fell below the absolute minimum
MaxAboveCeiling, // captured WOT raw rose above the absolute maximum
Extreme, // crossed/implausible values
}
/// <summary>
/// Replicates the legacy acceptance test against the absolute bounds read from
/// <see cref="Addresses.AbsBounds"/> ([0] = absMax, [1] = absMin).
/// </summary>
public static Validation Validate(int minRaw, int maxRaw, int absMin, int absMax)
{
if (minRaw < absMin) return Validation.MinBelowFloor;
if (maxRaw > absMax) return Validation.MaxAboveCeiling;
if (minRaw > absMax || maxRaw < absMin) return Validation.Extreme;
return Validation.Ok;
}
public static string Describe(Validation v, int minRaw, int maxRaw, int absMin, int absMax) => v switch
{
Validation.MinBelowFloor => $"Min raw {minRaw} is below the expected minimum of {absMin}. Please check your throttle.",
Validation.MaxAboveCeiling => $"Max raw {maxRaw} is above the expected maximum of {absMax}. Please check your throttle.",
Validation.Extreme => $"Calibration failed due to extreme TPS values (min {minRaw}, max {maxRaw}). Please check your throttle.",
_ => $"Calibration successful — min {minRaw}, max {maxRaw}.",
};
}
+232
View File
@@ -0,0 +1,232 @@
namespace TuneBoss.Core.Models;
/// <summary>
/// Complete data model for a 2D tuning table (Fuel PulseWidth, Spark Angle,
/// AFR Target, etc.).
///
/// ── Wire format on the device ────────────────────────────────────────────────
/// Total payload = 227 bytes, split across two reads/writes at 0x7F boundary:
///
/// Offset Length Field
/// ─────── ─────── ──────────────────────────────────────────────────────
/// 0 192 Data cells (24 cols × 8 rows, row-major, byte each)
/// 192 8 Load axis (8 bytes, ascending, 0–110 range)
/// 200 24 RPM axis (24 bytes, each × 100 = actual RPM)
/// 224 1 Max raw (byte; sbyte if signed)
/// 225 1 Min raw (byte; sbyte if signed)
/// 226 1 Mult (multiplier for display scaling)
/// 227 1 Sign (0 = unsigned byte, >0 = signed sbyte)
///
/// Split read:
/// Part 1: bytes [0..127] → lengthFirstPart = 0x7F (127)
/// Part 2: bytes [128..227] → lengthSecondPart = 227 - 127 - 1 = 99
/// Part 2 address = baseAddress + 0x7F + 1
///
/// Split write (same split, different order — data is written first):
/// Part 1 writes dataArray[0..127]
/// Part 2 writes dataArray[128..191] + loadArray[0..7]
/// + rpmArray[0..23] + modifiers[0..3]
///
/// ── Display / UI mapping ─────────────────────────────────────────────────────
/// RPM axis : stored as raw byte (÷100 on wire), displayed × 100 (e.g. 50→5000)
/// Load axis : stored as raw byte (0–110), displayed as-is
/// Data cells: if Sign > 0 → sbyte interpretation, else byte
/// minDataVal/maxDataVal derived from min/maxRawVal via sign flag
/// Color map : 7 linear bands from minDataVal to maxDataVal (red→green)
/// </summary>
public sealed record TuningTable
{
// ── Dimensions ────────────────────────────────────────────────────────────
public const int Cols = 24; // RPM columns
public const int Rows = 8; // Load rows
public const int DataBytes = Cols * Rows; // 192
// ── Split constants (match TableHandling lengthFirstPart) ─────────────────
public const int SplitFirstLength = 0x7F; // 127
public const int TotalPayloadBytes = DataBytes + Rows + Cols + 4; // 228
// ── Raw wire arrays ───────────────────────────────────────────────────────
/// <summary>192 bytes, row-major [row * 24 + col].</summary>
public byte[] Data { get; init; } = new byte[DataBytes];
/// <summary>8 bytes — load axis values (0–110).</summary>
public byte[] LoadAxis { get; init; } = new byte[Rows];
/// <summary>24 bytes — RPM axis, each × 100 = actual RPM.</summary>
public byte[] RpmAxis { get; init; } = new byte[Cols];
// ── Modifiers (bytes 224–227) ─────────────────────────────────────────────
/// <summary>Raw max value from device (index [0] in modifiersInArray).</summary>
public byte MaxRaw { get; init; }
/// <summary>Raw min value from device (index [1] in modifiersInArray).</summary>
public byte MinRaw { get; init; }
/// <summary>Multiplier for display scaling (index [2]).</summary>
public byte Mult { get; init; }
/// <summary>Sign flag: 0 = unsigned byte, >0 = signed sbyte (index [3]).</summary>
public byte Sign { get; init; }
// ── Derived display values ────────────────────────────────────────────────
public bool IsSigned => Sign > 0;
/// <summary>Display min — sbyte if signed, byte if unsigned.</summary>
public int MinDataVal => IsSigned
? unchecked((sbyte)MinRaw)
: (int)MinRaw;
/// <summary>Display max — sbyte if signed, byte if unsigned.</summary>
public int MaxDataVal => IsSigned
? unchecked((sbyte)MaxRaw)
: (int)MaxRaw;
/// <summary>
/// Gets the display value for a cell.
/// Applies sign interpretation matching UpdateTable(readCmd=1) in TuningTablePanel.
/// </summary>
public int GetCell(int row, int col) =>
IsSigned
? unchecked((sbyte)Data[row * Cols + col])
: Data[row * Cols + col];
/// <summary>RPM axis values in display units (raw × 100).</summary>
public int[] RpmValues => RpmAxis.Select(r => r * 100).ToArray();
/// <summary>Load axis values (raw, 0–110 range).</summary>
public int[] LoadValues => LoadAxis.Select(l => (int)l).ToArray();
/// <summary>
/// 7-band color range thresholds, matching setDataValRange() in TuningTablePanel.
/// dataValRange[x] = minDataVal + (x * (maxDataVal - minDataVal)) / 7
/// </summary>
public double[] ColorBandThresholds()
{
var range = new double[8];
int span = MaxDataVal - MinDataVal;
for (int x = 0; x < 8; x++)
range[x] = MinDataVal + (x * span) / 7.0;
return range;
}
// ── Serialisation (write path) ────────────────────────────────────────────
/// <summary>
/// Builds the combined 228-byte payload for the write path.
/// Matches the order in writeTableFunctionSplitThreadCustom:
/// [0..191] data cells
/// [192..199] load axis
/// [200..223] rpm axis
/// [224] MaxRaw
/// [225] MinRaw
/// [226] Mult
/// [227] Sign
/// </summary>
public byte[] ToWirePayload()
{
var buf = new byte[TotalPayloadBytes];
Buffer.BlockCopy(Data, 0, buf, 0, DataBytes);
Buffer.BlockCopy(LoadAxis,0, buf, DataBytes, Rows);
Buffer.BlockCopy(RpmAxis, 0, buf, DataBytes + Rows, Cols);
buf[DataBytes + Rows + Cols] = MaxRaw;
buf[DataBytes + Rows + Cols + 1] = MinRaw;
buf[DataBytes + Rows + Cols + 2] = Mult;
buf[DataBytes + Rows + Cols + 3] = Sign;
return buf;
}
/// <summary>First 128 bytes of the payload — sent as part 1 of split write.</summary>
public byte[] ToWirePayloadPart1() => ToWirePayload()[..( SplitFirstLength + 1)];
/// <summary>Remaining bytes — sent as part 2 of split write.</summary>
public byte[] ToWirePayloadPart2() => ToWirePayload()[(SplitFirstLength + 1)..];
// ── Deserialisation (read path) ───────────────────────────────────────────
/// <summary>
/// Parses a combined 228-byte buffer assembled from the two split reads.
/// Matches sendReadSplitTableToPanelThreadCustom() in Form1_TableHandling.cs.
///
/// Part 1 response[4..131] → dataCombined[0..127]
/// Part 2 response[4..103] → dataCombined[128..227]
/// </summary>
public static TuningTable FromWirePayload(byte[] combined)
{
if (combined.Length < TotalPayloadBytes)
throw new ArgumentException(
$"Expected {TotalPayloadBytes} bytes, got {combined.Length}.", nameof(combined));
var data = new byte[DataBytes];
var loadAxis = new byte[Rows];
var rpmAxis = new byte[Cols];
Buffer.BlockCopy(combined, 0, data, 0, DataBytes);
Buffer.BlockCopy(combined, DataBytes, loadAxis,0, Rows);
Buffer.BlockCopy(combined, DataBytes + Rows, rpmAxis, 0, Cols);
int modBase = DataBytes + Rows + Cols;
byte maxRaw = combined[modBase];
byte minRaw = combined[modBase + 1];
byte mult = combined[modBase + 2];
byte sign = combined[modBase + 3];
return new TuningTable
{
Data = data,
LoadAxis = loadAxis,
RpmAxis = rpmAxis,
MaxRaw = maxRaw,
MinRaw = minRaw,
Mult = mult,
Sign = sign,
};
}
/// <summary>
/// Assembles the combined payload from the two raw device response buffers.
/// Each response buffer has a 4-byte header; data starts at offset 4.
/// </summary>
public static TuningTable FromSplitResponses(byte[] part1Response, byte[] part2Response)
{
var combined = new byte[TotalPayloadBytes];
// Part 1: bytes [4 .. 4+SplitFirstLength] → combined[0..SplitFirstLength]
Buffer.BlockCopy(part1Response, 4, combined, 0,
SplitFirstLength + 1);
// Part 2: bytes [4 ..] → combined[SplitFirstLength+1..]
int part2Len = TotalPayloadBytes - (SplitFirstLength + 1);
Buffer.BlockCopy(part2Response, 4, combined, SplitFirstLength + 1,
part2Len);
return FromWirePayload(combined);
}
// ── Mutation (for +1/-1/+5/-5 operations) ────────────────────────────────
/// <summary>
/// Returns a new TuningTable with the cell at (row, col) adjusted by delta,
/// clamped to [MinDataVal, MaxDataVal].
/// </summary>
public TuningTable WithCellAdjusted(int row, int col, int delta)
{
var newData = (byte[])Data.Clone();
int idx = row * Cols + col;
int current = IsSigned ? unchecked((sbyte)newData[idx]) : newData[idx];
int adjusted = Math.Clamp(current + delta, MinDataVal, MaxDataVal);
newData[idx] = IsSigned
? unchecked((byte)(sbyte)adjusted)
: (byte)adjusted;
return new TuningTable
{
Data = newData,
LoadAxis = LoadAxis,
RpmAxis = RpmAxis,
MaxRaw = MaxRaw,
MinRaw = MinRaw,
Mult = Mult,
Sign = Sign,
};
}
}
@@ -0,0 +1,68 @@
using System.Xml.Linq;
namespace TuneBoss.Core.Models;
/// <summary>
/// Determines whether a bike is a two-cylinder model based on
/// manufacturer + model code, driven by twoCylModels.xml.
/// </summary>
public sealed class TwoCylinderRegistry
{
// Manufacturer codes
public const byte Yamaha = 1;
public const byte Honda = 2;
public const byte Kawasaki = 3;
public const byte Suzuki = 6;
private readonly Dictionary<byte, HashSet<uint>> _models = new();
private TwoCylinderRegistry() { }
/// <summary>
/// Loads from a twoCylModels.xml file path.
/// </summary>
public static TwoCylinderRegistry Load(string xmlPath)
{
var doc = XDocument.Load(xmlPath);
var registry = new TwoCylinderRegistry();
registry.LoadTag(doc, "ym", Yamaha);
registry.LoadTag(doc, "hn", Honda);
registry.LoadTag(doc, "kw", Kawasaki);
registry.LoadTag(doc, "su", Suzuki);
return registry;
}
/// <summary>
/// Loads from an XML string (useful for embedding or testing).
/// </summary>
public static TwoCylinderRegistry LoadFromString(string xml)
{
var doc = XDocument.Parse(xml);
var registry = new TwoCylinderRegistry();
registry.LoadTag(doc, "ym", Yamaha);
registry.LoadTag(doc, "hn", Honda);
registry.LoadTag(doc, "kw", Kawasaki);
registry.LoadTag(doc, "su", Suzuki);
return registry;
}
public bool IsTwoCylinder(byte manufacturer, uint model)
{
return _models.TryGetValue(manufacturer, out var set) && set.Contains(model);
}
private void LoadTag(XDocument doc, string tag, byte manufacturerCode)
{
var models = doc.Descendants(tag)
.Select(e => uint.TryParse(e.Value.Trim(), out var v) ? (uint?)v : null)
.Where(v => v.HasValue)
.Select(v => v!.Value)
.ToHashSet();
_models[manufacturerCode] = models;
}
}
+114
View File
@@ -0,0 +1,114 @@
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace TuneBoss.Core.Models;
/// <summary>
/// Which bike models have VVA (variable valve actuation), so the RPM Settings page can
/// gate the VVA RPM Trigger. Mirrors the legacy <c>vvaModels.xml</c> / <c>checkVvaModels</c>.
///
/// The list is loaded from an EDITABLE external file at
/// <c>%APPDATA%\TuneBoss\vvaModels.xml</c> so it can be changed without recompiling.
/// The file is auto-created (seeded with the defaults below) on first use if missing.
/// If it can't be read, the built-in defaults are used.
///
/// XML schema (same as legacy): &lt;vvaModels&gt;&lt;ym&gt;14&lt;/ym&gt;…&lt;hn&gt;…&lt;/hn&gt;
/// &lt;su&gt;…&lt;/su&gt;&lt;kw&gt;…&lt;/kw&gt;&lt;/vvaModels&gt;.
/// Element → manufacturer code: ym=1 Yamaha, hn=2 Honda, kw=3 Kawasaki, su=6 Suzuki.
/// </summary>
public static class VvaModelRegistry
{
private static readonly object _lock = new();
private static Dictionary<byte, HashSet<byte>>? _map;
/// <summary>Editable list file. Sits beside settings.json in %APPDATA%\TuneBoss.</summary>
public static string FilePath => System.IO.Path.Combine(
System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData),
"TuneBoss", "vvaModels.xml");
// Element name → manufacturer code.
private static readonly (string Elem, byte Mfr)[] Makes =
{
("ym", 1), ("hn", 2), ("kw", 3), ("su", 6),
};
// Built-in defaults (legacy vvaModels.xml): only these Yamaha models carry VVA.
private static Dictionary<byte, HashSet<byte>> Defaults() => new()
{
[1] = new HashSet<byte> { 14, 17, 21, 22 },
};
/// <summary>True when the given make/model is known to have VVA.</summary>
public static bool IsVvaModel(byte manufacturer, byte model)
{
var map = EnsureLoaded();
return map.TryGetValue(manufacturer, out var models) && models.Contains(model);
}
/// <summary>Force a re-read of the file on the next lookup (call after editing it).</summary>
public static void Reload()
{
lock (_lock) { _map = null; }
}
private static Dictionary<byte, HashSet<byte>> EnsureLoaded()
{
lock (_lock)
{
if (_map != null) return _map;
try
{
if (System.IO.File.Exists(FilePath))
{
_map = Parse(XDocument.Load(FilePath));
return _map;
}
// First run — seed the editable file with the defaults, then use them.
_map = Defaults();
TrySeedFile();
}
catch
{
// Missing / malformed / unreadable → fall back to the built-in list.
_map = Defaults();
}
return _map;
}
}
private static Dictionary<byte, HashSet<byte>> Parse(XDocument doc)
{
var map = new Dictionary<byte, HashSet<byte>>();
foreach (var (elem, mfr) in Makes)
{
var set = new HashSet<byte>();
foreach (var node in doc.Descendants(elem))
{
if (byte.TryParse(node.Value.Trim(), out byte m))
set.Add(m); // a 999 placeholder simply never matches a real model
}
if (set.Count > 0) map[mfr] = set;
}
return map.Count > 0 ? map : Defaults();
}
private static void TrySeedFile()
{
try
{
var dir = System.IO.Path.GetDirectoryName(FilePath);
if (!string.IsNullOrEmpty(dir)) System.IO.Directory.CreateDirectory(dir);
var doc = new XDocument(new XElement("vvaModels",
new XElement("ym", 14), new XElement("ym", 17),
new XElement("ym", 21), new XElement("ym", 22),
new XElement("hn", 999), new XElement("su", 999), new XElement("kw", 999)));
doc.Save(FilePath);
}
catch { /* seeding is best-effort; defaults still apply in memory */ }
}
}
+73
View File
@@ -0,0 +1,73 @@
namespace TuneBoss.Core.Protocol;
/// <summary>
/// Checksum helpers for the TuneBoss BLE packet protocol.
///
/// genCheckSumDW: accumulates payload as little-endian uint32 DWords,
/// sums them (wrapping uint32), then returns the bitwise inverse (~sum).
/// Verified against debug log 17-Mar-2026.
/// </summary>
public static class ChecksumHelper
{
/// <summary>
/// Computes the DWord checksum over a byte span.
/// The span length must be a multiple of 4 (pad before calling if needed).
/// </summary>
public static uint GenChecksumDW(ReadOnlySpan<byte> data)
{
if (data.Length % 4 != 0)
throw new ArgumentException("Data length must be a multiple of 4.", nameof(data));
uint cumResult = 0;
for (int i = 0; i < data.Length; i += 4)
{
uint dword = data[i]
| ((uint)data[i + 1] << 8)
| ((uint)data[i + 2] << 16)
| ((uint)data[i + 3] << 24);
cumResult += dword; // wrapping uint32 addition
}
return ~cumResult; // bitwise inverse
}
/// <summary>
/// Writes the 4-byte little-endian checksum into <paramref name="dest"/>.
/// </summary>
public static void WriteChecksumDW(ReadOnlySpan<byte> data, Span<byte> dest)
{
uint cs = GenChecksumDW(data);
dest[0] = (byte)(cs);
dest[1] = (byte)(cs >> 8);
dest[2] = (byte)(cs >> 16);
dest[3] = (byte)(cs >> 24);
}
/// <summary>
/// Computes the single-byte header inverse sum.
/// sum = TL_type + seqNum + dwCount; result = 0xFF - sum (byte wrap).
/// Verified: TL=02 seq=01 dw=02 → sum=05 → invSum=FA ✓
/// </summary>
public static byte HeaderInverseSum(byte tlType, byte seqNum, byte dwCount)
=> unchecked((byte)(0xFF - (tlType + seqNum + dwCount)));
/// <summary>
/// Verifies an inbound packet's DWord checksum.
/// The last 4 bytes of <paramref name="payload"/> are the checksum;
/// the preceding bytes are the data.
/// </summary>
public static bool VerifyChecksumDW(ReadOnlySpan<byte> payload)
{
if (payload.Length < 8 || payload.Length % 4 != 0)
return false;
int dataLen = payload.Length - 4;
var data = payload.Slice(0, dataLen);
var expected = payload.Slice(dataLen, 4);
uint computed = GenChecksumDW(data);
return expected[0] == (byte)(computed)
&& expected[1] == (byte)(computed >> 8)
&& expected[2] == (byte)(computed >> 16)
&& expected[3] == (byte)(computed >> 24);
}
}
+78
View File
@@ -0,0 +1,78 @@
namespace TuneBoss.Core.Protocol;
/// <summary>
/// TuneBoss hardware command bytes.
/// </summary>
public static class Commands
{
// ── Data Link layer ─────────────────────────────────────────────────────
public const byte DL_ACK = 0x11;
public const byte DL_NAK_HDR = 0x12;
public const byte DL_NAK_DATA = 0x13;
public const byte DL_NAK_OVF = 0x14; // Rx buffer overflow — use smaller packet
public const byte DL_NAK_TIMEOUT = 0x15;
// ── Transport layer ──────────────────────────────────────────────────────
public const byte TL_POSTED = 0x01; // Requires ACK from device
public const byte TL_NONPOSTED = 0x02; // No ACK; device returns a data packet
public const byte TL_NP_RETURN = 0x03; // Return packet for TL_NONPOSTED
public const byte TL_STREAMING = 0x04; // Streaming; no ACK/NAK required
public const byte DL_PING_NOREPLY = 0x21; // Host connectivity test; device ignores
// ── App commands — Non-Posted ────────────────────────────────────────────
public const byte APP_UNLOCK = 0x30; // Password + current date at byte 4
public const byte APP_LOCK = 0x31;
public const byte APP_MEMRD_SEQ = 0x32; // Legacy: 8-bit len @ b1, 16-bit addr @ b2-3
public const byte APP_UNLOCK2 = 0x33; // Basic ECU unlock (GEN3)
public const byte APP_MEMWR_SEQ = 0x34; // Legacy: 8-bit len @ b1, 16-bit addr @ b2-3
public const byte APP_FIRSTUSE = 0x35;
public const byte APP_FLASH_WR = 0x36;
public const byte APP_READ_INFO = 0x37; // Read ECU info / keepalive
public const byte APP_CHANGE_PWD = 0x38;
public const byte APP_IMMOBILIZER = 0x3A;
public const byte APP_READ_DEBUG = 0x3D;
public const byte APP_UPGRADE_MOD = 0x3E;
public const byte APP_MEM_INFO = 0x40; // Reserved / ignore for now
// ── App commands — Table read ────────────────────────────────────────────
public const byte APP_MEMRD_2D = 0x41; // 2D tables (tuner)
public const byte APP_MEMRD_SUBT = 0x42; // Subtables
public const byte APP_MEMRD_1D = 0x43; // 1D tables
public const byte APP_MEMRD_MISC = 0x44; // Misc values + device info
public const byte APP_MEMRD_2D_USER = 0x45; // 2D user tables (GEN3 basic ECU)
// ── App commands — Table write ───────────────────────────────────────────
public const byte APP_MEMWR_2D = 0x49;
public const byte APP_MEMWR_SUBT = 0x4A;
public const byte APP_MEMWR_1D = 0x4B;
public const byte APP_MEMWR_MISC = 0x4C;
public const byte APP_MEMWR_2D_USER = 0x4D; // GEN3 basic ECU
// ── App response codes ───────────────────────────────────────────────────
public const byte APP_CMD_SUCCESS = 0x51;
public const byte APP_CMD_FAIL = 0x52;
public const byte APP_CMD_INV = 0x53;
public const byte APP_MEMADDR_INV = 0x54; // Invalid read/write address
public const byte APP_MEMLEN_OVF = 0x55; // Length too large for Tx/Rx buffer
public const byte APP_MEMADDR_LOCK = 0x56; // Address locked (basic ECU)
public const byte APP_TUNER_LOCK = 0x57; // Command locked by tuner
// ── App commands — Diagnostics streaming ────────────────────────────────
public const byte APP_MONITORING = 0x70; // Streaming diagnostics frame
public const byte APP_MON_START = 0x71;
public const byte APP_MON_STOP = 0x72;
// ── App commands — Tuner lock domain ────────────────────────────────────
public const byte APP_UNLOCK_TUNER = 0x60; // Same usage model as APP_UNLOCK
public const byte APP_NEW_PWD_TUNER = 0x61; // Change tuner password (null×16 = disable)
public const byte APP_RST_PWD_TUNER = 0x62; // Reset tuner password (0x55×16 = disable + reset tables)
public const byte APP_ENCRYPT_READ = 0x63;
public const byte APP_ENCRYPT_WRITE = 0x64;
public const byte APP_RESET_SETTINGS = 0x65;
// ── App commands — Special ───────────────────────────────────────────────
public const byte APP_ERASE_ALL = 0xF0;
public const byte APP_LOCKED = 0xFF;
}
+135
View File
@@ -0,0 +1,135 @@
namespace TuneBoss.Core.Protocol;
/// <summary>
/// Hardware/firmware generation, discriminated by App_Info_Version byte.
/// </summary>
public enum GenerationType
{
Gen1 = 245, // App_Info_Version 0xF5 — legacy, APP_MEMRD_SEQ for all table ops
Gen2 = 1, // Dedicated read commands per table type; APP_UNLOCK
Gen3 = 2, // Same as Gen2 but 2D_USER uses APP_MEMRD_2D_USER; APP_UNLOCK2
}
/// <summary>
/// Per-generation command bytes and misc memory addresses resolved after
/// reading App_Info_Version from the device.
/// </summary>
public sealed class GenerationConfig
{
// ── Table read commands ──────────────────────────────────────────────────
public byte ReadCmd1D { get; init; }
public byte ReadCmd2D { get; init; }
public byte ReadCmd2DUser{ get; init; }
public byte ReadCmdSubT { get; init; }
public byte ReadCmdMisc { get; init; }
// ── Table write commands ─────────────────────────────────────────────────
public byte WriteCmd1D { get; init; }
public byte WriteCmd2D { get; init; }
public byte WriteCmd2DUser{ get; init; }
public byte WriteCmdSubT { get; init; }
public byte WriteCmdMisc { get; init; }
// ── Unlock command ───────────────────────────────────────────────────────
public byte UnlockCmd { get; init; }
// ── Misc memory addresses ────────────────────────────────────────────────
public ushort RpmLimitAddr { get; init; }
public ushort ShiftRpmLimitAddr { get; init; }
public ushort MusicModeStartAddr { get; init; }
public ushort ExtraPaddingAddr1 { get; init; }
public ushort ExtraPaddingAddr2 { get; init; }
public ushort ExtraPaddingAddr3 { get; init; }
public ushort ExtraPaddingAddr4 { get; init; }
public ushort ExtraPaddingAddr5 { get; init; }
public ushort ExtraPaddingAddr6 { get; init; }
// ── Factory ─────────────────────────────────────────────────────────────
public static GenerationConfig For(GenerationType gen) => gen switch
{
GenerationType.Gen1 => new GenerationConfig
{
ReadCmd1D = Commands.APP_MEMRD_SEQ,
ReadCmd2D = Commands.APP_MEMRD_SEQ,
ReadCmd2DUser = Commands.APP_MEMRD_SEQ,
ReadCmdSubT = Commands.APP_MEMRD_SEQ,
ReadCmdMisc = Commands.APP_MEMRD_SEQ,
WriteCmd1D = Commands.APP_MEMWR_SEQ,
WriteCmd2D = Commands.APP_MEMWR_SEQ,
WriteCmd2DUser = Commands.APP_MEMWR_SEQ,
WriteCmdSubT = Commands.APP_MEMWR_SEQ,
WriteCmdMisc = Commands.APP_MEMWR_SEQ,
UnlockCmd = Commands.APP_UNLOCK,
RpmLimitAddr = 0x0840,
ShiftRpmLimitAddr = 0x08A0,
MusicModeStartAddr = 0x090E,
ExtraPaddingAddr1 = 0x08BC,
ExtraPaddingAddr2 = 0x08C8,
ExtraPaddingAddr3 = 0x08D4,
ExtraPaddingAddr4 = 0x08E0,
ExtraPaddingAddr5 = 0x08FC,
ExtraPaddingAddr6 = 0x0918,
},
GenerationType.Gen2 => new GenerationConfig
{
ReadCmd1D = Commands.APP_MEMRD_1D,
ReadCmd2D = Commands.APP_MEMRD_2D,
ReadCmd2DUser = Commands.APP_MEMRD_2D,
ReadCmdSubT = Commands.APP_MEMRD_SUBT,
ReadCmdMisc = Commands.APP_MEMRD_MISC,
WriteCmd1D = Commands.APP_MEMWR_1D,
WriteCmd2D = Commands.APP_MEMWR_2D,
WriteCmd2DUser = Commands.APP_MEMWR_2D,
WriteCmdSubT = Commands.APP_MEMWR_SUBT,
WriteCmdMisc = Commands.APP_MEMWR_MISC,
UnlockCmd = Commands.APP_UNLOCK,
RpmLimitAddr = 0x000C,
ShiftRpmLimitAddr = 0x006C,
MusicModeStartAddr = 0x00DA,
ExtraPaddingAddr1 = 0x0088,
ExtraPaddingAddr2 = 0x0094,
ExtraPaddingAddr3 = 0x00A0,
ExtraPaddingAddr4 = 0x00AC,
ExtraPaddingAddr5 = 0x00C8,
ExtraPaddingAddr6 = 0x00E4,
},
GenerationType.Gen3 => new GenerationConfig
{
ReadCmd1D = Commands.APP_MEMRD_1D,
ReadCmd2D = Commands.APP_MEMRD_2D,
ReadCmd2DUser = Commands.APP_MEMRD_2D_USER, // ← key difference from Gen2
ReadCmdSubT = Commands.APP_MEMRD_SUBT,
ReadCmdMisc = Commands.APP_MEMRD_MISC,
WriteCmd1D = Commands.APP_MEMWR_1D,
WriteCmd2D = Commands.APP_MEMWR_2D,
WriteCmd2DUser = Commands.APP_MEMWR_2D_USER, // ← key difference from Gen2
WriteCmdSubT = Commands.APP_MEMWR_SUBT,
WriteCmdMisc = Commands.APP_MEMWR_MISC,
UnlockCmd = Commands.APP_UNLOCK2, // ← different unlock
RpmLimitAddr = 0x000C,
ShiftRpmLimitAddr = 0x006C,
MusicModeStartAddr = 0x00DA,
ExtraPaddingAddr1 = 0x0088,
ExtraPaddingAddr2 = 0x0094,
ExtraPaddingAddr3 = 0x00A0,
ExtraPaddingAddr4 = 0x00AC,
ExtraPaddingAddr5 = 0x00C8,
ExtraPaddingAddr6 = 0x00E4,
},
_ => throw new ArgumentOutOfRangeException(nameof(gen), gen, "Unknown generation")
};
/// <summary>
/// Resolves generation from the App_Info_Version byte on the wire.
/// </summary>
public static GenerationType ResolveGeneration(byte appInfoVersion) => appInfoVersion switch
{
245 => GenerationType.Gen1,
1 => GenerationType.Gen2,
2 => GenerationType.Gen3,
_ => throw new InvalidOperationException($"Unknown App_Info_Version: {appInfoVersion}")
};
}
+163
View File
@@ -0,0 +1,163 @@
namespace TuneBoss.Core.Protocol;
/// <summary>
/// Builds and parses TuneBoss BLE packets over Nordic UART Service (NUS).
///
/// Outbound frame layout (verified against debug log 17-Mar-2026):
/// [0..3] FF 00 FF 00 Preamble
/// [4] TL_type Transport layer type (TL_POSTED / TL_NONPOSTED / TL_STREAMING)
/// [5] SeqNum Sequence number (0 for streaming)
/// [6] DwCount Payload size in DWords (4-byte units)
/// [7] InvSum 0xFF - (TL_type + SeqNum + DwCount)
/// [8..] Data Command payload (DwCount × 4 bytes)
/// [last4] DataChecksum ~sum of data DWords, little-endian uint32
///
/// Total frame size = 8 (header) + DwCount×4 (data) + 4 (checksum)
/// </summary>
public static class PacketBuilder
{
private static readonly byte[] Preamble = { 0xFF, 0x00, 0xFF, 0x00 };
// ── Outbound ─────────────────────────────────────────────────────────────
/// <summary>
/// Builds a complete outbound packet.
/// </summary>
/// <param name="tlType">Transport layer type (TL_NONPOSTED, TL_STREAMING etc.)</param>
/// <param name="seqNum">Sequence number. Use 0 for streaming commands.</param>
/// <param name="data">Command payload. Will be zero-padded to DWord boundary.</param>
public static byte[] Build(byte tlType, byte seqNum, ReadOnlySpan<byte> data)
{
// Pad data to DWord boundary
int paddedLen = (data.Length + 3) & ~3;
byte[] paddedData = new byte[paddedLen];
data.CopyTo(paddedData);
byte dwCount = (byte)(paddedLen / 4);
byte invSum = ChecksumHelper.HeaderInverseSum(tlType, seqNum, dwCount);
// Total: 4 preamble + 4 header + paddedData + 4 checksum
byte[] frame = new byte[8 + paddedLen + 4];
// Preamble
frame[0] = 0xFF; frame[1] = 0x00; frame[2] = 0xFF; frame[3] = 0x00;
// Header
frame[4] = tlType;
frame[5] = seqNum;
frame[6] = dwCount;
frame[7] = invSum;
// Data
paddedData.CopyTo(frame, 8);
// Checksum
ChecksumHelper.WriteChecksumDW(paddedData, frame.AsSpan(8 + paddedLen));
return frame;
}
/// <summary>
/// Convenience: builds a TL_NONPOSTED packet with a single command byte
/// and optional parameters, auto-padded.
/// </summary>
public static byte[] BuildNonPosted(byte seqNum, byte command, ReadOnlySpan<byte> parameters = default)
{
byte[] payload = new byte[1 + parameters.Length];
payload[0] = command;
parameters.CopyTo(payload.AsSpan(1));
return Build(Commands.TL_NONPOSTED, seqNum, payload);
}
/// <summary>
/// Convenience: builds a TL_STREAMING packet (always seq=0).
/// </summary>
public static byte[] BuildStreaming(byte command)
{
return Build(Commands.TL_STREAMING, seqNum: 0, data: new[] { command });
}
/// <summary>
/// Builds an APP_MON_START (0x71) streaming packet.
/// </summary>
public static byte[] BuildMonStart() => BuildStreaming(Commands.APP_MON_START);
/// <summary>
/// Builds an APP_MON_STOP (0x72) streaming packet.
/// </summary>
public static byte[] BuildMonStop() => BuildStreaming(Commands.APP_MON_STOP);
/// <summary>
/// Builds an APP_READ_INFO (0x37) request.
/// Data = [0x37, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] — 2 DWords.
/// Verified: log line 5–7.
/// </summary>
public static byte[] BuildReadInfo(byte seqNum)
=> BuildNonPosted(seqNum, Commands.APP_READ_INFO, new byte[7]);
// ── Inbound ──────────────────────────────────────────────────────────────
/// <summary>
/// Result of parsing an inbound packet.
/// </summary>
public sealed class InboundPacket
{
public byte TlType { get; init; }
public byte SeqNum { get; init; }
public byte DwCount { get; init; }
public byte ResponseCode { get; init; } // First byte of payload (e.g. 0x51 = success)
public byte OriginalCmd { get; init; } // Second byte of payload (echoed command)
public byte[] Payload { get; init; } = Array.Empty<byte>(); // Full payload excl. checksum
public bool ChecksumValid { get; init; }
}
/// <summary>
/// Parses a raw inbound frame received over BLE.
/// Returns null if the preamble is missing or the frame is too short.
/// </summary>
public static InboundPacket? Parse(ReadOnlySpan<byte> frame)
{
// Minimum: 4 preamble + 4 header + 4 data + 4 checksum = 16 bytes
if (frame.Length < 16) return null;
// Validate preamble
if (frame[0] != 0xFF || frame[1] != 0x00 || frame[2] != 0xFF || frame[3] != 0x00)
return null;
byte tlType = frame[4];
byte seqNum = frame[5];
byte dwCount = frame[6];
// frame[7] = invSum (not validated here; add if needed)
int payloadLen = dwCount * 4;
int expectedLen = 8 + payloadLen + 4;
if (frame.Length < expectedLen) return null;
var payloadWithChecksum = frame.Slice(8, payloadLen + 4);
var payload = frame.Slice(8, payloadLen).ToArray();
bool csValid = ChecksumHelper.VerifyChecksumDW(payloadWithChecksum);
return new InboundPacket
{
TlType = tlType,
SeqNum = seqNum,
DwCount = dwCount,
ResponseCode = payload.Length > 0 ? payload[0] : (byte)0,
OriginalCmd = payload.Length > 1 ? payload[1] : (byte)0,
Payload = payload,
ChecksumValid = csValid,
};
}
// ── Diagnostics helpers ──────────────────────────────────────────────────
/// <summary>
/// Returns true if a raw frame is a diagnostics streaming packet (0x70).
/// Fast check without full parse — used in the hot receive path.
/// </summary>
public static bool IsDiagnosticsFrame(ReadOnlySpan<byte> frame)
=> frame.Length >= 9
&& frame[4] == Commands.TL_STREAMING
&& frame[8] == Commands.APP_MONITORING;
}
+15
View File
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0-windows10.0.19041.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Reactive" Version="6.0.1" />
</ItemGroup>
<ItemGroup>
<Folder Include="BLE\" />
<Folder Include="Models\" />
<Folder Include="Protocol\" />
</ItemGroup>
</Project>