Repository navigation
Drop ESCPOS_NET from CrossEscPos.Transports - #27
Open
danielmeza wants to merge 2 commits into
Open
danielmeza wants to merge 2 commits into
danielmeza wants to merge 2 commits into
Conversation
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.
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.
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why
ESCPOS_NET3.0.0 is the library's last release (2022-08-18); upstream's last commit is 2024-09-18.CrossEscPos.Transportsdepended on it for exactly one type, and paid for it with the package'swhole dependency floor.
UsbPrinterwas the only one of the four transports deriving from it. Its three siblings use thisrepository's own seam:
src/CrossEscPos.Transports/UsbPrinter.csESCPOS_NET.BasePrintersrc/CrossEscPos.Transports/NetClient.csIPrinterRespondersrc/CrossEscPos.Transports/SerialServer.csIPrinterRespondersrc/CrossEscPos.Transports/NetServer.csAnd it used almost none of
BasePrinter: it built its ownBinaryWriter/BinaryReaderover its ownUsbStreamand overrodeOverridableDispose(). Everything else in the file wasUsbStream, which isplain
System.IO.Stream.What
BasePrinteractually did with the status bytesMeasured by decompiling the exact DLL this repository restores
(
~/.nuget/packages/escpos_net/3.0.0/lib/netstandard2.0/ESCPOS_NET.dll, viailspycmd), not fromupstream source:
ReadLongRunningTask()β a background loop:await Task.Delay(100), thenReader.BaseStream.ReadByte(). One byte per 100 ms. Each byte went into aConcurrentQueue<byte>and then calledDataAvailable().DataAvailable()βif (ReadBuffer.Count() % 4 != 0) return;then dequeue exactly 4 bytes.Since it ran once per byte, this degenerates to plain 4-byte grouping.
TryUpdatePrinterStatus(byte[4])β validated byte 0 (bit 4 set; bits 0, 1, 7 clear), built a12-property
PrinterStatusEventArgs, and raisedStatusChanged. Byte 3 was never read. Ifvalidation failed,
Statuswas left stale but the event still fired β theif (StatusChanged != null)block sits outside the validationif.So
UsbPrinterdid already read the channel itself (UsbStream.Read, bulk-IN, its own timeout andbuffer);
BasePrintercontributed the pump cadence, the 4-byte framing, and the bit decode.Someone consumes it, so the behaviour is preserved
The brief offered three exits. Exit 2 is the one the measurement forces:
src/CrossEscPos.App.Desktop/Monitor/DesktopMonitorClient.csheld the printer asBasePrinter?,subscribed
StatusChanged, and mappedPrinterStatusEventArgsontoMonitorStatusβ which drivesthe Monitor's Printer / Paper / Cover / Cash drawer / Error indicators. Deleting the parse would have
silently blanked the desktop USB status panel.
It is preserved with code already in the repository rather than a new parser:
MonitorStatus.FromAutoStatusBackβ the browser head's decode of the same 4-byte block(
WebMonitorClient.OnStatusBytes) β was already a second, independent implementation ofTryUpdatePrinterStatus. The two are now one.AutoStatusBackReader(new, inCrossEscPos.Core) frames the channel into 4-byte blocks anddecodes one. It sits next to
StatusByteBuilder.AutoStatusBack, whose exact inverse it is, and atest asserts that inverse over all 144
PrinterStatecombinations.MonitorStatus.FromAutoStatusBacknow delegates to it, so the desktop and browser heads reporta given block identically β they did not before.
StreamPrinter(new, inCrossEscPos.Transports) is the host side of a printer conversationover any
Stream:IPrinterResponder.Sendout, raw blocks back onStatusFrameReceived.UsbPrinterderives from it and supplies theUsbStream. Transports keeps no bit semantics, thesame as its three siblings.
Two ESCPOS_NET details kept on purpose
Both are invisible against this emulator and reachable on real hardware, so dropping them would have
been a silent regression:
decoded.
FromAutoStatusBackhad no such check and would happily decode aDLE EOT/GS rreplyinto a status the printer never sent. (Note
0x12β theDLE EOTfixed pattern this emulatoremits β is exactly such a buffer.)
PrinterStatusEventArgs.IsInErrorStatewas the OR of byte-1 bits 6, 5, 3and 2 (recoverable, unrecoverable, autocutter, recoverable non-autocutter). The old browser decode
read
(b1 & 0x60)β bits 6 and 5 only. The emulator never sets 3 or 2, but a real printer does, sothe mask is now
0x6C.What is lost, stated rather than hidden
online recovery, feed button pushed. Demonstrated unused β
grep -rnfor each acrosssrc/,tests/,samples/and both heads (App.Browser,App.Desktop) returns the ESCPOS_NETdeclarations and nothing else.
MonitorStatushas six fields and reads none of the three. The bitsare still in the block
StatusFrameReceiveddelivers, so a consumer that wants them can read them.PaperLowwhilePaperOut. ESCPOS_NET read each paper pair with&&and no masking, so a rollthat is out reported
IsPaperLow == trueas well (this emulator sets both pairs in that state).The kept decode suppresses
PaperLowwhenPaperOutβ the pre-existing browser behaviour. This isunobservable through
MonitorStatus: every consumer ofPaperLowis already guarded byPaperOut(MonitorViewModel:s.PaperOut ? "Out" : s.PaperLow ? "Low" : "OK", andReadyreadsonly
PaperOut).GetStatus(),Status,PrinterName,Flush(β¦),Connected,Disconnectedare notreplaced.
GetStatus()threwNotImplementedExceptionupstream;Connected/Disconnectedwereonly ever raised by the network printer's reconnect path, never for USB.
StatusChangedwith anall-
nullPrinterStatusEventArgs, which== trueturned into "Offline, no error" β a spuriousoffline flash. Now nothing is raised.
Two deliberate behaviour improvements
Sendis synchronous and throws.BasePrinter.Writeenqueued onto a 100 ms background pumpwhose body was
catch (IOException) { } catch { }β a USB write failure was dropped on the floor.MonitorViewModel.Sendalready wrapsSendAsyncin atry/catchthat logs, so a failure nowreaches the Monitor log instead of vanishing. Job splitting at 15,000 bytes
(
BasePrinter._maxBytesPerWrite) is preserved, with one flush per job.BasePrinterconsumed one byte per 100 ms, so a 4-byte block took ~400 msto surface after arrival.
StreamPrinterreads up to a packet at a time, so a block surfaces in oneread cycle.
UsbStream's read buffering is untouched (it is still correct, and its doc comment nolonger refers to a type that is gone).
Tests
New project
tests/CrossEscPos.Transports.Testsβ 41 tests, no hardware. It referencesCoreandTransportsonly. Two redβgreen cycles, both observed:Feed,Parse, and an unsplitSendFailed: 13, Passed: 20, Total: 33Failed: 0, Passed: 33, Total: 33StreamPrinterDispose_WaitsForAnInFlightSendβ¦failedFailed: 0, Passed: 41, Total: 41Neither red was a compile error. The port's sharpest one is the write splitting carried over from
BasePrinter:and the review fixes' red was not a failure but a process abort, which is the whole point of that
finding:
Coverage, driven over a
FakeTransportstream that records each write separately and serves thestatus channel:
per job, a short job written whole, an empty job writing nothing,
Send(null),SendafterDispose,Sendpropagating a write failure (the headline behaviour change, and previouslyuntested), and
Sendserialising two concurrent jobs without interleaving their chunks.raises nothing, the 4th completes it); the read loop surviving a throwing read; the channel
surviving a throwing handler; a send-only stream never being read from.
StatusByteBuilder.AutoStatusBack(state)pushed onto the wire, framed by thetransport, decoded by the reader, asserted field by field. This is the whole path that used to run
through
BasePrinter.Disposedisposing the stream, stopping the status reads (the read count stopsadvancing), being idempotent, waiting out an in-flight
Sendso nothing is written afterteardown, and
Nameplus its fallback.a valid byte 0 so only the length can reject them) and of byte 0 without the fixed bits (
0x00,0x11,0x12,0x90); each byte-0 bit including the inverted drawer bit; all four error bitsindividually; paired paper bits (a lone bit is not a reading);
PaperOutwinning overPaperLow;byte 3 ignored.
reuses one buffer).
What is not covered, and cannot be without a device: libusb itself β
UsbPrinter's constructorand endpoint discovery (
FindBulkEndpoints),UsbStream's native read/write and itsteardown-vs-in-flight-transfer lock, and
EnsureNativeSearchPath. All of that is unchanged by thisPR except for moving the constructor body into a static
OpenDevicefactory (so the stream can bebuilt before the base constructor runs) and deleting the
BinaryWriter/BinaryReaderwrappers. TheUsbStreamclass itself is byte-identical apart from its doc comment. Also uncovered: theDesktopMonitorClientrewiring, which has no test project of its own.Full suite: 172 passed, 0 failed β 129 Core + 2 Controls + 41 Transports, up from 131.
What the adversarial review changed
A read-only review of the first commit found two defects worth the second commit, both reproduced
before being fixed:
StatusFrameReceivedhandler killed the process. The handler ran outside the readloop's
try, on a bareThreadβ an unhandled exception on a managed thread.BasePrinterdidnot behave this way: its
StatusChanged?.Invokesat inside a catch-all, so a throwingsubscriber was swallowed. That made this an unadmitted regression, and
StreamPrinterispublic packaged API, so it was a consumer's process at stake. Each invocation is now isolated.
Disposetore the stream down under an in-flightSend._writeLockdid not cover_stream.Dispose(), so a job already past the disposed check kept writing into a disposedstream.
Disposenow flips the flag atomically first (a waitingSendbounces), then takes thewrite lock β bounded, so a wedged transport cannot wedge teardown β before disposing.
Sendre-checks under the lock.
Three more were real but smaller: the
Join's comment claimed a guarantee it does not provide(the token is only checked between reads, so a blocking read is still in flight at teardown β the
native safety for USB is
UsbStream's own flag and lock, and the comment now says so);Dispose'sguard was a non-atomic read-then-write; and
ConnectAsynchad noawaitat all, so the now-realUSB write ran synchronously on the UI thread the Monitor awaits from β up to the 5 s bulk timeout,
where
main'sBasePrinter.Writewas just an enqueue. That one is moved off the caller's thread.Four claims of mine in
docs/Packages.mddid not survive and were corrected:PrinterNameisreplaced (by
Name, same value); theOverridableDisposerow only ever concerned aStreamPrintersubclass, since
UsbPrinteris and wassealed; "used almost none ofBasePrinter" undersold whatwas replaced; and the
IPrinterResponderline oversold a consistency that is really a directioninversion (below). Stale "over ESC-POS-.NET" prose in four more places was swept, and
App.Desktopnow declares its own
ESCPOS_NETreference instead of relying on a transitive path thatTransportsno longer carries.
One finding deliberately not acted on, for the owner to settle:
IPrinterResponderis documentedas "a channel the printer can write bytes back to the host over", and
ReceiptPrinter.RegisterResponderconsumes it as exactly that.
StreamPrinteris the host side, so implementing it inverts theinterface's direction β a
StreamPrintercould be registered as an emulator responder, where theemulator's status replies would be written out to the device as a print job. The contracts differ too:
NetClient.Sendlogs and swallows as a best-effort reply channel,StreamPrinter.Sendthrows.Nothing in the repo consumes
StreamPrinterthrough the interface, so dropping it would break no callsite. It is kept because it was asked for explicitly; say the word and it comes off.
Two findings were checked and left as documented preconditions rather than code changes, because
BasePrinterhad them identically and changing them would be a redesign:AutoStatusBackReaderissingle-reader (not thread-safe), and
Feed's grouping is positional, so a channel mixingDLE EOT/GS rreplies with ASB would desync permanently. Verified unreachable through the shippedMonitor, which never sends those requests.
The review also independently re-derived and confirmed the parts worth confirming:
Parseisbit-exact against both
StatusByteBuilder.AutoStatusBackand the decompiledTryUpdatePrinterStatus(no bit, mask or polarity wrong;
0x6Cis exactly the fourDid*propertiesIsInErrorStateORs);OpenDeviceis leak-equivalent to the original constructor on every throw path and the staticinitialiser still runs first;
Disconnect()is still safe twice, before connect, and after a failedconnect, with no printer leaked on any path; and
FromAutoStatusBackagrees with the old decode onevery byte sequence the emulator can emit, diverging only on real-hardware bytes where the new
behaviour matches both the Epson layout and
BasePrinter.The package has zero ImageSharp and zero ESCPOS_NET
The
SixLabors.ImageSharp2.1.13 pin existed only to lift ESCPOS_NET's transitive 2.1.3 (the commentabove it said so). No code in
Transportsused an ImageSharp API β verified: zero hits outside the.csproj. With ESCPOS_NET gone the pin has nothing to lift, so both are removed.Verified on the packed artefact, not on the project file:
And the project builds with the audit gate fully on (
NuGetAuditMode=all,TreatWarningsAsErrors=true, nothing suppressed):Nothing here touches the licence gate, suppresses an advisory, or adds a key.
CI is red, on 20 pre-existing errors β proven not to be this PR
Current state: run 37745824647
on
97bd84bfails at Restore with 20NU1902/NU1903errors. Every one isSixLabors.ImageSharp3.1.12, reaching throughCrossEscPos.Rendering.ImageSharp:Why this is not mine, measured rather than asserted
The first commit's CI ran green at 07:23 β build, all 164 tests, and all six packages packed. The
same commit, re-run at 07:52 with byte-identical code, failed with these same 20 errors:
cd0d18ecd0d18e97bd84bSo what changed between 07:23 and 07:52 was the runner's NuGet advisory feed catching up with the
Six Labors batch published 2026-10-07, not anything in this branch.
NuGetAuditMode=allplusTreatWarningsAsErrors=true(both inDirectory.Build.props) turn those advisories into errors.mainhas the same problem, worse β locally, with the gate untouched:main's last CI run was 2026-09-22, before the advisories existed, so its green badge is simply old.The local figures and CI now agree exactly β 20 errors, the same four projects, nothing from
Transports.It cannot be fixed here
The advisories' first patched release is 4.1.2; there is no patched 3.x. Clearing the remaining 20
means the ImageSharp 4 migration, which is
#25 β itself blocked on a Six Labors
licence only the owner can request. Doing it here would duplicate that PR and create exactly the
conflict this ordering is meant to avoid.
This PR strictly improves the number: 25 β 20. Nothing in it touches the audit, the licence gate,
NoWarn, or any workflow.What is nonetheless proven green
Build succeeded, 164 passed / 0 failed across all three test projects, and all six packagespacked including
CrossEscPos.Transports.1.3.2.nupkg.CrossEscPos.Transportsbuilds with the audit gate fully on, nothing suppressed:locally only, never committed:
tests/CrossEscPos.Transports.Testsneeds none of that: it does not referenceRendering.ImageSharp, so it builds and runs clean with the gate on. That is also why theAutoStatusBackReaderunit tests live there rather than inCrossEscPos.Core.Tests, which cannotcurrently be built at all β the test file says so, and says to move them once Move the ImageSharp backend to SixLabors.ImageSharp 4.1.2Β #25 lands.
Ordering against #25 β this one is meant to land first
#25 (
fix/imagesharp-4) also editssrc/CrossEscPos.Transports/CrossEscPos.Transports.csproj, moving the same ImageSharp pin from2.1.13 to 4.1.2. This PR deletes that pin and the
ESCPOS_NETreference above it. The twocollide on the same lines.
#25 is blocked indefinitely on a Six Labors Community licence only the owner can request. This PR is
blocked on nothing. So:
It removes one of the two licence-gate blockers
Worth stating precisely, because the obvious phrasing is wrong: no project trips the Six Labors
licence gate on
maintoday.ValidateLicenseTaskships only inSixLabors.ImageSharp4.x andSixLabors.ImageSharp.Drawing3.x β verified by looking for abuild/folder in each restoredpackage:
build/β¦targetswithValidateLicenseTaskSixLabors.ImageSharp2.1.3, 2.1.13build/folder at allSixLabors.ImageSharp3.1.12build/has only a.propsβ no targets, no taskSixLabors.ImageSharp4.1.2SixLabors.ImageSharp.Drawing2.1.7build/folder at allSixLabors.ImageSharp.Drawing3.1.2mainis on 2.1.13 / 3.1.12 + Drawing 2.1.7, so the gate is not reached. "Two projects trip it" istrue of #25's tree, not of
main.Conditional on #25, the "two projects" part checks out, and #25's own CI run says so directly rather
than by inference β 37735754861
fails twice, once per project, from two different packages' targets:
With this PR landed first,
Transportshas no ImageSharp at all, so the second of those two cannotoccur and #25 needs the key for
Rendering.ImageSharponly β two blockers become one. One keycleared both anyway, so this does not unblock #25; it narrows its blast radius and removes a project
from the licence surface permanently.
Breaking for consumers
UsbPrinterstops being aBasePrinter. Recorded for consumers indocs/Packages.mdunder a new## Breaking changesheading, in the same plainregister as the rest of that file: a was/is table for every member that moved, and the dropped flags
named individually.
<Version>is deliberately not bumped. This repository bumps it in its own commit (d7299e2 Bump version to 1.3.2), and #25 already editsDirectory.Build.propsto move the family to 1.4.0 βtouching it here would add a second conflict with #25 for no benefit. The docs entry states the
change without claiming a version.
docs/Architecture.mdstill listedESC-POS-.NETas aTransportsdependency; corrected.Not touched
CrossEscPos.Appkeeps its ownESCPOS_NETreference (MonitorViewModeluses theEPSONemitter tobuild test jobs), and
DesktopMonitorClientstill usesSerialPrinter/NetworkPrinter/BasePrinterfor the TCP and serial lanes. Those are out of scope: this PR removes the dependencyfrom the packaged library, where it sets a consumer's dependency floor, not from the app. The
consequence is that
DesktopMonitorClientnow bridges two unrelated printer types, which is what thenew private
IPrinterLinkseam is for β one implementation per status model, so the branching doesnot spread through
ConnectAsync,SendAsyncandDisconnect.One thing noticed and left alone: a
new UsbPrinter(...)that throws (the common libusb-missingcase) escapes
ConnectAsyncbefore thetrythat would callAppendLibusbHelp(), so that help textnever shows for a connect failure β only for a device-list failure. Pre-existing, unrelated to this
change, and fixing it would alter behaviour nobody asked about.