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

377 lines
15 KiB
C#

using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using TuneBoss.Core.BLE;
using TuneBoss.Core.Models;
namespace TuneBossPC.ViewModels.Tables;
// ────────────────────────────────────────────────────────────────────────────
// One bit sub-field editor (checkbox / combo / number) over a shared byte.
// ────────────────────────────────────────────────────────────────────────────
public partial class MiscBitEditorViewModel : ObservableObject
{
private readonly MiscFieldViewModel _owner;
public MiscBitField Field { get; }
private readonly int _shift;
private bool _suppress;
public string Label => Field.DisplayText; // display text (raw name stays in Field.Label)
public bool IsFlag => Field.Kind == MiscEditorKind.Flag;
public bool IsEnum => Field.Kind == MiscEditorKind.Enum;
public bool IsNumber => Field.Kind == MiscEditorKind.Number;
public string[]? Options => Field.Options;
public int Max => Field.Mask >> _shift;
public int BitIndex => _shift; // meaningful for single-bit flags
public MiscBitEditorViewModel(MiscFieldViewModel owner, MiscBitField field)
{
_owner = owner;
Field = field;
_shift = Shift(field.Mask);
RefreshFromByte();
}
[ObservableProperty] private bool _isChecked;
[ObservableProperty] private int _selectedIndex;
[ObservableProperty] private int _number;
partial void OnIsCheckedChanged(bool value) { if (!_suppress) Write(value ? 1 : 0); }
partial void OnSelectedIndexChanged(int value) { if (!_suppress && value >= 0) Write(value); }
partial void OnNumberChanged(int value) { if (!_suppress) Write(Math.Clamp(value, 0, Max)); }
private void Write(int raw)
{
var b = _owner.ByteValue;
b = (byte)((b & ~Field.Mask) | ((raw << _shift) & Field.Mask));
_owner.ByteValue = b;
_owner.OnBitChanged(this);
}
public void RefreshFromByte()
{
_suppress = true;
int raw = (_owner.ByteValue & Field.Mask) >> _shift;
if (IsFlag) IsChecked = raw != 0;
else if (IsEnum) SelectedIndex = raw;
else Number = raw;
_suppress = false;
}
private static int Shift(int mask)
{
if (mask == 0) return 0;
int s = 0;
while ((mask & 1) == 0) { mask >>= 1; s++; }
return s;
}
}
// ────────────────────────────────────────────────────────────────────────────
// One editable raw-byte field. Optionally carries a bit-field spec; when present
// it also exposes Bits (checkboxes / combos / numbers) over the same byte.
// ────────────────────────────────────────────────────────────────────────────
public partial class MiscFieldViewModel : ObservableObject
{
public MiscField Def { get; }
public MiscByteSpec? Spec { get; }
private readonly byte[] _block;
public string Label => Def.DisplayText; // display text (raw name stays in Def.Label)
public int Index => Def.Index;
public bool HasSpec => Spec != null;
public ObservableCollection<MiscBitEditorViewModel> Bits { get; } = new();
[ObservableProperty] private bool _isExpanded;
public MiscFieldViewModel(MiscField def, byte[] block, MiscByteSpec? spec = null)
{
Def = def;
_block = block;
Spec = spec;
_value = def.Index < block.Length ? block[def.Index] : 0;
if (spec != null)
foreach (var f in spec.Fields)
Bits.Add(new MiscBitEditorViewModel(this, f));
}
/// <summary>The underlying raw byte, read/written in place.</summary>
public byte ByteValue
{
get => Def.Index < _block.Length ? _block[Def.Index] : (byte)0;
set { if (Def.Index < _block.Length) _block[Def.Index] = value; }
}
[ObservableProperty] private int _value;
private bool _syncing;
partial void OnValueChanged(int value)
{
int clamped = Math.Clamp(value, 0, 255);
if (clamped != value) { Value = clamped; return; }
ByteValue = (byte)clamped;
if (!_syncing) RefreshBits();
}
/// <summary>Called after a bit edit: apply constraints, then resync siblings + raw value.</summary>
public void OnBitChanged(MiscBitEditorViewModel src)
{
if (Spec?.MutualExclusive != null)
foreach (var (a, b) in Spec.MutualExclusive)
if (BitSet(a) && BitSet(b))
SetBit(src.BitIndex == a ? b : a, false);
if (Spec?.Linked != null)
foreach (var (a, b) in Spec.Linked)
{
if (src.BitIndex == a) SetBit(b, BitSet(a));
else if (src.BitIndex == b) SetBit(a, BitSet(b));
}
RefreshBits();
_syncing = true; Value = ByteValue; _syncing = false;
}
public void RefreshBits() { foreach (var b in Bits) b.RefreshFromByte(); }
private bool BitSet(int i) => (ByteValue & (1 << i)) != 0;
private void SetBit(int i, bool on)
{
var b = ByteValue;
ByteValue = (byte)(on ? (b | (1 << i)) : (b & ~(1 << i)));
}
}
public partial class MiscSectionViewModel : ObservableObject
{
public string Label { get; init; } = string.Empty;
[ObservableProperty] private bool _isSelected;
public List<MiscFieldViewModel> Fields { get; } = new();
}
public partial class MiscBlockGroupViewModel : ObservableObject
{
public string Label { get; init; } = string.Empty;
[ObservableProperty] private bool _isExpanded = true;
public List<MiscSectionViewModel> Sections { get; } = new();
}
// ────────────────────────────────────────────────────────────────────────────
// Misc Values page
// ────────────────────────────────────────────────────────────────────────────
public partial class MiscValuesViewModel : ObservableObject, IDisposable
{
private readonly IBleService _ble;
private readonly TuneBossPC.Services.ISessionService _session;
private MiscValues? _misc;
public ObservableCollection<MiscBlockGroupViewModel> Groups { get; } = new();
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasSelection))]
private MiscSectionViewModel? _selectedSection;
public bool HasSelection => SelectedSection != null;
[ObservableProperty] private bool _isReading;
[ObservableProperty] private bool _isWriting;
/// <summary>Bumped on each confirmed flash — drives the FLASH button's green blink.</summary>
[ObservableProperty] private int _flashSuccessCount;
[ObservableProperty] private string _statusMessage = string.Empty;
public MiscValuesViewModel(IBleService ble, TuneBossPC.Services.ISessionService session)
{
_ble = ble;
_session = session;
_session.SessionChanged += () => OnPropertyChanged(nameof(CanComms));
}
/// <summary>True when hardware comms are allowed — a live session. Offline is view-only.</summary>
public bool CanComms => _session.IsActive;
[RelayCommand]
public void SelectSection(MiscSectionViewModel section)
{
if (SelectedSection != null) SelectedSection.IsSelected = false;
SelectedSection = section;
section.IsSelected = true;
}
public Task InitializeAllAsync(IProgress<string>? progress = null) => ReadAllAsync(progress);
[RelayCommand]
public Task ReadAsync() => ReadAllAsync(null);
/// <summary>ECU address of a misc block in the current layout (0 if no layout).
/// Used by the .fsr writer so each MISC section carries its real address.</summary>
public ushort RegionAddress(string blockName)
{
var l = _session.Layout;
if (l is null) return 0;
return blockName switch
{
"MiscCore" => l.MiscCore.Address,
"MiscLaunchFuel" => l.MiscLaunchFuel.Address,
"MiscLaunchFuel2" => l.MiscLaunchFuel2.Address,
"MiscAuxOut" => l.MiscAuxOut.Address,
"MiscExtended" => l.MiscExtended.Address,
_ => 0,
};
}
private async Task ReadAllAsync(IProgress<string>? progress)
{
if (!_session.HasLayout || _session.Layout is null) return;
var layout = _session.Layout;
IsReading = true;
StatusMessage = "Reading misc values…";
try
{
progress?.Report("Reading misc core…");
var core = await _ble.ReadMiscAsync(layout.MiscCore.Address, layout.MiscCore.Length);
if (!core.Success) { StatusMessage = $"Misc read failed: {core.ErrorMessage}"; return; }
byte[]? lf = await ReadBlock(layout.MiscLaunchFuel, progress, "launch fuel");
byte[]? lf2 = await ReadBlock(layout.MiscLaunchFuel2, progress, "launch fuel 2");
byte[]? ao = await ReadBlock(layout.MiscAuxOut, progress, "aux out");
byte[]? ext = await ReadBlock(layout.MiscExtended, progress, "extended");
_misc = MiscValues.FromPayloads(core.Payload, lf, lf2, ao, ext);
RebuildSections();
StatusMessage = "Misc read OK";
}
catch (Exception ex) { StatusMessage = $"Error: {ex.Message}"; }
finally { IsReading = false; }
}
private async Task<byte[]?> ReadBlock(MemoryRegion region, IProgress<string>? progress, string name)
{
if (!region.IsAvailable) return null;
progress?.Report($"Reading misc {name}…");
var r = await _ble.ReadMiscAsync(region.Address, region.Length);
return r.Success ? r.Payload : null;
}
[RelayCommand]
public async Task WriteAsync()
{
if (_misc is null || _session.Layout is null) return;
var layout = _session.Layout;
IsWriting = true;
StatusMessage = "Writing misc values…";
try
{
if (!await WriteBlock(layout.MiscCore, _misc.Core)) return;
if (!await WriteBlock(layout.MiscLaunchFuel, _misc.LaunchFuel)) return;
if (!await WriteBlock(layout.MiscLaunchFuel2, _misc.LaunchFuel2)) return;
if (!await WriteBlock(layout.MiscAuxOut, _misc.AuxOut)) return;
if (!await WriteBlock(layout.MiscExtended, _misc.Extended)) return;
StatusMessage = "Misc write OK — click Flash to make permanent";
}
catch (Exception ex) { StatusMessage = $"Error: {ex.Message}"; }
finally { IsWriting = false; }
}
private async Task<bool> WriteBlock(MemoryRegion region, byte[] data)
{
if (!region.IsAvailable || data.Length == 0) return true;
var w = await _ble.WriteMiscAsync(region.Address, data);
if (!w.Success) { StatusMessage = $"Misc write failed: {w.ErrorMessage}"; return false; }
return true;
}
[RelayCommand]
private async Task FlashAsync()
{
IsWriting = true;
StatusMessage = "Flashing to ECU…";
try
{
var fr = await _ble.FlashWriteAsync();
if (fr.Success) FlashSuccessCount++;
StatusMessage = fr.Success
? "Flash OK — settings saved to ECU"
: $"Flash failed: {fr.ErrorMessage}";
}
catch (Exception ex) { StatusMessage = $"Error: {ex.Message}"; }
finally { IsWriting = false; }
}
private void RebuildSections()
{
// Remember which section was open so a Read/refresh doesn't jump back to the top.
string? prevGroup = SelectedSection is null
? null
: Groups.FirstOrDefault(g => g.Sections.Contains(SelectedSection))?.Label;
string? prevSection = SelectedSection?.Label;
Groups.Clear();
SelectedSection = null;
if (_misc is null) return;
var groupByBlock = new Dictionary<MiscBlock, MiscBlockGroupViewModel>();
var sectionMap = new Dictionary<(MiscBlock, string), MiscSectionViewModel>();
foreach (var f in MiscFieldRegistry.All)
{
var arr = BlockArray(f.Block);
if (f.Index >= arr.Length) continue;
if (!groupByBlock.TryGetValue(f.Block, out var grp))
{
grp = new MiscBlockGroupViewModel { Label = BlockDisplay(f.Block) };
groupByBlock[f.Block] = grp;
Groups.Add(grp);
}
var key = (f.Block, f.Section);
if (!sectionMap.TryGetValue(key, out var sec))
{
sec = new MiscSectionViewModel { Label = f.Section };
sectionMap[key] = sec;
grp.Sections.Add(sec);
}
var spec = MiscBitSpecRegistry.Find(f.Block, f.Label);
sec.Fields.Add(new MiscFieldViewModel(f, arr, spec));
}
// Reselect the previously-open section if it still exists; otherwise fall back
// to the first one (initial load, or the section no longer present).
MiscSectionViewModel? restore = null;
if (prevSection != null)
restore = Groups
.Where(g => prevGroup == null || g.Label == prevGroup)
.SelectMany(g => g.Sections)
.FirstOrDefault(s => s.Label == prevSection);
var target = restore ?? Groups.SelectMany(g => g.Sections).FirstOrDefault();
if (target != null) SelectSection(target);
}
private byte[] BlockArray(MiscBlock b) => b switch
{
MiscBlock.Core => _misc!.Core,
MiscBlock.LaunchFuel => _misc!.LaunchFuel,
MiscBlock.LaunchFuel2 => _misc!.LaunchFuel2,
MiscBlock.AuxOut => _misc!.AuxOut,
MiscBlock.Extended => _misc!.Extended,
_ => Array.Empty<byte>(),
};
private static string BlockDisplay(MiscBlock b) => b switch
{
MiscBlock.Core => "Core",
MiscBlock.LaunchFuel => "Launch Fuel",
MiscBlock.LaunchFuel2 => "Launch Fuel 2",
MiscBlock.AuxOut => "Aux Out",
MiscBlock.Extended => "Extended",
_ => b.ToString(),
};
public void Dispose() { }
}