From cd0d18e22337ea95804d1868c87cf618ca3a6718 Mon Sep 17 00:00:00 2001 From: Daniel Meza Date: Thu, 8 Oct 2026 02:20:11 -0500 Subject: [PATCH 1/2] refactor(transports): drop ESCPOS_NET from CrossEscPos.Transports MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit UsbPrinter was the only transport deriving from ESCPOS_NET's BasePrinter, and used almost none of it: it built its own BinaryWriter/BinaryReader over its own UsbStream and overrode OverridableDispose. What BasePrinter did carry was the stream pump (write splitting at 15,000 bytes, a background read loop) and the parse of the 4-byte Automatic Status Back block into PrinterStatusEventArgs. Both now live in this repository: - StreamPrinter (Transports) is the host side of a printer conversation over any Stream — IPrinterResponder.Send out, raw ASB blocks back on StatusFrameReceived. UsbPrinter derives from it and supplies the UsbStream. - AutoStatusBackReader (Core) frames and decodes the block, next to StatusByteBuilder.AutoStatusBack, whose exact inverse it is. DesktopMonitorClient did consume the parsed status, so the behaviour is preserved rather than dropped: its USB link decodes the raw block through AutoStatusBackReader, which is the same decode the browser head already used via MonitorStatus.FromAutoStatusBack. Two ESCPOS_NET decode details are kept because a real printer can exercise them — rejecting a block whose first byte lacks the ASB fixed bits, and folding all four byte-1 error bits into the error flag. Three flags nothing reads (paper feeding, waiting for online recovery, feed button pushed) are not surfaced; the bits are still in the delivered block. With ESCPOS_NET gone, the SixLabors.ImageSharp 2.1.13 pin goes too — it existed only to lift ESCPOS_NET's transitive 2.1.3 and no code here used ImageSharp. CrossEscPos.Transports now builds with the NuGet audit fully on, clearing the 5 advisory findings it was contributing to the repository's 25. Breaking for consumers holding a UsbPrinter; recorded in docs/Packages.md. --- CrossEscPos.slnx | 1 + docs/Architecture.md | 2 +- docs/Packages.md | 38 +++ docs/Transports.md | 24 ++ .../Monitor/DesktopMonitorClient.cs | 125 ++++++--- src/CrossEscPos.App/Monitor/MonitorStatus.cs | 36 +-- .../Emulator/AutoStatusBackReader.cs | 93 +++++++ .../CrossEscPos.Transports.csproj | 4 - src/CrossEscPos.Transports/StreamPrinter.cs | 150 +++++++++++ src/CrossEscPos.Transports/UsbPrinter.cs | 46 ++-- .../AutoStatusBackReaderTests.cs | 228 ++++++++++++++++ .../CrossEscPos.Transports.Tests.csproj | 21 ++ .../FakeTransport.cs | 96 +++++++ .../StreamPrinterTests.cs | 244 ++++++++++++++++++ 14 files changed, 1033 insertions(+), 75 deletions(-) create mode 100644 src/CrossEscPos.Core/Emulator/AutoStatusBackReader.cs create mode 100644 src/CrossEscPos.Transports/StreamPrinter.cs create mode 100644 tests/CrossEscPos.Transports.Tests/AutoStatusBackReaderTests.cs create mode 100644 tests/CrossEscPos.Transports.Tests/CrossEscPos.Transports.Tests.csproj create mode 100644 tests/CrossEscPos.Transports.Tests/FakeTransport.cs create mode 100644 tests/CrossEscPos.Transports.Tests/StreamPrinterTests.cs diff --git a/CrossEscPos.slnx b/CrossEscPos.slnx index 8faa7ac..287d6c0 100644 --- a/CrossEscPos.slnx +++ b/CrossEscPos.slnx @@ -19,5 +19,6 @@ + diff --git a/docs/Architecture.md b/docs/Architecture.md index fb9217c..33ab675 100644 --- a/docs/Architecture.md +++ b/docs/Architecture.md @@ -14,7 +14,7 @@ swappable** and the **core runs headless** (and in the browser). The namespace i | `CrossEscPos.Core` | `CrossEscPos.Emulator`, `CrossEscPos.EscPos`, … | Headless ESC/POS interpreter, printer state machine, receipt document model, barcode/QR generation. ESC/POS code maps (2D families, code tables, barcode systems, status requests) are behaviour-carrying `SmartEnum`s, not magic-number switches | Abstractions, QRCoder, ZXing.Net, Ardalis.SmartEnum | | `CrossEscPos.Rendering.Skia` | `CrossEscPos.Rendering.Skia` | The default **render backend** (SkiaSharp). Swap it for another `IReceiptImageFactory`/`ITypefaceProvider`/`IImageEncoder` | Abstractions, SkiaSharp | | `CrossEscPos.Rendering.ImageSharp` | `CrossEscPos.Rendering.ImageSharp` | A **100% managed render backend** (ImageSharp) — no native dependency, so it runs in the browser (WebAssembly) without a native relink. Same output as the Skia backend | Abstractions, SixLabors.ImageSharp.Drawing | -| `CrossEscPos.Transports` | `CrossEscPos.Transports` | TCP / serial / USB transports (desktop only) | Core, System.IO.Ports, LibUsbDotNet, ESC-POS-.NET | +| `CrossEscPos.Transports` | `CrossEscPos.Transports` | TCP / serial / USB transports (desktop only) | Core, System.IO.Ports, LibUsbDotNet | | `CrossEscPos.Controls` | `CrossEscPos.Controls` | Reusable Avalonia controls (`ReceiptView`, `PrinterStatePanel`) — host apps consume these. **Backend-agnostic** (no SkiaSharp dependency) | Core, Avalonia | `Core` carries **no UI and no graphics-backend dependency**, so the library works headless or in WASM. diff --git a/docs/Packages.md b/docs/Packages.md index 85d4f84..a910122 100644 --- a/docs/Packages.md +++ b/docs/Packages.md @@ -35,6 +35,44 @@ flowchart BT Host -.-> Transports ``` +## Breaking changes + +### `CrossEscPos.Transports` drops ESCPOS_NET + +`UsbPrinter` no longer derives from `ESCPOS_NET.BasePrinter`. It derives from `StreamPrinter`, this +package's own host-side printer, and so is an `IPrinterResponder` like the other transports. The +`ESCPOS_NET` dependency is gone, and with it the `SixLabors.ImageSharp` reference that existed only +to lift ESCPOS_NET's transitive 2.1.3 — the package now depends on `CrossEscPos.Core`, +`LibUsbDotNet` and `System.IO.Ports`, and nothing else. + +What this changes for a consumer holding a `UsbPrinter`: + +| Was, on `BasePrinter` | Is now | +| --- | --- | +| `Write(byte[])`, `Write(byte[][])` | `Send(byte[])` — the `IPrinterResponder` method | +| `event EventHandler StatusChanged` with a parsed `PrinterStatusEventArgs` | `event Action StatusFrameReceived` with the raw 4-byte Automatic Status Back block; decode it with `CrossEscPos.Emulator.AutoStatusBackReader.Parse` | +| `Status`, `PrinterName`, `GetStatus()`, `Flush(…)`, `Connected` / `Disconnected` | not replaced — see below | +| writes queued on a background pump, failures swallowed | `Send` writes synchronously and throws on failure | +| `protected override void OverridableDispose()` | ordinary `IDisposable`; override `Dispose(bool)` | + +Three status flags ESCPOS_NET parsed are not surfaced: *paper currently feeding*, *waiting for +online recovery* and *feed button pushed*. Nothing in this repository read them, and the bits are +still in the block `StatusFrameReceived` hands over, so a consumer that needs them can read them. +`GetStatus()` threw `NotImplementedException` in ESCPOS_NET and has no replacement. `Connected` and +`Disconnected` never fired for USB, because `BasePrinter` only raised them from the network +printer's reconnect logic. + +Two decode details were kept deliberately, because ESCPOS_NET had them and a real printer can +exercise them: a block whose first byte lacks the ASB fixed bits is rejected rather than decoded, +and the error flag covers all four byte-1 error bits (recoverable, unrecoverable, autocutter and +recoverable non-autocutter), not just the two the emulator itself emits. + +Why: ESCPOS_NET 3.0.0 is its last release (2022-08-18) and upstream's last commit is 2024-09-18. It +pinned `SixLabors.ImageSharp` 2.x, which no longer has a release without published advisories, and +its `PrintImage` has been broken since ImageSharp 3.x. `UsbPrinter` used almost none of +`BasePrinter` — it built its own reader and writer and overrode disposal — so the dependency bought +a 4-byte status parse and cost the whole package's dependency floor. + ## Choosing a render backend | | `Rendering.Skia` | `Rendering.ImageSharp` | diff --git a/docs/Transports.md b/docs/Transports.md index ef538d7..a98087f 100644 --- a/docs/Transports.md +++ b/docs/Transports.md @@ -51,6 +51,30 @@ hardware"*. needs the native `libusb-1.0` at runtime (`brew install libusb`, `apt install libusb-1.0-0`; bundled on Windows). +Unlike the two servers above it is the *host* side of the conversation, so it is a `StreamPrinter`: +ESC/POS goes out through `Send` (the `IPrinterResponder` method, split into 15,000-byte writes), and +the printer's Automatic Status Back blocks come back on `StatusFrameReceived`, one raw 4-byte block +at a time. `CrossEscPos.Emulator.AutoStatusBackReader.Parse` turns a block into a +`PrinterStatusReport`. + +```csharp +using var usb = new UsbPrinter(vid: 0x04B8, pid: 0x0202); +usb.StatusFrameReceived += frame => +{ + if (AutoStatusBackReader.Parse(frame) is { } status) + Console.WriteLine($"online={status.Online} paper-out={status.PaperOut}"); +}; +usb.Send(escPosBytes); +``` + +`StreamPrinter` works over any `Stream`, so the same write splitting and status framing can drive a +device node or a test double without USB. A stream that cannot be read is treated as send-only and +no status thread is started. + +> **This replaced a dependency on ESCPOS_NET**, which `UsbPrinter` used to inherit its stream pump +> and status parse from. See [Packages → Breaking changes](Packages.md#breaking-changes) for what a +> consumer holding a `UsbPrinter` has to change. + ## Lifetime & threading Start transports after constructing the printer and stop them on shutdown. Receive happens on a diff --git a/src/CrossEscPos.App.Desktop/Monitor/DesktopMonitorClient.cs b/src/CrossEscPos.App.Desktop/Monitor/DesktopMonitorClient.cs index 0c3d7a3..31fa027 100644 --- a/src/CrossEscPos.App.Desktop/Monitor/DesktopMonitorClient.cs +++ b/src/CrossEscPos.App.Desktop/Monitor/DesktopMonitorClient.cs @@ -7,21 +7,28 @@ using ESCPOS_NET.Emitters; using CrossEscPos.App.Monitor; using CrossEscPos.App.Transports; +using CrossEscPos.Emulator; using CrossEscPos.Transports; namespace CrossEscPos.App.Desktop.Monitor; /// -/// Desktop : connects to the emulator/printer over TCP, serial, or USB using -/// ESC-POS-.NET's family. Enables Automatic Status Back on connect and maps the -/// library's parsed onto the shared . +/// Desktop : connects to the emulator/printer over TCP, serial, or USB, +/// enables Automatic Status Back on connect, and reports the printer's status as +/// . +/// +/// The transports do not share a base type: TCP and serial use ESC-POS-.NET's +/// family, which parses the status channel itself into +/// , while USB is this repository's own +/// , which hands the raw 4-byte block over for +/// to decode. is where the two meet. /// public sealed class DesktopMonitorClient : IMonitorClient { private const string Tcp = "TCP", Serial = "Serial", Usb = "USB"; private readonly EPSON _e = new(); - private BasePrinter? _printer; + private IPrinterLink? _link; // TCP fields. private readonly TransportField _host = new("Host", "127.0.0.1"); @@ -120,7 +127,7 @@ public Task ConnectAsync() case Usb: if (!_usbByDisplay.TryGetValue(_usbDevice.Value ?? "", out var dev)) throw new InvalidOperationException("No USB device selected."); - _printer = new UsbPrinter(dev.Vid, dev.Pid); + _link = new UsbLink(new UsbPrinter(dev.Vid, dev.Pid), RaiseStatus); target = dev.Display; break; @@ -128,25 +135,25 @@ public Task ConnectAsync() if (string.IsNullOrWhiteSpace(_serialPort.Value)) throw new InvalidOperationException("No serial port selected."); int baud = int.TryParse(_baud.Value, out var b) && b > 0 ? b : 9600; - _printer = new SerialPrinter(portName: _serialPort.Value, baudRate: baud); + _link = new EscPosNetLink( + new SerialPrinter(portName: _serialPort.Value, baudRate: baud), RaiseStatus); target = $"serial {_serialPort.Value} @ {baud}"; break; default: // TCP - _printer = new NetworkPrinter(new NetworkPrinterSettings + _link = new EscPosNetLink(new NetworkPrinter(new NetworkPrinterSettings { ConnectionString = $"{_host.Value}:{_port.Value}", PrinterName = "Monitor" - }); + }), RaiseStatus); target = $"{_host.Value}:{_port.Value}"; break; } try { - _printer.StatusChanged += OnStatusChanged; // Ask the emulator to push status on every state change (panel toggles show up here). - _printer.Write(_e.EnableAutomaticStatusBack()); + _link.Write(_e.EnableAutomaticStatusBack()); } catch (Exception ex) { @@ -161,35 +168,93 @@ public Task ConnectAsync() public Task SendAsync(byte[] data) { - var printer = _printer ?? throw new InvalidOperationException("Not connected."); - return Task.Run(() => printer.Write(data)); + var link = _link ?? throw new InvalidOperationException("Not connected."); + return Task.Run(() => link.Write(data)); } public void Disconnect() { - try + try { _link?.Dispose(); } + catch { /* ignore */ } + _link = null; + } + + private void RaiseStatus(MonitorStatus status) => StatusReceived?.Invoke(status); + + /// The connected printer, whichever transport it arrived over. + private interface IPrinterLink : IDisposable + { + void Write(byte[] data); + } + + /// + /// TCP and serial, over ESC-POS-.NET. The library owns the status channel and raises its own + /// parsed , which is mapped onto the shared snapshot here. + /// + private sealed class EscPosNetLink : IPrinterLink + { + private readonly BasePrinter _printer; + private readonly Action _onStatus; + + public EscPosNetLink(BasePrinter printer, Action onStatus) { - if (_printer is not null) - { - _printer.StatusChanged -= OnStatusChanged; - _printer.Dispose(); - } + _printer = printer; + _onStatus = onStatus; + _printer.StatusChanged += OnStatusChanged; + } + + public void Write(byte[] data) => _printer.Write(data); + + private void OnStatusChanged(object? sender, EventArgs e) + { + if (e is not PrinterStatusEventArgs s) + return; + _onStatus(new MonitorStatus( + Online: s.IsPrinterOnline == true, + PaperOut: s.IsPaperOut == true, + PaperLow: s.IsPaperLow == true, + CoverOpen: s.IsCoverOpen == true, + DrawerOpen: s.IsCashDrawerOpen == true, + Error: s.IsInErrorState == true)); + } + + public void Dispose() + { + _printer.StatusChanged -= OnStatusChanged; + _printer.Dispose(); } - catch { /* ignore */ } - _printer = null; } - private void OnStatusChanged(object? sender, EventArgs e) + /// + /// USB, over this repository's own transport. It frames the status channel into ASB blocks but + /// leaves the meaning of the bits to — the same decode the + /// browser head uses, so both heads report a given block identically. + /// + private sealed class UsbLink : IPrinterLink { - if (e is not PrinterStatusEventArgs s) - return; - StatusReceived?.Invoke(new MonitorStatus( - Online: s.IsPrinterOnline == true, - PaperOut: s.IsPaperOut == true, - PaperLow: s.IsPaperLow == true, - CoverOpen: s.IsCoverOpen == true, - DrawerOpen: s.IsCashDrawerOpen == true, - Error: s.IsInErrorState == true)); + private readonly UsbPrinter _printer; + private readonly Action _onStatus; + + public UsbLink(UsbPrinter printer, Action onStatus) + { + _printer = printer; + _onStatus = onStatus; + _printer.StatusFrameReceived += OnStatusFrame; + } + + public void Write(byte[] data) => _printer.Send(data); + + private void OnStatusFrame(byte[] frame) + { + if (MonitorStatus.From(AutoStatusBackReader.Parse(frame)) is { } status) + _onStatus(status); + } + + public void Dispose() + { + _printer.StatusFrameReceived -= OnStatusFrame; + _printer.Dispose(); + } } /// True when an exception was caused by libusb not being loadable. diff --git a/src/CrossEscPos.App/Monitor/MonitorStatus.cs b/src/CrossEscPos.App/Monitor/MonitorStatus.cs index 7e2fb5c..c758fac 100644 --- a/src/CrossEscPos.App/Monitor/MonitorStatus.cs +++ b/src/CrossEscPos.App/Monitor/MonitorStatus.cs @@ -1,9 +1,12 @@ +using System; +using CrossEscPos.Emulator; + namespace CrossEscPos.App.Monitor; /// -/// A platform-neutral snapshot of the printer status the emulator reports back. The desktop client maps -/// ESC-POS-.NET's parsed status onto this; the browser client parses the raw 4-byte Automatic Status Back -/// block itself (see ), so both drive the same indicator UI. +/// A platform-neutral snapshot of the printer status the emulator reports back. Both clients decode +/// the raw 4-byte Automatic Status Back block with and map it +/// here, so the desktop and browser heads drive the same indicator UI from the same decode. /// public sealed record MonitorStatus( bool Online, @@ -16,25 +19,24 @@ public sealed record MonitorStatus( public bool Ready => Online && !PaperOut && !CoverOpen && !Error; /// - /// Reverses StatusByteBuilder.AutoStatusBack: interprets the emulator's 4-byte ASB block. - /// Returns null when the buffer isn't a 4-byte block (e.g. an unrelated response). + /// Interprets the emulator's 4-byte ASB block. Returns null when the buffer isn't a whole number + /// of blocks, or when the last block isn't an ASB block at all (an unrelated response). /// public static MonitorStatus? FromAutoStatusBack(byte[] data) { // The emulator emits ASB as discrete 4-byte frames; if several arrive coalesced, read the last. - if (data is null || data.Length < 4 || data.Length % 4 != 0) + if (data is null || data.Length < AutoStatusBackReader.FrameLength + || data.Length % AutoStatusBackReader.FrameLength != 0) return null; - int off = data.Length - 4; - byte b0 = data[off], b1 = data[off + 1], b2 = data[off + 2]; - - bool drawerOpen = (b0 & 0x04) == 0; // bit2 SET = drawer closed - bool online = (b0 & 0x08) == 0; // bit3 SET = offline - bool coverOpen = (b0 & 0x20) != 0; // bit5 = cover open - bool error = (b1 & 0x60) != 0; // bits5,6 = recoverable / unrecoverable error - bool paperOut = (b2 & 0x0C) != 0; // bits2,3 = paper end - bool paperLow = !paperOut && (b2 & 0x03) != 0; // bits0,1 = near-end - - return new MonitorStatus(online, paperOut, paperLow, coverOpen, drawerOpen, error); + return From(AutoStatusBackReader.Parse( + data.AsSpan(data.Length - AutoStatusBackReader.FrameLength))); } + + /// Maps a decoded status block onto the indicator snapshot; null in, null out. + public static MonitorStatus? From(PrinterStatusReport? report) + => report is null + ? null + : new MonitorStatus(report.Online, report.PaperOut, report.PaperLow, + report.CoverOpen, report.DrawerOpen, report.Error); } diff --git a/src/CrossEscPos.Core/Emulator/AutoStatusBackReader.cs b/src/CrossEscPos.Core/Emulator/AutoStatusBackReader.cs new file mode 100644 index 0000000..fd4d6dd --- /dev/null +++ b/src/CrossEscPos.Core/Emulator/AutoStatusBackReader.cs @@ -0,0 +1,93 @@ +using System; + +namespace CrossEscPos.Emulator; + +/// +/// What one Automatic Status Back block says about the printer, as a host reading the status channel +/// sees it — the inverse of . +/// +/// +/// The ASB block carries three further flags that nothing in this repository reads +/// (paper currently feeding, waiting for online recovery, feed button pushed), +/// so they are not surfaced here. Add them to this record if a consumer ever needs them. +/// +public sealed record PrinterStatusReport( + bool Online, + bool PaperOut, + bool PaperLow, + bool CoverOpen, + bool DrawerOpen, + bool Error); + +/// +/// Reassembles and decodes the Automatic Status Back blocks a printer pushes back on its status +/// channel. A transport feeds raw bytes in as they arrive — in whatever sizes the wire delivers them +/// — and gets one complete 4-byte block out at a time. +/// +/// Bit layouts are the Epson TM ASB format, read back exactly as +/// writes them. +/// +public sealed class AutoStatusBackReader +{ + /// Length of one ASB block, in bytes. + public const int FrameLength = 4; + + // Byte 0 of a block has bit 4 set and bits 0, 1 and 7 clear. + private const byte Byte0MustBeClear = 0b1000_0011; + private const byte Byte0MustBeSet = 0b0001_0000; + + private readonly byte[] _frame = new byte[FrameLength]; + private int _filled; + + /// + /// Feeds bytes read from the status channel, invoking once per + /// complete block. Bytes left over from a partial block are kept for the next call, so a block + /// split across reads is still delivered whole. + /// + public void Feed(ReadOnlySpan data, Action onFrame) + { + ArgumentNullException.ThrowIfNull(onFrame); + + foreach (byte b in data) + { + _frame[_filled++] = b; + if (_filled < FrameLength) + continue; + + _filled = 0; + // A copy: the buffer is refilled by the next block, and a handler may keep this one. + onFrame(_frame.AsSpan().ToArray()); + } + } + + /// + /// Decodes one ASB block. Returns null when is not an ASB block + /// — the wrong length, or byte 0 without the block's fixed bit pattern (a DLE EOT or + /// GS r reply that happens to be four bytes long, say). Rejecting those rather than + /// decoding them keeps a status the printer never sent out of the host's hands. + /// + public static PrinterStatusReport? Parse(ReadOnlySpan frame) + { + if (frame.Length != FrameLength) + return null; + + byte printer = frame[0], error = frame[1], paper = frame[2]; + + if ((printer & Byte0MustBeClear) != 0 || (printer & Byte0MustBeSet) == 0) + return null; + + // Each paper sensor reading is duplicated across two bits, so both must agree before it + // counts; and once the roll is out, near-end says nothing a caller still needs. + bool paperOut = (paper & 0x04) != 0 && (paper & 0x08) != 0; // bits 2 + 3 + bool paperLow = !paperOut && (paper & 0x01) != 0 && (paper & 0x02) != 0; // bits 0 + 1 + + return new PrinterStatusReport( + Online: (printer & 0x08) == 0, // bit 3 set = offline + PaperOut: paperOut, + PaperLow: paperLow, + CoverOpen: (printer & 0x20) != 0, // bit 5 + DrawerOpen: (printer & 0x04) == 0, // bit 2 set = drawer closed + // Recoverable (6), unrecoverable (5), autocutter (3), recoverable non-autocutter (2). + Error: (error & 0x6C) != 0); + } +} diff --git a/src/CrossEscPos.Transports/CrossEscPos.Transports.csproj b/src/CrossEscPos.Transports/CrossEscPos.Transports.csproj index 2e827b7..0726144 100644 --- a/src/CrossEscPos.Transports/CrossEscPos.Transports.csproj +++ b/src/CrossEscPos.Transports/CrossEscPos.Transports.csproj @@ -14,12 +14,8 @@ - - - - diff --git a/src/CrossEscPos.Transports/StreamPrinter.cs b/src/CrossEscPos.Transports/StreamPrinter.cs new file mode 100644 index 0000000..ebea12e --- /dev/null +++ b/src/CrossEscPos.Transports/StreamPrinter.cs @@ -0,0 +1,150 @@ +using System; +using System.IO; +using System.Threading; +using CrossEscPos.Emulator; + +namespace CrossEscPos.Transports; + +/// +/// A printer driven over a byte stream: ESC/POS jobs go out through , and the +/// Automatic Status Back blocks the printer pushes back arrive on . +/// +/// This is the host side of the conversation — the mirror of / +/// , which play the printer. It carries no ESC/POS knowledge beyond +/// handing the status channel to ; subclasses supply the stream. +/// +public class StreamPrinter : IPrinterResponder, IDisposable +{ + /// + /// Largest single write handed to the stream; a longer job is split into this many bytes at a + /// time. Receipt printers have small input buffers and some transports cap a transfer's size. + /// + public const int MaxBytesPerWrite = 15_000; + + private const int ReadBufferSize = 64; // one full-speed bulk packet; an ASB block is 4 bytes. + private const int IdleReadDelayMs = 50; // back-off after a read that returned nothing. + private const int StopTimeoutMs = 2_000; // bound on waiting for the status thread to finish. + + private readonly Stream _stream; + private readonly AutoStatusBackReader _statusReader = new(); + private readonly CancellationTokenSource _stopping = new(); + private readonly Lock _writeLock = new(); + private readonly Thread? _statusThread; + + private volatile bool _disposed; + + /// A label for logs and errors (the device or endpoint this talks to). + public string Name { get; } + + /// + /// Raised once per complete 4-byte Automatic Status Back block read from the printer. Raised on + /// the status thread, so a handler that touches UI state must marshal to its own thread. + /// Decode a block with . + /// + public event Action? StatusFrameReceived; + + /// + /// The transport. Writes are the ESC/POS channel; reads are the printer's status channel. A + /// stream whose is false is treated as send-only and no status + /// thread is started. Disposed with this instance. + /// + /// A label for this printer; see . + public StreamPrinter(Stream stream, string name) + { + _stream = stream ?? throw new ArgumentNullException(nameof(stream)); + Name = string.IsNullOrEmpty(name) ? stream.GetType().Name : name; + + if (!_stream.CanRead) + return; + + _statusThread = new Thread(ReadStatusLoop) { IsBackground = true, Name = $"{Name} status" }; + _statusThread.Start(); + } + + /// + /// Writes an ESC/POS job to the printer, split into -byte writes + /// and flushed once the whole job is out. Calls are serialised, so two senders cannot interleave + /// halves of their jobs on the wire. + /// + /// This printer has been disposed. + public void Send(byte[] data) + { + ArgumentNullException.ThrowIfNull(data); + ObjectDisposedException.ThrowIf(_disposed, this); + + if (data.Length == 0) + return; + + lock (_writeLock) + { + for (int sent = 0; sent < data.Length;) + { + int chunk = Math.Min(MaxBytesPerWrite, data.Length - sent); + _stream.Write(data, sent, chunk); + sent += chunk; + } + _stream.Flush(); + } + } + + private void ReadStatusLoop() + { + var buffer = new byte[ReadBufferSize]; + var token = _stopping.Token; + + while (!token.IsCancellationRequested) + { + int read; + try + { + read = _stream.Read(buffer, 0, buffer.Length); + } + catch (ObjectDisposedException) + { + return; // the stream is gone for good — there is nothing left to retry. + } + catch (Exception) + { + // A failed status read must not take printing down with it, and must not turn into a + // hot loop: treat it as "nothing arrived", back off below, and try again. A hard + // transport failure still surfaces to the caller through Send. + read = 0; + } + + if (read <= 0) + { + // A zero-length read means "no status yet", not end of stream: the status channel + // stays open for the printer's whole life and is idle most of the time. + if (!token.IsCancellationRequested) + Thread.Sleep(IdleReadDelayMs); + continue; + } + + _statusReader.Feed(buffer.AsSpan(0, read), frame => StatusFrameReceived?.Invoke(frame)); + } + } + + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (_disposed) + return; + _disposed = true; + + if (!disposing) + return; + + // Stop the status thread and wait for it before the stream goes away: letting a read sit in + // flight while the transport is torn down is a native use-after-free on USB, which no + // managed catch can recover from. + try { _stopping.Cancel(); } catch { /* ignore */ } + try { _statusThread?.Join(StopTimeoutMs); } catch { /* ignore */ } + try { _stream.Dispose(); } catch { /* ignore */ } + try { _stopping.Dispose(); } catch { /* ignore */ } + } +} diff --git a/src/CrossEscPos.Transports/UsbPrinter.cs b/src/CrossEscPos.Transports/UsbPrinter.cs index 74d412e..515f7e5 100644 --- a/src/CrossEscPos.Transports/UsbPrinter.cs +++ b/src/CrossEscPos.Transports/UsbPrinter.cs @@ -3,7 +3,6 @@ using System.IO; using System.Linq; using System.Threading; -using ESCPOS_NET; using LibUsbDotNet.LibUsb; using LibUsbDotNet.Main; @@ -19,10 +18,11 @@ public sealed record UsbDeviceInfo(int Vid, int Pid) /// A backed by a USB device's bulk endpoints: writes go to the bulk-OUT /// endpoint, reads come from the bulk-IN endpoint (the printer's status channel). /// -/// USB bulk transfers are packet-oriented, but reads its status channel -/// one byte at a time. So reads are buffered: a single bulk transfer fills an internal buffer that -/// is then served byte-by-byte. returns 0 on timeout (no data yet) rather than -/// blocking, which keeps the printer's read loop responsive without hot-spinning. +/// USB bulk transfers are packet-oriented while a stream reader may ask for fewer bytes than a +/// packet carries, so reads are buffered: one bulk transfer fills an internal buffer that is then +/// served across as many calls as it takes. returns 0 on +/// timeout (no data yet) rather than blocking, which keeps the status read loop responsive without +/// hot-spinning. /// internal sealed class UsbStream : Stream { @@ -80,7 +80,7 @@ public override int Read(byte[] buffer, int offset, int count) if (_reader is null || _closing) { // Send-only device (no bulk-IN endpoint), or we're tearing down: idle briefly so the - // printer's read loop doesn't spin, and never touch the (closing) native handle. + // status read loop doesn't spin, and never touch the (closing) native handle. Thread.Sleep(ReadTimeoutMs); return 0; } @@ -127,25 +127,31 @@ protected override void Dispose(bool disposing) } /// -/// Direct USB printing via libusb (LibUsbDotNet), exposed as an ESC-POS so -/// it shares the exact same write queue and Automatic-Status-Back pipeline as the serial/TCP -/// printers — bytes go out the bulk-OUT endpoint and status comes back on the bulk-IN endpoint, so -/// the monitor reflects the emulator's reported state for USB too. +/// Direct USB printing via libusb (LibUsbDotNet): a over the device's +/// bulk endpoints, so ESC/POS goes out the bulk-OUT endpoint and Automatic Status Back comes back on +/// the bulk-IN endpoint — the monitor reflects the emulator's reported state for USB too. /// /// Requires native libusb-1.0 at runtime (macOS: brew install libusb; Debian/Ubuntu: /// apt install libusb-1.0-0; bundled on Windows). If it's missing, or the OS already owns the /// device (e.g. a print queue has claimed it), construction throws and the caller surfaces the error. /// -public sealed class UsbPrinter : BasePrinter +public sealed class UsbPrinter : StreamPrinter { private const byte EndpointDirectionMask = 0x80; // bit 7 of bEndpointAddress: 0 = OUT, 1 = IN. private const byte EndpointTransferTypeMask = 0x03; // low 2 bits of bmAttributes select the transfer type. - private readonly UsbStream _stream; - static UsbPrinter() => EnsureNativeSearchPath(); - public UsbPrinter(int vid, int pid) : base($"USB {vid:X4}:{pid:X4}") + public UsbPrinter(int vid, int pid) : base(OpenDevice(vid, pid), $"USB {vid:X4}:{pid:X4}") + { + } + + /// + /// Opens the device and claims its first interface, returning a stream over its bulk endpoints. + /// Runs before the base constructor, so everything it allocates is either handed to the returned + /// stream (which owns it from then on) or released here. + /// + private static UsbStream OpenDevice(int vid, int pid) { EnsureNativeSearchPath(); @@ -174,10 +180,9 @@ public UsbPrinter(int vid, int pid) : base($"USB {vid:X4}:{pid:X4}") catch { reader = null; } } - _stream = new UsbStream(context, devices, device, writer, reader); - Writer = new BinaryWriter(_stream); - Reader = new BinaryReader(_stream); - transferred = true; // _stream now owns the device collection + context. + var stream = new UsbStream(context, devices, device, writer, reader); + transferred = true; // the stream now owns the device collection + context. + return stream; } finally { @@ -189,11 +194,6 @@ public UsbPrinter(int vid, int pid) : base($"USB {vid:X4}:{pid:X4}") } } - protected override void OverridableDispose() - { - try { _stream?.Dispose(); } catch { /* ignore */ } - } - /// Enumerates connected USB devices (vendor/product ids). public static IReadOnlyList ListDevices() { diff --git a/tests/CrossEscPos.Transports.Tests/AutoStatusBackReaderTests.cs b/tests/CrossEscPos.Transports.Tests/AutoStatusBackReaderTests.cs new file mode 100644 index 0000000..c2a1279 --- /dev/null +++ b/tests/CrossEscPos.Transports.Tests/AutoStatusBackReaderTests.cs @@ -0,0 +1,228 @@ +using System; +using System.Collections.Generic; +using CrossEscPos.Emulator; +using CrossEscPos.Emulator.Enums; +using Xunit; + +namespace CrossEscPos.Transports.Tests; + +/// +/// Framing and bit-layout coverage for the Automatic Status Back reader — the decode a host does on +/// the printer's status channel, and the exact inverse of +/// . +/// +/// +/// These cover CrossEscPos.Core and belong in CrossEscPos.Core.Tests; they live here +/// because that project cannot currently be built — it references +/// CrossEscPos.Rendering.ImageSharp, whose ImageSharp 3.1.12 pin fails the repository's +/// warnings-as-errors NuGet audit. Move them once that is resolved. +/// +public class AutoStatusBackReaderTests +{ + private static readonly bool[] Bools = { false, true }; + + /// Byte 0 with only the block's fixed bit set — an otherwise all-clear status. + private const byte Byte0Fixed = 0x10; + + #region Round trip against the emulator + + [Fact] + public void Parse_IsTheInverseOfAutoStatusBack_ForEveryPrinterState() + { + var mismatches = new List(); + + foreach (bool online in Bools) + foreach (bool cover in Bools) + foreach (var paper in Enum.GetValues()) + foreach (bool drawer in Bools) + foreach (var error in Enum.GetValues()) + foreach (bool feed in Bools) + { + var state = new PrinterState + { + Online = online, + CoverOpen = cover, + Paper = paper, + DrawerOpen = drawer, + Error = error, + FeedButtonPressed = feed, + }; + + var expected = new PrinterStatusReport( + Online: online, + PaperOut: paper == PaperLevel.Out, + PaperLow: paper == PaperLevel.NearEnd, + CoverOpen: cover, + DrawerOpen: drawer, + Error: error != PrinterErrorState.None); + + var actual = AutoStatusBackReader.Parse(StatusByteBuilder.AutoStatusBack(state)); + + if (actual != expected) + mismatches.Add( + $"online={online} cover={cover} paper={paper} drawer={drawer} " + + $"error={error} feed={feed}: expected {expected}, got " + + (actual?.ToString() ?? "null")); + } + + Assert.True(mismatches.Count == 0, + $"{mismatches.Count} state(s) did not round-trip:{Environment.NewLine}" + + string.Join(Environment.NewLine, mismatches)); + } + + #endregion + + #region Rejecting what is not a block + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(3)] + [InlineData(5)] + [InlineData(8)] + public void Parse_RejectsAnythingThatIsNotExactlyOneBlock(int length) + => Assert.Null(AutoStatusBackReader.Parse(new byte[length])); + + [Theory] + [InlineData(0x00)] // bit 4 clear + [InlineData(0x11)] // bit 0 set + [InlineData(0x12)] // bits 1 + 4 — the DLE EOT / GS r fixed pattern, which is not an ASB block + [InlineData(0x90)] // bit 7 set + public void Parse_RejectsAByteZeroWithoutTheBlocksFixedBits(byte byte0) + => Assert.Null(AutoStatusBackReader.Parse(new byte[] { byte0, 0x00, 0x00, 0x00 })); + + #endregion + + #region Bit layout + + [Fact] + public void Parse_ReadsByteZero() + { + Assert.False(Parse(Byte0Fixed | 0x08).Online); // bit 3 set = offline + Assert.True(Parse(Byte0Fixed).Online); + Assert.True(Parse(Byte0Fixed | 0x20).CoverOpen); // bit 5 + Assert.False(Parse(Byte0Fixed).CoverOpen); + + // The drawer bit is inverted: set means the drawer is closed. + Assert.True(Parse(Byte0Fixed).DrawerOpen); + Assert.False(Parse(Byte0Fixed | 0x04).DrawerOpen); + + static PrinterStatusReport Parse(int byte0) + => AutoStatusBackReader.Parse(new byte[] { (byte)byte0, 0x00, 0x00, 0x00 })!; + } + + [Fact] + public void Parse_FoldsAllFourErrorBitsIntoTheErrorFlag() + { + // ESC-POS-.NET's IsInErrorState was the OR of four byte-1 bits: recoverable (6), + // unrecoverable (5), autocutter (3) and recoverable-non-autocutter (2). The emulator only + // ever sets 5 and 6, but a real printer sets the other two, so all four are honoured. + foreach (int bit in new[] { 2, 3, 5, 6 }) + Assert.True(Parse(1 << bit).Error, $"byte 1 bit {bit} should read as an error"); + + // Bit 1 is "feed button pushed" and bit 4 is fixed — neither is an error. + Assert.False(Parse(0b0001_0010).Error); + + static PrinterStatusReport Parse(int byte1) + => AutoStatusBackReader.Parse(new byte[] { Byte0Fixed, (byte)byte1, 0x00, 0x00 })!; + } + + [Fact] + public void Parse_TreatsThePaperSensorBitsAsPairs() + { + // The Epson layout duplicates each sensor reading across two bits; a lone bit is not a + // reading, so it is not reported as one. + Assert.False(Parse(0b0000_0001).PaperLow); + Assert.False(Parse(0b0000_0010).PaperLow); + Assert.True(Parse(0b0000_0011).PaperLow); + + Assert.False(Parse(0b0000_0100).PaperOut); + Assert.False(Parse(0b0000_1000).PaperOut); + Assert.True(Parse(0b0000_1100).PaperOut); + + static PrinterStatusReport Parse(int byte2) + => AutoStatusBackReader.Parse(new byte[] { Byte0Fixed, 0x00, (byte)byte2, 0x00 })!; + } + + [Fact] + public void Parse_LetsPaperOutWinOverPaperLow() + { + // The emulator sets the near-end pair as well once the roll is out, and every consumer reads + // PaperLow only when PaperOut is false. + var report = AutoStatusBackReader.Parse(new byte[] { Byte0Fixed, 0x00, 0b0000_1111, 0x00 })!; + + Assert.True(report.PaperOut); + Assert.False(report.PaperLow); + } + + [Fact] + public void Parse_IgnoresByteThree() + { + // Byte 3 of the block carries nothing this reader uses; a value there must not change the + // decode or get the block rejected. + var plain = AutoStatusBackReader.Parse(new byte[] { Byte0Fixed, 0x00, 0x00, 0x00 }); + var noisy = AutoStatusBackReader.Parse(new byte[] { Byte0Fixed, 0x00, 0x00, 0xFF }); + + Assert.Equal(plain, noisy); + } + + #endregion + + #region Framing + + [Fact] + public void Feed_EmitsOneFramePerFourBytes() + { + var frames = new List(); + new AutoStatusBackReader().Feed(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, frames.Add); + + Assert.Equal(2, frames.Count); + Assert.Equal(new byte[] { 1, 2, 3, 4 }, frames[0]); + Assert.Equal(new byte[] { 5, 6, 7, 8 }, frames[1]); + } + + [Fact] + public void Feed_HoldsBackAPartialFrameUntilItCompletes() + { + var reader = new AutoStatusBackReader(); + var frames = new List(); + + reader.Feed(new byte[] { 1, 2, 3 }, frames.Add); + Assert.Empty(frames); + + reader.Feed(new byte[] { 4, 5 }, frames.Add); + Assert.Equal(new byte[] { 1, 2, 3, 4 }, Assert.Single(frames)); + + reader.Feed(new byte[] { 6, 7, 8 }, frames.Add); + Assert.Equal(2, frames.Count); + Assert.Equal(new byte[] { 5, 6, 7, 8 }, frames[1]); + } + + [Fact] + public void Feed_HandsOutFramesThatOutliveTheNextOne() + { + // The reader fills one buffer repeatedly; a caller that keeps a frame must not watch it + // change under them when the next block arrives. + var frames = new List(); + new AutoStatusBackReader().Feed(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, frames.Add); + + Assert.Equal(new byte[] { 1, 2, 3, 4 }, frames[0]); + Assert.NotSame(frames[0], frames[1]); + } + + [Fact] + public void Feed_DoesNothingWithNoBytes() + { + var frames = new List(); + new AutoStatusBackReader().Feed(ReadOnlySpan.Empty, frames.Add); + + Assert.Empty(frames); + } + + [Fact] + public void Feed_RejectsANullCallback() + => Assert.Throws( + () => new AutoStatusBackReader().Feed(new byte[] { 1 }, null!)); + + #endregion +} diff --git a/tests/CrossEscPos.Transports.Tests/CrossEscPos.Transports.Tests.csproj b/tests/CrossEscPos.Transports.Tests/CrossEscPos.Transports.Tests.csproj new file mode 100644 index 0000000..01e08e5 --- /dev/null +++ b/tests/CrossEscPos.Transports.Tests/CrossEscPos.Transports.Tests.csproj @@ -0,0 +1,21 @@ + + + + false + true + + false + + + + + + + + + + + + + + diff --git a/tests/CrossEscPos.Transports.Tests/FakeTransport.cs b/tests/CrossEscPos.Transports.Tests/FakeTransport.cs new file mode 100644 index 0000000..6c8dcca --- /dev/null +++ b/tests/CrossEscPos.Transports.Tests/FakeTransport.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; + +namespace CrossEscPos.Transports.Tests; + +/// +/// A standing in for a device, so the host-side transport can be exercised +/// without hardware. Writes are recorded individually (making write splitting observable) and reads +/// serve whatever the test queued on the status channel, returning 0 when nothing is pending — the +/// way a bulk read that timed out does. +/// +internal class FakeTransport : Stream +{ + private readonly Lock _gate = new(); + private readonly List _writes = new(); + private readonly Queue _status = new(); + private readonly bool _canRead; + + private int _flushes; + private int _readAttempts; + private bool _disposed; + + public FakeTransport(bool canRead = true) => _canRead = canRead; + + /// Every write the printer issued, in order and un-coalesced. + public IReadOnlyList Writes { get { lock (_gate) return _writes.ToArray(); } } + + /// Everything written, concatenated back into one job. + public byte[] WrittenBytes + { + get + { + lock (_gate) + { + var all = new List(); + foreach (var w in _writes) + all.AddRange(w); + return all.ToArray(); + } + } + } + + public int Flushes { get { lock (_gate) return _flushes; } } + public int ReadAttempts { get { lock (_gate) return _readAttempts; } } + public bool IsDisposed { get { lock (_gate) return _disposed; } } + + /// Makes bytes available on the printer's status channel. + public void PushStatus(params byte[] data) + { + lock (_gate) + foreach (var b in data) + _status.Enqueue(b); + } + + public override bool CanRead => _canRead; + public override bool CanWrite => true; + public override bool CanSeek => false; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + + public override void Flush() { lock (_gate) _flushes++; } + + public override void Write(byte[] buffer, int offset, int count) + { + lock (_gate) + _writes.Add(buffer.AsSpan(offset, count).ToArray()); + } + + public override int Read(byte[] buffer, int offset, int count) + { + lock (_gate) + { + _readAttempts++; + if (!_canRead) + throw new NotSupportedException("send-only transport"); + + int n = 0; + while (n < count && _status.Count > 0) + buffer[offset + n++] = _status.Dequeue(); + return n; // 0 — nothing on the status channel yet. + } + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) + lock (_gate) + _disposed = true; + base.Dispose(disposing); + } +} diff --git a/tests/CrossEscPos.Transports.Tests/StreamPrinterTests.cs b/tests/CrossEscPos.Transports.Tests/StreamPrinterTests.cs new file mode 100644 index 0000000..08135f3 --- /dev/null +++ b/tests/CrossEscPos.Transports.Tests/StreamPrinterTests.cs @@ -0,0 +1,244 @@ +using System; +using System.Collections.Concurrent; +using System.Linq; +using System.Threading; +using CrossEscPos.Emulator; +using CrossEscPos.Emulator.Enums; +using Xunit; + +namespace CrossEscPos.Transports.Tests; + +/// +/// The host side of a printer conversation over a stream: job splitting on the way out, and +/// Automatic Status Back framing on the way back. Driven over , so every +/// behaviour here is covered without a device attached. +/// +/// This is the behaviour UsbPrinter used to inherit from ESC-POS-.NET's BasePrinter. +/// +public class StreamPrinterTests +{ + /// Generous: the status thread backs off between reads, so a frame takes a moment. + private const int FrameWaitMs = 5_000; + + private static (StreamPrinter printer, FakeTransport transport, BlockingCollection frames) Connect() + { + var transport = new FakeTransport(); + var printer = new StreamPrinter(transport, "fake"); + var frames = new BlockingCollection(); + printer.StatusFrameReceived += frames.Add; + return (printer, transport, frames); + } + + #region Sending + + [Fact] + public void Send_SplitsAJobLongerThanOneWrite() + { + var transport = new FakeTransport(); + using var printer = new StreamPrinter(transport, "fake"); + + var job = new byte[StreamPrinter.MaxBytesPerWrite * 2 + 1_234]; + Random.Shared.NextBytes(job); + + printer.Send(job); + + Assert.Equal( + new[] { StreamPrinter.MaxBytesPerWrite, StreamPrinter.MaxBytesPerWrite, 1_234 }, + transport.Writes.Select(w => w.Length).ToArray()); + Assert.Equal(job, transport.WrittenBytes); + Assert.Equal(1, transport.Flushes); // one flush per job, not per chunk + } + + [Fact] + public void Send_WritesAShortJobWhole() + { + var transport = new FakeTransport(); + using var printer = new StreamPrinter(transport, "fake"); + + var job = new byte[] { 0x1B, 0x40, 0x0A }; // ESC @ then LF + printer.Send(job); + + Assert.Equal(job, Assert.Single(transport.Writes)); + Assert.Equal(1, transport.Flushes); + } + + [Fact] + public void Send_WritesNothingForAnEmptyJob() + { + var transport = new FakeTransport(); + using var printer = new StreamPrinter(transport, "fake"); + + printer.Send(Array.Empty()); + + Assert.Empty(transport.Writes); + Assert.Equal(0, transport.Flushes); + } + + [Fact] + public void Send_AfterDispose_Throws() + { + var printer = new StreamPrinter(new FakeTransport(), "fake"); + printer.Dispose(); + + Assert.Throws(() => printer.Send(new byte[] { 0x0A })); + } + + #endregion + + #region Status channel + + [Fact] + public void StatusChannel_RaisesOneFramePerFourByteBlock() + { + var (printer, transport, frames) = Connect(); + using (printer) + { + transport.PushStatus(0x10, 0x00, 0x00, 0x00, 0x14, 0x00, 0x03, 0x00); + + Assert.True(frames.TryTake(out var first, FrameWaitMs), "no first frame"); + Assert.True(frames.TryTake(out var second, FrameWaitMs), "no second frame"); + Assert.Equal(new byte[] { 0x10, 0x00, 0x00, 0x00 }, first); + Assert.Equal(new byte[] { 0x14, 0x00, 0x03, 0x00 }, second); + } + } + + [Fact] + public void StatusChannel_ReassemblesABlockSplitAcrossReads() + { + var (printer, transport, frames) = Connect(); + using (printer) + { + // Three bytes is not a block: nothing may be raised until the fourth arrives. + transport.PushStatus(0x10, 0x01, 0x02); + Assert.False(frames.TryTake(out _, 500), "a partial block was raised"); + + transport.PushStatus(0x03); + Assert.True(frames.TryTake(out var frame, FrameWaitMs), "no frame after completion"); + Assert.Equal(new byte[] { 0x10, 0x01, 0x02, 0x03 }, frame); + } + } + + [Fact] + public void StatusChannel_DecodesTheEmulatorsOwnBlock() + { + // End to end: the emulator writes the block, the transport frames it off the wire, and the + // reader decodes it — the whole path that used to run through BasePrinter. + var state = new PrinterState + { + Online = false, + CoverOpen = true, + Paper = PaperLevel.Out, + DrawerOpen = true, + Error = PrinterErrorState.Recoverable, + }; + + var (printer, transport, frames) = Connect(); + using (printer) + { + transport.PushStatus(StatusByteBuilder.AutoStatusBack(state)); + + Assert.True(frames.TryTake(out var frame, FrameWaitMs), "no status frame"); + var report = AutoStatusBackReader.Parse(frame); + + Assert.NotNull(report); + Assert.False(report.Online); + Assert.True(report.CoverOpen); + Assert.True(report.PaperOut); + Assert.False(report.PaperLow); // paper out wins over near-end + Assert.True(report.DrawerOpen); + Assert.True(report.Error); + } + } + + [Fact] + public void StatusChannel_KeepsReadingAfterAFailedRead() + { + // A status read that throws must not end status reporting; the next block still arrives. + var transport = new ThrowOnceTransport(); + using var printer = new StreamPrinter(transport, "fake"); + var frames = new BlockingCollection(); + printer.StatusFrameReceived += frames.Add; + + transport.PushStatus(0x10, 0x00, 0x00, 0x00); + + Assert.True(frames.TryTake(out var frame, FrameWaitMs), "no frame after a failed read"); + Assert.Equal(new byte[] { 0x10, 0x00, 0x00, 0x00 }, frame); + Assert.True(transport.Threw, "the transport never got to throw"); + } + + [Fact] + public void SendOnlyTransport_IsNeverReadFrom() + { + var transport = new FakeTransport(canRead: false); + using var printer = new StreamPrinter(transport, "fake"); + + printer.Send(new byte[] { 0x0A }); + Thread.Sleep(300); // long enough for a status thread to have tried several reads + + Assert.Equal(0, transport.ReadAttempts); + Assert.Single(transport.Writes); + } + + #endregion + + #region Lifetime + + [Fact] + public void Dispose_DisposesTheStream() + { + var transport = new FakeTransport(); + var printer = new StreamPrinter(transport, "fake"); + + printer.Dispose(); + + Assert.True(transport.IsDisposed); + } + + [Fact] + public void Dispose_StopsReadingTheStatusChannel() + { + var transport = new FakeTransport(); + var printer = new StreamPrinter(transport, "fake"); + + Thread.Sleep(200); // let the status thread get going + printer.Dispose(); + + int after = transport.ReadAttempts; + Thread.Sleep(300); + + Assert.Equal(after, transport.ReadAttempts); + } + + [Fact] + public void Dispose_IsIdempotent() + { + var printer = new StreamPrinter(new FakeTransport(), "fake"); + + printer.Dispose(); + printer.Dispose(); + } + + [Fact] + public void Constructor_RejectsANullStream() + => Assert.Throws(() => new StreamPrinter(null!, "fake")); + + #endregion + + /// A transport whose first status read throws, to prove the read loop survives it. + private sealed class ThrowOnceTransport : FakeTransport + { + private int _reads; + + public bool Threw { get; private set; } + + public override int Read(byte[] buffer, int offset, int count) + { + if (Interlocked.Increment(ref _reads) == 1) + { + Threw = true; + throw new InvalidOperationException("transient read failure"); + } + return base.Read(buffer, offset, count); + } + } +} From 97bd84b21aaa5da1b4f4842bd99452ecb147eef8 Mon Sep 17 00:00:00 2001 From: Daniel Meza Date: Thu, 8 Oct 2026 02:49:13 -0500 Subject: [PATCH 2/2] fix(transports): close the review findings on StreamPrinter MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A throwing StatusFrameReceived handler killed the process. The handler ran outside the read loop's try, on a bare thread, so a subscriber's exception was an unhandled exception on a managed thread. Reproduced: the test host aborted with "Unhandled exception ... at StreamPrinter.ReadStatusLoop". ESCPOS_NET's BasePrinter did not behave this way — its StatusChanged invoke sat inside a catch-all — so this was an unadmitted regression. Each invocation is now isolated, with a backstop around the framing. Dispose tore the stream down under an in-flight Send: _writeLock did not cover _stream.Dispose(), so a job already past the disposed check kept writing into a disposed stream. Dispose now flips the flag atomically first (so a Send waiting on the lock bounces), and takes the write lock — bounded, so a wedged transport cannot wedge teardown — before disposing the stream. Send re-checks under the lock. The Interlocked guard also stops two racing Dispose calls both running the teardown. The join's comment claimed it prevented a read being in flight at teardown. It does not: the token is only checked between reads. Corrected to state the real precondition — the stream bounds its own reads, and the native safety for USB is UsbStream's _closing flag and lock. Timeout cut 2 s -> 1 s, well clear of UsbStream's 200 ms read timeout. ConnectAsync did a synchronous USB bulk write on the UI thread: it had no await, and the Monitor awaits it from the UI thread. On main that call was BasePrinter.Write, an enqueue; it is now a real write that blocks up to the 5 s bulk timeout. Moved off the caller's thread. Also: MaxBytesPerWrite is static readonly rather than const, so it is not baked into consumers; documented that AutoStatusBackReader is single-reader and that Feed's positional grouping assumes an ASB-only channel (BasePrinter had the same property); documented that the status thread starts in the constructor. docs/Packages.md corrections: PrinterName IS replaced, by Name, with the same value; the OverridableDispose row only ever concerned a StreamPrinter subclass, since UsbPrinter is and was sealed; "used almost none of BasePrinter" undersold what was replaced (the pump, chunking, flush policy, read loop and framing, not just a 4-byte parse); and the IPrinterResponder line now says plainly that StreamPrinter is the host driving a printer while NetClient/SerialServer are the printer answering a host. Swept stale ESC-POS-.NET prose that is now wrong for USB (IMonitorClient, IPlatformServices, StatusByteBuilder, docs/Using-the-App.md), and declared App.Desktop's own ESCPOS_NET reference: it uses NetworkPrinter/SerialPrinter directly and was relying on a transitive path that Transports no longer carries. Tests 33 -> 41. New: a throwing handler does not stop the channel; Dispose waits out an in-flight Send and nothing is written post-teardown; Send propagates a write failure (the headline behaviour change, previously untested); Send serialises concurrent jobs; Send(null); Name and its fallback. Tightened the block-length rejection rows, which passed for the wrong reason — their byte 0 also failed the fixed-bit guard. Red before, against the pre-fix StreamPrinter: test host crashed on the handler test, Dispose_WaitsForAnInFlightSend failed. Green after: 41/41, and 172/172 across all three test projects. --- docs/Packages.md | 24 ++-- docs/Using-the-App.md | 3 +- .../CrossEscPos.App.Desktop.csproj | 4 + .../Monitor/DesktopMonitorClient.cs | 10 +- src/CrossEscPos.App/CrossEscPos.App.csproj | 3 +- src/CrossEscPos.App/IPlatformServices.cs | 3 +- src/CrossEscPos.App/Monitor/IMonitorClient.cs | 3 +- .../Emulator/AutoStatusBackReader.cs | 20 ++- .../Emulator/StatusByteBuilder.cs | 3 +- src/CrossEscPos.Transports/StreamPrinter.cs | 71 ++++++++-- .../AutoStatusBackReaderTests.cs | 12 +- .../FakeTransport.cs | 9 ++ .../StreamPrinterTests.cs | 125 ++++++++++++++++++ 13 files changed, 259 insertions(+), 31 deletions(-) diff --git a/docs/Packages.md b/docs/Packages.md index a910122..df64e0c 100644 --- a/docs/Packages.md +++ b/docs/Packages.md @@ -40,10 +40,12 @@ flowchart BT ### `CrossEscPos.Transports` drops ESCPOS_NET `UsbPrinter` no longer derives from `ESCPOS_NET.BasePrinter`. It derives from `StreamPrinter`, this -package's own host-side printer, and so is an `IPrinterResponder` like the other transports. The -`ESCPOS_NET` dependency is gone, and with it the `SixLabors.ImageSharp` reference that existed only -to lift ESCPOS_NET's transitive 2.1.3 — the package now depends on `CrossEscPos.Core`, -`LibUsbDotNet` and `System.IO.Ports`, and nothing else. +package's own host-side printer, whose one-method write surface is `IPrinterResponder.Send` — the +same interface `NetClient` and `SerialServer` implement, though note those two are the *printer* +answering a host, while `StreamPrinter` is the host driving a printer. The `ESCPOS_NET` dependency is +gone, and with it the `SixLabors.ImageSharp` reference that existed only to lift ESCPOS_NET's +transitive 2.1.3 — the package now depends on `CrossEscPos.Core`, `LibUsbDotNet` and +`System.IO.Ports`, and nothing else. What this changes for a consumer holding a `UsbPrinter`: @@ -51,9 +53,10 @@ What this changes for a consumer holding a `UsbPrinter`: | --- | --- | | `Write(byte[])`, `Write(byte[][])` | `Send(byte[])` — the `IPrinterResponder` method | | `event EventHandler StatusChanged` with a parsed `PrinterStatusEventArgs` | `event Action StatusFrameReceived` with the raw 4-byte Automatic Status Back block; decode it with `CrossEscPos.Emulator.AutoStatusBackReader.Parse` | -| `Status`, `PrinterName`, `GetStatus()`, `Flush(…)`, `Connected` / `Disconnected` | not replaced — see below | +| `PrinterName` | `Name` — same value, still `$"USB {vid:X4}:{pid:X4}"` | +| `Status`, `GetStatus()`, `Flush(…)`, `Connected` / `Disconnected` | not replaced — see below | | writes queued on a background pump, failures swallowed | `Send` writes synchronously and throws on failure | -| `protected override void OverridableDispose()` | ordinary `IDisposable`; override `Dispose(bool)` | +| `protected override void OverridableDispose()` | ordinary `IDisposable`. `UsbPrinter` is `sealed` (it already was), so this only concerns a `StreamPrinter` subclass, which overrides `Dispose(bool)` | Three status flags ESCPOS_NET parsed are not surfaced: *paper currently feeding*, *waiting for online recovery* and *feed button pushed*. Nothing in this repository read them, and the bits are @@ -69,9 +72,12 @@ recoverable non-autocutter), not just the two the emulator itself emits. Why: ESCPOS_NET 3.0.0 is its last release (2022-08-18) and upstream's last commit is 2024-09-18. It pinned `SixLabors.ImageSharp` 2.x, which no longer has a release without published advisories, and -its `PrintImage` has been broken since ImageSharp 3.x. `UsbPrinter` used almost none of -`BasePrinter` — it built its own reader and writer and overrode disposal — so the dependency bought -a 4-byte status parse and cost the whole package's dependency floor. +its `PrintImage` has been broken since ImageSharp 3.x. `UsbPrinter` already owned the parts that +touch the device — it built its own stream, reader and writer, and overrode disposal — so what the +dependency actually supplied was the generic stream pump above it: the write queue, the 15,000-byte +chunking, the flush policy, the read loop, the 4-byte framing and the bit decode. That is what +`StreamPrinter` and `AutoStatusBackReader` now do, in about 150 lines, without setting the whole +package's dependency floor. ## Choosing a render backend diff --git a/docs/Using-the-App.md b/docs/Using-the-App.md index 5b460e8..b357586 100644 --- a/docs/Using-the-App.md +++ b/docs/Using-the-App.md @@ -9,7 +9,8 @@ client that drives it over the wire (just like a real application would). The Mo both heads: click **Open monitor…** to launch it — a window on desktop, an in-page overlay in the browser. Its test jobs and status display are identical; only the transport differs: -- **Desktop** (built on [ESC-POS-.NET](https://github.com/lukevp/ESC-POS-.NET)) — pick a transport: +- **Desktop** (TCP and serial via [ESC-POS-.NET](https://github.com/lukevp/ESC-POS-.NET), USB via + `CrossEscPos.Transports`) — pick a transport: - **TCP/IP** — connect to the emulator's listener (or any networked printer). - **Serial** — pick a port + baud; pairs with the emulator's serial transport via a virtual port bridge. - **USB** — print **directly to a real USB printer** selected from the connected-device list (by diff --git a/src/CrossEscPos.App.Desktop/CrossEscPos.App.Desktop.csproj b/src/CrossEscPos.App.Desktop/CrossEscPos.App.Desktop.csproj index 559969b..e795a58 100644 --- a/src/CrossEscPos.App.Desktop/CrossEscPos.App.Desktop.csproj +++ b/src/CrossEscPos.App.Desktop/CrossEscPos.App.Desktop.csproj @@ -17,6 +17,10 @@ + + diff --git a/src/CrossEscPos.App.Desktop/Monitor/DesktopMonitorClient.cs b/src/CrossEscPos.App.Desktop/Monitor/DesktopMonitorClient.cs index 31fa027..19b12eb 100644 --- a/src/CrossEscPos.App.Desktop/Monitor/DesktopMonitorClient.cs +++ b/src/CrossEscPos.App.Desktop/Monitor/DesktopMonitorClient.cs @@ -119,7 +119,7 @@ private static void SetOptions(TransportField field, string[] options, string? k field.Value = keep is not null && options.Contains(keep) ? keep : options.FirstOrDefault() ?? ""; } - public Task ConnectAsync() + public async Task ConnectAsync() { string target; switch (_mode) @@ -153,7 +153,11 @@ public Task ConnectAsync() try { // Ask the emulator to push status on every state change (panel toggles show up here). - _link.Write(_e.EnableAutomaticStatusBack()); + // Off the caller's thread: this is now a real write rather than ESC-POS-.NET's enqueue, + // and on USB it blocks for up to the bulk write timeout — which would freeze the UI, + // since the Monitor awaits this from the UI thread. + var link = _link; + await Task.Run(() => link.Write(_e.EnableAutomaticStatusBack())).ConfigureAwait(false); } catch (Exception ex) { @@ -163,7 +167,7 @@ public Task ConnectAsync() throw; } - return Task.FromResult(target); + return target; } public Task SendAsync(byte[] data) diff --git a/src/CrossEscPos.App/CrossEscPos.App.csproj b/src/CrossEscPos.App/CrossEscPos.App.csproj index 50b59b1..470b2b8 100644 --- a/src/CrossEscPos.App/CrossEscPos.App.csproj +++ b/src/CrossEscPos.App/CrossEscPos.App.csproj @@ -17,7 +17,8 @@ + building). The desktop head declares its own reference for the serial/TCP printer types; + USB no longer comes from here at all. --> diff --git a/src/CrossEscPos.App/IPlatformServices.cs b/src/CrossEscPos.App/IPlatformServices.cs index 6ca4f35..4eb9ff1 100644 --- a/src/CrossEscPos.App/IPlatformServices.cs +++ b/src/CrossEscPos.App/IPlatformServices.cs @@ -34,7 +34,8 @@ public interface IPlatformServices IReadOnlyList CreateTransports(ReceiptPrinter printer); /// - /// Creates the platform's Monitor transport (desktop: TCP/serial/USB over ESC-POS-.NET; browser: + /// Creates the platform's Monitor transport (desktop: TCP/serial over ESC-POS-.NET, USB over + /// CrossEscPos.Transports; browser: /// SignalR to the host's proxy hub), or null if the platform has no Monitor. The shared Monitor view /// + test-job generation are platform-agnostic. /// diff --git a/src/CrossEscPos.App/Monitor/IMonitorClient.cs b/src/CrossEscPos.App/Monitor/IMonitorClient.cs index fa19431..1eb057a 100644 --- a/src/CrossEscPos.App/Monitor/IMonitorClient.cs +++ b/src/CrossEscPos.App/Monitor/IMonitorClient.cs @@ -7,7 +7,8 @@ namespace CrossEscPos.App.Monitor; /// /// The transport the shared uses to reach the emulator/printer. Desktop -/// implements TCP / serial / USB over ESC-POS-.NET; the browser implements a single SignalR mode that +/// implements TCP and serial over ESC-POS-.NET and USB over CrossEscPos.Transports' own UsbPrinter; +/// the browser implements a single SignalR mode that /// rides the host's proxy hub to the in-page emulator. The view model owns the test-job generation and the /// status/indicator UI; the client only carries bytes and surfaces the status the emulator sends back. /// diff --git a/src/CrossEscPos.Core/Emulator/AutoStatusBackReader.cs b/src/CrossEscPos.Core/Emulator/AutoStatusBackReader.cs index fd4d6dd..5f3851a 100644 --- a/src/CrossEscPos.Core/Emulator/AutoStatusBackReader.cs +++ b/src/CrossEscPos.Core/Emulator/AutoStatusBackReader.cs @@ -24,9 +24,14 @@ public sealed record PrinterStatusReport( /// channel. A transport feeds raw bytes in as they arrive — in whatever sizes the wire delivers them /// — and gets one complete 4-byte block out at a time. /// -/// Bit layouts are the Epson TM ASB format, read back exactly as -/// writes them. +/// Bit layouts are the Epson TM ASB format, read back as +/// writes them — with one deliberate exception, noted +/// on : near-end is not reported once the roll is out. /// +/// +/// Not thread-safe: carries the partial block between calls, so one instance +/// belongs to one reader loop. is static and safe to call from anywhere. +/// public sealed class AutoStatusBackReader { /// Length of one ASB block, in bytes. @@ -44,6 +49,13 @@ public sealed class AutoStatusBackReader /// complete block. Bytes left over from a partial block are kept for the next call, so a block /// split across reads is still delivered whole. /// + /// + /// Precondition: the channel carries nothing but ASB blocks. Grouping is positional — there is + /// no frame delimiter in the protocol to resynchronise on — so a single stray byte shifts every + /// later block by one, and then rejects all of them. A host that mixes + /// DLE EOT / GS r replies onto the same channel as ASB must frame those itself. + /// (ESC-POS-.NET's reader had the same positional grouping.) + /// public void Feed(ReadOnlySpan data, Action onFrame) { ArgumentNullException.ThrowIfNull(onFrame); @@ -65,6 +77,10 @@ public void Feed(ReadOnlySpan data, Action onFrame) /// — the wrong length, or byte 0 without the block's fixed bit pattern (a DLE EOT or /// GS r reply that happens to be four bytes long, say). Rejecting those rather than /// decoding them keeps a status the printer never sent out of the host's hands. + /// + /// is false whenever + /// is true, even though the printer sets both sensor + /// pairs in that state: near-end tells a caller nothing once the roll has run out. /// public static PrinterStatusReport? Parse(ReadOnlySpan frame) { diff --git a/src/CrossEscPos.Core/Emulator/StatusByteBuilder.cs b/src/CrossEscPos.Core/Emulator/StatusByteBuilder.cs index 1eb28cd..c2d4177 100644 --- a/src/CrossEscPos.Core/Emulator/StatusByteBuilder.cs +++ b/src/CrossEscPos.Core/Emulator/StatusByteBuilder.cs @@ -64,7 +64,8 @@ public static byte TransmitDrawerStatus(PrinterState s) /// /// The 4-byte Automatic Status Back block (sent on GS a / on every state change while enabled). - /// Byte layout matches the Epson TM ASB format as parsed by ESC-POS-.NET: byte 0 has fixed bit 4 + /// Byte layout matches the Epson TM ASB format, as read back by + /// (keep the two in step): byte 0 has fixed bit 4 /// (and bits 0,1,7 clear); the cash-drawer bit is inverted (open = bit 2 clear); paper-low/out /// use paired bits. /// diff --git a/src/CrossEscPos.Transports/StreamPrinter.cs b/src/CrossEscPos.Transports/StreamPrinter.cs index ebea12e..738beaa 100644 --- a/src/CrossEscPos.Transports/StreamPrinter.cs +++ b/src/CrossEscPos.Transports/StreamPrinter.cs @@ -19,11 +19,12 @@ public class StreamPrinter : IPrinterResponder, IDisposable /// Largest single write handed to the stream; a longer job is split into this many bytes at a /// time. Receipt printers have small input buffers and some transports cap a transfer's size. /// - public const int MaxBytesPerWrite = 15_000; + // Not a const: this ships in a package, and a const would be baked into every consumer. + public static readonly int MaxBytesPerWrite = 15_000; private const int ReadBufferSize = 64; // one full-speed bulk packet; an ASB block is 4 bytes. private const int IdleReadDelayMs = 50; // back-off after a read that returned nothing. - private const int StopTimeoutMs = 2_000; // bound on waiting for the status thread to finish. + private const int StopTimeoutMs = 1_000; // bound on waiting out the status thread / an in-flight write. private readonly Stream _stream; private readonly AutoStatusBackReader _statusReader = new(); @@ -31,7 +32,9 @@ public class StreamPrinter : IPrinterResponder, IDisposable private readonly Lock _writeLock = new(); private readonly Thread? _statusThread; - private volatile bool _disposed; + private int _disposed; // 0 = live, 1 = disposed. Interlocked, so Dispose runs its body once. + + private bool IsDisposed => Volatile.Read(ref _disposed) != 0; /// A label for logs and errors (the device or endpoint this talks to). public string Name { get; } @@ -49,6 +52,12 @@ public class StreamPrinter : IPrinterResponder, IDisposable /// thread is started. Disposed with this instance. /// /// A label for this printer; see . + /// + /// The status thread starts here, so can fire before a derived + /// constructor has finished: a subclass must not depend on its own initialisation being complete + /// by the first frame. Blocks that arrive before a handler is attached are dropped, which is what + /// the ESC-POS-.NET base class this replaced also did. + /// public StreamPrinter(Stream stream, string name) { _stream = stream ?? throw new ArgumentNullException(nameof(stream)); @@ -70,13 +79,17 @@ public StreamPrinter(Stream stream, string name) public void Send(byte[] data) { ArgumentNullException.ThrowIfNull(data); - ObjectDisposedException.ThrowIf(_disposed, this); + ObjectDisposedException.ThrowIf(IsDisposed, this); if (data.Length == 0) return; lock (_writeLock) { + // Re-checked under the lock: Dispose may have run while this call waited for it, and + // writing into a stream that has already been disposed is undefined for most streams. + ObjectDisposedException.ThrowIf(IsDisposed, this); + for (int sent = 0; sent < data.Length;) { int chunk = Math.Min(MaxBytesPerWrite, data.Length - sent); @@ -120,10 +133,28 @@ private void ReadStatusLoop() continue; } - _statusReader.Feed(buffer.AsSpan(0, read), frame => StatusFrameReceived?.Invoke(frame)); + try + { + _statusReader.Feed(buffer.AsSpan(0, read), RaiseStatusFrame); + } + catch (Exception) + { + // Backstop. This runs on a bare thread, so anything escaping here would be an + // unhandled exception on a managed thread — a process abort. + } } } + /// + /// Raises one block. A subscriber that throws must not take the status channel down with it, and + /// must not cost its siblings their block either, so each invocation is isolated. + /// + private void RaiseStatusFrame(byte[] frame) + { + try { StatusFrameReceived?.Invoke(frame); } + catch (Exception) { /* the subscriber's problem, not the transport's */ } + } + public void Dispose() { Dispose(disposing: true); @@ -132,19 +163,37 @@ public void Dispose() protected virtual void Dispose(bool disposing) { - if (_disposed) + // Flipped first and atomically: a Send waiting on the write lock re-checks this and bounces + // rather than writing into a stream that is about to go away, and two racing Dispose calls + // do not both run the teardown. + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; - _disposed = true; if (!disposing) return; - // Stop the status thread and wait for it before the stream goes away: letting a read sit in - // flight while the transport is torn down is a native use-after-free on USB, which no - // managed catch can recover from. + // Ask the status thread to stop and give it a moment. This is a bound, not a guarantee: the + // token is only checked between reads, so a stream whose Read blocks indefinitely will still + // be sitting in one when it is disposed below. Streams used here bound their own reads + // (UsbStream times out at 200 ms), and the native teardown-vs-in-flight-transfer safety for + // USB comes from UsbStream's own _closing flag and lock, not from this join. try { _stopping.Cancel(); } catch { /* ignore */ } try { _statusThread?.Join(StopTimeoutMs); } catch { /* ignore */ } - try { _stream.Dispose(); } catch { /* ignore */ } + + // Let an in-flight Send finish before the stream is disposed under it — bounded, so a wedged + // transport cannot wedge teardown as well. + bool holdingWriteLock = false; + try { holdingWriteLock = _writeLock.TryEnter(StopTimeoutMs); } catch { /* ignore */ } + try + { + try { _stream.Dispose(); } catch { /* ignore */ } + } + finally + { + if (holdingWriteLock) + _writeLock.Exit(); + } + try { _stopping.Dispose(); } catch { /* ignore */ } } } diff --git a/tests/CrossEscPos.Transports.Tests/AutoStatusBackReaderTests.cs b/tests/CrossEscPos.Transports.Tests/AutoStatusBackReaderTests.cs index c2a1279..735c0e3 100644 --- a/tests/CrossEscPos.Transports.Tests/AutoStatusBackReaderTests.cs +++ b/tests/CrossEscPos.Transports.Tests/AutoStatusBackReaderTests.cs @@ -77,11 +77,21 @@ public void Parse_IsTheInverseOfAutoStatusBack_ForEveryPrinterState() [Theory] [InlineData(0)] [InlineData(1)] + [InlineData(2)] [InlineData(3)] [InlineData(5)] [InlineData(8)] public void Parse_RejectsAnythingThatIsNotExactlyOneBlock(int length) - => Assert.Null(AutoStatusBackReader.Parse(new byte[length])); + { + // Byte 0 is a valid block header wherever there is room for one, so the length is the only + // thing that can make these invalid — otherwise the over-length rows would pass for the + // wrong reason. + var buffer = new byte[length]; + if (length > 0) + buffer[0] = Byte0Fixed; + + Assert.Null(AutoStatusBackReader.Parse(buffer)); + } [Theory] [InlineData(0x00)] // bit 4 clear diff --git a/tests/CrossEscPos.Transports.Tests/FakeTransport.cs b/tests/CrossEscPos.Transports.Tests/FakeTransport.cs index 6c8dcca..6883308 100644 --- a/tests/CrossEscPos.Transports.Tests/FakeTransport.cs +++ b/tests/CrossEscPos.Transports.Tests/FakeTransport.cs @@ -46,6 +46,11 @@ public byte[] WrittenBytes public int ReadAttempts { get { lock (_gate) return _readAttempts; } } public bool IsDisposed { get { lock (_gate) return _disposed; } } + /// Writes that landed after this stream was disposed — undefined behaviour for a real stream. + public int WritesAfterDispose { get { lock (_gate) return _writesAfterDispose; } } + + private int _writesAfterDispose; + /// Makes bytes available on the printer's status channel. public void PushStatus(params byte[] data) { @@ -65,7 +70,11 @@ public void PushStatus(params byte[] data) public override void Write(byte[] buffer, int offset, int count) { lock (_gate) + { + if (_disposed) + _writesAfterDispose++; _writes.Add(buffer.AsSpan(offset, count).ToArray()); + } } public override int Read(byte[] buffer, int offset, int count) diff --git a/tests/CrossEscPos.Transports.Tests/StreamPrinterTests.cs b/tests/CrossEscPos.Transports.Tests/StreamPrinterTests.cs index 08135f3..9846396 100644 --- a/tests/CrossEscPos.Transports.Tests/StreamPrinterTests.cs +++ b/tests/CrossEscPos.Transports.Tests/StreamPrinterTests.cs @@ -1,7 +1,9 @@ using System; using System.Collections.Concurrent; +using System.IO; using System.Linq; using System.Threading; +using System.Threading.Tasks; using CrossEscPos.Emulator; using CrossEscPos.Emulator.Enums; using Xunit; @@ -83,6 +85,50 @@ public void Send_AfterDispose_Throws() Assert.Throws(() => printer.Send(new byte[] { 0x0A })); } + [Fact] + public void Send_RejectsNull() + { + using var printer = new StreamPrinter(new FakeTransport(), "fake"); + + Assert.Throws(() => printer.Send(null!)); + } + + [Fact] + public void Send_PropagatesAWriteFailure() + { + // The headline change from the ESC-POS-.NET base class, which queued writes onto a pump that + // swallowed every exception: a failed write now reaches the caller. + using var printer = new StreamPrinter(new FailingWriteTransport(), "fake"); + + var ex = Assert.Throws(() => printer.Send(new byte[] { 0x1B, 0x40 })); + Assert.Equal("the device went away", ex.Message); + } + + [Fact] + public async Task Send_DoesNotInterleaveConcurrentJobs() + { + var transport = new SlowWriteTransport(perWriteMs: 50); + using var printer = new StreamPrinter(transport, "fake"); + + var a = Job(0xAA); + var b = Job(0xBB); + await Task.WhenAll(Task.Run(() => printer.Send(a)), Task.Run(() => printer.Send(b))); + + // Four writes, two per job. Serialised means two runs of two, not an alternation. + var marks = transport.Writes.Select(w => w[0]).ToArray(); + Assert.Equal(4, marks.Length); + Assert.Equal(marks[0], marks[1]); + Assert.Equal(marks[2], marks[3]); + Assert.NotEqual(marks[0], marks[2]); + + static byte[] Job(byte mark) + { + var job = new byte[StreamPrinter.MaxBytesPerWrite + 1]; + Array.Fill(job, mark); + return job; + } + } + #endregion #region Status channel @@ -166,6 +212,32 @@ public void StatusChannel_KeepsReadingAfterAFailedRead() Assert.True(transport.Threw, "the transport never got to throw"); } + [Fact] + public void StatusChannel_SurvivesAThrowingHandler() + { + // The status loop runs on a bare thread: an exception escaping a subscriber would be an + // unhandled exception on a managed thread, i.e. the whole process goes down. + var transport = new FakeTransport(); + using var printer = new StreamPrinter(transport, "fake"); + var seen = new BlockingCollection(); + int calls = 0; + + printer.StatusFrameReceived += frame => + { + seen.Add(frame); + if (Interlocked.Increment(ref calls) == 1) + throw new InvalidOperationException("handler blew up"); + }; + + transport.PushStatus(0x10, 0x00, 0x00, 0x00); + Assert.True(seen.TryTake(out _, FrameWaitMs), "the first block never reached the handler"); + + // The handler threw on that block; the channel must still be delivering. + transport.PushStatus(0x14, 0x00, 0x00, 0x00); + Assert.True(seen.TryTake(out var second, FrameWaitMs), "the channel died with the handler"); + Assert.Equal(new byte[] { 0x14, 0x00, 0x00, 0x00 }, second); + } + [Fact] public void SendOnlyTransport_IsNeverReadFrom() { @@ -218,12 +290,65 @@ public void Dispose_IsIdempotent() printer.Dispose(); } + [Fact] + public async Task Dispose_WaitsForAnInFlightSendBeforeTearingTheStreamDown() + { + // Writing into an already-disposed stream is undefined for most streams; Dispose must not + // pull the transport out from under a Send that is already part-way through a job. + var transport = new SlowWriteTransport(perWriteMs: 100); + var printer = new StreamPrinter(transport, "fake"); + + var job = new byte[StreamPrinter.MaxBytesPerWrite * 2 + 1]; // three writes, ~300 ms + var sending = Task.Run(() => printer.Send(job)); + + Assert.True(transport.FirstWriteStarted.Wait(FrameWaitMs), "the send never got going"); + printer.Dispose(); + await sending; // rethrows if the send was torn apart + + Assert.Equal(0, transport.WritesAfterDispose); + Assert.Equal(3, transport.Writes.Count); + Assert.True(transport.IsDisposed); + } + [Fact] public void Constructor_RejectsANullStream() => Assert.Throws(() => new StreamPrinter(null!, "fake")); + [Fact] + public void Name_IsTheLabelGiven() + => Assert.Equal("USB 04B8:0202", new StreamPrinter(new FakeTransport(), "USB 04B8:0202").Name); + + [Fact] + public void Name_FallsBackToTheStreamTypeWhenBlank() + => Assert.Equal(nameof(FakeTransport), new StreamPrinter(new FakeTransport(), "").Name); + #endregion + /// A transport whose writes fail, to prove Send does not swallow them. + private sealed class FailingWriteTransport : FakeTransport + { + public override void Write(byte[] buffer, int offset, int count) + => throw new IOException("the device went away"); + } + + /// A transport with slow writes, for the serialisation and teardown races. + private sealed class SlowWriteTransport : FakeTransport + { + private readonly int _perWriteMs; + + public SlowWriteTransport(int perWriteMs) => _perWriteMs = perWriteMs; + + public ManualResetEventSlim FirstWriteStarted { get; } = new(false); + + public override void Write(byte[] buffer, int offset, int count) + { + FirstWriteStarted.Set(); + // Recorded after the delay, so a write that lands post-teardown is visible as one. + Thread.Sleep(_perWriteMs); + base.Write(buffer, offset, count); + } + } + /// A transport whose first status read throws, to prove the read loop survives it. private sealed class ThrowOnceTransport : FakeTransport {