From 778219e5b70a97688ad2cf1f190258db574da338 Mon Sep 17 00:00:00 2001 From: Alejandro Mora Date: Tue, 10 Nov 2026 09:29:09 -0500 Subject: [PATCH 1/2] feat(bridge): two-way DSO150 bridge profile and app-side send The ESP32 bridge (renamed firmware/readout-bridge) now picks its chip at build time: FS9721 (unchanged: receive-only, 2400 baud, deep sleep) and DSO150 (two-way UART at 115200 8N1, direct 3.3 V wiring, never sleeps). Envs per chip and board: fs9721-esp32dev(-vdd), fs9721-esp32c3(-vdd), dso150-esp32dev, dso150-esp32c3. - New RX characteristic (write, write without response) whose bytes go out the UART unchanged; info reports chip and baud; advertises as "Readout DSO150 XXXX" with the same advertising layout. - MTU 247, notifications sized to the negotiated MTU less 3, flushed on a full chunk or a short gap; retries on NimBLE ENOMEM, 4 KB UART buffer and a 15-30 ms connection interval for waveform throughput. - Core: MeterModel.Dso150, MeterCapabilities.Dso150, a placeholder Dso150Driver (no readings yet), and explicit driver and capability switches so no model falls through to the 121GW's. - IMeterConnection.SendAsync (and MeterSession.SendAsync) writes to a bridge's RX characteristic: Plugin.BLE, BlueZ and the simulated meter. - Bridges get MTU 247 after connecting (logged); DSO150 notifications are logged as text until its driver decodes them. - Bridge README: DSO150 wiring and power, a milestone-0 hardware test, throughput notes and the open SYST:BAUD vs fixed 921600 decision. Co-Authored-By: Claude Opus 5.5 --- Readout.Core/Connection/IMeterConnection.cs | 10 +- Readout.Core/Connection/IMeterDriver.cs | 5 +- Readout.Core/Connection/MeterCapabilities.cs | 10 +- Readout.Core/Connection/MeterSession.cs | 4 + .../Connection/SimulatedMeterConnection.cs | 14 + Readout.Core/Display/MeterReading.cs | 5 + Readout.Core/Dso150/Dso150Driver.cs | 25 ++ Readout.Core/Protocol/BridgeBluetooth.cs | 24 +- Readout.Linux/BlueZ/BlueZMeterConnection.cs | 36 +- Readout.Linux/BlueZ/BlueZNames.cs | 4 + Readout.Mcp/MeterTools.cs | 7 +- Readout.Tests/BlueZTests.cs | 20 + Readout.Tests/BridgeBluetoothTests.cs | 30 +- Readout.Tests/Dso150Tests.cs | 82 ++++ Readout.Tests/MeterSessionTests.cs | 40 ++ Readout/Services/BleMeterConnection.cs | 84 +++- deploy-esp.sh | 12 +- firmware/fs9721-bridge/README.md | 162 ------- firmware/fs9721-bridge/platformio.ini | 67 --- firmware/fs9721-bridge/src/main.cpp | 266 ------------ .../.gitignore | 0 firmware/readout-bridge/README.md | 287 ++++++++++++ firmware/readout-bridge/platformio.ini | 92 ++++ firmware/readout-bridge/src/main.cpp | 410 ++++++++++++++++++ 24 files changed, 1177 insertions(+), 519 deletions(-) create mode 100644 Readout.Core/Dso150/Dso150Driver.cs create mode 100644 Readout.Tests/Dso150Tests.cs delete mode 100644 firmware/fs9721-bridge/README.md delete mode 100644 firmware/fs9721-bridge/platformio.ini delete mode 100644 firmware/fs9721-bridge/src/main.cpp rename firmware/{fs9721-bridge => readout-bridge}/.gitignore (100%) create mode 100644 firmware/readout-bridge/README.md create mode 100644 firmware/readout-bridge/platformio.ini create mode 100644 firmware/readout-bridge/src/main.cpp diff --git a/Readout.Core/Connection/IMeterConnection.cs b/Readout.Core/Connection/IMeterConnection.cs index 5baad07..6bd730f 100644 --- a/Readout.Core/Connection/IMeterConnection.cs +++ b/Readout.Core/Connection/IMeterConnection.cs @@ -53,6 +53,14 @@ public interface IMeterConnection Task DisconnectAsync(); - /// Presses one of the meter's buttons remotely. + /// Presses one of the meter's buttons remotely (the 121GW). Task SendKeyAsync(MeterKey key, bool longPress = false, CancellationToken ct = default); + + /// + /// Sends bytes to the meter as they are: a two-way bridge writes them to its chip's serial + /// input (). Does nothing while not + /// connected. + /// + /// The connected meter takes no bytes (a 121GW, an FS9721 bridge). + Task SendAsync(ReadOnlyMemory data, CancellationToken ct = default); } diff --git a/Readout.Core/Connection/IMeterDriver.cs b/Readout.Core/Connection/IMeterDriver.cs index 7f8d2fe..82c50a3 100644 --- a/Readout.Core/Connection/IMeterDriver.cs +++ b/Readout.Core/Connection/IMeterDriver.cs @@ -1,4 +1,5 @@ using Readout.Core.Display; +using Readout.Core.Dso150; using Readout.Core.Fs9721; namespace Readout.Core.Connection; @@ -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."), }; } diff --git a/Readout.Core/Connection/MeterCapabilities.cs b/Readout.Core/Connection/MeterCapabilities.cs index 2683924..3219b93 100644 --- a/Readout.Core/Connection/MeterCapabilities.cs +++ b/Readout.Core/Connection/MeterCapabilities.cs @@ -15,9 +15,17 @@ public sealed record MeterCapabilities(bool RemoteKeys, bool ClockSync, bool Sub /// An FS9721 through a bridge: it only sends, 3¾ digits, nothing else. public static readonly MeterCapabilities Fs9721 = new(RemoteKeys: false, ClockSync: false, SubDisplay: false, BarGraph: false, Digits: 4); + /// + /// 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. + /// + 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."), }; } diff --git a/Readout.Core/Connection/MeterSession.cs b/Readout.Core/Connection/MeterSession.cs index e4e070c..93698b7 100644 --- a/Readout.Core/Connection/MeterSession.cs +++ b/Readout.Core/Connection/MeterSession.cs @@ -190,6 +190,10 @@ public Task SendKeyAsync(MeterKey key, bool longPress = false, CancellationToken return Active.SendKeyAsync(key, longPress, ct); } + /// Sends bytes to the connected meter as they are (a DSO150's commands); see . + public Task SendAsync(ReadOnlyMemory data, CancellationToken ct = default) => + Active.State == ConnectionState.Connected ? Active.SendAsync(data, ct) : Task.CompletedTask; + private async Task LeaveDemoAsync() { if (!IsDemo) return; diff --git a/Readout.Core/Connection/SimulatedMeterConnection.cs b/Readout.Core/Connection/SimulatedMeterConnection.cs index 33227f0..a8f9a8f 100644 --- a/Readout.Core/Connection/SimulatedMeterConnection.cs +++ b/Readout.Core/Connection/SimulatedMeterConnection.cs @@ -29,6 +29,9 @@ public sealed class SimulatedMeterConnection : IMeterConnection, IDisposable /// A key press reached the simulated meter (for tests). public event EventHandler? KeySent; + /// Bytes sent with reached the simulated meter (for tests). + public event EventHandler>? DataSent; + public ConnectionState State { get; private set; } public DiscoveredMeter? Meter { get; private set; } @@ -99,6 +102,17 @@ public Task SendKeyAsync(MeterKey key, bool longPress = false, CancellationToken return Task.CompletedTask; } + /// + /// The demo meter takes the bytes and ignores them: it plays a 121GW, which answers only key + /// presses. A simulated DSO150 will answer them. + /// + public Task SendAsync(ReadOnlyMemory data, CancellationToken ct = default) + { + if (State == ConnectionState.Connected && !data.IsEmpty) + DataSent?.Invoke(this, data.ToArray()); + return Task.CompletedTask; + } + /// Makes the next packet arrive now (tests drive the meter with this instead of waiting). public void Tick() { diff --git a/Readout.Core/Display/MeterReading.cs b/Readout.Core/Display/MeterReading.cs index bc5a70e..7b1e067 100644 --- a/Readout.Core/Display/MeterReading.cs +++ b/Readout.Core/Display/MeterReading.cs @@ -9,6 +9,11 @@ public enum MeterModel Eevblog121Gw, /// A meter built on Fortune's FS9721_LP3 chip, through a DIY Bluetooth bridge. Fs9721, + /// + /// 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). + /// + Dso150, } /// Everything the meter's LCD shows for one packet or frame, decoded for display and logging. diff --git a/Readout.Core/Dso150/Dso150Driver.cs b/Readout.Core/Dso150/Dso150Driver.cs new file mode 100644 index 0000000..de201e7 --- /dev/null +++ b/Readout.Core/Dso150/Dso150Driver.cs @@ -0,0 +1,25 @@ +using Readout.Core.Connection; +using Readout.Core.Display; + +namespace Readout.Core.Dso150; + +/// +/// A DSO150 oscilloscope running DSOShell, through the two-way bridge. For now it only takes the +/// bytes and makes no readings: decoding MEAS records into readings (and waveforms after +/// that) is the next step. It exists so a DSO150 gets its own driver, never the 121GW's. +/// +public sealed class Dso150Driver : IMeterDriver +{ + public MeterModel Model => MeterModel.Dso150; + + /// Bytes received since the last . + public long BytesReceived { get; private set; } + + public IReadOnlyList Receive(ReadOnlySpan data, DateTimeOffset now) + { + BytesReceived += data.Length; + return []; + } + + public void Reset() => BytesReceived = 0; +} diff --git a/Readout.Core/Protocol/BridgeBluetooth.cs b/Readout.Core/Protocol/BridgeBluetooth.cs index aa18e94..25d2d07 100644 --- a/Readout.Core/Protocol/BridgeBluetooth.cs +++ b/Readout.Core/Protocol/BridgeBluetooth.cs @@ -3,9 +3,10 @@ namespace Readout.Core.Protocol; /// -/// 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 firmware/fs9721-bridge). -/// 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 firmware/readout-bridge). 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. /// public static class BridgeBluetooth { @@ -16,11 +17,17 @@ public static class BridgeBluetooth public static readonly Guid DataCharacteristicUuid = Guid.Parse("4D19A30C-94D7-404E-A69D-B513188F13DC"); /// - /// Readable text, one key=value per line: chip (FS9721), symbols (the - /// meter's maker-chosen symbols, comma separated) and firmware. + /// Readable text, one key=value per line: chip (FS9721, DSO150), symbols + /// (an FS9721 meter's maker-chosen symbols, comma separated), baud and firmware. /// public static readonly Guid InfoCharacteristicUuid = Guid.Parse("6DAA6868-77CD-4539-8B02-6A82B3C6BC0C"); + /// + /// 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. + /// + public static readonly Guid RxCharacteristicUuid = Guid.Parse("3065C3CA-B78A-4B98-96B6-280CF0784EC4"); + /// Bridges advertise as "Readout <chip> <id>", for example "Readout FS9721 A1B2". public const string NamePrefix = "Readout "; @@ -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; } + + /// The ATT MTU the app and the bridge ask for: 244-byte notifications instead of 20. + public const int PreferredMtu = 247; } diff --git a/Readout.Linux/BlueZ/BlueZMeterConnection.cs b/Readout.Linux/BlueZ/BlueZMeterConnection.cs index 7672306..894ba3d 100644 --- a/Readout.Linux/BlueZ/BlueZMeterConnection.cs +++ b/Readout.Linux/BlueZ/BlueZMeterConnection.cs @@ -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 logger) { @@ -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); @@ -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); @@ -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 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(); @@ -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); diff --git a/Readout.Linux/BlueZ/BlueZNames.cs b/Readout.Linux/BlueZ/BlueZNames.cs index fef4f12..1dcde66 100644 --- a/Readout.Linux/BlueZ/BlueZNames.cs +++ b/Readout.Linux/BlueZ/BlueZNames.cs @@ -93,6 +93,10 @@ public static bool IsLeOnly(string? addressType, byte[]? advertisingFlags) => !(Guid.TryParse(c.ServiceUuid, out var service) && MeterBluetooth.StandardServices.Contains(service))); } + /// A two-way bridge's RX characteristic, where commands for its chip go; null on other meters. + public static GattCharacteristicInfo? PickRxCharacteristic(IEnumerable characteristics) => + characteristics.FirstOrDefault(c => Guid.TryParse(c.Uuid, out var id) && id == BridgeBluetooth.RxCharacteristicUuid); + /// /// WriteValue's "type": a write request (acknowledged) when the characteristic takes one, /// else a write command. diff --git a/Readout.Mcp/MeterTools.cs b/Readout.Mcp/MeterTools.cs index cba515b..0ae5543 100644 --- a/Readout.Mcp/MeterTools.cs +++ b/Readout.Mcp/MeterTools.cs @@ -114,7 +114,12 @@ public Task 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, diff --git a/Readout.Tests/BlueZTests.cs b/Readout.Tests/BlueZTests.cs index c988be8..5792242 100644 --- a/Readout.Tests/BlueZTests.cs +++ b/Readout.Tests/BlueZTests.cs @@ -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)); @@ -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() { diff --git a/Readout.Tests/BridgeBluetoothTests.cs b/Readout.Tests/BridgeBluetoothTests.cs index 663b892..6de400d 100644 --- a/Readout.Tests/BridgeBluetoothTests.cs +++ b/Readout.Tests/BridgeBluetoothTests.cs @@ -9,21 +9,35 @@ public class BridgeBluetoothTests [InlineData("Readout FS9721 A1B2", MeterModel.Fs9721)] [InlineData("readout fs9721 00FF", MeterModel.Fs9721)] [InlineData("Readout FS9721", MeterModel.Fs9721)] + [InlineData("Readout DSO150 A1B2", MeterModel.Dso150)] + [InlineData("readout dso150 00ff", MeterModel.Dso150)] public void ModelFromName_Bridge_IsItsChip(string name, MeterModel model) => Assert.Equal(model, BridgeBluetooth.ModelFromName(name)); [Theory] [InlineData("121GW")] [InlineData("Readout ES51922 A1B2")] + [InlineData("Readout DSO1501 A1B2")] + [InlineData("DSO150")] [InlineData("Readout")] [InlineData("")] [InlineData(null)] public void ModelFromName_NotAKnownBridge_IsNull(string? name) => Assert.Null(BridgeBluetooth.ModelFromName(name)); + [Theory] + [InlineData("Readout FS9721 A1B2")] + [InlineData("Readout DSO150 A1B2")] + public void BridgeNames_AreNotTakenFor121GWs(string name) => + Assert.False(MeterBluetooth.IsMeterName(name)); + [Fact] - public void BridgeNames_AreNotTakenFor121GWs() => - Assert.False(MeterBluetooth.IsMeterName("Readout FS9721 A1B2")); + public void Uuids_AreDistinct() + { + Guid[] uuids = [BridgeBluetooth.ServiceUuid, BridgeBluetooth.DataCharacteristicUuid, BridgeBluetooth.InfoCharacteristicUuid, + BridgeBluetooth.RxCharacteristicUuid, MeterBluetooth.DataCharacteristicUuid]; + Assert.Equal(uuids.Length, uuids.Distinct().Count()); + } [Fact] public void Firmware_UsesTheSameUuids() @@ -33,10 +47,18 @@ public void Firmware_UsesTheSameUuids() while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "Readout.slnx"))) dir = dir.Parent; Assert.NotNull(dir); - var firmware = File.ReadAllText(Path.Combine(dir.FullName, "firmware", "fs9721-bridge", "src", "main.cpp")); + var firmware = File.ReadAllText(Path.Combine(dir.FullName, "firmware", "readout-bridge", "src", "main.cpp")); - foreach (var uuid in new[] { BridgeBluetooth.ServiceUuid, BridgeBluetooth.DataCharacteristicUuid, BridgeBluetooth.InfoCharacteristicUuid }) + foreach (var uuid in new[] { BridgeBluetooth.ServiceUuid, BridgeBluetooth.DataCharacteristicUuid, BridgeBluetooth.InfoCharacteristicUuid, BridgeBluetooth.RxCharacteristicUuid }) Assert.Contains(uuid.ToString(), firmware, StringComparison.OrdinalIgnoreCase); Assert.Contains("\"Readout %s %02X%02X\"", firmware, StringComparison.Ordinal); + + // Every chip it builds for is one the app recognises by name. + foreach (var chip in new[] { "FS9721", "DSO150" }) + { + Assert.Contains($"#define CHIP_NAME \"{chip}\"", firmware, StringComparison.Ordinal); + Assert.NotNull(BridgeBluetooth.ModelFromName($"Readout {chip} A1B2")); + } + Assert.Contains($"PREFERRED_MTU = {BridgeBluetooth.PreferredMtu};", firmware, StringComparison.Ordinal); } } diff --git a/Readout.Tests/Dso150Tests.cs b/Readout.Tests/Dso150Tests.cs new file mode 100644 index 0000000..b708f1f --- /dev/null +++ b/Readout.Tests/Dso150Tests.cs @@ -0,0 +1,82 @@ +using Readout.Core.Connection; +using Readout.Core.Display; +using Readout.Core.Dso150; +using Readout.Core.Fs9721; +using Microsoft.Extensions.Time.Testing; + +namespace Readout.Tests; + +public class Dso150Tests +{ + private static readonly DateTimeOffset Now = new(2026, 11, 7, 12, 0, 0, TimeSpan.Zero); + + [Fact] + public void Driver_TakesBytes_AndMakesNoReadings() + { + var driver = new Dso150Driver(); + + Assert.Equal(MeterModel.Dso150, driver.Model); + Assert.Empty(driver.Receive("DSOShell,DSO150,1234,0.1\n"u8, Now)); + Assert.Empty(driver.Receive("EVT:KEY,down=0x01,up=0x00\n"u8, Now)); + Assert.Equal(51, driver.BytesReceived); + + driver.Reset(); + Assert.Equal(0, driver.BytesReceived); + } + + [Theory] + [InlineData(MeterModel.Eevblog121Gw, typeof(Eevblog121GwDriver))] + [InlineData(MeterModel.Fs9721, typeof(Fs9721Driver))] + [InlineData(MeterModel.Dso150, typeof(Dso150Driver))] + public void EachModel_GetsItsOwnDriver(MeterModel model, Type driver) + { + var picked = MeterDrivers.For(model); + Assert.IsType(driver, picked); + Assert.Equal(model, picked.Model); + } + + [Fact] + public void EveryModel_HasADriverAndCapabilities() + { + // A new model must be added to both switches, not fall through to the 121GW's. + foreach (var model in Enum.GetValues()) + { + Assert.Equal(model, MeterDrivers.For(model).Model); + Assert.NotNull(MeterCapabilities.For(model)); + } + } + + [Fact] + public void UnknownModel_IsRefused() + { + Assert.Throws(() => MeterDrivers.For((MeterModel)99)); + Assert.Throws(() => MeterCapabilities.For((MeterModel)99)); + } + + [Fact] + public void Capabilities_NoKeysClockOrLcdExtras() + { + var caps = MeterCapabilities.For(MeterModel.Dso150); + + Assert.Same(MeterCapabilities.Dso150, caps); + Assert.False(caps.RemoteKeys); + Assert.False(caps.ClockSync); + Assert.False(caps.SubDisplay); + Assert.False(caps.BarGraph); + } + + [Fact] + public async Task SimulatedConnection_TakesBytesOnlyWhileConnected() + { + using var demo = new SimulatedMeterConnection(new FakeTimeProvider(Now)); + var sent = new List(); + demo.DataSent += (_, data) => sent.Add(data.ToArray()); + + await demo.SendAsync("*IDN?\n"u8.ToArray(), TestContext.Current.CancellationToken); + await demo.ConnectAsync(SimulatedMeterConnection.DemoMeter, TestContext.Current.CancellationToken); + await demo.SendAsync("*IDN?\n"u8.ToArray(), TestContext.Current.CancellationToken); + await demo.SendAsync(ReadOnlyMemory.Empty, TestContext.Current.CancellationToken); + + Assert.Equal("*IDN?\n"u8.ToArray(), Assert.Single(sent)); + } +} diff --git a/Readout.Tests/MeterSessionTests.cs b/Readout.Tests/MeterSessionTests.cs index de995bc..8c12ff4 100644 --- a/Readout.Tests/MeterSessionTests.cs +++ b/Readout.Tests/MeterSessionTests.cs @@ -60,6 +60,14 @@ public Task SendKeyAsync(MeterKey key, bool longPress = false, CancellationToken return Task.CompletedTask; } + public List Sent { get; } = []; + + public Task SendAsync(ReadOnlyMemory data, CancellationToken ct = default) + { + Sent.Add(data.ToArray()); + return Task.CompletedTask; + } + public void Discover(DiscoveredMeter meter) => MeterDiscovered?.Invoke(this, meter); public void Send(MeterPacket packet) => Send(packet.Bytes.ToArray()); public void Send(byte[] bytes) => DataReceived?.Invoke(this, bytes); @@ -130,6 +138,38 @@ public async Task Fs9721Meter_FramesSplitAcrossNotifications_AreDecodedAndLogged Assert.Null(r.Packet); } + private static readonly DiscoveredMeter Scope = new("ee:ff", "Readout DSO150 A1B2", -60, MeterModel.Dso150); + + [Fact] + public async Task Dso150_GetsItsOwnDriver_AndNo121GwReadings() + { + await _session.ConnectAsync(Scope); + Assert.Equal(MeterModel.Dso150, _session.Model); + Assert.Equal(MeterCapabilities.Dso150, _session.Capabilities); + + // Not even a valid 121GW packet turns into a reading from a DSO150 bridge. + _bluetooth.Send("DSOShell,DSO150,1234,0.1\n"u8.ToArray()); + _bluetooth.Send(new PacketBuilder { MainRangeIndex = 1, MainRawValue = 12345 }.BuildPacket()); + + Assert.Null(_session.Latest); + Assert.Equal(0, _session.Log.Count); + } + + [Fact] + public async Task SendAsync_GoesToTheConnectedMeter() + { + await _session.SendAsync("*IDN?\n"u8.ToArray()); + Assert.Empty(_bluetooth.Sent); + + await _session.ConnectAsync(Scope); + await _session.SendAsync("*IDN?\n"u8.ToArray()); + + Assert.Equal("*IDN?\n"u8.ToArray(), Assert.Single(_bluetooth.Sent)); + // A DSO150 has no keys to press. + await _session.SendKeyAsync(MeterKey.Hold); + Assert.Empty(_bluetooth.Keys); + } + [Fact] public async Task Capabilities_FollowTheConnectedMeter() { diff --git a/Readout/Services/BleMeterConnection.cs b/Readout/Services/BleMeterConnection.cs index 493bd57..4d79aae 100644 --- a/Readout/Services/BleMeterConnection.cs +++ b/Readout/Services/BleMeterConnection.cs @@ -24,6 +24,10 @@ public sealed class BleMeterConnection : IMeterConnection, IDisposable { private static readonly TimeSpan ConnectTimeout = TimeSpan.FromSeconds(15); + // An attribute value holds at most 512 bytes; a write with response longer than the MTU + // allows goes as a long write, which the platforms split up themselves. + private const int MaxWriteLength = 512; + private readonly IBluetoothLE _ble; private readonly IAdapter _adapter; private readonly ILogger _logger; @@ -33,6 +37,8 @@ public sealed class BleMeterConnection : IMeterConnection, IDisposable private CancellationTokenSource? _rssiCts; private IDevice? _device; private ICharacteristic? _data; + private ICharacteristic? _rx; + private readonly SemaphoreSlim _writeGate = new(1, 1); private bool _disconnecting; public BleMeterConnection(IBluetoothLE ble, ILogger logger) @@ -132,17 +138,27 @@ public async Task ConnectAsync(DiscoveredMeter meter, CancellationToken ct = def { await _adapter.ConnectToDeviceAsync(device, new ConnectParameters(autoConnect: false, forceBleTransport: true), timeout.Token); _device = device; + if (meter.Model != MeterModel.Eevblog121Gw) + await RequestMtuAsync(device, timeout.Token); var data = await FindDataCharacteristicAsync(device, timeout.Token) ?? throw new InvalidOperationException("This device has no meter data characteristic."); + // A two-way bridge (the DSO150's) takes bytes for its chip here. + if (meter.Model != MeterModel.Eevblog121Gw) + { + _rx = await data.Service.GetCharacteristicAsync(BridgeBluetooth.RxCharacteristicUuid, timeout.Token); + if (_rx is not null) + _rx.WriteType = CharacteristicWriteType.WithResponse; + } + data.ValueUpdated += OnValueUpdated; await data.StartUpdatesAsync(timeout.Token); _data = data; SignalStrength = device.Rssi; SetState(ConnectionState.Connected); - _logger.LogInformation("connected, data on {Characteristic}", data.Id); + _logger.LogInformation("connected, data on {Characteristic}{Rx}", data.Id, _rx is null ? "" : ", commands on " + _rx.Id); StartRssiPolling(device); } catch (Exception ex) @@ -155,6 +171,25 @@ public async Task ConnectAsync(DiscoveredMeter meter, CancellationToken ct = def } } + /// + /// Asks for a bigger MTU so a bridge's notifications carry 244 bytes instead of 20 (DSO150 + /// waveforms are about 1.1 KB). Android needs the request; iOS and Windows negotiate the + /// largest they can by themselves, and this only reports what they got. + /// + private async Task RequestMtuAsync(IDevice device, CancellationToken ct) + { + try + { + var mtu = await device.RequestMtuAsync(BridgeBluetooth.PreferredMtu, ct); + _logger.LogInformation("mtu {Mtu} (asked for {Preferred})", mtu, BridgeBluetooth.PreferredMtu); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // The link still works at the default 23, only slower. + _logger.LogWarning(ex, "mtu request failed"); + } + } + /// /// The data characteristic by UUID, else the first one that can notify outside the standard services. /// Windows can answer with no services right after connecting, before it has read them from the @@ -228,6 +263,29 @@ public async Task SendKeyAsync(MeterKey key, bool longPress = false, Cancellatio await _data.WriteAsync(command, ct); } + public async Task SendAsync(ReadOnlyMemory data, CancellationToken ct = default) + { + if (State != ConnectionState.Connected || data.IsEmpty) return; + var rx = _rx ?? throw new NotSupportedException($"{Meter?.Name ?? "This meter"} takes no data."); + + // One write at a time: Android fails a write started while another is in flight. + await _writeGate.WaitAsync(ct); + try + { + for (var offset = 0; offset < data.Length; offset += MaxWriteLength) + { + var chunk = data.Slice(offset, Math.Min(MaxWriteLength, data.Length - offset)).ToArray(); + var result = await rx.WriteAsync(chunk, ct); + if (result != 0) + throw new InvalidOperationException($"The bridge refused the write (error {result})."); + } + } + finally + { + _writeGate.Release(); + } + } + // The signal strength isn't pushed; ask for it every few seconds while connected. private void StartRssiPolling(IDevice device) { @@ -258,6 +316,7 @@ private async Task CloseLinkAsync() var data = _data; var device = _device; _data = null; + _rx = null; _device = null; if (data is not null) @@ -291,10 +350,31 @@ private void OnValueUpdated(object? sender, CharacteristicUpdatedEventArgs e) var value = e.Characteristic.Value; if (value is null || value.Length == 0) return; + // Until the DSO150's driver decodes its lines, the log is where they show up. + if (Meter?.Model == MeterModel.Dso150 && _logger.IsEnabled(LogLevel.Information)) + _logger.LogInformation("dso150 rx {Text}", Dso150LogText(value)); + // Copied: the platform may reuse the buffer, and the session reads it later on the main thread. DataReceived?.Invoke(this, value.ToArray()); } + /// Text as it is, other bytes as \xNN, cut short: waveform blocks are binary. + private static string Dso150LogText(byte[] value) + { + const int max = 160; + var text = new System.Text.StringBuilder(); + foreach (var b in value.AsSpan(0, Math.Min(value.Length, max))) + text.Append(b switch + { + (byte)'\n' => @"\n", + (byte)'\r' => @"\r", + >= 0x20 and < 0x7F => ((char)b).ToString(), + _ => @"\x" + b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture), + }); + if (value.Length > max) text.Append(System.Globalization.CultureInfo.InvariantCulture, $"... ({value.Length} bytes)"); + return text.ToString(); + } + private void OnLinkDropped(IDevice device, string? error) { if (_disconnecting || _device is null || device.Id != _device.Id) return; @@ -306,6 +386,7 @@ private void OnLinkDropped(IDevice device, string? error) _rssiCts = null; SignalStrength = null; _data = null; + _rx = null; _device = null; Meter = null; SetState(ConnectionState.Disconnected); @@ -316,6 +397,7 @@ public void Dispose() { _scanCts?.Dispose(); _rssiCts?.Dispose(); + _writeGate.Dispose(); } private void SetState(ConnectionState state) diff --git a/deploy-esp.sh b/deploy-esp.sh index e90e181..2cbaa9a 100755 --- a/deploy-esp.sh +++ b/deploy-esp.sh @@ -1,15 +1,15 @@ #!/bin/bash -# Build the FS9721 bridge firmware and flash it to an ESP32 on USB. -# ./deploy-esp.sh esp32dev (TXD lights the optocoupler's LED) -# ./deploy-esp.sh esp32dev-vdd another build: esp32dev-vdd, esp32c3, esp32c3-vdd +# Build the Readout bridge firmware and flash it to an ESP32 on USB. +# ./deploy-esp.sh fs9721-esp32dev (TXD lights the optocoupler's LED) +# ./deploy-esp.sh dso150-esp32c3 another build: fs9721-esp32dev-vdd, fs9721-esp32c3(-vdd), dso150-esp32dev, dso150-esp32c3 # ./deploy-esp.sh --log ...then follow its serial output (Ctrl-C stops) # ./deploy-esp.sh --port /dev/cu.usbserial-0001 when more than one board is plugged in -# The builds and their wiring are in firmware/fs9721-bridge/README.md. +# The builds and their wiring are in firmware/readout-bridge/README.md. set -e SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -FIRMWARE="$SCRIPT_DIR/firmware/fs9721-bridge" -ENV=esp32dev +FIRMWARE="$SCRIPT_DIR/firmware/readout-bridge" +ENV=fs9721-esp32dev PORT="" LOG=0 diff --git a/firmware/fs9721-bridge/README.md b/firmware/fs9721-bridge/README.md deleted file mode 100644 index 37baf96..0000000 --- a/firmware/fs9721-bridge/README.md +++ /dev/null @@ -1,162 +0,0 @@ -# Readout bridge for FS9721 meters - -An ESP32 inside (or clipped onto) a cheap meter built on Fortune's FS9721_LP3 chip. It reads -the chip's serial output and forwards it over Bluetooth LE to Readout, which shows, logs and -graphs the readings like a 121GW's. `docs/FS9721.md` explains the chip and how to find its pins. - -The bridge doesn't decode anything: it sends the bytes as they arrive, and the app frames and -decodes them. It advertises as **Readout FS9721 XXXX** (the last four hex digits of its MAC). - -It turns on and off with the meter: after 10 seconds without data (the meter is off, or its -serial output is) it goes to deep sleep, and the meter's next frame wakes it. The app then -reconnects by itself. - -## What you need - -- An ESP32 board: a classic ESP32 board such as an ESP-WROOM-32 DevKit (`esp32dev`), or an - ESP32-C3 board such as the C3 SuperMini (`esp32c3`). -- An optocoupler: a PC817 (or similar), or the slotted optical switch from an old ball mouse - (pins A, K, C, E). A 330 Ω resistor for its LED and a 10–47 kΩ pull-up (10 kΩ for a PC817, - more for a mouse switch, which passes less light). -- A small switch for ENTX, so serial can be turned off: while it's on, the meter's own auto - power-off is off. -- Power of its own (below). Not the meter's 9 V battery: keeping that isolated would take a DC-DC - converter that wastes more than the ESP32 uses. - -## Wiring - -There are two ways to light the optocoupler's LED. Pick one, and flash the matching build. - -### TXD lights the LED (3 wires out of the meter) — `esp32dev`, `esp32c3` - -``` - Meter (FS9721 side) ESP32 side - - ENTX ──── switch ──── VSS (button common) - - TXD ──── 330 Ω ──── LED anode (A, pin 1) collector (C, pin 4) ──┬── GPIO 33 (esp32dev) - VSS ──────────────── LED cathode (K, pin 2) │ GPIO 3 (esp32c3) - └── 10–47 kΩ ── 3.3 V - emitter (E, pin 3) ────── GND -``` - -Only TXD, VSS and ENTX leave the meter (two, with the ENTX switch inside the case). The LED is -lit whenever the meter is on and idle, which costs the meter's battery about 1–2 mA, about as -much as the meter itself: it lasts roughly half as long. The signal arrives inverted, which these -builds expect. - -### VDD lights the LED (4 wires, least drain) — `esp32dev-vdd`, `esp32c3-vdd` - -``` - VDD ──── 330 Ω ──── LED anode (A) - TXD ──────────────── LED cathode (K) (ESP32 side as above) -``` - -The LED lights only during the 0 bits of each byte, so it draws next to nothing between frames, -and the signal arrives the right way up. VDD is the chip's positive supply, about 3 V above VSS: -the chip pad next to AGND and VSS (docs/FS9721.md), or measure for it. - -### Either way - -- **VSS** is the chip's negative supply. The push buttons' common side is VSS, which is also - where ENTX goes; it's a much bigger pad to solder to than the ones around the chip. -- The optocoupler keeps the ESP32 apart from the meter's circuit, which floats at whatever the - probes touch. Don't connect ESP32 GND to the meter. -- The input has to be a pin that can wake the chip from deep sleep: one of the RTC pins on a - classic ESP32 (such as 4, 25–27 or 32–39), GPIO 0–5 on an ESP32-C3. -- A mouse's slotted switch: cover the slot so room light doesn't switch it, and check K to E - reads open once it's off the mouse's board (mice tie them together on the board). -- Adding parts and wires inside the case shrinks the gaps its safety rating relies on. Treat a - modified meter as a low-voltage bench meter. - -### Bench test without the optocoupler - -For a first try, TXD can go straight to the input pin and VSS to GND, with a `-vdd` build (the -signal isn't inverted). The ESP32 is then connected to the meter's circuit: keep the test leads -out of anything but low voltages, and never measure mains while the ESP32 is on USB. - -## Power - -A 1S LiPo with a charger, into the board's **3V3 pin** through a regulator that draws little -while idle: - -``` -LiPo ── TP4056 module (with protection) ── HT7333 or MCP1700-3302 ── 3V3 pin - GND ── GND -``` - -- Use the 3V3 pin, not 5V or VIN. A dev board's own regulator (often an AMS1117) needs about - 4.4 V in and draws around 5 mA doing nothing. -- Take a TP4056 module with battery protection (a DW01 chip next to it, B+/B− and OUT+/OUT− - pads): it cuts off before the cell runs flat. -- Remove the board's power LED, which draws 1–3 mA all the time. -- Don't connect USB and the battery's regulator at the same time. - -While connected it draws roughly 30–60 mA (less on an ESP32-C3); asleep, a dev board still -draws a few hundred microamps through its USB chip, which a 500 mAh cell lasts weeks on. - -## Build and flash - -With [PlatformIO](https://platformio.org) installed, from the repository's root: - -```bash -./deploy-esp.sh --log # finds the board, builds, flashes, then follows its output -./deploy-esp.sh esp32dev-vdd # another build: see Wiring -``` - -Or with PlatformIO directly (the CLI, or the VS Code extension): - -```bash -cd firmware/fs9721-bridge -pio run -e esp32dev -t upload # or esp32dev-vdd, esp32c3, esp32c3-vdd: see Wiring -pio device monitor # 115200 baud -``` - -The monitor prints each frame as it's forwarded, so you can check the wiring before opening -the app: - -``` -Readout bridge 0.2.0 (powered on): FS9721 on GPIO 33 -advertising as "Readout FS9721 A1B2" -17 25 3b 4f 5f 67 7f 87 9f a0 b0 c0 d4 e8 -… -no data for 10 s: sleeping until GPIO 33 goes low -``` - -Every line should run `1x 2x … ex`. Lines of other bytes, the same every frame, mean the build -doesn't match the wiring: flash the other one (with or without `-vdd`). When nothing arrives -for 5 seconds, the bridge says what the input pin is doing, and how far its voltage swings: - -- *always high*, flat near 3.3 V: no light reaches the optocoupler. Check ENTX (the RS232 symbol - should be on), that the LED's A and K are the right way round for your wiring, and its wires. -- *always low*: the optocoupler is stuck on (room light in a mouse switch's slot, C and E - swapped), or the build doesn't match the wiring. -- *changing, but no bytes*, or a swing that dips but stays above about 0.8 V: too little light. - Use a larger pull-up (47 kΩ) or a smaller LED resistor. - -The LED blinks with each frame (GPIO 2 on dev boards, GPIO 8 on the C3 SuperMini). After a -wake-up the first line says "woken by the meter". - -## Settings - -In `platformio.ini`: - -| Flag | What it is | -|---|---| -| `METER_RX_PIN` | The GPIO the signal reaches; must be able to wake the chip | -| `METER_RX_INVERTED` | 1 when TXD lights the LED; 0 when VDD does, or TXD is wired straight to the pin. Set by the build you pick | -| `SLEEP_AFTER_S` | Deep sleep after this many seconds without data (10); 0 never sleeps | -| `METER_SYMBOLS` | The meter's four maker-chosen LCD symbols, bit 0 first (`°F,hFE,°C,` on the Miyako 890G) | -| `LED_PIN`, `LED_ACTIVE_LOW` | The status LED, or -1 for none | - -## Bluetooth layout - -One service, matching `Readout.Core/Protocol/BridgeBluetooth.cs`: - -| UUID | | | -|---|---|---| -| `1ac73563-3941-40bc-90d4-47fb89f88271` | Service | Advertised | -| `4d19a30c-94d7-404e-a69d-b513188f13dc` | Notify | The meter's bytes, one notification per frame | -| `6daa6868-77cd-4539-8b02-6a82b3c6bc0c` | Read | `chip=FS9721`, `symbols=…`, `firmware=…`, one per line | - -The app doesn't read the info characteristic yet; it uses the Miyako 890G's symbols. diff --git a/firmware/fs9721-bridge/platformio.ini b/firmware/fs9721-bridge/platformio.ini deleted file mode 100644 index 46c9ba2..0000000 --- a/firmware/fs9721-bridge/platformio.ini +++ /dev/null @@ -1,67 +0,0 @@ -; Readout bridge for FS9721 meters: reads the meter chip's TXD and forwards the bytes over -; Bluetooth LE to the Readout app. See README.md for the wiring. -; -; Pick the target for your board and your optocoupler wiring: -; -; pio run -e esp32dev -t upload classic ESP32 (ESP-WROOM-32); TXD lights the LED (3 wires) -; pio run -e esp32dev-vdd -t upload classic ESP32; VDD lights the LED (4 wires, least drain), -; or TXD wired straight to the GPIO for a bench test -; pio run -e esp32c3 -t upload ESP32-C3, TXD lights the LED -; pio run -e esp32c3-vdd -t upload ESP32-C3, VDD lights the LED -; pio device monitor watch the frames it forwards (115200 baud) -; -; SLEEP_AFTER_S=10 (in build_flags) sets the deep sleep after that many seconds without data; -; 0 never sleeps. - -[platformio] -default_envs = esp32dev - -[env] -platform = espressif32@6.5.0 -framework = arduino -monitor_speed = 115200 -lib_deps = h2zero/NimBLE-Arduino@^1.4.3 -build_flags = - ; The meter's maker-chosen LCD symbols, bit 0 first (docs/FS9721.md). The Miyako 890G's. - -D 'METER_SYMBOLS="°F,hFE,°C,"' - -; Classic ESP32 boards. GPIO 33 can wake the chip from deep sleep. -[esp32dev] -board = esp32dev -build_flags = - ${env.build_flags} - -D METER_RX_PIN=33 - -D METER_TX_PIN=17 - -D LED_PIN=2 - -; ESP32-C3 boards (C3 SuperMini, C3 DevKitM). Only GPIO 0–5 can wake the chip from deep sleep. -[esp32c3] -board = esp32-c3-devkitm-1 -build_flags = - ${env.build_flags} - -D METER_RX_PIN=3 - -D METER_TX_PIN=21 - -D LED_PIN=8 - -D LED_ACTIVE_LOW=1 - -D ARDUINO_USB_MODE=1 - -D ARDUINO_USB_CDC_ON_BOOT=1 - -; TXD lights the LED: the phototransistor pulls the pin low while TXD is high, so the signal -; arrives inverted. -[env:esp32dev] -board = ${esp32dev.board} -build_flags = ${esp32dev.build_flags} -D METER_RX_INVERTED=1 - -[env:esp32c3] -board = ${esp32c3.board} -build_flags = ${esp32c3.build_flags} -D METER_RX_INVERTED=1 - -; VDD lights the LED through TXD (or TXD is wired straight to the pin): the signal arrives the -; right way up. -[env:esp32dev-vdd] -board = ${esp32dev.board} -build_flags = ${esp32dev.build_flags} -D METER_RX_INVERTED=0 - -[env:esp32c3-vdd] -board = ${esp32c3.board} -build_flags = ${esp32c3.build_flags} -D METER_RX_INVERTED=0 diff --git a/firmware/fs9721-bridge/src/main.cpp b/firmware/fs9721-bridge/src/main.cpp deleted file mode 100644 index 07b7601..0000000 --- a/firmware/fs9721-bridge/src/main.cpp +++ /dev/null @@ -1,266 +0,0 @@ -// Readout bridge for FS9721 meters. -// -// Reads the meter chip's serial output (2400 baud, 8N1, 14-byte frames of LCD segments) and -// forwards the bytes over Bluetooth LE as they come. The Readout app frames and decodes them, -// so this stays the same for any chip that only sends. The Bluetooth layout matches -// Readout.Core/Protocol/BridgeBluetooth.cs. -// -// It turns on and off with the meter: when no data has arrived for SLEEP_AFTER_S seconds (the -// meter is off, or its serial output is), it goes to deep sleep, and the next change on the -// input line wakes it. - -#include -#include -#include -#if CONFIG_IDF_TARGET_ESP32 -#include -#endif - -#ifndef METER_RX_PIN -#define METER_RX_PIN 16 -#endif -#ifndef METER_TX_PIN -#define METER_TX_PIN 17 // Unused (the meter only sends), but the UART needs a pin. -#endif -#ifndef METER_RX_INVERTED -#define METER_RX_INVERTED 0 -#endif -#ifndef SLEEP_AFTER_S -#define SLEEP_AFTER_S 10 // 0 never sleeps -#endif -#ifndef METER_SYMBOLS -#define METER_SYMBOLS "°F,hFE,°C," -#endif -#ifndef LED_PIN -#define LED_PIN -1 -#endif -#ifndef LED_ACTIVE_LOW -#define LED_ACTIVE_LOW 0 -#endif - -static const char *FIRMWARE_VERSION = "0.2.0"; -static const char *CHIP = "FS9721"; - -// Must match BridgeBluetooth in the app. -static const char *SERVICE_UUID = "1ac73563-3941-40bc-90d4-47fb89f88271"; -static const char *DATA_UUID = "4d19a30c-94d7-404e-a69d-b513188f13dc"; -static const char *INFO_UUID = "6daa6868-77cd-4539-8b02-6a82b3c6bc0c"; - -static const uint32_t METER_BAUD = 2400; -// A byte takes about 4 ms at 2400 baud and frames come about 300 ms apart, so a pause this -// long means the frame is done: send what has arrived in one notification. -static const uint32_t FRAME_GAP_MS = 15; -// Default ATT payload is 20 bytes; a frame is 14. -static const size_t MAX_CHUNK = 20; - -static HardwareSerial &meter = Serial1; -static NimBLECharacteristic *dataCharacteristic = nullptr; - -static uint8_t pending[MAX_CHUNK]; -static size_t pendingLength = 0; -static uint32_t lastByteAt = 0; -static uint32_t framesSent = 0; -static uint32_t ledOffAt = 0; - -// When nothing arrives for a while, say what the RX pin is doing, to help with the wiring. -static const uint32_t QUIET_REPORT_MS = 5000; -static uint32_t quietSince = 0; -static uint32_t samplesHigh = 0; -static uint32_t samplesLow = 0; - -static void reportQuiet() { - uint32_t total = samplesHigh + samplesLow; - const char *level = samplesLow == 0 ? "always high: nothing is arriving (is RS232 on the meter's LCD? is the LED wired right?)" - : samplesHigh == 0 ? "always low: check the wires, or flash the build for your wiring (with or without -vdd)" - : "changing, but no bytes: flash the build for your wiring (with or without -vdd)"; - Serial.printf("no data for %lu s; GPIO %d is %s (%lu%% high)\n", (unsigned long)(QUIET_REPORT_MS / 1000), - METER_RX_PIN, level, (unsigned long)(total ? samplesHigh * 100 / total : 0)); - - // How far the line actually swings, measured over half a second (frames come about 3 a - // second): an optocoupler that gets some light but too little pulls it only partway down. - // The ESP32 reads below about 0.8 V as low. - uint32_t lowest = UINT32_MAX, highest = 0; - uint32_t until = millis() + 500; - while ((int32_t)(millis() - until) < 0) { - uint32_t mv = analogReadMilliVolts(METER_RX_PIN); - if (mv < lowest) lowest = mv; - if (mv > highest) highest = mv; - } - Serial.printf(" GPIO %d swings %lu–%lu mV%s\n", METER_RX_PIN, (unsigned long)lowest, (unsigned long)highest, - lowest > 800 && highest - lowest > 200 ? ": the optocoupler dips but not to a low; try a larger pull-up or more LED current" : ""); - // Measuring switched the pin to analog (it reads as low then) and took it from the UART; - // make it a digital input again and give it back. - pinMode(METER_RX_PIN, INPUT); - meter.begin(METER_BAUD, SERIAL_8N1, METER_RX_PIN, METER_TX_PIN, METER_RX_INVERTED != 0); -} - -static void setLed(bool on); - -static const char *wakeReason() { - switch (esp_sleep_get_wakeup_cause()) { - case ESP_SLEEP_WAKEUP_EXT0: - case ESP_SLEEP_WAKEUP_GPIO: - return "woken by the meter"; - case ESP_SLEEP_WAKEUP_UNDEFINED: - return "powered on"; - default: - return "woken"; - } -} - -// Deep sleep until the input line changes. Usually it rests high (the meter idles high, or is -// off with the optocoupler's pull-up), and the next start bit wakes it. Wired directly, a meter -// that's off holds the line low instead, so then it waits for the line to go high (the meter -// switching on). Either way it wakes on whatever comes next. -static void sleepUntilTheMeterTalks() { - int level = digitalRead(METER_RX_PIN); - Serial.printf("no data for %d s: sleeping until GPIO %d goes %s\n", SLEEP_AFTER_S, METER_RX_PIN, - level ? "low" : "high"); - Serial.flush(); - setLed(false); - meter.end(); - // A weak pull toward the level it rests at, so a line nothing drives (a loose wire, a meter - // that lets go of TXD) doesn't wake it on noise. The optocoupler's 10 kΩ pull-up wins anyway. - gpio_num_t pin = (gpio_num_t)METER_RX_PIN; -#if CONFIG_IDF_TARGET_ESP32 - rtc_gpio_init(pin); - rtc_gpio_set_direction(pin, RTC_GPIO_MODE_INPUT_ONLY); - if (level) { rtc_gpio_pulldown_dis(pin); rtc_gpio_pullup_en(pin); } - else { rtc_gpio_pullup_dis(pin); rtc_gpio_pulldown_en(pin); } - esp_sleep_enable_ext0_wakeup(pin, level ? 0 : 1); -#else - gpio_set_pull_mode(pin, level ? GPIO_PULLUP_ONLY : GPIO_PULLDOWN_ONLY); - esp_deep_sleep_enable_gpio_wakeup(1ULL << METER_RX_PIN, - level ? ESP_GPIO_WAKEUP_GPIO_LOW : ESP_GPIO_WAKEUP_GPIO_HIGH); -#endif - esp_deep_sleep_start(); -} - -static void setLed(bool on) { - if (LED_PIN < 0) return; - digitalWrite(LED_PIN, (on != (LED_ACTIVE_LOW != 0)) ? HIGH : LOW); -} - -class ServerCallbacks : public NimBLEServerCallbacks { - void onConnect(NimBLEServer *server) override { - Serial.printf("app connected (%d)\n", server->getConnectedCount()); - } - void onDisconnect(NimBLEServer *server) override { - // NimBLE starts advertising again by itself. - Serial.println("app disconnected"); - } -}; - -static String deviceName() { - // The last two bytes of the chip's MAC, so several bridges can be told apart. - uint64_t mac = ESP.getEfuseMac(); - char name[32]; - snprintf(name, sizeof name, "Readout %s %02X%02X", CHIP, - (unsigned)((mac >> 32) & 0xFF), (unsigned)((mac >> 40) & 0xFF)); - return String(name); -} - -static void startBluetooth() { - String name = deviceName(); - NimBLEDevice::init(name.c_str()); - NimBLEDevice::setPower(ESP_PWR_LVL_P9); - - NimBLEServer *server = NimBLEDevice::createServer(); - server->setCallbacks(new ServerCallbacks()); - - NimBLEService *service = server->createService(SERVICE_UUID); - dataCharacteristic = service->createCharacteristic(DATA_UUID, NIMBLE_PROPERTY::NOTIFY); - - NimBLECharacteristic *info = service->createCharacteristic(INFO_UUID, NIMBLE_PROPERTY::READ); - String text = String("chip=") + CHIP + "\nsymbols=" + METER_SYMBOLS + "\nfirmware=" + FIRMWARE_VERSION; - info->setValue(text.c_str()); - - service->start(); - - // The name goes in the advertisement itself: apps find bridges by it, and some scanners - // (BlueZ on Linux) don't always pick up a scan response. The 128-bit service UUID doesn't fit - // beside it, so it goes in the scan response. "BR/EDR not supported" tells BlueZ to use LE. - NimBLEAdvertisementData advertisement; - advertisement.setFlags(BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP); - advertisement.setName(name.c_str()); - NimBLEAdvertisementData scanResponse; - scanResponse.setCompleteServices(NimBLEUUID(SERVICE_UUID)); - - NimBLEAdvertising *advertising = NimBLEDevice::getAdvertising(); - advertising->setAdvertisementData(advertisement); - advertising->setScanResponseData(scanResponse); - advertising->start(); - - Serial.printf("advertising as \"%s\"\n", name.c_str()); -} - -static void sendPending() { - if (pendingLength == 0) return; - - if (Serial) { - for (size_t i = 0; i < pendingLength; i++) - Serial.printf("%02x ", pending[i]); - Serial.println(); - } - - NimBLEServer *server = NimBLEDevice::getServer(); - if (server != nullptr && server->getConnectedCount() > 0) { - dataCharacteristic->setValue(pending, pendingLength); - dataCharacteristic->notify(); - framesSent++; - } - - setLed(true); - ledOffAt = millis() + 30; - pendingLength = 0; -} - -void setup() { - Serial.begin(115200); - if (LED_PIN >= 0) pinMode(LED_PIN, OUTPUT); - setLed(false); - -#if CONFIG_IDF_TARGET_ESP32 - // The wake-up left the pin as an RTC pad; hand it back to the UART. - rtc_gpio_deinit((gpio_num_t)METER_RX_PIN); -#endif - meter.begin(METER_BAUD, SERIAL_8N1, METER_RX_PIN, METER_TX_PIN, METER_RX_INVERTED != 0); - Serial.printf("Readout bridge %s (%s): %s on GPIO %d%s\n", FIRMWARE_VERSION, wakeReason(), CHIP, - METER_RX_PIN, METER_RX_INVERTED ? ", inverted" : ""); - lastByteAt = millis(); - - startBluetooth(); -} - -void loop() { - bool received = false; - while (meter.available() > 0) { - if (pendingLength == MAX_CHUNK) sendPending(); - pending[pendingLength++] = (uint8_t)meter.read(); - lastByteAt = millis(); - received = true; - } - - // The line as the UART sees it: idle is high once the inversion is right. - bool high = (digitalRead(METER_RX_PIN) == HIGH) != (METER_RX_INVERTED != 0); - (high ? samplesHigh : samplesLow)++; - if (received) { - quietSince = millis(); - samplesHigh = samplesLow = 0; - } else if (millis() - quietSince >= QUIET_REPORT_MS) { - reportQuiet(); - quietSince = millis(); - samplesHigh = samplesLow = 0; - } - - if (pendingLength > 0 && millis() - lastByteAt >= FRAME_GAP_MS) sendPending(); - - if (SLEEP_AFTER_S > 0 && millis() - lastByteAt >= SLEEP_AFTER_S * 1000UL) sleepUntilTheMeterTalks(); - - if (ledOffAt != 0 && (int32_t)(millis() - ledOffAt) >= 0) { - setLed(false); - ledOffAt = 0; - } - - delay(1); -} diff --git a/firmware/fs9721-bridge/.gitignore b/firmware/readout-bridge/.gitignore similarity index 100% rename from firmware/fs9721-bridge/.gitignore rename to firmware/readout-bridge/.gitignore diff --git a/firmware/readout-bridge/README.md b/firmware/readout-bridge/README.md new file mode 100644 index 0000000..d170b84 --- /dev/null +++ b/firmware/readout-bridge/README.md @@ -0,0 +1,287 @@ +# Readout bridge + +An ESP32 wired to a chip's serial port that forwards its bytes over Bluetooth LE to Readout, +which frames and decodes them. The bridge doesn't decode anything: all protocol knowledge +lives in the app (`Readout.Core`) and, for the DSO150, in its firmware. + +The chip is picked at build time. Each build advertises as **Readout <chip> XXXX** (the +last four hex digits of its MAC), and the app picks the driver from that name. + +| Chip | Builds | Direction | Serial | Wiring | Sleeps | +|---|---|---|---|---|---| +| FS9721 (cheap meters) | `fs9721-esp32dev`, `fs9721-esp32dev-vdd`, `fs9721-esp32c3`, `fs9721-esp32c3-vdd` | meter to app | 2400 8N1 | optocoupler | after 10 s without data | +| DSO150 running [DSOShell](#dso150-oscilloscope) | `dso150-esp32dev`, `dso150-esp32c3` | both ways | 115200 8N1 | direct, 3.3 V | never | + +Boards: a classic ESP32 such as an ESP-WROOM-32 DevKit (`esp32dev`), or an ESP32-C3 such as +the C3 SuperMini (`esp32c3`). + +## Build and flash + +With [PlatformIO](https://platformio.org) installed, from the repository's root: + +```bash +./deploy-esp.sh --log # fs9721-esp32dev: finds the board, builds, flashes, follows its output +./deploy-esp.sh dso150-esp32c3 --log # another build +``` + +Or with PlatformIO directly (the CLI, or the VS Code extension): + +```bash +cd firmware/readout-bridge +pio run -e dso150-esp32c3 -t upload # any build from the table above +pio device monitor # 115200 baud +``` + +## FS9721 meters + +An ESP32 inside (or clipped onto) a cheap meter built on Fortune's FS9721_LP3 chip. It reads +the chip's serial output and forwards it, and Readout shows, logs and graphs the readings like a +121GW's. `docs/FS9721.md` explains the chip and how to find its pins. + +It turns on and off with the meter: after 10 seconds without data (the meter is off, or its +serial output is) it goes to deep sleep, and the meter's next frame wakes it. The app then +reconnects by itself. + +### What you need + +- An ESP32 board (above). +- An optocoupler: a PC817 (or similar), or the slotted optical switch from an old ball mouse + (pins A, K, C, E). A 330 Ω resistor for its LED and a 10–47 kΩ pull-up (10 kΩ for a PC817, + more for a mouse switch, which passes less light). +- A small switch for ENTX, so serial can be turned off: while it's on, the meter's own auto + power-off is off. +- Power of its own (below). Not the meter's 9 V battery: keeping that isolated would take a DC-DC + converter that wastes more than the ESP32 uses. + +### Wiring + +There are two ways to light the optocoupler's LED. Pick one, and flash the matching build. + +#### TXD lights the LED (3 wires out of the meter): `fs9721-esp32dev`, `fs9721-esp32c3` + +``` + Meter (FS9721 side) ESP32 side + + ENTX ──── switch ──── VSS (button common) + + TXD ──── 330 Ω ──── LED anode (A, pin 1) collector (C, pin 4) ──┬── GPIO 33 (esp32dev) + VSS ──────────────── LED cathode (K, pin 2) │ GPIO 3 (esp32c3) + └── 10–47 kΩ ── 3.3 V + emitter (E, pin 3) ────── GND +``` + +Only TXD, VSS and ENTX leave the meter (two, with the ENTX switch inside the case). The LED is +lit whenever the meter is on and idle, which costs the meter's battery about 1–2 mA, about as +much as the meter itself: it lasts roughly half as long. The signal arrives inverted, which these +builds expect. + +#### VDD lights the LED (4 wires, least drain): `fs9721-esp32dev-vdd`, `fs9721-esp32c3-vdd` + +``` + VDD ──── 330 Ω ──── LED anode (A) + TXD ──────────────── LED cathode (K) (ESP32 side as above) +``` + +The LED lights only during the 0 bits of each byte, so it draws next to nothing between frames, +and the signal arrives the right way up. VDD is the chip's positive supply, about 3 V above VSS: +the chip pad next to AGND and VSS (docs/FS9721.md), or measure for it. + +#### Either way + +- **VSS** is the chip's negative supply. The push buttons' common side is VSS, which is also + where ENTX goes; it's a much bigger pad to solder to than the ones around the chip. +- The optocoupler keeps the ESP32 apart from the meter's circuit, which floats at whatever the + probes touch. Don't connect ESP32 GND to the meter. +- The input has to be a pin that can wake the chip from deep sleep: one of the RTC pins on a + classic ESP32 (such as 4, 25–27 or 32–39), GPIO 0–5 on an ESP32-C3. +- A mouse's slotted switch: cover the slot so room light doesn't switch it, and check K to E + reads open once it's off the mouse's board (mice tie them together on the board). +- Adding parts and wires inside the case shrinks the gaps its safety rating relies on. Treat a + modified meter as a low-voltage bench meter. + +#### Bench test without the optocoupler + +For a first try, TXD can go straight to the input pin and VSS to GND, with a `-vdd` build (the +signal isn't inverted). The ESP32 is then connected to the meter's circuit: keep the test leads +out of anything but low voltages, and never measure mains while the ESP32 is on USB. + +### Power + +A 1S LiPo with a charger, into the board's **3V3 pin** through a regulator that draws little +while idle: + +``` +LiPo ── TP4056 module (with protection) ── HT7333 or MCP1700-3302 ── 3V3 pin + GND ── GND +``` + +- Use the 3V3 pin, not 5V or VIN. A dev board's own regulator (often an AMS1117) needs about + 4.4 V in and draws around 5 mA doing nothing. +- Take a TP4056 module with battery protection (a DW01 chip next to it, B+/B− and OUT+/OUT− + pads): it cuts off before the cell runs flat. +- Remove the board's power LED, which draws 1–3 mA all the time. +- Don't connect USB and the battery's regulator at the same time. + +While connected it draws roughly 30–60 mA (less on an ESP32-C3); asleep, a dev board still +draws a few hundred microamps through its USB chip, which a 500 mAh cell lasts weeks on. + +### Checking it + +The monitor prints each frame as it's forwarded, so you can check the wiring before opening +the app: + +``` +Readout bridge 0.3.0 (powered on): FS9721 on GPIO 33, inverted +advertising as "Readout FS9721 A1B2" +17 25 3b 4f 5f 67 7f 87 9f a0 b0 c0 d4 e8 +… +no data for 10 s: sleeping until GPIO 33 goes low +``` + +Every line should run `1x 2x … ex`. Lines of other bytes, the same every frame, mean the build +doesn't match the wiring: flash the other one (with or without `-vdd`). When nothing arrives +for 5 seconds, the bridge says what the input pin is doing, and how far its voltage swings: + +- *always high*, flat near 3.3 V: no light reaches the optocoupler. Check ENTX (the RS232 symbol + should be on), that the LED's A and K are the right way round for your wiring, and its wires. +- *always low*: the optocoupler is stuck on (room light in a mouse switch's slot, C and E + swapped), or the build doesn't match the wiring. +- *changing, but no bytes*, or a swing that dips but stays above about 0.8 V: too little light. + Use a larger pull-up (47 kΩ) or a smaller LED resistor. + +The LED blinks with each frame (GPIO 2 on dev boards, GPIO 8 on the C3 SuperMini). After a +wake-up the first line says "woken by the meter". + +## DSO150 oscilloscope + +A JYE Tech DSO150 pocket oscilloscope running DSOShell, an open firmware with a serial +protocol (text lines, plus IEEE 488.2 `#` binary blocks for waveforms; DSOShell's +`docs/PROTOCOL.md`). The bridge is a transparent two-way pipe: what the scope sends goes to the +app as notifications on DATA, and what the app writes to RX goes out to the scope unchanged. +It never sleeps (the scope says nothing until asked) and powers up with the scope. + +### Wiring + +Both sides are 3.3 V logic, so the UART goes straight across: + +``` + DSO150 ESP32 + dso150-esp32dev dso150-esp32c3 + UART TX (PA9) ──────────────────────────── GPIO 16 (RX) GPIO 20 (RX) + UART RX (PA10) ──────────────────────────── GPIO 17 (TX) GPIO 21 (TX) + GND ─────────────────────────────────────── GND + + 9 V input ──── buck converter to 3.3 V ──── 3V3 pin + GND ──────────────────────────────────────── GND +``` + +- **Power**: from the scope's 9 V input through a small buck converter (an MP1584 module set + to 3.3 V, or a fixed 3.3 V buck), into the ESP32's 3V3 pin. Not from the scope's own 3.3 V + LDO: it can't supply the ESP32's radio peaks (a few hundred mA for a moment) and the scope + would brown out. A buck after the scope's power switch turns the bridge on and off with it. +- **Ground**: the ESP32's ground is the scope's ground, which is also the probe's ground clip. + With the bridge on its own power and no USB cable, nothing else ties the clip to earth. While + the ESP32 is on USB to a PC (flashing, the serial monitor), the clip is at the PC's ground: + don't clip it to anything that isn't at earth potential then. +- Where the PA9 and PA10 pads are on the board is in DSOShell's docs. Phase 5 of the plan adds + two more wires (BOOT0 and NRST) so the app can update the scope's firmware; not needed yet. + +### Hardware test (DSOShell milestone 0) + +The M0 firmware answers `*IDN?`, `SYST:INFO?`, `INP?` and `HELP?` and sends `EVT:KEY` and +`EVT:ENC` lines when buttons are pressed and the encoder turns. That's enough to check the +whole path. + +1. Flash DSOShell M0 to the scope (DSOShell's README). Optional first check without the + bridge: a USB-serial adapter on PA9/PA10 at 115200, type `*IDN?` and Enter. +2. Wire the bridge as above and flash it: `./deploy-esp.sh dso150-esp32c3 --log` (or + `dso150-esp32dev`). The monitor says: + + ``` + Readout bridge 0.3.0 (powered on): DSO150 at 115200 baud, RX on GPIO 20, TX on GPIO 21 + advertising as "Readout DSO150 A1B2" + ``` + +3. In **nRF Connect** (phone or desktop), scan and connect to **Readout DSO150 XXXX**. On + Android, ask for MTU 247 from the menu (iOS negotiates by itself); the monitor prints + `mtu 247: notifications of up to 244 bytes`. +4. In service `1ac73563-…`: + - read INFO (`6daa6868-…`): `chip=DSO150`, `baud=115200`, `firmware=0.3.0`. + - turn on notifications for DATA (`4d19a30c-…`). + - write to RX (`3065c3ca-…`) the bytes `2A 49 44 4E 3F 0A` (`*IDN?` and a newline; + nRF Connect's text mode doesn't add the newline, so send it as a byte array). +5. DATA notifies `DSOShell,DSO150,,` and a newline. The monitor shows both + directions: `<- *IDN?` and `-> DSOShell,DSO150,…`. Try `SYST:INFO?` + (`53 59 53 54 3A 49 4E 46 4F 3F 0A`) and `HELP?` (`48 45 4C 50 3F 0A`) too: `HELP?`'s reply + is several lines and may arrive in one notification. +6. Press the scope's buttons and turn its encoder: `EVT:KEY,down=0x..,up=0x..` and + `EVT:ENC,,` lines arrive on DATA without asking. +7. With **Readout**: the scan lists **Readout DSO150 XXXX**; connect. The meter page stays empty + (the DSO150 driver makes no readings yet), and the app's log shows + `mtu … (asked for 247)`, `connected, data on …, commands on 3065c3ca-…` and a + `dso150 rx …` line for each notification, so pressing the scope's buttons shows its + `EVT:KEY` lines (Mac: `./deploy-mac.sh --log`; Windows: the debugger's output). Readout has + no screen to type commands yet, so the `*IDN?` round trip is nRF Connect's. + +If nothing comes back: swap TX and RX (the most common mistake), check the grounds are joined, +and check the scope answers on its own (step 1). + +### Throughput + +A waveform frame is about 1.1 KB (1024 samples and a header), so the DSO150 builds are tuned +for it: + +- MTU 247 on both ends; each notification carries up to the negotiated MTU less 3 (244 bytes, + or 20 when the app didn't negotiate). +- A notification goes out when it's full, or when the scope pauses for 3 ms (the end of a line + or a frame). The UART hands bytes over every 16, and a 4 KB buffer holds what arrives while + the radio is busy. +- When NimBLE's buffers are full the bridge waits and retries instead of dropping bytes (twice + NimBLE's default buffers, too). Bytes it still has to drop are counted on the monitor; the + app drops the frame (its CRC fails) rather than show a broken one. +- It asks the app for a 15–30 ms connection interval. + +At 115200 baud the serial link is the limit: about 11.5 KB/s, so roughly 10 frames a second +at most with nothing else on the line. BLE with 244-byte notifications carries more than that +on current phones. + +**Open decision: faster serial.** DSOShell's `SYST:BAUD` switches the scope up to 921600 for +streaming waveforms. This bridge stays at 115200 for now: after `SYST:BAUD` the scope and the +bridge no longer understand each other until the scope resets. The two ways forward: + +1. **The bridge follows `SYST:BAUD`**: it watches the bytes the app writes for the command and + the scope's `OK`, then switches its own UART. The bridge stays a byte pipe in every other + way, but this is the one place it would peek at the protocol. +2. **A fixed 921600 link**: DSOShell boots at 921600 when it detects the bridge (or always), and + the bridge builds for 921600 (`-D UART_BAUD=921600`). Simpler, but a serial terminal then + needs 921600 too. + +## Settings + +In `platformio.ini`: + +| Flag | What it is | +|---|---| +| `CHIP_DSO150` | Build for the DSO150 (two-way); without it, the FS9721 | +| `UART_RX_PIN`, `UART_TX_PIN` | The GPIOs the chip's TX reaches and its RX is driven from. For the FS9721, RX must be able to wake the chip | +| `UART_RX_INVERTED` | FS9721: 1 when TXD lights the LED; 0 when VDD does, or TXD is wired straight to the pin. Set by the build you pick | +| `UART_BAUD` | 2400 for the FS9721, 115200 for the DSO150 | +| `SLEEP_AFTER_S` | Deep sleep after this many seconds without data (10 for the FS9721); 0 never sleeps (the DSO150's default) | +| `METER_SYMBOLS` | FS9721: the meter's four maker-chosen LCD symbols, bit 0 first (`°F,hFE,°C,` on the Miyako 890G) | +| `LED_PIN`, `LED_ACTIVE_LOW` | The status LED, or -1 for none. It blinks with each chunk, both ways | + +## Bluetooth layout + +One service, matching `Readout.Core/Protocol/BridgeBluetooth.cs` (a test checks the UUIDs, the +name format and the MTU against this firmware): + +| UUID | | | +|---|---|---| +| `1ac73563-3941-40bc-90d4-47fb89f88271` | Service | In the scan response (the name is in the advertisement) | +| `4d19a30c-94d7-404e-a69d-b513188f13dc` | Notify | The chip's bytes as they arrive, up to MTU less 3 per notification | +| `6daa6868-77cd-4539-8b02-6a82b3c6bc0c` | Read | `chip=FS9721` or `chip=DSO150`, `baud=…`, `firmware=…` and, for the FS9721, `symbols=…`, one per line | +| `3065c3ca-b78a-4b98-96b6-280cf0784ec4` | Write, write without response | DSO150 builds only: bytes for the chip, out the UART unchanged | + +The app writes to RX with a response (a write longer than the MTU allows goes as a long write, +up to 512 bytes). It doesn't read the info characteristic yet; for the FS9721 it uses the +Miyako 890G's symbols. diff --git a/firmware/readout-bridge/platformio.ini b/firmware/readout-bridge/platformio.ini new file mode 100644 index 0000000..5294e87 --- /dev/null +++ b/firmware/readout-bridge/platformio.ini @@ -0,0 +1,92 @@ +; Readout bridge: an ESP32 wired to a chip's serial port that forwards its bytes over Bluetooth +; LE to the Readout app (and, for two-way chips, the app's bytes back). See README.md. +; +; Pick the build for your chip, board and wiring: +; +; FS9721 meters (receive-only, through an optocoupler) +; pio run -e fs9721-esp32dev -t upload classic ESP32 (ESP-WROOM-32); TXD lights the LED (3 wires) +; pio run -e fs9721-esp32dev-vdd -t upload classic ESP32; VDD lights the LED (4 wires, least drain), +; or TXD wired straight to the GPIO for a bench test +; pio run -e fs9721-esp32c3 -t upload ESP32-C3, TXD lights the LED +; pio run -e fs9721-esp32c3-vdd -t upload ESP32-C3, VDD lights the LED +; +; DSO150 oscilloscope running DSOShell (two-way, wired directly) +; pio run -e dso150-esp32dev -t upload classic ESP32 +; pio run -e dso150-esp32c3 -t upload ESP32-C3 +; +; pio device monitor what it forwards (115200 baud) +; +; SLEEP_AFTER_S=10 (in build_flags) sets the deep sleep after that many seconds without data; +; 0 never sleeps (the DSO150 builds' default). + +[platformio] +default_envs = fs9721-esp32dev + +[env] +platform = espressif32@6.5.0 +framework = arduino +monitor_speed = 115200 +lib_deps = h2zero/NimBLE-Arduino@^1.4.3 + +; The boards. +[esp32dev] +board = esp32dev +build_flags = + -D LED_PIN=2 + +[esp32c3] +board = esp32-c3-devkitm-1 +build_flags = + -D LED_PIN=8 + -D LED_ACTIVE_LOW=1 + -D ARDUINO_USB_MODE=1 + -D ARDUINO_USB_CDC_ON_BOOT=1 + +; FS9721: the meter's maker-chosen LCD symbols, bit 0 first (docs/FS9721.md). The Miyako 890G's. +; The input must be able to wake the chip from deep sleep: GPIO 33 on a classic ESP32, only +; GPIO 0–5 on a C3. +[fs9721] +build_flags = + -D 'METER_SYMBOLS="°F,hFE,°C,"' + +[fs9721-esp32dev] +build_flags = ${esp32dev.build_flags} ${fs9721.build_flags} -D UART_RX_PIN=33 -D UART_TX_PIN=17 + +[fs9721-esp32c3] +build_flags = ${esp32c3.build_flags} ${fs9721.build_flags} -D UART_RX_PIN=3 -D UART_TX_PIN=21 + +; TXD lights the LED: the phototransistor pulls the pin low while TXD is high, so the signal +; arrives inverted. +[env:fs9721-esp32dev] +board = ${esp32dev.board} +build_flags = ${fs9721-esp32dev.build_flags} -D UART_RX_INVERTED=1 + +[env:fs9721-esp32c3] +board = ${esp32c3.board} +build_flags = ${fs9721-esp32c3.build_flags} -D UART_RX_INVERTED=1 + +; VDD lights the LED through TXD (or TXD is wired straight to the pin): the signal arrives the +; right way up. +[env:fs9721-esp32dev-vdd] +board = ${esp32dev.board} +build_flags = ${fs9721-esp32dev.build_flags} -D UART_RX_INVERTED=0 + +[env:fs9721-esp32c3-vdd] +board = ${esp32c3.board} +build_flags = ${fs9721-esp32c3.build_flags} -D UART_RX_INVERTED=0 + +; DSO150: 115200 baud both ways, 3.3 V logic straight to the scope's PA9 (its TX) and PA10 (its +; RX). Twice NimBLE's default buffers, so a waveform's notifications can queue while the link +; catches up. +[dso150] +build_flags = + -D CHIP_DSO150=1 + -D CONFIG_BT_NIMBLE_MSYS1_BLOCK_COUNT=24 + +[env:dso150-esp32dev] +board = ${esp32dev.board} +build_flags = ${esp32dev.build_flags} ${dso150.build_flags} -D UART_RX_PIN=16 -D UART_TX_PIN=17 + +[env:dso150-esp32c3] +board = ${esp32c3.board} +build_flags = ${esp32c3.build_flags} ${dso150.build_flags} -D UART_RX_PIN=20 -D UART_TX_PIN=21 diff --git a/firmware/readout-bridge/src/main.cpp b/firmware/readout-bridge/src/main.cpp new file mode 100644 index 0000000..a377c38 --- /dev/null +++ b/firmware/readout-bridge/src/main.cpp @@ -0,0 +1,410 @@ +// Readout bridge: an ESP32 wired to a chip's serial port that forwards its bytes over +// Bluetooth LE to the Readout app, which frames and decodes them. The Bluetooth layout matches +// Readout.Core/Protocol/BridgeBluetooth.cs. +// +// The chip is picked at build time (platformio.ini): +// +// - FS9721 (the default): a cheap meter's FS9721_LP3 chip. Receive-only at 2400 baud, 8N1, +// 14-byte frames of LCD segments, usually through an optocoupler. It turns on and off with the +// meter: when no data has arrived for SLEEP_AFTER_S seconds (the meter is off, or its serial +// output is), it goes to deep sleep, and the next change on the input line wakes it. +// - DSO150 (CHIP_DSO150): a JYE Tech DSO150 oscilloscope running DSOShell. Two-way at 115200 +// baud, 8N1, wired directly (both sides are 3.3 V). What the app writes to the RX +// characteristic goes out the UART unchanged. It never sleeps: the scope is quiet until asked. +// +// Either way the bridge doesn't look inside the bytes. + +#include +#include +#include +#if CONFIG_IDF_TARGET_ESP32 +#include +#endif + +#if defined(CHIP_DSO150) +#define CHIP_NAME "DSO150" +#define TWO_WAY 1 +#ifndef UART_BAUD +#define UART_BAUD 115200 +#endif +#ifndef SLEEP_AFTER_S +#define SLEEP_AFTER_S 0 +#endif +// A byte takes 87 µs at 115200 baud, and the UART hands them over in bursts (see setup), so a +// pause this long means the chip has stopped talking for now. +#define FLUSH_GAP_US 3000 +#else +#define CHIP_NAME "FS9721" +#define TWO_WAY 0 +#ifndef UART_BAUD +#define UART_BAUD 2400 +#endif +#ifndef SLEEP_AFTER_S +#define SLEEP_AFTER_S 10 // 0 never sleeps +#endif +// A byte takes about 4 ms at 2400 baud and frames come about 300 ms apart, so a pause this +// long means the frame is done: send what has arrived in one notification. +#define FLUSH_GAP_US 15000 +#endif + +#ifndef UART_RX_PIN +#define UART_RX_PIN 16 +#endif +#ifndef UART_TX_PIN +#define UART_TX_PIN 17 // Unused by receive-only chips, but the UART needs a pin. +#endif +#ifndef UART_RX_INVERTED +#define UART_RX_INVERTED 0 +#endif +#ifndef METER_SYMBOLS +#define METER_SYMBOLS "°F,hFE,°C," +#endif +#ifndef LED_PIN +#define LED_PIN -1 +#endif +#ifndef LED_ACTIVE_LOW +#define LED_ACTIVE_LOW 0 +#endif + +static const char *FIRMWARE_VERSION = "0.3.0"; +static const char *CHIP = CHIP_NAME; + +// Must match BridgeBluetooth in the app. +static const char *SERVICE_UUID = "1ac73563-3941-40bc-90d4-47fb89f88271"; +static const char *DATA_UUID = "4d19a30c-94d7-404e-a69d-b513188f13dc"; +static const char *INFO_UUID = "6daa6868-77cd-4539-8b02-6a82b3c6bc0c"; +static const char *RX_UUID = "3065c3ca-b78a-4b98-96b6-280cf0784ec4"; + +// Asked for at connect (BridgeBluetooth.PreferredMtu); a notification carries the negotiated +// MTU less 3 bytes of header: 244 at 247, 20 at the default 23. +static const uint16_t PREFERRED_MTU = 247; +static const uint16_t DEFAULT_MTU = 23; +static const size_t MAX_CHUNK = PREFERRED_MTU - 3; + +static HardwareSerial &chip = Serial1; +static NimBLECharacteristic *dataCharacteristic = nullptr; + +static uint8_t pending[MAX_CHUNK]; +static size_t pendingLength = 0; +static uint32_t lastByteAt = 0; // millis(), for the sleep timer +static uint32_t lastByteAtUs = 0; // micros(), for the flush gap +static uint32_t ledOffAt = 0; + +// The connected app's MTU. Notifications longer than it allows would be cut short. +static volatile uint16_t peerMtu = DEFAULT_MTU; +static size_t chunkLimit() { + size_t limit = peerMtu > 3 ? peerMtu - 3 : 20; + return limit < MAX_CHUNK ? limit : MAX_CHUNK; +} + +// What the last notify() reported (it reports through the callback, while it runs). +static volatile int lastNotifyError = 0; +static uint32_t notifyRetries = 0; +static uint32_t bytesDropped = 0; + +static void setLed(bool on) { + if (LED_PIN < 0) return; + digitalWrite(LED_PIN, (on != (LED_ACTIVE_LOW != 0)) ? HIGH : LOW); +} + +static void blink() { + setLed(true); + ledOffAt = millis() + 30; + if (ledOffAt == 0) ledOffAt = 1; +} + +// Text as it is, anything else as a dot; long chunks (waveform blocks) only as a byte count, so +// the USB serial port doesn't fall behind the scope. +static void printChunk(const char *direction, const uint8_t *data, size_t length) { + if (length > 64) { + Serial.printf("%s [%u bytes]\n", direction, (unsigned)length); + return; + } + char text[70]; + size_t n = 0; + for (size_t i = 0; i < length; i++) { + uint8_t c = data[i]; + if (c == '\n' || c == '\r') continue; + text[n++] = (c >= 0x20 && c < 0x7f) ? (char)c : '.'; + } + text[n] = 0; + Serial.printf("%s %s\n", direction, text); +} + +#if !TWO_WAY +// When nothing arrives for a while, say what the RX pin is doing, to help with the wiring. +static const uint32_t QUIET_REPORT_MS = 5000; +static uint32_t quietSince = 0; +static uint32_t samplesHigh = 0; +static uint32_t samplesLow = 0; + +static void reportQuiet() { + uint32_t total = samplesHigh + samplesLow; + const char *level = samplesLow == 0 ? "always high: nothing is arriving (is RS232 on the meter's LCD? is the LED wired right?)" + : samplesHigh == 0 ? "always low: check the wires, or flash the build for your wiring (with or without -vdd)" + : "changing, but no bytes: flash the build for your wiring (with or without -vdd)"; + Serial.printf("no data for %lu s; GPIO %d is %s (%lu%% high)\n", (unsigned long)(QUIET_REPORT_MS / 1000), + UART_RX_PIN, level, (unsigned long)(total ? samplesHigh * 100 / total : 0)); + + // How far the line actually swings, measured over half a second (frames come about 3 a + // second): an optocoupler that gets some light but too little pulls it only partway down. + // The ESP32 reads below about 0.8 V as low. + uint32_t lowest = UINT32_MAX, highest = 0; + uint32_t until = millis() + 500; + while ((int32_t)(millis() - until) < 0) { + uint32_t mv = analogReadMilliVolts(UART_RX_PIN); + if (mv < lowest) lowest = mv; + if (mv > highest) highest = mv; + } + Serial.printf(" GPIO %d swings %lu–%lu mV%s\n", UART_RX_PIN, (unsigned long)lowest, (unsigned long)highest, + lowest > 800 && highest - lowest > 200 ? ": the optocoupler dips but not to a low; try a larger pull-up or more LED current" : ""); + // Measuring switched the pin to analog (it reads as low then) and took it from the UART; + // make it a digital input again and give it back. + pinMode(UART_RX_PIN, INPUT); + chip.begin(UART_BAUD, SERIAL_8N1, UART_RX_PIN, UART_TX_PIN, UART_RX_INVERTED != 0); +} +#endif + +static const char *wakeReason() { + switch (esp_sleep_get_wakeup_cause()) { + case ESP_SLEEP_WAKEUP_EXT0: + case ESP_SLEEP_WAKEUP_GPIO: + return "woken by the meter"; + case ESP_SLEEP_WAKEUP_UNDEFINED: + return "powered on"; + default: + return "woken"; + } +} + +// Deep sleep until the input line changes. Usually it rests high (the meter idles high, or is +// off with the optocoupler's pull-up), and the next start bit wakes it. Wired directly, a meter +// that's off holds the line low instead, so then it waits for the line to go high (the meter +// switching on). Either way it wakes on whatever comes next. +static void sleepUntilTheMeterTalks() { + int level = digitalRead(UART_RX_PIN); + Serial.printf("no data for %d s: sleeping until GPIO %d goes %s\n", SLEEP_AFTER_S, UART_RX_PIN, + level ? "low" : "high"); + Serial.flush(); + setLed(false); + chip.end(); + // A weak pull toward the level it rests at, so a line nothing drives (a loose wire, a meter + // that lets go of TXD) doesn't wake it on noise. The optocoupler's 10 kΩ pull-up wins anyway. + gpio_num_t pin = (gpio_num_t)UART_RX_PIN; +#if CONFIG_IDF_TARGET_ESP32 + rtc_gpio_init(pin); + rtc_gpio_set_direction(pin, RTC_GPIO_MODE_INPUT_ONLY); + if (level) { rtc_gpio_pulldown_dis(pin); rtc_gpio_pullup_en(pin); } + else { rtc_gpio_pullup_dis(pin); rtc_gpio_pulldown_en(pin); } + esp_sleep_enable_ext0_wakeup(pin, level ? 0 : 1); +#else + gpio_set_pull_mode(pin, level ? GPIO_PULLUP_ONLY : GPIO_PULLDOWN_ONLY); + esp_deep_sleep_enable_gpio_wakeup(1ULL << UART_RX_PIN, + level ? ESP_GPIO_WAKEUP_GPIO_LOW : ESP_GPIO_WAKEUP_GPIO_HIGH); +#endif + esp_deep_sleep_start(); +} + +class ServerCallbacks : public NimBLEServerCallbacks { + void onConnect(NimBLEServer *server, ble_gap_conn_desc *desc) override { + peerMtu = DEFAULT_MTU; + Serial.printf("app connected (%d)\n", server->getConnectedCount()); +#if TWO_WAY + // Waveforms are about 1.1 KB: ask for a short connection interval (15–30 ms, in 1.25 ms + // units) so several notifications go out every few milliseconds. Timeout 4 s (10 ms units). + server->updateConnParams(desc->conn_handle, 12, 24, 0, 400); +#endif + } + void onDisconnect(NimBLEServer *server) override { + // NimBLE starts advertising again by itself. + peerMtu = DEFAULT_MTU; + Serial.println("app disconnected"); + } + void onMTUChange(uint16_t mtu, ble_gap_conn_desc *desc) override { + peerMtu = mtu; + Serial.printf("mtu %u: notifications of up to %u bytes\n", mtu, (unsigned)chunkLimit()); + } +}; + +class DataCallbacks : public NimBLECharacteristicCallbacks { + void onStatus(NimBLECharacteristic *characteristic, Status status, int code) override { + lastNotifyError = status == SUCCESS_NOTIFY ? 0 : (code != 0 ? code : -1); + } +}; + +#if TWO_WAY +// The app's bytes for the chip: out the UART as they are. +class RxCallbacks : public NimBLECharacteristicCallbacks { + void onWrite(NimBLECharacteristic *characteristic) override { + NimBLEAttValue value = characteristic->getValue(); + if (value.length() == 0) return; + chip.write(value.data(), value.length()); + printChunk("<-", value.data(), value.length()); + blink(); + } +}; +#endif + +static String deviceName() { + // The last two bytes of the chip's MAC, so several bridges can be told apart. + uint64_t mac = ESP.getEfuseMac(); + char name[32]; + snprintf(name, sizeof name, "Readout %s %02X%02X", CHIP, + (unsigned)((mac >> 32) & 0xFF), (unsigned)((mac >> 40) & 0xFF)); + return String(name); +} + +static void startBluetooth() { + String name = deviceName(); + NimBLEDevice::init(name.c_str()); + NimBLEDevice::setPower(ESP_PWR_LVL_P9); + NimBLEDevice::setMTU(PREFERRED_MTU); + + NimBLEServer *server = NimBLEDevice::createServer(); + server->setCallbacks(new ServerCallbacks()); + + NimBLEService *service = server->createService(SERVICE_UUID); + dataCharacteristic = service->createCharacteristic(DATA_UUID, NIMBLE_PROPERTY::NOTIFY); + dataCharacteristic->setCallbacks(new DataCallbacks()); + + NimBLECharacteristic *info = service->createCharacteristic(INFO_UUID, NIMBLE_PROPERTY::READ); + String text = String("chip=") + CHIP + "\nbaud=" + UART_BAUD + "\nfirmware=" + FIRMWARE_VERSION; +#if !TWO_WAY + text += String("\nsymbols=") + METER_SYMBOLS; +#endif + info->setValue(text.c_str()); + +#if TWO_WAY + NimBLECharacteristic *rx = + service->createCharacteristic(RX_UUID, NIMBLE_PROPERTY::WRITE | NIMBLE_PROPERTY::WRITE_NR); + rx->setCallbacks(new RxCallbacks()); +#endif + + service->start(); + + // The name goes in the advertisement itself: apps find bridges by it, and some scanners + // (BlueZ on Linux) don't always pick up a scan response. The 128-bit service UUID doesn't fit + // beside it, so it goes in the scan response. "BR/EDR not supported" tells BlueZ to use LE. + NimBLEAdvertisementData advertisement; + advertisement.setFlags(BLE_HS_ADV_F_DISC_GEN | BLE_HS_ADV_F_BREDR_UNSUP); + advertisement.setName(name.c_str()); + NimBLEAdvertisementData scanResponse; + scanResponse.setCompleteServices(NimBLEUUID(SERVICE_UUID)); + + NimBLEAdvertising *advertising = NimBLEDevice::getAdvertising(); + advertising->setAdvertisementData(advertisement); + advertising->setScanResponseData(scanResponse); + advertising->start(); + + Serial.printf("advertising as \"%s\"\n", name.c_str()); +} + +// One notification. When the Bluetooth stack's buffers are full (BLE_HS_ENOMEM: notifications +// queued faster than the link sends them), wait a little and try again rather than lose bytes; +// the UART's buffer holds what arrives meanwhile. +static void notify(const uint8_t *data, size_t length) { + for (int attempt = 0; attempt < 50; attempt++) { + lastNotifyError = 0; + dataCharacteristic->setValue(data, length); + dataCharacteristic->notify(); + if (lastNotifyError != BLE_HS_ENOMEM) return; + notifyRetries++; + delay(2); + } + bytesDropped += length; + Serial.printf("dropped %u bytes: the link isn't keeping up (%lu dropped so far)\n", (unsigned)length, + (unsigned long)bytesDropped); +} + +static void sendPending() { + if (pendingLength == 0) return; + +#if TWO_WAY + printChunk("->", pending, pendingLength); +#else + if (Serial) { + for (size_t i = 0; i < pendingLength; i++) + Serial.printf("%02x ", pending[i]); + Serial.println(); + } +#endif + + NimBLEServer *server = NimBLEDevice::getServer(); + if (server != nullptr && server->getConnectedCount() > 0) notify(pending, pendingLength); + + blink(); + pendingLength = 0; +} + +void setup() { + Serial.begin(115200); + if (LED_PIN >= 0) pinMode(LED_PIN, OUTPUT); + setLed(false); + +#if CONFIG_IDF_TARGET_ESP32 + // A wake-up from deep sleep left the pin as an RTC pad; hand it back to the UART. + rtc_gpio_deinit((gpio_num_t)UART_RX_PIN); +#endif +#if TWO_WAY + // Room for several waveforms while a notification waits for the link (1.1 KB each). + chip.setRxBufferSize(4096); +#endif + chip.begin(UART_BAUD, SERIAL_8N1, UART_RX_PIN, UART_TX_PIN, UART_RX_INVERTED != 0); +#if TWO_WAY + // The UART passes bytes on when 120 have queued in its FIFO, or after a pause: 10 ms bursts + // at 115200. Smaller bursts keep the flush gap short and notifications evenly filled. + chip.setRxFIFOFull(16); +#endif +#if TWO_WAY + Serial.printf("Readout bridge %s (%s): %s at %d baud, RX on GPIO %d, TX on GPIO %d\n", FIRMWARE_VERSION, + wakeReason(), CHIP, UART_BAUD, UART_RX_PIN, UART_TX_PIN); +#else + Serial.printf("Readout bridge %s (%s): %s on GPIO %d%s\n", FIRMWARE_VERSION, wakeReason(), CHIP, UART_RX_PIN, + UART_RX_INVERTED ? ", inverted" : ""); +#endif + lastByteAt = millis(); + lastByteAtUs = micros(); + + startBluetooth(); +} + +void loop() { + bool received = false; + size_t limit = chunkLimit(); + while (chip.available() > 0) { + if (pendingLength >= limit) sendPending(); + pending[pendingLength++] = (uint8_t)chip.read(); + received = true; + } + if (received) { + lastByteAt = millis(); + lastByteAtUs = micros(); + } + if (pendingLength >= limit) sendPending(); + +#if !TWO_WAY + // The line as the UART sees it: idle is high once the inversion is right. + bool high = (digitalRead(UART_RX_PIN) == HIGH) != (UART_RX_INVERTED != 0); + (high ? samplesHigh : samplesLow)++; + if (received) { + quietSince = millis(); + samplesHigh = samplesLow = 0; + } else if (millis() - quietSince >= QUIET_REPORT_MS) { + reportQuiet(); + quietSince = millis(); + samplesHigh = samplesLow = 0; + } +#endif + + if (pendingLength > 0 && micros() - lastByteAtUs >= FLUSH_GAP_US) sendPending(); + + if (SLEEP_AFTER_S > 0 && millis() - lastByteAt >= SLEEP_AFTER_S * 1000UL) sleepUntilTheMeterTalks(); + + if (ledOffAt != 0 && (int32_t)(millis() - ledOffAt) >= 0) { + setLed(false); + ledOffAt = 0; + } + + // Busy while bytes are coming; otherwise rest a little. + if (!received) delay(1); +} From c91be4c673d657ac17e78b9d4d3ea469e1c53890 Mon Sep 17 00:00:00 2001 From: Alejandro Mora Date: Tue, 10 Nov 2026 09:29:19 -0500 Subject: [PATCH 2/2] docs: point at the renamed bridge and note the DSO150 work Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 5 +++-- docs/FS9721.md | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 57b9a5b..debb1f9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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. @@ -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-.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 diff --git a/docs/FS9721.md b/docs/FS9721.md index b67e2e5..dd2751d 100644 --- a/docs/FS9721.md +++ b/docs/FS9721.md @@ -94,7 +94,8 @@ A second meter type touches four layers. Each step below keeps the 121GW working (`BridgeBluetooth`). It advertises as "Readout FS9721 XXXX"; `BleMeterConnection` finds it by that name next to the 121GW's and the session picks the driver from it. Decoding stays in the app, so supporting another chip (FS9922, ES51922…) is a decoder and tests, with no - firmware change. The PlatformIO project and wiring are in `firmware/fs9721-bridge`. + firmware change. The PlatformIO project and wiring are in `firmware/readout-bridge` (the + `fs9721-*` builds). Later: the symbol map read from the bridge's info characteristic instead of the 890G's, a simulated FS9721 meter for tests and the demo, and the bridge's own battery level in the