Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ Readout is a companion app for the EEVblog 121GW multimeter over Bluetooth LE, b
- `Readout.Linux/`: the Linux head (see Linux below). `BlueZ/` is the meter connection over BlueZ; the other files fill gaps in the GTK backend.
- `Readout.Tests/`: xUnit v3 tests for the core and the MCP server (end to end with the SDK's client), plus the Linux head's `BlueZNames` and `RecentRssi`, compiled in as linked files (they must stay free of D-Bus and GTK).
- `docs/PROTOCOL.md`: the packet format. Read it before touching `Protocol/` or `Display/`.
- `Readout.Core/Fs9721/`: the decoder for Fortune FS9721_LP3 meters (a DIY Bluetooth bridge on cheap meters), written from Fortune's datasheet. Readings go through the same log, graphs and MCP tools. `firmware/fs9721-bridge/` is the ESP32 bridge (PlatformIO, NimBLE) that forwards the chip's bytes over BLE; its UUIDs and name must match `Protocol/BridgeBluetooth` (a test checks). `docs/FS9721.md` has the frame format and the plan. Tests use real frames from `Readout.Tests/TestData/fs9721-890g.txt`.
- `Readout.Core/Fs9721/`: the decoder for Fortune FS9721_LP3 meters (a DIY Bluetooth bridge on cheap meters), written from Fortune's datasheet. Readings go through the same log, graphs and MCP tools. `firmware/readout-bridge/` is the ESP32 bridge (PlatformIO, NimBLE) that forwards the chip's bytes over BLE, with a chip profile picked at build time (`fs9721-*` and `dso150-*` envs); its UUIDs, name and MTU must match `Protocol/BridgeBluetooth` (a test checks). `docs/FS9721.md` has the frame format and the plan. Tests use real frames from `Readout.Tests/TestData/fs9721-890g.txt`.
- `Readout.Core/Dso150/`: the JYE Tech DSO150 oscilloscope running DSOShell (the user's open firmware for it, in its own repo: the plan is its `docs/READOUT.md`, the wire protocol its `docs/PROTOCOL.md`). Through the bridge's two-way `dso150-*` builds: 115200 8N1, and the app writes commands to the bridge's RX characteristic with `IMeterConnection.SendAsync` (`MeterSession.SendAsync`). `Dso150Driver` is a placeholder that makes no readings yet; `BleMeterConnection` logs what a DSO150 sends (`dso150 rx ...`) until it decodes them. Bridges get MTU 247 (`RequestMtuAsync`; only Android needs the request).

The protocol is ported from the official EEVblog app's `PrivatePostRelease` branch (https://gitlab.com/eevblog/app-121gw, MIT, David Ledger), and matches EEVblog's "Revised Packet Format Blob V2" document. Its `master` branch has an obsolete 52-character text parser; ignore it. Keep the David Ledger credit in THIRD_PARTY_NOTICES.md and the About page.

Expand All @@ -38,7 +39,7 @@ dotnet build Readout -f net10.0-android
git tag v1.2.0 && git push origin v1.2.0 # release.yml: every store + a GitHub release (docs/STORE-CI.md)
dotnet build Readout.Linux # the Linux head (plain net10.0, builds on the Mac too, no workload)
./publish-linux.sh x64 arm64 # self-contained Readout-linux-<arch>.tar.gz in Readout.Linux/bin/publish/
./deploy-esp.sh # build and flash the FS9721 bridge to an ESP32 on USB (--log follows it; other builds: esp32dev-vdd, esp32c3…)
./deploy-esp.sh # build and flash the bridge to an ESP32 on USB (--log follows it; default fs9721-esp32dev, others: fs9721-esp32c3, dso150-esp32dev…)
```

## Things to know
Expand Down
10 changes: 9 additions & 1 deletion Readout.Core/Connection/IMeterConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,14 @@ public interface IMeterConnection

Task DisconnectAsync();

/// <summary>Presses one of the meter's buttons remotely.</summary>
/// <summary>Presses one of the meter's buttons remotely (the 121GW).</summary>
Task SendKeyAsync(MeterKey key, bool longPress = false, CancellationToken ct = default);

/// <summary>
/// Sends bytes to the meter as they are: a two-way bridge writes them to its chip's serial
/// input (<see cref="BridgeBluetooth.RxCharacteristicUuid"/>). Does nothing while not
/// connected.
/// </summary>
/// <exception cref="NotSupportedException">The connected meter takes no bytes (a 121GW, an FS9721 bridge).</exception>
Task SendAsync(ReadOnlyMemory<byte> data, CancellationToken ct = default);
}
5 changes: 4 additions & 1 deletion Readout.Core/Connection/IMeterDriver.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Readout.Core.Display;
using Readout.Core.Dso150;
using Readout.Core.Fs9721;

namespace Readout.Core.Connection;
Expand Down Expand Up @@ -28,7 +29,9 @@ public static class MeterDrivers
{
public static IMeterDriver For(MeterModel model) => model switch
{
MeterModel.Eevblog121Gw => new Eevblog121GwDriver(),
MeterModel.Fs9721 => new Fs9721Driver(),
_ => new Eevblog121GwDriver(),
MeterModel.Dso150 => new Dso150Driver(),
_ => throw new ArgumentOutOfRangeException(nameof(model), model, "No driver for this meter."),
};
}
10 changes: 9 additions & 1 deletion Readout.Core/Connection/MeterCapabilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,17 @@ public sealed record MeterCapabilities(bool RemoteKeys, bool ClockSync, bool Sub
/// <summary>An FS9721 through a bridge: it only sends, 3¾ digits, nothing else.</summary>
public static readonly MeterCapabilities Fs9721 = new(RemoteKeys: false, ClockSync: false, SubDisplay: false, BarGraph: false, Digits: 4);

/// <summary>
/// A DSO150 oscilloscope through a bridge: no buttons to press (it takes commands instead),
/// no clock, no LCD extras. Its measurements come from an 8-bit ADC, so 4 digits is plenty.
/// </summary>
public static readonly MeterCapabilities Dso150 = new(RemoteKeys: false, ClockSync: false, SubDisplay: false, BarGraph: false, Digits: 4);

public static MeterCapabilities For(MeterModel model) => model switch
{
MeterModel.Eevblog121Gw => Eevblog121Gw,
MeterModel.Fs9721 => Fs9721,
_ => Eevblog121Gw,
MeterModel.Dso150 => Dso150,
_ => throw new ArgumentOutOfRangeException(nameof(model), model, "No capabilities for this meter."),
};
}
4 changes: 4 additions & 0 deletions Readout.Core/Connection/MeterSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,10 @@ public Task SendKeyAsync(MeterKey key, bool longPress = false, CancellationToken
return Active.SendKeyAsync(key, longPress, ct);
}

/// <summary>Sends bytes to the connected meter as they are (a DSO150's commands); see <see cref="IMeterConnection.SendAsync"/>.</summary>
public Task SendAsync(ReadOnlyMemory<byte> data, CancellationToken ct = default) =>
Active.State == ConnectionState.Connected ? Active.SendAsync(data, ct) : Task.CompletedTask;

private async Task LeaveDemoAsync()
{
if (!IsDemo) return;
Expand Down
14 changes: 14 additions & 0 deletions Readout.Core/Connection/SimulatedMeterConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ public sealed class SimulatedMeterConnection : IMeterConnection, IDisposable
/// <summary>A key press reached the simulated meter (for tests).</summary>
public event EventHandler<MeterKey>? KeySent;

/// <summary>Bytes sent with <see cref="SendAsync"/> reached the simulated meter (for tests).</summary>
public event EventHandler<ReadOnlyMemory<byte>>? DataSent;

public ConnectionState State { get; private set; }
public DiscoveredMeter? Meter { get; private set; }

Expand Down Expand Up @@ -99,6 +102,17 @@ public Task SendKeyAsync(MeterKey key, bool longPress = false, CancellationToken
return Task.CompletedTask;
}

/// <summary>
/// The demo meter takes the bytes and ignores them: it plays a 121GW, which answers only key
/// presses. A simulated DSO150 will answer them.
/// </summary>
public Task SendAsync(ReadOnlyMemory<byte> data, CancellationToken ct = default)
{
if (State == ConnectionState.Connected && !data.IsEmpty)
DataSent?.Invoke(this, data.ToArray());
return Task.CompletedTask;
}

/// <summary>Makes the next packet arrive now (tests drive the meter with this instead of waiting).</summary>
public void Tick()
{
Expand Down
5 changes: 5 additions & 0 deletions Readout.Core/Display/MeterReading.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ public enum MeterModel
Eevblog121Gw,
/// <summary>A meter built on Fortune's FS9721_LP3 chip, through a DIY Bluetooth bridge.</summary>
Fs9721,
/// <summary>
/// A JYE Tech DSO150 pocket oscilloscope running DSOShell, through the two-way bridge. Its
/// protocol is text lines and binary waveform blocks (DSOShell's docs/PROTOCOL.md).
/// </summary>
Dso150,
}

/// <summary>Everything the meter's LCD shows for one packet or frame, decoded for display and logging.</summary>
Expand Down
25 changes: 25 additions & 0 deletions Readout.Core/Dso150/Dso150Driver.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Readout.Core.Connection;
using Readout.Core.Display;

namespace Readout.Core.Dso150;

/// <summary>
/// A DSO150 oscilloscope running DSOShell, through the two-way bridge. For now it only takes the
/// bytes and makes no readings: decoding <c>MEAS</c> records into readings (and waveforms after
/// that) is the next step. It exists so a DSO150 gets its own driver, never the 121GW's.
/// </summary>
public sealed class Dso150Driver : IMeterDriver
{
public MeterModel Model => MeterModel.Dso150;

/// <summary>Bytes received since the last <see cref="Reset"/>.</summary>
public long BytesReceived { get; private set; }

public IReadOnlyList<DriverReading> Receive(ReadOnlySpan<byte> data, DateTimeOffset now)
{
BytesReceived += data.Length;
return [];
}

public void Reset() => BytesReceived = 0;
}
24 changes: 18 additions & 6 deletions Readout.Core/Protocol/BridgeBluetooth.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
namespace Readout.Core.Protocol;

/// <summary>
/// How a Readout bridge shows up over Bluetooth LE: an ESP32 that reads a meter chip's serial
/// output and forwards the bytes as they come (firmware in <c>firmware/fs9721-bridge</c>).
/// The app frames and decodes them, so supporting another chip needs no firmware change.
/// How a Readout bridge shows up over Bluetooth LE: an ESP32 wired to a meter chip's serial port
/// that forwards the bytes as they come (firmware in <c>firmware/readout-bridge</c>). The app
/// frames and decodes them, so supporting another chip needs no change to what the bridge does
/// with the bytes. Two-way bridges (the DSO150's) also pass what the app writes to the chip.
/// </summary>
public static class BridgeBluetooth
{
Expand All @@ -16,11 +17,17 @@ public static class BridgeBluetooth
public static readonly Guid DataCharacteristicUuid = Guid.Parse("4D19A30C-94D7-404E-A69D-B513188F13DC");

/// <summary>
/// Readable text, one <c>key=value</c> per line: <c>chip</c> (FS9721), <c>symbols</c> (the
/// meter's maker-chosen symbols, comma separated) and <c>firmware</c>.
/// Readable text, one <c>key=value</c> per line: <c>chip</c> (FS9721, DSO150), <c>symbols</c>
/// (an FS9721 meter's maker-chosen symbols, comma separated), <c>baud</c> and <c>firmware</c>.
/// </summary>
public static readonly Guid InfoCharacteristicUuid = Guid.Parse("6DAA6868-77CD-4539-8B02-6A82B3C6BC0C");

/// <summary>
/// Writable (with or without response) on two-way bridges only: the bytes go out the chip's
/// serial input unchanged. Receive-only bridges (FS9721) don't have it.
/// </summary>
public static readonly Guid RxCharacteristicUuid = Guid.Parse("3065C3CA-B78A-4B98-96B6-280CF0784EC4");

/// <summary>Bridges advertise as "Readout &lt;chip&gt; &lt;id&gt;", for example "Readout FS9721 A1B2".</summary>
public const string NamePrefix = "Readout ";

Expand All @@ -30,6 +37,11 @@ public static class BridgeBluetooth
if (string.IsNullOrEmpty(name) || !name.StartsWith(NamePrefix, StringComparison.OrdinalIgnoreCase))
return null;
var chip = name[NamePrefix.Length..].Split(' ', 2)[0];
return chip.Equals("FS9721", StringComparison.OrdinalIgnoreCase) ? MeterModel.Fs9721 : null;
if (chip.Equals("FS9721", StringComparison.OrdinalIgnoreCase)) return MeterModel.Fs9721;
if (chip.Equals("DSO150", StringComparison.OrdinalIgnoreCase)) return MeterModel.Dso150;
return null;
}

/// <summary>The ATT MTU the app and the bridge ask for: 244-byte notifications instead of 20.</summary>
public const int PreferredMtu = 247;
}
36 changes: 33 additions & 3 deletions Readout.Linux/BlueZ/BlueZMeterConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,10 @@ internal sealed class BlueZMeterConnection : IMeterConnection, IDisposable
private string? _devicePath;
private string? _dataPath;
private string _writeType = "request";
// A two-way bridge's RX characteristic (the DSO150's), where SendAsync writes.
private string? _rxPath;
private readonly SemaphoreSlim _writeGate = new(1, 1);
private const int MaxWriteLength = 512;

public BlueZMeterConnection(BlueZBus bus, ILogger<BlueZMeterConnection> logger)
{
Expand Down Expand Up @@ -231,7 +235,8 @@ private async Task ConnectCoreAsync(DiscoveredMeter meter, CancellationToken ct)
while (!await ServicesResolvedAsync(devicePath).ConfigureAwait(false))
await Task.Delay(100, ct).ConfigureAwait(false);

var data = BlueZNames.PickDataCharacteristic(await CharacteristicsAsync(devicePath).ConfigureAwait(false))
var characteristics = await CharacteristicsAsync(devicePath).ConfigureAwait(false);
var data = BlueZNames.PickDataCharacteristic(characteristics)
?? throw new InvalidOperationException("This device has no meter data characteristic.");
if (!BlueZNames.IsKnownDataCharacteristic(data.Uuid))
_logger.LogWarning("data characteristic not found by UUID, using {Uuid}", data.Uuid);
Expand All @@ -240,6 +245,7 @@ private async Task ConnectCoreAsync(DiscoveredMeter meter, CancellationToken ct)
{
_dataPath = data.Path;
_writeType = BlueZNames.WriteType(data.Flags);
_rxPath = BlueZNames.PickRxCharacteristic(characteristics)?.Path;
}
await _bus.CallAsync(data.Path, BlueZNames.GattCharacteristic1, "StartNotify").WaitAsync(ct).ConfigureAwait(false);

Expand Down Expand Up @@ -370,13 +376,37 @@ public async Task SendKeyAsync(MeterKey key, bool longPress = false, Cancellatio
await _bus.WriteValueAsync(dataPath, MeterCommands.KeyPress(key, longPress), writeType).WaitAsync(ct).ConfigureAwait(false);
}

public async Task SendAsync(ReadOnlyMemory<byte> data, CancellationToken ct = default)
{
string? rxPath;
lock (_gate) rxPath = _dataPath is null ? null : _rxPath ?? "";
if (rxPath is null || data.IsEmpty) return;
if (rxPath.Length == 0) throw new NotSupportedException($"{Meter?.Name ?? "This meter"} takes no data.");

// In order, one at a time. A write request longer than the MTU allows goes as a long
// write, which BlueZ splits up; one attribute holds at most 512 bytes.
await _writeGate.WaitAsync(ct).ConfigureAwait(false);
try
{
for (var offset = 0; offset < data.Length; offset += MaxWriteLength)
{
var chunk = data.Slice(offset, Math.Min(MaxWriteLength, data.Length - offset)).ToArray();
await _bus.WriteValueAsync(rxPath, chunk, "request").WaitAsync(ct).ConfigureAwait(false);
}
}
finally
{
_writeGate.Release();
}
}

private async Task CloseLinkAsync()
{
string? devicePath, dataPath;
lock (_gate)
{
(devicePath, dataPath) = (_devicePath, _dataPath);
_devicePath = _dataPath = null;
_devicePath = _dataPath = _rxPath = null;
}
_rssi.Clear();

Expand Down Expand Up @@ -461,7 +491,7 @@ private void OnDeviceChanged(string path, string address, Props changed, string[
private void OnLinkDropped()
{
_logger.LogWarning("link lost");
lock (_gate) _devicePath = _dataPath = null;
lock (_gate) _devicePath = _dataPath = _rxPath = null;
_rssi.Clear();
Meter = null;
SetState(ConnectionState.Disconnected);
Expand Down
4 changes: 4 additions & 0 deletions Readout.Linux/BlueZ/BlueZNames.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ public static bool IsLeOnly(string? addressType, byte[]? advertisingFlags) =>
!(Guid.TryParse(c.ServiceUuid, out var service) && MeterBluetooth.StandardServices.Contains(service)));
}

/// <summary>A two-way bridge's RX characteristic, where commands for its chip go; null on other meters.</summary>
public static GattCharacteristicInfo? PickRxCharacteristic(IEnumerable<GattCharacteristicInfo> characteristics) =>
characteristics.FirstOrDefault(c => Guid.TryParse(c.Uuid, out var id) && id == BridgeBluetooth.RxCharacteristicUuid);

/// <summary>
/// WriteValue's "type": a write request (acknowledged) when the characteristic takes one,
/// else a write command.
Expand Down
7 changes: 6 additions & 1 deletion Readout.Mcp/MeterTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,12 @@ public Task<string> GetStatusAsync() => ui.InvokeAsync(() =>
return McpResultJson.Serialize(new StatusResult(
session.State.ToString(),
session.Meter?.Name,
session.Model == MeterModel.Fs9721 ? "FS9721" : "121GW",
session.Model switch
{
MeterModel.Fs9721 => "FS9721",
MeterModel.Dso150 => "DSO150",
_ => "121GW",
},
session.Capabilities.RemoteKeys,
session.IsDemo,
rssi,
Expand Down
20 changes: 20 additions & 0 deletions Readout.Tests/BlueZTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ public void MeterName_ComesFromTheNameOrAlias(string? name, string? alias, strin
[InlineData("121GW", MeterModel.Eevblog121Gw)]
[InlineData("Bluegiga", MeterModel.Eevblog121Gw)]
[InlineData("Readout FS9721 B1CC", MeterModel.Fs9721)]
[InlineData("Readout DSO150 B1CC", MeterModel.Dso150)]
public void Model_ComesFromTheName(string name, MeterModel model) =>
Assert.Equal(model, BlueZNames.ModelFromName(name));

Expand All @@ -69,6 +70,25 @@ public void BridgeDataCharacteristic_IsFoundByUuid()
Assert.Equal(Device + "/service0010/char0013", picked?.Path);
}

[Fact]
public void TwoWayBridge_RxCharacteristic_IsFoundByUuid()
{
GattCharacteristicInfo[] characteristics =
[
new(Device + "/service0010/char0011", BridgeBluetooth.ServiceUuid.ToString(), BridgeBluetooth.DataCharacteristicUuid.ToString(), ["notify"]),
new(Device + "/service0010/char0016", BridgeBluetooth.ServiceUuid.ToString(), BridgeBluetooth.RxCharacteristicUuid.ToString().ToUpperInvariant(), ["write", "write-without-response"]),
];

Assert.Equal(Device + "/service0010/char0016", BlueZNames.PickRxCharacteristic(characteristics)?.Path);
// Data is still the notifying one, not the writable one.
Assert.Equal(Device + "/service0010/char0011", BlueZNames.PickDataCharacteristic(characteristics)?.Path);
}

[Fact]
public void ReceiveOnlyBridge_HasNoRxCharacteristic() =>
Assert.Null(BlueZNames.PickRxCharacteristic(
[new(Device + "/service0010/char0013", BridgeBluetooth.ServiceUuid.ToString(), BridgeBluetooth.DataCharacteristicUuid.ToString(), ["notify"])]));

[Fact]
public void DataCharacteristic_IsFoundByUuid_InAnyCase()
{
Expand Down
Loading
Loading