Files
TuneBossPC/TuneBossPC/ViewModels/RpmSettingsViewModel.cs
T
2026-09-28 16:55:31 +08:00

257 lines
11 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using TuneBoss.Core.BLE;
using TuneBoss.Core.Models;
using TuneBossPC.Services;
namespace TuneBossPC.ViewModels;
/// <summary>
/// One adjustable RPM setting (RPM Limit / Shift Light / VVA Trigger). Values are shown
/// to the user in RPM; the ECU stores each as a single byte = RPM ÷ 100.
/// </summary>
public sealed partial class RpmSettingItem : ObservableObject
{
public const int Step = 100; // one raw unit = 100 RPM
public const int MinRpm = 5000; // legacy − buttons floor at 50 × 100
public const int ByteMaxRpm = 25500; // 255 × 100 — a single byte cannot hold more
private readonly System.Func<RpmSettingItem, System.Threading.Tasks.Task> _setAsync;
public string Title { get; }
public bool HasMaximum { get; } // whether the "Maximum" row is shown (VVA hides it)
/// <summary>Raw units subtracted for the paired recovery/off byte written alongside the
/// value (legacy: RPM Limit −1, Shift Light −2, VVA −5 → 100/200/500 RPM hysteresis).</summary>
public int RecoveryDelta { get; }
/// <summary>False when this setting isn't present on the connected unit (e.g. VVA on a non-VVA ECU).</summary>
[ObservableProperty] private bool _isAvailable = true;
[NotifyPropertyChangedFor(nameof(Ceiling))]
[ObservableProperty] private int _maxRpm; // 0 when HasMaximum == false
[ObservableProperty] private int _currentRpm;
[ObservableProperty] private int _newRpm;
public RpmSettingItem(string title, bool hasMaximum, int recoveryDelta,
System.Func<RpmSettingItem, System.Threading.Tasks.Task> setAsync)
{
Title = title;
HasMaximum = hasMaximum;
RecoveryDelta = recoveryDelta;
_setAsync = setAsync;
}
/// <summary>Upper bound for the New value — the licensed RPM cap (all three cap at it;
/// VVA just doesn't display the Maximum row), else the byte ceiling.</summary>
public int Ceiling => MaxRpm > 0 ? System.Math.Min(MaxRpm, ByteMaxRpm) : ByteMaxRpm;
/// <summary>Apply a freshly-read current value and reset the pending New value to match.</summary>
public void SetCurrent(int rpm)
{
CurrentRpm = rpm;
NewRpm = rpm;
}
[RelayCommand] private void Increment() => NewRpm = System.Math.Min(Ceiling, NewRpm + Step);
[RelayCommand] private void Decrement() => NewRpm = System.Math.Max(MinRpm, NewRpm - Step);
[RelayCommand] private System.Threading.Tasks.Task Set() => _setAsync(this);
}
/// <summary>
/// RPM Settings page — read/adjust/write the RPM Limit, Shift Light and VVA RPM Trigger.
/// Ported from the legacy WinForms "RPM Settings" tab (three Max/Current/New groups).
///
/// Each value is a single misc-Core / misc-Extended byte (RPM ÷ 100), written with a
/// targeted 1-byte write so nothing else in the block is touched (same approach as the
/// killswitch). "Set" writes to RAM (takes effect immediately); FLASH persists to flash.
/// </summary>
public sealed partial class RpmSettingsViewModel : ObservableObject
{
private readonly IBleService _ble;
private readonly ISessionService _session;
private readonly DiagnosticsStripViewModel _strip;
// ── Byte offsets within their misc block (from MiscFieldRegistry / legacy layout).
// Change here if a firmware revision moves them.
// NOTE: legacy shiftRpmLimitAddr was Core[108]; the current Gen3 registry places
// ShiftLight_On_RPM at Core[109] — verify the read-back on hardware.
private const int RpmLimitCoreOffset = 12; // Core[12] RPM_Limit_div100
private const int ShiftLightCoreOffset = 109; // Core[109] ShiftLight_On_RPM_div100
private const int VvaExtendedOffset = 124; // Extended[124] VVA_On_RPM_div100
public RpmSettingItem RpmLimit { get; }
public RpmSettingItem ShiftLight { get; }
public RpmSettingItem Vva { get; }
[ObservableProperty] private string _statusMessage = "Press READ to load current values.";
[ObservableProperty] private bool _isBusy;
[ObservableProperty] private int _flashSuccessCount;
public bool CanComms => _session.IsActive;
public RpmSettingsViewModel(IBleService ble, ISessionService session, DiagnosticsStripViewModel strip)
{
_ble = ble;
_session = session;
_strip = strip;
// recoveryDelta = raw units for the paired recovery/off byte (matches legacy).
RpmLimit = new RpmSettingItem("RPM Limit", hasMaximum: true, recoveryDelta: 1, WriteItemAsync);
ShiftLight = new RpmSettingItem("Shift Light RPM", hasMaximum: true, recoveryDelta: 2, WriteItemAsync);
Vva = new RpmSettingItem("VVA RPM Trigger", hasMaximum: false, recoveryDelta: 5, WriteItemAsync);
}
// ── Address resolvers ───────────────────────────────────────────────────────
private ushort? RpmLimitAddr => Addr(_session.Layout?.MiscCore, RpmLimitCoreOffset);
private ushort? ShiftLightAddr => Addr(_session.Layout?.MiscCore, ShiftLightCoreOffset);
private ushort? VvaAddr => Addr(_session.Layout?.MiscExtended, VvaExtendedOffset);
private static ushort? Addr(MemoryRegion? region, int offset)
=> region is { IsAvailable: true } r && r.Length > offset
? (ushort)(r.Address + offset)
: (ushort?)null;
// ── Read ─────────────────────────────────────────────────────────────────────
[RelayCommand]
private async System.Threading.Tasks.Task ReadAllAsync()
{
OnPropertyChanged(nameof(CanComms));
if (IsBusy) return;
if (!_session.IsActive || _session.Layout is null)
{
StatusMessage = "Connect to a device first.";
return;
}
IsBusy = true;
try
{
// All three cap at the licensed RPM max (legacy + buttons cap here, VVA too).
int maxRpm = (_session.Info?.UpgradeRpmMax ?? 0) * 100;
RpmLimit.MaxRpm = maxRpm;
ShiftLight.MaxRpm = maxRpm;
Vva.MaxRpm = maxRpm;
await ReadOneAsync(RpmLimit, RpmLimitAddr);
await ReadOneAsync(ShiftLight, ShiftLightAddr);
// VVA is gated by the bike model (legacy checkVvaModels / vvaModels.xml),
// and the extended byte must be reachable on this layout.
bool isVvaModel = VvaModelRegistry.IsVvaModel(
_session.Info?.BikeManufacturer ?? 0, _session.Info?.BikeModel ?? 0);
Vva.IsAvailable = isVvaModel && VvaAddr.HasValue;
if (Vva.IsAvailable) await ReadOneAsync(Vva, VvaAddr);
StatusMessage = "Current values loaded.";
}
catch (System.Exception ex) { StatusMessage = $"Read error: {ex.Message}"; }
finally { IsBusy = false; await ResumeDiagAsync(); }
}
/// <summary>
/// Targeted read of one setting. Misc read responses are [0x51][3-byte header][data…],
/// so the value sits at Payload[4] (same offset MiscValues.FromPayloads slices from).
/// Reads 2 bytes like the proven killswitch read and uses only the first.
/// </summary>
private async System.Threading.Tasks.Task ReadOneAsync(RpmSettingItem item, ushort? addr)
{
if (addr is null) { item.IsAvailable = false; return; }
var r = await _ble.ReadMiscAsync(addr.Value, 2);
if (!r.Success || r.Payload is null || r.Payload.Length < 6)
{
StatusMessage = $"{item.Title}: read failed ({r.ErrorMessage}).";
return;
}
item.IsAvailable = true;
item.SetCurrent(r.Payload[4] * 100);
}
// ── Write ────────────────────────────────────────────────────────────────────
private async System.Threading.Tasks.Task WriteItemAsync(RpmSettingItem item)
{
OnPropertyChanged(nameof(CanComms));
if (IsBusy) return;
if (!_session.IsActive)
{
StatusMessage = "Connect to a device first.";
return;
}
if (item == Vva && !Vva.IsAvailable)
{
StatusMessage = "This model does not have VVA.";
return;
}
ushort? addr = item == RpmLimit ? RpmLimitAddr
: item == ShiftLight ? ShiftLightAddr
: item == Vva ? VvaAddr
: null;
if (addr is null)
{
StatusMessage = $"{item.Title}: not available on this unit.";
return;
}
// Round to a whole 100-RPM step and clamp to [floor, licensed cap].
int rpm = System.Math.Clamp(
(int)System.Math.Round(item.NewRpm / 100.0) * 100,
RpmSettingItem.MinRpm, item.Ceiling);
byte raw = (byte)(rpm / 100);
// Paired recovery/off byte written to value+1 (legacy hysteresis: −1/−2/−5 raw).
byte recovery = (byte)System.Math.Max(0, raw - item.RecoveryDelta);
IsBusy = true;
try
{
// Targeted 2-byte write: [value, recovery/off] — leaves the surrounding
// bytes (failsafe / output-select) untouched, matching the legacy result.
var w = await _ble.WriteMiscAsync(addr.Value, new byte[] { raw, recovery });
if (!w.Success)
{
StatusMessage = $"{item.Title}: write failed ({w.ErrorMessage}).";
return;
}
await ReadOneAsync(item, addr); // read back to confirm what the ECU stored
StatusMessage = $"{item.Title} set to {item.CurrentRpm} RPM. Press FLASH to save permanently.";
}
catch (System.Exception ex) { StatusMessage = $"{item.Title}: {ex.Message}"; }
finally { IsBusy = false; await ResumeDiagAsync(); }
}
// ── Flash (persist RAM edits) ────────────────────────────────────────────────
[RelayCommand]
private async System.Threading.Tasks.Task FlashAsync()
{
if (IsBusy) return;
if (!_session.IsActive)
{
StatusMessage = "Connect to a device first.";
return;
}
IsBusy = true;
try
{
var fr = await _ble.FlashWriteAsync();
if (fr.Success) { FlashSuccessCount++; StatusMessage = "Saved to ECU flash."; }
else { StatusMessage = $"Flash failed: {fr.ErrorMessage}"; }
}
catch (System.Exception ex) { StatusMessage = $"Flash error: {ex.Message}"; }
finally { IsBusy = false; await ResumeDiagAsync(); }
}
// Misc read/write pause diagnostics at the BLE layer — resume if the strip is live
// (VM-layer resume only; never restart at the BLE layer — a duplicate MON_START storms).
private async System.Threading.Tasks.Task ResumeDiagAsync()
{
try { if (_strip.IsRunning) await _ble.StartDiagnosticsAsync(); }
catch { /* best-effort */ }
}
}