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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CrossEscPos.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,6 @@
<Folder Name="/tests/">
<Project Path="tests/CrossEscPos.Controls.Tests/CrossEscPos.Controls.Tests.csproj" />
<Project Path="tests/CrossEscPos.Core.Tests/CrossEscPos.Core.Tests.csproj" />
<Project Path="tests/CrossEscPos.Transports.Tests/CrossEscPos.Transports.Tests.csproj" />
</Folder>
</Solution>
2 changes: 1 addition & 1 deletion docs/Architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
44 changes: 44 additions & 0 deletions docs/Packages.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,50 @@ 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, 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`:

| Was, on `BasePrinter` | Is now |
| --- | --- |
| `Write(byte[])`, `Write(byte[][])` | `Send(byte[])` — the `IPrinterResponder` method |
| `event EventHandler StatusChanged` with a parsed `PrinterStatusEventArgs` | `event Action<byte[]> StatusFrameReceived` with the raw 4-byte Automatic Status Back block; decode it with `CrossEscPos.Emulator.AutoStatusBackReader.Parse` |
| `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`. `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
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` 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

| | `Rendering.Skia` | `Rendering.ImageSharp` |
Expand Down
24 changes: 24 additions & 0 deletions docs/Transports.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion docs/Using-the-App.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions src/CrossEscPos.App.Desktop/CrossEscPos.App.Desktop.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
</ItemGroup>

<ItemGroup>
<!-- The Monitor's TCP and serial lanes use ESC-POS-.NET's NetworkPrinter / SerialPrinter and its
parsed status events. Declared here rather than relied on transitively: USB stopped going
through this library, so CrossEscPos.Transports no longer carries it. -->
<PackageReference Include="ESCPOS_NET" Version="3.0.0" />
<PackageReference Include="Avalonia.Desktop" Version="12.0.4" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="12.0.4" />
<PackageReference Include="Avalonia.Fonts.Inter" Version="12.0.4" />
Expand Down
133 changes: 101 additions & 32 deletions src/CrossEscPos.App.Desktop/Monitor/DesktopMonitorClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/// <summary>
/// Desktop <see cref="IMonitorClient"/>: connects to the emulator/printer over TCP, serial, or USB using
/// ESC-POS-.NET's <see cref="BasePrinter"/> family. Enables Automatic Status Back on connect and maps the
/// library's parsed <see cref="PrinterStatusEventArgs"/> onto the shared <see cref="MonitorStatus"/>.
/// Desktop <see cref="IMonitorClient"/>: connects to the emulator/printer over TCP, serial, or USB,
/// enables Automatic Status Back on connect, and reports the printer's status as
/// <see cref="MonitorStatus"/>.
///
/// The transports do not share a base type: TCP and serial use ESC-POS-.NET's
/// <see cref="BasePrinter"/> family, which parses the status channel itself into
/// <see cref="PrinterStatusEventArgs"/>, while USB is this repository's own
/// <see cref="UsbPrinter"/>, which hands the raw 4-byte block over for
/// <see cref="AutoStatusBackReader"/> to decode. <see cref="IPrinterLink"/> is where the two meet.
/// </summary>
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");
Expand Down Expand Up @@ -112,41 +119,45 @@ private static void SetOptions(TransportField field, string[] options, string? k
field.Value = keep is not null && options.Contains(keep) ? keep : options.FirstOrDefault() ?? "";
}

public Task<string> ConnectAsync()
public async Task<string> ConnectAsync()
{
string target;
switch (_mode)
{
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;

case Serial:
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());
// 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)
{
Expand All @@ -156,40 +167,98 @@ public Task<string> ConnectAsync()
throw;
}

return Task.FromResult(target);
return target;
}

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);

/// <summary>The connected printer, whichever transport it arrived over.</summary>
private interface IPrinterLink : IDisposable
{
void Write(byte[] data);
}

/// <summary>
/// TCP and serial, over ESC-POS-.NET. The library owns the status channel and raises its own
/// parsed <see cref="PrinterStatusEventArgs"/>, which is mapped onto the shared snapshot here.
/// </summary>
private sealed class EscPosNetLink : IPrinterLink
{
private readonly BasePrinter _printer;
private readonly Action<MonitorStatus> _onStatus;

public EscPosNetLink(BasePrinter printer, Action<MonitorStatus> 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)
/// <summary>
/// USB, over this repository's own transport. It frames the status channel into ASB blocks but
/// leaves the meaning of the bits to <see cref="AutoStatusBackReader"/> — the same decode the
/// browser head uses, so both heads report a given block identically.
/// </summary>
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<MonitorStatus> _onStatus;

public UsbLink(UsbPrinter printer, Action<MonitorStatus> 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();
}
}

/// <summary>True when an exception was caused by libusb not being loadable.</summary>
Expand Down
3 changes: 2 additions & 1 deletion src/CrossEscPos.App/CrossEscPos.App.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
<PackageReference Include="Avalonia.Fonts.Inter" Version="12.0.4" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0" />
<!-- The Monitor's test-job generator uses the ESCPOS_NET EPSON emitter (pure managed byte
building; the native serial/USB printers live in the desktop head's transports). -->
building). The desktop head declares its own reference for the serial/TCP printer types;
USB no longer comes from here at all. -->
<PackageReference Include="ESCPOS_NET" Version="3.0.0" />
</ItemGroup>

Expand Down
3 changes: 2 additions & 1 deletion src/CrossEscPos.App/IPlatformServices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ public interface IPlatformServices
IReadOnlyList<Transports.TransportEntry> CreateTransports(ReceiptPrinter printer);

/// <summary>
/// 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.
/// </summary>
Expand Down
3 changes: 2 additions & 1 deletion src/CrossEscPos.App/Monitor/IMonitorClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ namespace CrossEscPos.App.Monitor;

/// <summary>
/// The transport the shared <see cref="MonitorViewModel"/> 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.
/// </summary>
Expand Down
Loading
Loading