using TuneBoss.Core.Models;
using TuneBoss.Core.Protocol;
namespace TuneBoss.Core.BLE;
///
/// Represents a discovered BLE device before connection.
///
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";
}
///
/// Connection state published to observers.
///
public enum BleConnectionState
{
Disconnected,
Connecting,
Connected,
Disconnecting,
}
///
/// Result of a command sent to the device.
///
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(), message);
public static CommandResult Timeout() =>
new(false, 0x00, Array.Empty(), "Command timed out");
}
///
/// The primary BLE service contract.
/// All table and device operations go through this interface.
/// The UI layer never touches BLE APIs directly.
///
public interface IBleService : IDisposable
{
// ── State ────────────────────────────────────────────────────────────────
BleConnectionState ConnectionState { get; }
bool IsConnected { get; }
/// Observable connection state changes.
IObservable ConnectionStateChanged { get; }
// ── Scanning ─────────────────────────────────────────────────────────────
/// Starts BLE advertisement scanning. Emits discovered devices.
IObservable StartScan();
/// Stops active scan.
void StopScan();
// ── Connection ───────────────────────────────────────────────────────────
///
/// Connects to a device. Handles GATT channel opening, NUS service
/// discovery, notification subscription, and the post-connect APP_READ_INFO.
///
Task ConnectAsync(BleDeviceInfo device, CancellationToken ct = default);
/// Gracefully disconnects, stops diagnostics, cleans up GATT resources.
Task DisconnectAsync();
// ── Device info ──────────────────────────────────────────────────────────
///
/// Reads ECU info (APP_READ_INFO). Returns null on timeout or failure.
/// Also sets the active GenerationConfig internally.
///
Task ReadEcuInfoAsync(CancellationToken ct = default);
// ── Auth ─────────────────────────────────────────────────────────────────
/// Sends unlock command with password and current date.
Task UnlockAsync(string password, CancellationToken ct = default);
/// Sends tuner unlock command.
Task UnlockTunerAsync(string password, CancellationToken ct = default);
// ── Table operations ─────────────────────────────────────────────────────
///
/// Reads a 2D table (split read: two halves, with diagnostics pause/resume).
/// Returns the raw combined payload.
///
Task ReadTable2DAsync(
ushort address,
byte lengthBytes,
bool userTable = false,
CancellationToken ct = default);
/// Writes a 2D table (split write).
Task WriteTable2DAsync(
ushort address,
byte[] data,
bool userTable = false,
CancellationToken ct = default);
/// Reads a 1D table.
Task ReadTable1DAsync(
ushort address,
byte lengthBytes,
CancellationToken ct = default);
/// Writes a 1D table.
Task WriteTable1DAsync(
ushort address,
byte[] data,
CancellationToken ct = default);
/// Reads a subtable.
Task ReadSubTableAsync(
ushort address,
CancellationToken ct = default);
/// Writes a subtable.
Task WriteSubTableAsync(
ushort address,
byte[] data,
CancellationToken ct = default);
/// Reads misc values block.
Task ReadMiscAsync(
ushort address,
byte lengthBytes,
CancellationToken ct = default);
/// Writes misc values block.
Task WriteMiscAsync(
ushort address,
byte[] data,
CancellationToken ct = default);
// ── Flash ────────────────────────────────────────────────────────────────
/// Sends APP_FLASH_WR to persist all writes to ECU flash.
Task FlashWriteAsync(CancellationToken ct = default);
///
/// Writes the 4-byte first-use settings block via APP_FIRSTUSE (0x35).
/// Byte[0] (DD slot) carries the TPS-calibration-done flag.
///
Task WriteFirstUseAsync(byte[] fourBytes, CancellationToken ct = default);
// ── Diagnostics streaming ────────────────────────────────────────────────
///
/// Observable stream of diagnostics frames (APP_MONITORING 0x70).
/// Emits continuously while diagnostics are running.
///
IObservable DiagnosticsFrames { get; }
bool DiagnosticsRunning { get; }
/// Sends APP_MON_START and begins emitting DiagnosticsFrames.
Task StartDiagnosticsAsync(CancellationToken ct = default);
///
/// Sends APP_MON_STOP and waits for silence before returning.
/// Safe to call even if diagnostics aren't running.
///
Task StopDiagnosticsAsync(CancellationToken ct = default);
// ── Keepalive ────────────────────────────────────────────────────────────
///
/// Called by the keepalive timer. Sends APP_READ_INFO if idle for > 15s.
/// Internally managed — exposed for test visibility only.
///
void OnKeepaliveTimer();
}