Initial Commit
This commit is contained in:
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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)}.");
|
||||
}
|
||||
}
|
||||
@@ -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)..]);
|
||||
}
|
||||
}
|
||||
@@ -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__<24 wire bytes>____</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__<bytes>____</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;
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user