diff --git a/docs/plans/job-store.md b/docs/plans/job-store.md index 9220ce1..3381469 100644 --- a/docs/plans/job-store.md +++ b/docs/plans/job-store.md @@ -280,7 +280,7 @@ PRINT ACKNOWLEDGEMENT ON EPSON PRINTERS - Unverified: whether the response reaches the host over port 9100 through the printer's Ethernet board (UB-E02 or UB-E03), and what happens to a response sent after the host closed the connection. Only a paper test can tell. - No other mechanism on raw port 9100 reports a job's progress. `DLE EOT`, automatic status (`GS a`) and `GS ( H` fn 49 report the printer's state. `GS r 1` answers once the preceding lines have fed, without an ID. ePOS-Print on newer models reports a print result over HTTP, a different transport. - Even a perfect acknowledgement leaves a window between the printer finishing and the daemon recording it, so the store must be safe without one. -- A side finding: the UB-E02 and UB-E03 boards turn automatic status on at power-on, and the `ESC @` that starts each job turns it off, as Epson's guides confirm (docs/plans/printers.md, Investigation findings). Until the first job after a power-on, the printer may send unrequested 4-byte status frames, which `printer.Client.Status`, reading one byte per request, could take as "status unsupported". Whether the frames reach a port 9100 client is unverified. +- A side finding: the UB-E02 and UB-E03 boards turn automatic status on at power-on, and the `ESC @` that starts each job turns it off, as Epson's guides confirm (docs/plans/printers.md, Investigation findings). Until the first job after a power-on, the printer may send unrequested 4-byte status frames. `printer.Client.Status` and `Send` pass over them, by the fixed bits of a frame's first byte, so they read neither as "status unsupported" nor as an answer to `GS r 1`, and with confirmation each `Send` turns them off with `GS a 0`. Whether the frames reach a port 9100 client is unverified. WHERE THE REPORTS DISAGREE OR ARE UNSURE - WAL bytes per job: about 15 KB (spike: small table, no pruning), 20-40 KiB (the key-value track's estimate) and 57.7 KiB (SQLite track: full history with pruning). The setups differ. The schema under RECORDS appended 46.1 KiB (11.46 frames) on leil-test-1. diff --git a/docs/plans/printers.md b/docs/plans/printers.md index 44232c6..2866b7a 100644 --- a/docs/plans/printers.md +++ b/docs/plans/printers.md @@ -200,9 +200,9 @@ For stage 4a: 28. **The TM-T88VII's near-end through `GS r 1`.** `Status` sends it last, only when `DLE EOT` says online and ready, under a deadline of its own, 500 ms. The anycast check (decision 23) never sends it. - Its reply has a decoder of its own, since its fixed bits differ from `DLE EOT`'s and `Status.Apply` would refuse it. The decoder accepts the byte the TM-T88VII actually sends, since Epson's page contradicts itself. - No answer means near-end is unknown: `paper` reads as `DLE EOT 4` gave it, never `timeout`, never `503`. - - The connection closes after a missed answer, since a late one could be read as the answer to the next request. Closing does not stop a late reply: the board, not TCP, routes the printer's output, so the reply can reach the next connection. There it fails the `DLE EOT` mask, since its bits 0 and 1 are both clear or both set, and reads once as unsupported (`unknown`, `200`). - - Trade-off: `GS r 1` is not real-time. It is answered once the lines before it have printed, so during a long print it is usually missed. A late reply costs one `unknown` reading. -29. **More status bits, and frames nobody asked for.** `Ready()` also counts `DLE EOT 2` bit 6 (an error occurred) and `DLE EOT 3` bit 2 (a recoverable error; the TM-T88IV lacks it), read again like the rest. `Normalized()` clears `DLE EOT 2` bit 6 while `DLE EOT 1` says online, as it clears that byte's other bits, so a stale bit while cutting does not read as not ready. On the TM-T88VII the autocutter-error bit also means a paper jam; api.md says so. Automatic-status frames are left alone until stage 4a's first step shows whether they reach a port 9100 client. The UB-E02 and UB-E03 boards turn them on at power-on, and a TM-T88VII with DIP switch 2-1 on keeps them on. If they do reach the client, job-store phase 5's frame reader comes forward. + - The connection closes after a missed answer, since a late one could be read as the answer to the next request. Closing does not stop a late reply: the board, not TCP, routes the printer's output, so the reply can reach the next connection. There it fails the `DLE EOT` mask, since its bits 0 and 1 are both clear or both set, so `Status` passes over it, and `Send`'s ready wait drops it with its own answer when it comes within 100 ms of that answer. + - Trade-off: `GS r 1` is not real-time. It is answered once the lines before it have printed, so during a long print it is usually missed. A late reply costs nothing: one the printer sent before the next connection's requests reached it comes ahead of the answer to the `DLE EOT 1` that opens that connection, and is dropped with everything before it, and one still queued comes just before the answer to the ready request, and is dropped with it. +29. **More status bits, and frames nobody asked for.** `Ready()` also counts `DLE EOT 2` bit 6 (an error occurred) and `DLE EOT 3` bit 2 (a recoverable error; the TM-T88IV lacks it), read again like the rest. `Normalized()` clears `DLE EOT 2` bit 6 while `DLE EOT 1` says online, as it clears that byte's other bits, so a stale bit while cutting does not read as not ready. On the TM-T88VII the autocutter-error bit also means a paper jam; api.md says so. `Status` and `Send` pass over automatic-status frames, by the fixed bits of a frame's first byte, so a frame that reaches a port 9100 client reads neither as unsupported nor as an answer to `GS r 1`. The UB-E02 and UB-E03 boards turn them on at power-on, and a TM-T88VII with DIP switch 2-1 on keeps them on. With confirmation, `Send` opens each connection with `DLE EOT 1`, `GS a 0` and `GS r 1` and drops everything that comes before the `DLE EOT` answer, a frame's leftover bytes included, turns frames off again before the job's confirmation request, and asks `DLE EOT 1` again before it writes; `Status` reads to the end of any frame before it closes. Stage 4a's first step shows whether they reach the client; job-store phase 5's frame reader replaces the skipping. - Trade-off: `/healthz` can answer `503` on a recoverable error where it answered `200`. For stage 4b: @@ -302,7 +302,7 @@ THE THREE PRINTERS (Epson's Technical Reference Guides and command reference) - Every command the renderer sends is in each model's command list, and so are the code pages it uses (0, 2, 16 and 19). Each job starts with `ESC @` then `ESC t`, so a printer's own default page never matters. - The TM-m50II's command list includes `GS ( H` fn 48, which job-store.md lists as unconfirmed for it. It is still unverified over port 9100. - Only the first accepted connection prints; the others connect, and their data waits until it closes. -- The UB-E02 and UB-E03 turn automatic status on at power-on; a job's `ESC @` turns it off. A TM-T88VII with DIP switch 2-1 on keeps it on after `ESC @`. A frame's first byte fails the `DLE EOT` mask, so `Status` would read it as "unsupported". +- The UB-E02 and UB-E03 turn automatic status on at power-on; a job's `ESC @` turns it off. A TM-T88VII with DIP switch 2-1 on keeps it on after `ESC @`. A frame's first byte fails the `DLE EOT` mask, and `Status` passes over the frame by it. - A byte string inside a command's parameters that matches a real-time command is executed as one: image or `raw` bytes that hold `10 04 n` make the printer send a status byte during a send. - Buffers: - Each model keeps a receive buffer per interface. @@ -1060,7 +1060,7 @@ internal/app/uberbringer First, before any code, with the owner's OK. These are status reads only, nothing printed, and they settle the details of decisions 28 and 29: 1. On the TM-T88VII: the `GS r 1` reply byte with a full roll, and with a roll past the near-end mark if he has one, read by a probe run from outside the repository. -2. On the TM-T88IV just after power-on, and on the TM-T88VII with DIP switch 2-1 as it is set: does `/healthz` read `unknown`, a sign that automatic-status frames reach the connection? +2. On the TM-T88IV just after power-on, and on the TM-T88VII with DIP switch 2-1 as it is set: do automatic-status frames reach the connection? A probe run from outside the repository reads the raw bytes, since `Status` passes over the frames and `/healthz` does not show them. It also shows whether a frame's four bytes ever arrive apart, and checks what `Send` assumes (design.md): that no frame follows the answer to a `GS r 1` sent after `GS a 0`, that `DLE EOT 1` is answered ahead of a `GS r 1` sent just after it, and that no answer to `DLE EOT` comes between a frame's bytes. One between the last bytes of a frame whose header went to an earlier connection would let those bytes count as answers to `GS r 1`; within one connection the header keeps them apart. On the TM-m50II it also reads `DLE EOT 1` and `GS r 1` during the auto feed and cut at cover close, to see whether the printer reports online before it has run a queued `GS r 1`. 3. The TM-T88VII's status sheet, read by the owner: column mode, paper width, paper reduction, top margin, the port 9100 time-out and DIP switch 2-1 (decision 31). internal/pkg/escpos diff --git a/internal/pkg/escpos/escpos_test.go b/internal/pkg/escpos/escpos_test.go index 2130883..d778c6d 100644 --- a/internal/pkg/escpos/escpos_test.go +++ b/internal/pkg/escpos/escpos_test.go @@ -442,6 +442,35 @@ func TestStatusRequest(t *testing.T) { if got := escpos.StatusRequest(escpos.StatusPaper); !bytes.Equal(got, []byte{0x10, 0x04, 4}) { t.Errorf("got % X", got) } + if got := escpos.TransmitStatusRequest(); !bytes.Equal(got, []byte{0x1D, 0x72, 1}) { + t.Errorf("GS r 1: got % X", got) + } + if got := escpos.AutomaticStatusOff(); !bytes.Equal(got, []byte{0x1D, 0x61, 0}) { + t.Errorf("GS a 0: got % X", got) + } +} + +func TestClassifyReply(t *testing.T) { + tests := []struct { + b byte + want escpos.Reply + }{ + {0x00, escpos.ReplyTransmit}, // GS r 1: paper present, not near its end + {0x0F, escpos.ReplyTransmit}, // GS r 1: paper near its end and out + {0x16, escpos.ReplyRealTime}, // DLE EOT 1, as the TM-T88IV answers + {0x12, escpos.ReplyRealTime}, // DLE EOT with no flag set + {0x72, escpos.ReplyRealTime}, // DLE EOT 4 with paper out + {0x10, escpos.ReplyAutomaticHeader}, // automatic status, first byte + {0x14, escpos.ReplyAutomaticHeader}, + {0x13, escpos.ReplyOther}, + {0x80, escpos.ReplyOther}, + {0x37, escpos.ReplyOther}, // a process ID response's first byte + } + for _, tt := range tests { + if got := escpos.ClassifyReply(tt.b); got != tt.want { + t.Errorf("ClassifyReply(0x%02X) = %d, want %d", tt.b, got, tt.want) + } + } } func TestLookupProfile(t *testing.T) { diff --git a/internal/pkg/escpos/status.go b/internal/pkg/escpos/status.go index f33b76b..f7b3698 100644 --- a/internal/pkg/escpos/status.go +++ b/internal/pkg/escpos/status.go @@ -97,3 +97,53 @@ func (s *Status) Apply(kind StatusKind, resp byte) error { } return nil } + +// TransmitStatusRequest returns GS r 1, which asks for the paper sensor +// status. Unlike the real-time DLE EOT, the printer answers it only once it +// has processed every byte sent before it, so its answer confirms that a +// job reached the printer and ran. +func TransmitStatusRequest() []byte { + return []byte{gs, 'r', 1} +} + +// AutomaticStatusOff returns GS a 0, which stops the printer sending +// automatic status blocks. Like GS r, it runs in order with the bytes +// before it, so no block follows an answer to a GS r sent after it. +func AutomaticStatusOff() []byte { + return []byte{gs, 'a', 0} +} + +// Reply is what a byte the printer sends is, by its fixed bits. +type Reply int + +// Kinds of Reply. +const ( + // ReplyOther is a byte none of the others describe. + ReplyOther Reply = iota + + // ReplyRealTime answers DLE EOT: bits 0 and 7 are 0, bits 1 and 4 are + // 1. Bytes of a job, such as an image's, can hold DLE EOT n, which the + // printer answers too. + ReplyRealTime + + // ReplyAutomaticHeader starts a four-byte automatic status block: bits + // 0, 1 and 7 are 0 and bit 4 is 1. The three bytes after it have bits 4 + // and 7 at 0, as a ReplyTransmit has. + ReplyAutomaticHeader + + // ReplyTransmit answers GS r: bits 4 and 7 are 0. + ReplyTransmit +) + +// ClassifyReply returns what b is, by its fixed bits. +func ClassifyReply(b byte) Reply { + switch { + case b&statusFixedMask == statusFixedBits: + return ReplyRealTime + case b&statusFixedMask == 0x10: + return ReplyAutomaticHeader + case b&0x90 == 0: + return ReplyTransmit + } + return ReplyOther +} diff --git a/internal/pkg/printer/printer.go b/internal/pkg/printer/printer.go index a95134f..5e7c8c9 100644 --- a/internal/pkg/printer/printer.go +++ b/internal/pkg/printer/printer.go @@ -7,6 +7,8 @@ import ( "errors" "fmt" "net" + "slices" + "sync/atomic" "time" "uberbringer/internal/pkg/escpos" @@ -17,9 +19,35 @@ import ( const statusTimeout = 2 * time.Second // ErrStatusUnsupported is returned by Status when the printer accepts the -// connection but does not answer DLE EOT requests. +// connection but does not answer DLE EOT requests, or answers them with +// bytes that are not DLE EOT answers. var ErrStatusUnsupported = errors.New("printer: no answer to status request") +// UnconfirmedError is returned by Send when every byte of a job was written +// but the printer did not confirm it: its answer did not come before the +// write deadline, or the connection failed or closed first. The operating +// system may still have held part of the job, so it may have printed in +// full, in part or not at all; it must not be sent again. +type UnconfirmedError struct { + Err error +} + +// Error implements error. +func (e *UnconfirmedError) Error() string { + return "the printer did not confirm the job: " + e.Err.Error() +} + +// Unwrap returns the cause. +func (e *UnconfirmedError) Unwrap() error { + return e.Err +} + +// Unconfirmed reports true, so that a caller can recognise the error by +// its behaviour without importing this package. +func (e *UnconfirmedError) Unconfirmed() bool { + return true +} + // Client sends data to one printer. Network printers accept a single // connection at a time, so the Client serialises its connections. It is safe // for concurrent use. @@ -27,6 +55,7 @@ type Client struct { addr string dialTimeout time.Duration writeTimeout time.Duration + confirm bool dialer net.Dialer // slot holds a token while a connection is open; acquiring it respects @@ -34,21 +63,34 @@ type Client struct { slot chan struct{} } +// Option changes how a Client sends. +type Option func(*Client) + +// Confirm, when on, makes Send wait for the printer to confirm each job +// before it returns; see Send. +func Confirm(on bool) Option { + return func(c *Client) { c.confirm = on } +} + // NewClient returns a Client for the printer at addr ("host:port"). -func NewClient(addr string, dialTimeout, writeTimeout time.Duration) *Client { +func NewClient(addr string, dialTimeout, writeTimeout time.Duration, options ...Option) *Client { if addr == "" { panic("printer.NewClient: addr must not be empty") } if dialTimeout <= 0 || writeTimeout <= 0 { panic("printer.NewClient: timeouts must be positive") } - return &Client{ + c := &Client{ addr: addr, dialTimeout: dialTimeout, writeTimeout: writeTimeout, dialer: net.Dialer{Timeout: dialTimeout}, slot: make(chan struct{}, 1), } + for _, option := range options { + option(c) + } + return c } // Addr returns the printer address. @@ -63,6 +105,30 @@ func (c *Client) Addr() string { // slow beforeWrite does not shorten the write. ctx bounds the wait for the // connection and the dial, and its deadline bounds the write; cancelling // it once the connection is open does not stop the write. +// +// A write returns once the operating system holds the bytes, not once the +// printer has them. With Confirm on, Send asks for status with GS r 1, which +// the printer answers only once it has run every byte before it, and, on the +// TM-T88IV, only while it can print. First, before beforeWrite, it sends +// DLE EOT 1, which the printer answers on receipt, GS a 0, so that the +// printer sends no automatic status blocks, whose last bytes look like an +// answer, and GS r 1. It drops everything that comes before the answer to +// DLE EOT 1, which the printer sent before it had the request, and waits for +// an answer to GS r 1 after it, up to the write timeout or ctx's deadline, +// so that nothing is sent to a printer that is offline, has its cover open, +// is out of paper or is waiting for the rest of an earlier job. It then +// waits until 100 ms have passed without another answer, and drops every +// answer read, so that an answer to an earlier request still queued in the +// printer is not taken for the job's, and asks DLE EOT 1 again, up to 2 s +// more, to check that the printer is online, then reads on for 100 ms. +// Without an answer to either, if the deadline or the connection's end cuts +// those 100 ms short, if the printer reports itself offline, or if an +// answer to GS r 1 comes after the 100 ms of quiet, it returns an error +// with nothing written. Then, after the job, it sends GS a 0 again, since +// the job's own ESC @ can turn blocks back on, and GS r 1, and returns once +// the answer arrives. If that answer does not arrive before the write +// deadline, or the connection fails after the job was written in full, Send +// returns an *UnconfirmedError. With Confirm off, Send writes data alone. func (c *Client) Send(ctx context.Context, data []byte, beforeWrite func() error) error { conn, release, err := c.connect(ctx) if err != nil { @@ -70,6 +136,12 @@ func (c *Client) Send(ctx context.Context, data []byte, beforeWrite func() error } defer release() + l := &line{conn: conn} + if c.confirm { + if err := c.awaitReady(ctx, l); err != nil { + return err + } + } if beforeWrite != nil { if err := beforeWrite(); err != nil { return err @@ -82,14 +154,358 @@ func (c *Client) Send(ctx context.Context, data []byte, beforeWrite func() error if _, err := conn.Write(data); err != nil { return fmt.Errorf("writing to printer %s: %w", c.addr, err) } + if !c.confirm { + return nil + } + if err := c.awaitConfirmation(l, writeDeadline); err != nil { + return &UnconfirmedError{Err: err} + } return nil } +// settleTime is how long Send waits after an answer to GS r 1 for another +// before it takes the printer to be ready, and how long the client waits +// for the rest of an automatic status block. A printer sends answers that +// are queued together, and a block's four bytes, within milliseconds. +const settleTime = 100 * time.Millisecond + +// drainTime is how long Status reads on after its last answer for bytes +// the printer has already sent. +const drainTime = 20 * time.Millisecond + +// awaitReady sends DLE EOT 1, GS a 0 and GS r 1 in one write, and waits for +// the printer to answer, until the write timeout or ctx's deadline. +// +// The printer answers DLE EOT on receipt, ahead of anything it receives +// after it, so the answer is a fence: every byte before it left the printer +// before the request reached it. Those are dropped: answers owed to +// requests the printer ran earlier, on an earlier connection or for an +// earlier run of the daemon, and the last bytes of an automatic status block +// whose header went to an earlier connection. The fence is waited for until +// the deadline, however long a lost segment delays it. A late answer to an +// earlier connection's DLE EOT looks like the fence's and stands in for +// it; the last step below catches what follows from that. +// +// After the fence, answers to GS r 1 still carry nothing that tells them +// apart: requests queued in the printer ahead of this one, unanswered when +// the fence arrived, are answered first. So it reads every answer until +// settleTime has passed since the last, and drops them all, so that none +// can be taken for a job's confirmation later. If the deadline or the +// connection's end comes first, the printer is not ready, as without an +// answer. The wait takes settleTime at least. +// +// A printer may run GS r 1 while it is offline, so it then asks DLE EOT 1 +// again, for up to statusTimeout or the write timeout, whichever is +// shorter, and the printer is ready only if it answers that it is online. +// +// Last, it reads on for settleTime after that answer. Once the answers have +// settled, no answer to GS r 1 is owed, so one that comes during the +// online check or after it means an answer taken for this request's was +// not: one owed from before, read after a late DLE EOT answer that stood +// in for the fence while this connection's own request was held back. The +// printer is then not ready, and nothing is written. +// +// Cancelling ctx stops the wait at once; nothing of a job has been written +// then. awaitReady returns only once a cancellation that raced its end has +// finished with the connection, so that it cannot cut the job's +// confirmation short. +func (c *Client) awaitReady(ctx context.Context, l *line) error { + deadline, _ := c.deadline(ctx, c.writeTimeout) + if err := l.conn.SetDeadline(deadline); err != nil { + return fmt.Errorf("setting printer deadline: %w", err) + } + cancelled := make(chan struct{}) + stop := context.AfterFunc(ctx, func() { + defer close(cancelled) + l.stopped.Store(true) + _ = l.conn.SetReadDeadline(time.Unix(1, 0)) + }) + defer func() { + if !stop() { + <-cancelled + } + }() + request := slices.Concat(escpos.StatusRequest(escpos.StatusPrinter), escpos.AutomaticStatusOff(), + escpos.TransmitStatusRequest()) + if _, err := l.conn.Write(request); err != nil { + return fmt.Errorf("asking printer %s whether it is ready: %w", c.addr, err) + } + if err := l.awaitFence(); err != nil { + if ctx.Err() != nil { + return fmt.Errorf("waiting for printer %s to be ready: %w", c.addr, ctx.Err()) + } + return fmt.Errorf("printer %s is not ready: it did not answer a real-time status request (DLE EOT 1) "+ + "in time, so nothing was sent (%w)", c.addr, err) + } + got, err := l.readAnswers(deadline, settleTime) + switch { + case ctx.Err() != nil: + return fmt.Errorf("waiting for printer %s to be ready: %w", c.addr, ctx.Err()) + case got == 0: + return fmt.Errorf("printer %s is not ready: it did not answer a status request (GS r 1) in time, "+ + "so nothing was sent (%w)", c.addr, err) + case err != nil: + return fmt.Errorf("printer %s is not ready: it answered a status request (GS r 1), but not %v before "+ + "the deadline or the connection's end, so nothing was sent (%w)", c.addr, settleTime, err) + } + + deadline, _ = c.deadline(ctx, min(statusTimeout, c.writeTimeout)) + if err := l.conn.SetDeadline(deadline); err != nil { + return fmt.Errorf("setting printer deadline: %w", err) + } + // A cancellation before the deadline above was set has had its past + // read deadline replaced; one after it cuts the read short. + if ctx.Err() != nil { + return fmt.Errorf("waiting for printer %s to be ready: %w", c.addr, ctx.Err()) + } + if _, err := l.conn.Write(escpos.StatusRequest(escpos.StatusPrinter)); err != nil { + return fmt.Errorf("asking printer %s whether it is online: %w", c.addr, err) + } + settled := l.answers + resp, err := l.realTimeAnswer(deadline) + switch { + case ctx.Err() != nil: + return fmt.Errorf("waiting for printer %s to be ready: %w", c.addr, ctx.Err()) + case err != nil: + return fmt.Errorf("printer %s is not ready: it did not answer a real-time status request (DLE EOT 1) "+ + "after a status request (GS r 1), so nothing was sent (%w)", c.addr, err) + } + var status escpos.Status + if err := status.Apply(escpos.StatusPrinter, resp); err != nil || !status.Online { + return fmt.Errorf("printer %s is not ready: it reports itself offline (DLE EOT 1 answered 0x%02X), "+ + "so nothing was sent", c.addr, resp) + } + end := time.Now().Add(settleTime) + if deadline.Before(end) { + end = deadline + } + err = l.readUntil(end) + switch { + case ctx.Err() != nil: + return fmt.Errorf("waiting for printer %s to be ready: %w", c.addr, ctx.Err()) + case err != nil: + return fmt.Errorf("printer %s is not ready: reading after its status answers: %w", c.addr, err) + case l.answers > settled: + return fmt.Errorf("printer %s is not ready: it answered a status request (GS r 1) after its answers "+ + "had settled, so an answer taken for its own was owed from before, and nothing was sent", c.addr) + } + return nil +} + +// awaitConfirmation sends GS a 0 and GS r 1 after a job and waits until +// deadline for the answer. If the answer came with the start of an +// automatic status block, it reads on for the rest; see line.finishBlock. +func (c *Client) awaitConfirmation(l *line, deadline time.Time) error { + request := append(escpos.AutomaticStatusOff(), escpos.TransmitStatusRequest()...) + if _, err := l.conn.Write(request); err != nil { + return fmt.Errorf("asking printer %s to confirm: %w", c.addr, err) + } + if err := l.conn.SetReadDeadline(deadline); err != nil { + return fmt.Errorf("setting printer read deadline: %w", err) + } + if _, err := l.readAnswers(deadline, 0); err != nil { + return fmt.Errorf("waiting for printer %s to confirm: %w", c.addr, err) + } + l.finishBlock(deadline) + return nil +} + +// line reads what the printer sends on one connection. skip counts the +// bytes of an automatic status block still to come after its header, which +// can come in a later read than the header. The printer sends a block's +// four bytes together, so the rest follows within milliseconds, on the same +// connection while it stays open. A line starts at zero on each connection: +// a block cut short by a closed connection or a power cycle never takes +// bytes on a later one. answers counts the answers to GS r read on the +// connection. +type line struct { + conn net.Conn + skip int + answers int + + // stopped is set when the ready wait is cancelled, before the read + // deadline is moved to the past, so that a read deadline set later, + // which would undo that, is followed by a check of it. + stopped atomic.Bool +} + +// errStopped is returned by a read on a line whose wait was cancelled. +var errStopped = errors.New("printer: the wait was cancelled") + +// reply returns what b, the next byte read on the line, is. The three bytes +// after an automatic status block's header are ReplyOther, though they have +// an answer's fixed bits. +func (l *line) reply(b byte) escpos.Reply { + if l.skip > 0 { + l.skip-- + return escpos.ReplyOther + } + r := escpos.ClassifyReply(b) + switch r { + case escpos.ReplyAutomaticHeader: + l.skip = 3 + case escpos.ReplyTransmit: + l.answers++ + } + return r +} + +// awaitFence reads one byte at a time, until the read deadline, up to the +// first answer to DLE EOT outside an automatic status block, and drops +// everything before it. +func (l *line) awaitFence() error { + b := make([]byte, 1) + for { + if _, err := l.conn.Read(b); err != nil { + return err + } + if l.reply(b[0]) == escpos.ReplyRealTime { + return nil + } + } +} + +// readAnswers reads answers to GS r 1 until deadline. With settle 0 it +// stops at the first; otherwise it stops once settle has passed since the +// last answer, so that other bytes, such as status blocks, cannot hold it +// open. It passes over the bytes that look like an answer but are not: +// answers to DLE EOT n, which a job's own bytes, such as an image's, can +// hold, and the last three bytes of automatic status blocks. It returns how +// many answers it read, and the read error unless it stopped on an answer +// or once settle had passed. +func (l *line) readAnswers(deadline time.Time, settle time.Duration) (int, error) { + buf := make([]byte, 64) + got := 0 + for { + n, err := l.conn.Read(buf) + before := got + for _, b := range buf[:n] { + if l.reply(b) == escpos.ReplyTransmit { + got++ + } + } + if got > 0 && settle == 0 { + return got, nil + } + var netErr net.Error + if err != nil && got > 0 && settle > 0 && errors.As(err, &netErr) && netErr.Timeout() && time.Now().Before(deadline) { + return got, nil + } + if err != nil { + return got, err + } + if got > before && settle > 0 { + quiet := time.Now().Add(settle) + if deadline.Before(quiet) { + quiet = deadline + } + if err := l.conn.SetReadDeadline(quiet); err != nil { + return got, err + } + if l.stopped.Load() { + return got, errStopped + } + } + } +} + +// readUntil reads until end, passing each byte through reply, so that the +// answers that come meanwhile are counted. Reaching end is no error. +func (l *line) readUntil(end time.Time) error { + if err := l.conn.SetReadDeadline(end); err != nil { + return err + } + if l.stopped.Load() { + return errStopped + } + buf := make([]byte, 64) + for { + n, err := l.conn.Read(buf) + for _, b := range buf[:n] { + l.reply(b) + } + if err == nil { + continue + } + var netErr net.Error + if errors.As(err, &netErr) && netErr.Timeout() && !l.stopped.Load() && !time.Now().Before(end) { + return nil + } + return err + } +} + +// finishBlock reads on while the line is inside an automatic status block, +// for settleTime at most and not past deadline, so that the connection +// stays open until the block's last bytes have come, and they are read on +// the connection that carried its header. A tail that has not come by then +// ends with the connection. +func (l *line) finishBlock(deadline time.Time) { + if l.skip == 0 { + return + } + end := time.Now().Add(settleTime) + if deadline.Before(end) { + end = deadline + } + if l.conn.SetReadDeadline(end) != nil { + return + } + b := make([]byte, 1) + for l.skip > 0 { + if _, err := l.conn.Read(b); err != nil { + return + } + l.reply(b[0]) + } +} + +// drain reads what the printer has sent on the line until none has come for +// drainTime, and the rest of any automatic status block among it for +// settleTime at most, so that a block's last bytes come on this connection +// and not on the next. It stops at deadline, or 2 settleTime after it +// started, whichever comes first. +func (l *line) drain(deadline time.Time) { + if end := time.Now().Add(2 * settleTime); end.Before(deadline) { + deadline = end + } + b := make([]byte, 16) + for { + wait := drainTime + if l.skip > 0 { + wait = settleTime + } + end := time.Now().Add(wait) + if deadline.Before(end) { + end = deadline + } + if l.conn.SetReadDeadline(end) != nil { + return + } + n, err := l.conn.Read(b) + for _, x := range b[:n] { + l.reply(x) + } + if err != nil { + return + } + } +} + +// errNotRealTime is returned by realTimeAnswer when the printer answered +// with a byte that cannot be an answer to DLE EOT. +var errNotRealTime = errors.New("printer: a status answer without DLE EOT's fixed bits") + // Status queries the printer's real-time status, normalized so that offline // causes are only reported while the printer is offline. It returns // ErrStatusUnsupported when the printer is reachable but gives no answer -// within statusTimeout, and an error wrapping context.DeadlineExceeded when -// ctx ran out first, since the printer may simply not have answered yet. +// within statusTimeout, or answers with bytes that are not DLE EOT answers, +// and an error wrapping context.DeadlineExceeded when ctx ran out first, +// since the printer may simply not have answered yet. Status sends no +// GS a 0: it is not real-time, and the printer does not run it while +// offline. So before it closes the connection, Status reads what has come, +// to the end of any automatic status block, so that no block's last bytes +// reach the next connection. func (c *Client) Status(ctx context.Context) (escpos.Status, error) { var status escpos.Status conn, release, err := c.connect(ctx) @@ -98,7 +514,7 @@ func (c *Client) Status(ctx context.Context) (escpos.Status, error) { } defer release() - resp := make([]byte, 1) + l := &line{conn: conn} for _, kind := range escpos.StatusKinds() { deadline, fromContext := c.deadline(ctx, statusTimeout) if err := conn.SetDeadline(deadline); err != nil { @@ -107,23 +523,70 @@ func (c *Client) Status(ctx context.Context) (escpos.Status, error) { if _, err := conn.Write(escpos.StatusRequest(kind)); err != nil { return status, fmt.Errorf("requesting printer status: %w", err) } - if _, err := conn.Read(resp); err != nil { + resp, err := l.realTimeAnswer(deadline) + if err != nil { var netErr net.Error - if errors.As(err, &netErr) && netErr.Timeout() { - if fromContext { - return status, fmt.Errorf("reading printer status: %w", context.DeadlineExceeded) - } + switch { + case errors.Is(err, errNotRealTime): + return status, ErrStatusUnsupported + case errors.As(err, &netErr) && netErr.Timeout() && fromContext: + return status, fmt.Errorf("reading printer status: %w", context.DeadlineExceeded) + case errors.As(err, &netErr) && netErr.Timeout(): return status, ErrStatusUnsupported } return status, fmt.Errorf("reading printer status: %w", err) } - if err := status.Apply(kind, resp[0]); err != nil { + if err := status.Apply(kind, resp); err != nil { return status, ErrStatusUnsupported } } + deadline, _ := c.deadline(ctx, statusTimeout) + l.drain(deadline) return status.Normalized(), nil } +// realTimeAnswer reads one byte at a time until a byte with the fixed bits +// of an answer to DLE EOT, which the printer sends at once, or until +// deadline. It passes over automatic status blocks, and over bytes with an +// answer to GS r's fixed bits, such as a late answer to an earlier GS r 1, +// though once it has met one it waits settleTime at most for the real-time +// answer: a printer that answers DLE EOT with such a byte has answered. A +// byte that fits neither answer ends it at once with errNotRealTime. It +// stops only on an answer, which never comes inside a block, so it leaves +// the line inside one only when it returns an error. +func (l *line) realTimeAnswer(deadline time.Time) (byte, error) { + b := make([]byte, 1) + stray := false + for { + if _, err := l.conn.Read(b); err != nil { + var netErr net.Error + if stray && errors.As(err, &netErr) && netErr.Timeout() && time.Now().Before(deadline) { + return 0, errNotRealTime + } + return 0, err + } + inBlock := l.skip > 0 + switch r := l.reply(b[0]); { + case r == escpos.ReplyRealTime: + return b[0], nil + case inBlock, r == escpos.ReplyAutomaticHeader: + case r == escpos.ReplyTransmit: + if !stray { + stray = true + end := time.Now().Add(settleTime) + if deadline.Before(end) { + end = deadline + } + if err := l.conn.SetReadDeadline(end); err != nil { + return 0, err + } + } + default: + return 0, errNotRealTime + } + } +} + // connect waits for the connection slot and dials the printer. The returned // release func closes the connection and frees the slot. func (c *Client) connect(ctx context.Context) (net.Conn, func(), error) { diff --git a/internal/pkg/printer/printer_test.go b/internal/pkg/printer/printer_test.go index b690f3e..337d87e 100644 --- a/internal/pkg/printer/printer_test.go +++ b/internal/pkg/printer/printer_test.go @@ -4,8 +4,11 @@ import ( "bytes" "context" "errors" + "fmt" "io" "net" + "slices" + "sync/atomic" "testing" "time" @@ -111,6 +114,1428 @@ func TestSendCallsBeforeWrite(t *testing.T) { } } +// readJob reads from conn until the bytes end with GS r 1, which Send asks +// before a job and again after it, and returns the bytes before it without +// the GS a 0 that Send sends before each GS r 1. On the way it answers a +// DLE EOT 1 that begins what it reads, as an online printer does: Send asks +// one at the start of a connection, and another once the printer is ready. +func readJob(conn net.Conn) ([]byte, error) { + var got []byte + buf := make([]byte, 256) + online := escpos.StatusRequest(escpos.StatusPrinter) + for !bytes.HasSuffix(got, escpos.TransmitStatusRequest()) { + n, err := conn.Read(buf) + got = append(got, buf[:n]...) + if bytes.HasPrefix(got, online) { + got = got[len(online):] + if _, err := conn.Write([]byte{0x12}); err != nil { + return got, err + } + } + if err != nil { + return got, err + } + } + got = bytes.TrimSuffix(got, escpos.TransmitStatusRequest()) + return bytes.TrimSuffix(got, escpos.AutomaticStatusOff()), nil +} + +// answerReady reads the DLE EOT 1, GS a 0 and GS r 1 that Send sends before +// a job, answers the DLE EOT 1 and the GS r 1, then answers the DLE EOT 1 +// that follows, as an online printer that can print does. +func answerReady(conn net.Conn) error { + before, err := readJob(conn) + if err != nil { + return err + } + if len(before) != 0 { + return fmt.Errorf("got % X before the ready request", before) + } + if _, err := conn.Write([]byte{0x00}); err != nil { + return err + } + req := make([]byte, 3) + if _, err := io.ReadFull(conn, req); err != nil { + return err + } + if !bytes.Equal(req, escpos.StatusRequest(escpos.StatusPrinter)) { + return fmt.Errorf("got % X after the ready answer, want DLE EOT 1", req) + } + _, err = conn.Write([]byte{0x12}) + return err +} + +// With Confirm, Send asks whether the printer is ready before the job, and +// returns only once the printer answers the GS r 1 after it, passing over +// the bytes before the answer: an automatic status block, whose last bytes +// look like the answer, and an answer to a DLE EOT in the job. +func TestSendWaitsForConfirmation(t *testing.T) { + job := make(chan []byte, 1) + answer := make(chan struct{}) + addr := fakePrinter(t, func(conn net.Conn) { + if err := answerReady(conn); err != nil { + job <- nil + return + } + data, err := readJob(conn) + job <- data + if err != nil { + return + } + _, _ = conn.Write([]byte{0x10, 0x00, 0x00, 0x00, 0x16}) + <-answer + _, _ = conn.Write([]byte{0x00}) + _, _ = io.ReadAll(conn) + }) + client := printer.NewClient(addr, time.Second, 5*time.Second, printer.Confirm(true)) + sent := make(chan error, 1) + go func() { sent <- client.Send(context.Background(), []byte("receipt"), nil) }() + + if got := <-job; !bytes.Equal(got, []byte("receipt")) { + t.Errorf("printer got %q, then GS r 1", got) + } + select { + case err := <-sent: + t.Fatalf("Send returned %v before the printer answered", err) + case <-time.After(300 * time.Millisecond): + } + close(answer) + select { + case err := <-sent: + if err != nil { + t.Errorf("Send = %v, want nil once the printer answered", err) + } + case <-time.After(5 * time.Second): + t.Fatal("Send did not return after the printer answered") + } +} + +// With Confirm, a job written in full that the printer does not confirm, +// because it never answers or closes the connection first, gives an +// UnconfirmedError; the printer has every byte. +func TestSendUnconfirmed(t *testing.T) { + for name, after := range map[string]func(net.Conn){ + "no answer before the deadline": func(conn net.Conn) { _, _ = io.ReadAll(conn) }, + "the connection closed": func(net.Conn) {}, + } { + t.Run(name, func(t *testing.T) { + job := make(chan []byte, 1) + addr := fakePrinter(t, func(conn net.Conn) { + if err := answerReady(conn); err != nil { + job <- nil + return + } + data, _ := readJob(conn) + job <- data + after(conn) + }) + client := printer.NewClient(addr, time.Second, 300*time.Millisecond, printer.Confirm(true)) + err := client.Send(context.Background(), []byte("receipt"), nil) + var unconfirmed *printer.UnconfirmedError + if !errors.As(err, &unconfirmed) || !unconfirmed.Unconfirmed() { + t.Errorf("Send = %v, want an UnconfirmedError", err) + } + if got := <-job; !bytes.Equal(got, []byte("receipt")) { + t.Errorf("printer got %q", got) + } + }) + } +} + +// With Confirm, a printer that does not answer the ready request, as with +// its cover open, gets nothing of the job: Send returns a plain error +// without calling beforeWrite. +func TestSendToAPrinterNotReady(t *testing.T) { + received := make(chan []byte, 1) + addr := fakePrinter(t, func(conn net.Conn) { + data, _ := io.ReadAll(conn) + received <- data + }) + client := printer.NewClient(addr, time.Second, 300*time.Millisecond, printer.Confirm(true)) + called := false + err := client.Send(context.Background(), []byte("receipt"), func() error { called = true; return nil }) + var unconfirmed *printer.UnconfirmedError + if err == nil || errors.As(err, &unconfirmed) { + t.Errorf("Send = %v, want a plain error", err) + } + if called { + t.Error("beforeWrite ran although the printer was not ready") + } + if got, want := <-received, slices.Concat(escpos.StatusRequest(escpos.StatusPrinter), escpos.AutomaticStatusOff(), + escpos.TransmitStatusRequest()); !bytes.Equal(got, want) { + t.Errorf("printer got % X, want only the ready request, % X", got, want) + } +} + +// After a job the printer did not confirm, its answer can still come, late, +// on the next connection, or never. Either way it never confirms the next +// job: the ready request before it reads and drops the late answer. +func TestSendDropsALateAnswer(t *testing.T) { + for name, late := range map[string][]byte{"the late answer comes": {0x00}, "it never comes": nil} { + t.Run(name, func(t *testing.T) { + answer := make(chan struct{}) + var conns atomic.Int32 + addr := fakePrinter(t, func(conn net.Conn) { + if conns.Add(1) == 1 { + if answerReady(conn) == nil { + _, _ = readJob(conn) + } + return + } + _, _ = conn.Write(late) + if answerReady(conn) != nil { + return + } + if _, err := readJob(conn); err != nil { + return + } + <-answer + _, _ = conn.Write([]byte{0x00}) + _, _ = io.ReadAll(conn) + }) + client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) + var unconfirmed *printer.UnconfirmedError + if err := client.Send(context.Background(), []byte("first"), nil); !errors.As(err, &unconfirmed) { + t.Fatalf("first Send = %v, want an UnconfirmedError", err) + } + sent := make(chan error, 1) + go func() { sent <- client.Send(context.Background(), []byte("second"), nil) }() + select { + case err := <-sent: + t.Fatalf("second Send returned %v before the printer confirmed it", err) + case <-time.After(500 * time.Millisecond): + } + close(answer) + if err := <-sent; err != nil { + t.Errorf("second Send = %v, want nil once the printer confirmed it", err) + } + }) + } +} + +// sendUntilAnswered sends data and checks that Send returns nil, and not +// before answer is closed, which the fake printer waits on before it +// confirms the job. +func sendUntilAnswered(t *testing.T, client *printer.Client, data []byte, answer chan struct{}) { + t.Helper() + sent := make(chan error, 1) + go func() { sent <- client.Send(context.Background(), data, nil) }() + select { + case err := <-sent: + close(answer) + t.Errorf("Send returned %v before the printer confirmed the job", err) + return + case <-time.After(500 * time.Millisecond): + } + close(answer) + if err := <-sent; err != nil { + t.Errorf("Send = %v once the printer confirmed the job", err) + } +} + +// An answer the printer owes to a request this Client never sent, as from +// an earlier run of the daemon, comes before the answer to the ready +// request, in a read of its own. The ready wait drops both, so neither +// confirms the job. +func TestSendDropsAnAnswerOwedToAnEarlierRun(t *testing.T) { + answer := make(chan struct{}) + addr := fakePrinter(t, func(conn net.Conn) { + if _, err := readJob(conn); err != nil { + return + } + _, _ = conn.Write([]byte{0x00}) + time.Sleep(20 * time.Millisecond) + _, _ = conn.Write([]byte{0x00}) + if _, err := readJob(conn); err != nil { + return + } + <-answer + _, _ = conn.Write([]byte{0x00}) + _, _ = io.ReadAll(conn) + }) + client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) + sendUntilAnswered(t, client, []byte("job"), answer) +} + +// A job whose own bytes hold GS r 1 is confirmed by that request's answer, +// and the answer to the request after it comes on the next connection. It +// never confirms the next job. +func TestSendDropsTheAnswerOwedAfterAJobsOwnRequest(t *testing.T) { + var conns atomic.Int32 + answer := make(chan struct{}) + raw := append(append([]byte("before "), escpos.TransmitStatusRequest()...), []byte(" after")...) + addr := fakePrinter(t, func(conn net.Conn) { + if conns.Add(1) == 1 { + if answerReady(conn) != nil { + return + } + buf := make([]byte, len(raw)+len(escpos.AutomaticStatusOff())+len(escpos.TransmitStatusRequest())) + if _, err := io.ReadFull(conn, buf); err != nil { + return + } + _, _ = conn.Write([]byte{0x00}) + _, _ = io.ReadAll(conn) + return + } + if _, err := readJob(conn); err != nil { + return + } + _, _ = conn.Write([]byte{0x00}) + time.Sleep(20 * time.Millisecond) + _, _ = conn.Write([]byte{0x00}) + if _, err := readJob(conn); err != nil { + return + } + <-answer + _, _ = conn.Write([]byte{0x00}) + _, _ = io.ReadAll(conn) + }) + client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) + if err := client.Send(context.Background(), raw, nil); err != nil { + t.Fatalf("first Send = %v", err) + } + sendUntilAnswered(t, client, []byte("second"), answer) +} + +// An automatic status block whose header comes in the read with the ready +// answer, and whose last bytes come in the next, is passed over. +func TestSendSkipsAStatusBlockSplitAcrossReads(t *testing.T) { + answer := make(chan struct{}) + addr := fakePrinter(t, func(conn net.Conn) { + if _, err := readJob(conn); err != nil { + return + } + _, _ = conn.Write([]byte{0x00, 0x10}) + time.Sleep(20 * time.Millisecond) + _, _ = conn.Write([]byte{0x00, 0x00, 0x00}) + if _, err := readJob(conn); err != nil { + return + } + <-answer + _, _ = conn.Write([]byte{0x00}) + _, _ = io.ReadAll(conn) + }) + client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) + sendUntilAnswered(t, client, []byte("job"), answer) +} + +// firstJobThen serves the first connection as a printer that answers the +// ready request, reads the job and its confirmation request, writes +// confirmation, then calls after with the connection, if not nil, and holds +// it until the client closes it. Every later connection goes to later. +func firstJobThen(t *testing.T, confirmation []byte, after, later func(net.Conn)) string { + t.Helper() + var conns atomic.Int32 + return fakePrinter(t, func(conn net.Conn) { + if conns.Add(1) == 1 { + if answerReady(conn) != nil { + return + } + if _, err := readJob(conn); err != nil { + return + } + _, _ = conn.Write(confirmation) + if after != nil { + after(conn) + } + _, _ = io.ReadAll(conn) + return + } + later(conn) + }) +} + +// A job's confirmation comes with an automatic status block's header, and +// the block's last three bytes follow 50 ms later on whichever connection +// is open. Send keeps the connection open until they come, so they are read +// as the block's on that connection, and none is taken for an answer to the +// next job's ready request, which the printer sends only later. +func TestSendReadsAStatusBlockTailBeforeClosing(t *testing.T) { + var current atomic.Pointer[net.Conn] + answer := make(chan struct{}) + addr := firstJobThen(t, []byte{0x00, 0x10}, + func(conn net.Conn) { + current.CompareAndSwap(nil, &conn) + time.Sleep(50 * time.Millisecond) + _, _ = (*current.Load()).Write([]byte{0x00, 0x00, 0x00}) + }, + func(conn net.Conn) { + current.Store(&conn) + if _, err := readJob(conn); err != nil { + return + } + time.Sleep(300 * time.Millisecond) + _, _ = conn.Write([]byte{0x00}) + if _, err := readJob(conn); err != nil { + return + } + <-answer + _, _ = conn.Write([]byte{0x00}) + _, _ = io.ReadAll(conn) + }) + client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) + if err := client.Send(context.Background(), []byte("first"), nil); err != nil { + t.Fatalf("first Send = %v", err) + } + sendUntilAnswered(t, client, []byte("second"), answer) +} + +// A job's confirmation comes with an automatic status block's header, and +// the rest of the block never comes, as when the printer is switched off. +// The next connections start afresh: the next jobs' ready answers and the +// status answers count. +func TestSendForgetsAStatusBlockCutShort(t *testing.T) { + var statusConns atomic.Bool + addr := firstJobThen(t, []byte{0x00, 0x10}, nil, func(conn net.Conn) { + if statusConns.Load() { + req := make([]byte, 3) + for { + if _, err := io.ReadFull(conn, req); err != nil { + return + } + _, _ = conn.Write([]byte{0x12}) + } + } + if answerReady(conn) != nil { + return + } + if _, err := readJob(conn); err != nil { + return + } + _, _ = conn.Write([]byte{0x00}) + _, _ = io.ReadAll(conn) + }) + client := printer.NewClient(addr, time.Second, 500*time.Millisecond, printer.Confirm(true)) + if err := client.Send(context.Background(), []byte("first"), nil); err != nil { + t.Fatalf("first Send = %v", err) + } + for i := 2; i <= 4; i++ { + if err := client.Send(context.Background(), []byte("next"), nil); err != nil { + t.Errorf("Send %d = %v, want nil: the printer answered and confirmed", i, err) + } + } + statusConns.Store(true) + if status, err := client.Status(context.Background()); err != nil || !status.Online { + t.Errorf("Status = %+v, %v, want online", status, err) + } +} + +// A printer with its cover open sends an automatic status block saying so +// and does not answer the ready request, whether or not the last job's +// confirmation came with a header whose block was cut short. Nothing of +// the next job is written, and Send fails. +func TestSendToAPrinterReportingItsCoverOpen(t *testing.T) { + for name, confirmation := range map[string][]byte{ + "after a block cut short": {0x00, 0x10}, + "after a plain answer": {0x00}, + } { + t.Run(name, func(t *testing.T) { + written := make(chan []byte, 1) + closeCover := make(chan struct{}) + addr := firstJobThen(t, confirmation, nil, func(conn net.Conn) { + if before, err := readJob(conn); err != nil || len(before) != 0 { + written <- nil + return + } + _, _ = conn.Write([]byte{0x38, 0x00, 0x00, 0x00}) + job, err := readJob(conn) + if err != nil { + written <- nil + return + } + written <- job + <-closeCover + _, _ = conn.Write([]byte{0x10, 0x00, 0x00, 0x00, 0x00}) + _, _ = io.ReadAll(conn) + }) + client := printer.NewClient(addr, time.Second, 600*time.Millisecond, printer.Confirm(true)) + if err := client.Send(context.Background(), []byte("first"), nil); err != nil { + t.Fatalf("first Send = %v", err) + } + sent := make(chan error, 1) + go func() { sent <- client.Send(context.Background(), []byte("second"), nil) }() + select { + case job := <-written: + if job != nil { + t.Errorf("printer with its cover open got %q", job) + } + case <-time.After(3 * time.Second): + t.Fatal("fake printer saw neither a job nor a close") + } + close(closeCover) + if err := <-sent; err == nil { + t.Error("second Send = nil, want an error: the printer never answered") + } + }) + } +} + +// An answer owed to the last job's confirmation request comes just before +// the ready wait's deadline, and the answer to the ready request just after +// it. The deadline cuts the wait short, so the printer is not ready and +// nothing is written; the late ready answer is never taken for the job's. +func TestSendNotReadyWhenTheDeadlineCutsTheWait(t *testing.T) { + var conns atomic.Int32 + written := make(chan []byte, 1) + addr := fakePrinter(t, func(conn net.Conn) { + if conns.Add(1) == 1 { + if answerReady(conn) != nil { + return + } + _, _ = readJob(conn) + _, _ = io.ReadAll(conn) + return + } + if _, err := readJob(conn); err != nil { + return + } + time.Sleep(560 * time.Millisecond) + _, _ = conn.Write([]byte{0x00}) + time.Sleep(60 * time.Millisecond) + _, _ = conn.Write([]byte{0x00}) + job, _ := io.ReadAll(conn) + written <- job + }) + client := printer.NewClient(addr, time.Second, 600*time.Millisecond, printer.Confirm(true)) + var unconfirmed *printer.UnconfirmedError + if err := client.Send(context.Background(), []byte("first"), nil); !errors.As(err, &unconfirmed) { + t.Fatalf("first Send = %v, want an UnconfirmedError", err) + } + called := false + err := client.Send(context.Background(), []byte("second"), func() error { called = true; return nil }) + if err == nil || errors.As(err, &unconfirmed) || called { + t.Errorf("second Send = %v, beforeWrite called %v; want a plain error before beforeWrite", err, called) + } + if got := <-written; len(got) != 0 { + t.Errorf("printer got % X after the ready request", got) + } +} + +// After the ready answer the printer sends an automatic status block every +// 50 ms. Only answers keep the ready wait open, so Send writes the job and +// returns on its confirmation, and a cancelled one returns at once. +func TestSendOnALineFullOfStatusBlocks(t *testing.T) { + addr := fakePrinter(t, func(conn net.Conn) { + if answerReady(conn) != nil { + return + } + stop := make(chan struct{}) + defer close(stop) + go func() { + for { + select { + case <-stop: + return + case <-time.After(50 * time.Millisecond): + if _, err := conn.Write([]byte{0x10, 0x00, 0x00, 0x00}); err != nil { + return + } + } + } + }() + if _, err := readJob(conn); err != nil { + return + } + _, _ = conn.Write([]byte{0x00}) + _, _ = io.ReadAll(conn) + }) + client := printer.NewClient(addr, time.Second, 700*time.Millisecond, printer.Confirm(true)) + start := time.Now() + if err := client.Send(context.Background(), []byte("job"), nil); err != nil { + t.Errorf("Send = %v, want nil", err) + } + if took := time.Since(start); took > 500*time.Millisecond { + t.Errorf("Send took %v", took) + } + + ctx, cancel := context.WithCancel(context.Background()) + time.AfterFunc(50*time.Millisecond, cancel) + start = time.Now() + err := client.Send(ctx, []byte("job"), func() error { return errors.New("beforeWrite called") }) + if err == nil { + t.Error("cancelled Send = nil") + } + if took := time.Since(start); took > 500*time.Millisecond { + t.Errorf("cancelled Send took %v", took) + } +} + +// With Confirm, Send sends DLE EOT 1, GS a 0 and GS r 1, DLE EOT 1 again +// once they are answered, then the job with GS a 0 and GS r 1 after it, and +// nothing else. +func TestSendWithConfirmSendsTheseBytes(t *testing.T) { + received := make(chan []byte, 1) + addr := fakePrinter(t, func(conn net.Conn) { + var all []byte + defer func() { received <- all }() + for _, step := range []struct { + read int + answer []byte + }{{9, []byte{0x12, 0x00}}, {3, []byte{0x12}}, {len("receipt") + 6, []byte{0x00}}} { + buf := make([]byte, step.read) + n, err := io.ReadFull(conn, buf) + all = append(all, buf[:n]...) + if err != nil { + return + } + if _, err := conn.Write(step.answer); err != nil { + return + } + } + rest, _ := io.ReadAll(conn) + all = append(all, rest...) + }) + client := printer.NewClient(addr, time.Second, time.Second, printer.Confirm(true)) + if err := client.Send(context.Background(), []byte("receipt"), nil); err != nil { + t.Fatalf("Send = %v", err) + } + want := []byte("\x10\x04\x01\x1Da\x00\x1Dr\x01\x10\x04\x01receipt\x1Da\x00\x1Dr\x01") + if got := <-received; !bytes.Equal(got, want) { + t.Errorf("printer got % X\nwant % X", got, want) + } +} + +// With Confirm, a printer that answers the ready request but reports +// itself offline to DLE EOT 1 gets nothing of the job: Send returns a plain +// error without calling beforeWrite. +func TestSendToAnOfflinePrinter(t *testing.T) { + rest := make(chan []byte, 1) + addr := fakePrinter(t, func(conn net.Conn) { + if _, err := readJob(conn); err != nil { + rest <- nil + return + } + _, _ = conn.Write([]byte{0x00}) + req := make([]byte, 3) + if _, err := io.ReadFull(conn, req); err != nil { + rest <- nil + return + } + _, _ = conn.Write([]byte{0x1A}) + data, _ := io.ReadAll(conn) + rest <- data + }) + client := printer.NewClient(addr, time.Second, time.Second, printer.Confirm(true)) + called := false + err := client.Send(context.Background(), []byte("receipt"), func() error { called = true; return nil }) + var unconfirmed *printer.UnconfirmedError + if err == nil || errors.As(err, &unconfirmed) || called { + t.Errorf("Send = %v, beforeWrite called %v; want a plain error before beforeWrite", err, called) + } + if got := <-rest; len(got) != 0 { + t.Errorf("printer got % X after DLE EOT 1", got) + } +} + +// tailBoard is a fake printer whose output goes to whichever connection is +// open, as a print server board can route it. The first connection goes to +// first, every later one to later. The tail func first gets writes bytes to +// the next connection once it is accepted, or after 90 ms to the first, so +// a block's last bytes always come within 100 ms of its header. +func tailBoard(t *testing.T, first func(conn net.Conn, tail func([]byte)), later func(net.Conn)) string { + t.Helper() + var conns atomic.Int32 + next := make(chan net.Conn, 1) + return fakePrinter(t, func(conn net.Conn) { + if conns.Add(1) == 1 { + first(conn, func(b []byte) { + select { + case c := <-next: + _, _ = c.Write(b) + case <-time.After(90 * time.Millisecond): + _, _ = conn.Write(b) + } + }) + _, _ = io.ReadAll(conn) + return + } + select { + case next <- conn: + default: + } + later(conn) + }) +} + +// coverOpen serves a connection as a printer with its cover open: it +// answers nothing, and reports on written everything it was sent. +func coverOpen(written chan<- []byte) func(net.Conn) { + return func(conn net.Conn) { + data, _ := io.ReadAll(conn) + written <- data + } +} + +// expectNoJob checks that Send failed and that the printer got nothing on +// written but the requests Send asks before a job. +func expectNoJob(t *testing.T, written <-chan []byte, err error) { + t.Helper() + select { + case got := <-written: + for _, request := range [][]byte{ + escpos.AutomaticStatusOff(), escpos.TransmitStatusRequest(), escpos.StatusRequest(escpos.StatusPrinter), + } { + got = bytes.ReplaceAll(got, request, nil) + } + if len(got) != 0 { + t.Errorf("printer with its cover open got %q; Send = %v", got, err) + } + case <-time.After(3 * time.Second): + t.Fatal("the fake printer saw no second connection end") + } + if err == nil { + t.Error("Send = nil, though the printer never answered") + } +} + +// The cover opens as Status reads its last answer: an automatic status +// block's header follows that answer, and its last bytes come 90 ms later. +// Status reads them before it closes the connection, so the next job's +// connection, on which the printer answers nothing until the job is +// written, gets none, and nothing of the job is written. +func TestStatusReadsTheBlockAfterItsLastAnswer(t *testing.T) { + for name, later := range map[string]func(chan<- []byte) func(net.Conn){ + "the cover stays open": coverOpen, + "the cover closes once the job is written": func(written chan<- []byte) func(net.Conn) { + return func(conn net.Conn) { + if _, err := readJob(conn); err != nil { + written <- nil + return + } + job, err := readJob(conn) + written <- job + if err != nil { + return + } + _, _ = conn.Write([]byte{0x00}) + _, _ = io.ReadAll(conn) + } + }, + } { + t.Run(name, func(t *testing.T) { + written := make(chan []byte, 1) + addr := tailBoard(t, func(conn net.Conn, tail func([]byte)) { + req := make([]byte, 3) + for kind := 1; kind <= 4; kind++ { + if _, err := io.ReadFull(conn, req); err != nil { + return + } + answer := []byte{0x12} + if kind == 4 { + answer = []byte{0x12, 0x38} + } + _, _ = conn.Write(answer) + } + tail([]byte{0x00, 0x00, 0x00}) + }, later(written)) + client := printer.NewClient(addr, time.Second, 400*time.Millisecond, printer.Confirm(true)) + if status, err := client.Status(context.Background()); err != nil { + t.Fatalf("Status = %+v, %v", status, err) + } + err := client.Send(context.Background(), []byte("second"), nil) + expectNoJob(t, written, err) + }) + } +} + +// An automatic status block's header comes on one connection and its last +// bytes on the next, which reaches a printer with its cover open. They look +// like answers to the ready request, but the printer does not answer DLE +// EOT 1 as online, so nothing of the job is written. +func TestSendToACoverOpenPrinterAfterABlockCutShort(t *testing.T) { + tests := []struct { + name string + writeTimeout time.Duration + first func(conn net.Conn, tail func([]byte)) + firstSend func(error) bool + }{ + { + name: "a header just after the confirmation", + writeTimeout: 400 * time.Millisecond, + first: func(conn net.Conn, tail func([]byte)) { + if answerReady(conn) != nil { + return + } + if _, err := readJob(conn); err != nil { + return + } + _, _ = conn.Write([]byte{0x00}) + time.Sleep(5 * time.Millisecond) + _, _ = conn.Write([]byte{0x38}) + tail([]byte{0x00, 0x00, 0x00}) + }, + firstSend: func(err error) bool { return err == nil }, + }, + { + name: "a header just before the confirmation deadline", + writeTimeout: 500 * time.Millisecond, + first: func(conn net.Conn, tail func([]byte)) { + if answerReady(conn) != nil { + return + } + if _, err := readJob(conn); err != nil { + return + } + time.Sleep(450 * time.Millisecond) + _, _ = conn.Write([]byte{0x38}) + tail([]byte{0x00, 0x00, 0x00}) + }, + firstSend: func(err error) bool { + var unconfirmed *printer.UnconfirmedError + return errors.As(err, &unconfirmed) + }, + }, + { + name: "the confirmation and a header just before the write deadline", + writeTimeout: 600 * time.Millisecond, + first: func(conn net.Conn, tail func([]byte)) { + if answerReady(conn) != nil { + return + } + if _, err := readJob(conn); err != nil { + return + } + time.Sleep(520 * time.Millisecond) + _, _ = conn.Write([]byte{0x00, 0x38}) + tail([]byte{0x00, 0x00, 0x00}) + }, + firstSend: func(err error) bool { return err == nil }, + }, + { + name: "a header just before the ready deadline", + writeTimeout: 500 * time.Millisecond, + first: func(conn net.Conn, tail func([]byte)) { + if _, err := readJob(conn); err != nil { + return + } + time.Sleep(450 * time.Millisecond) + _, _ = conn.Write([]byte{0x38}) + tail([]byte{0x00, 0x03, 0x00}) + }, + firstSend: func(err error) bool { return err != nil }, + }, + { + name: "a whole block after the confirmation", + writeTimeout: 400 * time.Millisecond, + first: func(conn net.Conn, _ func([]byte)) { + if answerReady(conn) != nil { + return + } + if _, err := readJob(conn); err != nil { + return + } + _, _ = conn.Write([]byte{0x00, 0x38, 0x00, 0x00, 0x00}) + }, + firstSend: func(err error) bool { return err == nil }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + written := make(chan []byte, 1) + addr := tailBoard(t, tt.first, coverOpen(written)) + client := printer.NewClient(addr, time.Second, tt.writeTimeout, printer.Confirm(true)) + if err := client.Send(context.Background(), []byte("first"), nil); !tt.firstSend(err) { + t.Fatalf("first Send = %v", err) + } + err := client.Send(context.Background(), []byte("second"), nil) + expectNoJob(t, written, err) + }) + } +} + +// Owed answers with an automatic status block among them, whole or split +// across reads, are all dropped, and the job waits for its own +// confirmation. +func TestSendDropsOwedAnswersAroundAStatusBlock(t *testing.T) { + for name, seq := range map[string][][]byte{ + "a whole block": {{0x00}, {0x10, 0x00, 0x00, 0x00}, {0x00}, {0x00}}, + "a split block": {{0x00}, {0x10}, {0x00, 0x00, 0x00}, {0x00}, {0x00}}, + "a header with an owed answer": {{0x00, 0x10}, {0x00}, {0x00, 0x00}, {0x00}}, + } { + t.Run(name, func(t *testing.T) { + answer := make(chan struct{}) + addr := fakePrinter(t, func(conn net.Conn) { + if _, err := readJob(conn); err != nil { + return + } + for _, b := range seq { + _, _ = conn.Write(b) + time.Sleep(25 * time.Millisecond) + } + if _, err := readJob(conn); err != nil { + return + } + <-answer + _, _ = conn.Write([]byte{0x00}) + _, _ = io.ReadAll(conn) + }) + client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) + sendUntilAnswered(t, client, []byte("job"), answer) + }) + } +} + +// readFence reads the DLE EOT 1, GS a 0 and GS r 1 that Send sends at the +// start of a connection. +func readFence(conn net.Conn) error { + want := slices.Concat(escpos.StatusRequest(escpos.StatusPrinter), escpos.AutomaticStatusOff(), + escpos.TransmitStatusRequest()) + got := make([]byte, len(want)) + if _, err := io.ReadFull(conn, got); err != nil { + return err + } + if !bytes.Equal(got, want) { + return fmt.Errorf("got % X at the start of the connection, want % X", got, want) + } + return nil +} + +// An answer owed to a request the printer ran earlier comes at the start of +// the connection, and the requests reach the printer 150 ms later, as after +// a lost segment. The answer comes before the fence's, so it is dropped, +// and the job waits for its own confirmation, whether the ready answer +// comes with the fence's or 150 ms after it. +func TestSendDropsAnOwedAnswerBeforeTheFence(t *testing.T) { + for name, readyAfter := range map[string]time.Duration{ + "the ready answer with the fence's": 0, + "the ready answer 150 ms later": 150 * time.Millisecond, + } { + t.Run(name, func(t *testing.T) { + answer := make(chan struct{}) + addr := fakePrinter(t, func(conn net.Conn) { + _, _ = conn.Write([]byte{0x00}) + time.Sleep(150 * time.Millisecond) + if readFence(conn) != nil { + return + } + _, _ = conn.Write([]byte{0x12}) + time.Sleep(readyAfter) + _, _ = conn.Write([]byte{0x00}) + if _, err := readJob(conn); err != nil { + return + } + <-answer + _, _ = conn.Write([]byte{0x00}) + _, _ = io.ReadAll(conn) + }) + client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) + sendUntilAnswered(t, client, []byte("job"), answer) + }) + } +} + +// An owed answer at the start of the connection, while the cover is open; +// the cover closes, and the printer answers every DLE EOT 1 at once as +// online but runs GS r 1 only 300 ms later, as after a feed and cut at +// cover close. The owed answer comes before the fence's and is dropped, so +// the job waits for the late ready answer and then for its own +// confirmation. +func TestSendAfterAnOwedAnswerAndACoverClosing(t *testing.T) { + answer := make(chan struct{}) + addr := fakePrinter(t, func(conn net.Conn) { + _, _ = conn.Write([]byte{0x00}) + if readFence(conn) != nil { + return + } + _, _ = conn.Write([]byte{0x12}) + ready := time.AfterFunc(300*time.Millisecond, func() { _, _ = conn.Write([]byte{0x00}) }) + defer ready.Stop() + if _, err := readJob(conn); err != nil { + return + } + <-answer + _, _ = conn.Write([]byte{0x00}) + _, _ = io.ReadAll(conn) + }) + client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) + sendUntilAnswered(t, client, []byte("job"), answer) +} + +// A block's header comes just after a job's confirmation and its last bytes +// begin the next connection, ahead of the fence's answer. The printer is +// online but answers the ready request only 300 ms later, still busy. The +// last bytes are dropped with everything before the fence, so the job waits +// for the ready answer, and that answer never confirms it. +func TestSendDropsABlockTailBeforeTheFence(t *testing.T) { + answer := make(chan struct{}) + addr := tailBoard(t, func(conn net.Conn, tail func([]byte)) { + if answerReady(conn) != nil { + return + } + if _, err := readJob(conn); err != nil { + return + } + _, _ = conn.Write([]byte{0x00}) + time.Sleep(5 * time.Millisecond) + _, _ = conn.Write([]byte{0x38}) + tail([]byte{0x00, 0x00, 0x00}) + }, func(conn net.Conn) { + time.Sleep(20 * time.Millisecond) + if readFence(conn) != nil { + return + } + _, _ = conn.Write([]byte{0x12}) + ready := time.AfterFunc(300*time.Millisecond, func() { _, _ = conn.Write([]byte{0x00}) }) + defer ready.Stop() + if _, err := readJob(conn); err != nil { + return + } + <-answer + _, _ = conn.Write([]byte{0x00}) + _, _ = io.ReadAll(conn) + }) + client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) + if err := client.Send(context.Background(), []byte("first"), nil); err != nil { + t.Fatalf("first Send = %v", err) + } + sendUntilAnswered(t, client, []byte("second"), answer) +} + +// The answer owed to an unconfirmed job comes after the fence's; then the +// cover opens before the ready request runs, and the printer answers the +// online check as offline. Nothing of the job is written. +func TestSendAfterAnOwedAnswerAndACoverOpening(t *testing.T) { + rest := make(chan []byte, 1) + var conns atomic.Int32 + addr := fakePrinter(t, func(conn net.Conn) { + if conns.Add(1) == 1 { + if answerReady(conn) != nil { + return + } + _, _ = readJob(conn) + _, _ = io.ReadAll(conn) + return + } + if readFence(conn) != nil { + rest <- nil + return + } + _, _ = conn.Write([]byte{0x12, 0x00}) + req := make([]byte, 3) + if _, err := io.ReadFull(conn, req); err != nil { + rest <- nil + return + } + _, _ = conn.Write([]byte{0x3A}) + data, _ := io.ReadAll(conn) + rest <- data + }) + client := printer.NewClient(addr, time.Second, 500*time.Millisecond, printer.Confirm(true)) + var unconfirmed *printer.UnconfirmedError + if err := client.Send(context.Background(), []byte("first"), nil); !errors.As(err, &unconfirmed) { + t.Fatalf("first Send = %v, want an UnconfirmedError", err) + } + err := client.Send(context.Background(), []byte("second"), nil) + if got := <-rest; len(got) != 0 { + t.Errorf("printer with its cover open got %q", got) + } + if err == nil { + t.Error("second Send = nil, want an error: the printer reported itself offline") + } +} + +// After the ready answer the printer floods bytes like answers to GS r and +// never answers the online check: Send gives up within its bounds, with +// nothing of the job written. +func TestSendBoundedByAFloodDuringTheOnlineCheck(t *testing.T) { + rest := make(chan []byte, 1) + addr := fakePrinter(t, func(conn net.Conn) { + if readFence(conn) != nil { + rest <- nil + return + } + _, _ = conn.Write([]byte{0x12, 0x00}) + online := make([]byte, 3) + if _, err := io.ReadFull(conn, online); err != nil { + rest <- nil + return + } + stop := make(chan struct{}) + go func() { + for { + select { + case <-stop: + return + default: + } + if _, err := conn.Write([]byte{0x00}); err != nil { + return + } + time.Sleep(time.Millisecond) + } + }() + data, _ := io.ReadAll(conn) + close(stop) + rest <- data + }) + client := printer.NewClient(addr, time.Second, 5*time.Second, printer.Confirm(true)) + start := time.Now() + err := client.Send(context.Background(), []byte("job"), nil) + if took := time.Since(start); err == nil || took > 6*time.Second { + t.Errorf("Send = %v after %v, want an error within 6 s", err, took) + } + if got := bytes.ReplaceAll(<-rest, escpos.StatusRequest(escpos.StatusPrinter), nil); len(got) != 0 { + t.Errorf("printer got % X after the online check", got) + } +} + +// With Confirm off, Send writes the job's bytes alone, whatever the +// printer sends back. +func TestSendWithConfirmOffSendsOnlyTheJob(t *testing.T) { + job := []byte("\x1b@receipt\x1dr\x01") + received := make(chan []byte, 1) + addr := fakePrinter(t, func(conn net.Conn) { + got := make([]byte, len(job)) + n, _ := io.ReadFull(conn, got) + _, _ = conn.Write([]byte{0x00, 0x10, 0x00, 0x00, 0x00, 0x12}) + extra, _ := io.ReadAll(conn) + received <- append(got[:n], extra...) + }) + client := printer.NewClient(addr, time.Second, time.Second, printer.Confirm(false)) + if err := client.Send(context.Background(), job, nil); err != nil { + t.Fatal(err) + } + if got := <-received; !bytes.Equal(got, job) { + t.Errorf("printer got % X", got) + } +} + +// Status against a printer that sends an automatic status block every 5 ms, +// before and after its answers, returns within its bounds. +func TestStatusBoundedByAFloodOfBlocks(t *testing.T) { + addr := fakePrinter(t, func(conn net.Conn) { + stop := make(chan struct{}) + defer close(stop) + go func() { + for { + select { + case <-stop: + return + case <-time.After(5 * time.Millisecond): + if _, err := conn.Write([]byte{0x10, 0x00, 0x00, 0x00}); err != nil { + return + } + } + } + }() + req := make([]byte, 3) + for { + if _, err := io.ReadFull(conn, req); err != nil { + return + } + _, _ = conn.Write([]byte{0x12}) + } + }) + start := time.Now() + status, err := printer.NewClient(addr, time.Second, time.Second).Status(context.Background()) + if took := time.Since(start); err != nil || !status.Online || took > time.Second { + t.Errorf("Status = %+v, %v after %v, want online within 1 s", status, err, took) + } +} + +// sendResidual sends data as sendUntilAnswered does, but only logs a Send +// that returns before answer is closed: the case is one the client leaves +// open, and the test shows how it ends. +func sendResidual(t *testing.T, client *printer.Client, data []byte, answer chan struct{}) { + t.Helper() + sent := make(chan error, 1) + go func() { sent <- client.Send(context.Background(), data, nil) }() + select { + case err := <-sent: + close(answer) + t.Logf("RESIDUAL: Send returned %v before the printer confirmed the job", err) + return + case <-time.After(500 * time.Millisecond): + } + close(answer) + t.Logf("Send = %v once the printer confirmed the job", <-sent) +} + +// A late answer to an earlier connection's DLE EOT and an owed answer to +// GS r reach this connection at once, while its own requests are held back +// 300 ms, as by a lost segment. The late answer stands in for the fence and +// the owed one for the ready answer; then this connection's own answers +// come, in either order, or a GS r answer comes during the online check. +// An answer to GS r after the answers settled makes the printer not ready, +// and nothing of the job is written. +func TestSendRefusesAnAnswerAfterAFakeFence(t *testing.T) { + for name, answers := range map[string][]byte{ + "fence, ready, online": {0x12, 0x00, 0x12}, + "fence, online, ready": {0x12, 0x12, 0x00}, + "an answer during the online check": {0x00, 0x12}, + } { + t.Run(name, func(t *testing.T) { + rest := make(chan []byte, 1) + addr := fakePrinter(t, func(conn net.Conn) { + _, _ = conn.Write([]byte{0x12, 0x00}) + time.Sleep(300 * time.Millisecond) + if readFence(conn) != nil { + rest <- nil + return + } + online := make([]byte, 3) + if _, err := io.ReadFull(conn, online); err != nil { + rest <- nil + return + } + _, _ = conn.Write(answers) + data, _ := io.ReadAll(conn) + rest <- data + }) + client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) + called := false + err := client.Send(context.Background(), []byte("job"), func() error { called = true; return nil }) + var unconfirmed *printer.UnconfirmedError + if err == nil || errors.As(err, &unconfirmed) || called { + t.Errorf("Send = %v, beforeWrite called %v; want a plain error before beforeWrite", err, called) + } + if got := <-rest; len(got) != 0 { + t.Errorf("printer got % X after the online check", got) + } + }) + } +} + +// A late answer to an earlier connection's DLE EOT alone, with no answer to +// GS r owed after it, stands in for the fence harmlessly: nothing is +// counted before this connection's own ready answer. +func TestSendAfterALateFenceAnswerAlone(t *testing.T) { + answer := make(chan struct{}) + addr := fakePrinter(t, func(conn net.Conn) { + _, _ = conn.Write([]byte{0x12}) + time.Sleep(300 * time.Millisecond) + if readFence(conn) != nil { + return + } + _, _ = conn.Write([]byte{0x12, 0x00}) + if _, err := readJob(conn); err != nil { + return + } + <-answer + _, _ = conn.Write([]byte{0x00}) + _, _ = io.ReadAll(conn) + }) + client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) + sendUntilAnswered(t, client, []byte("job"), answer) +} + +// Job A is unconfirmed, the printer still printing it. On B's connection +// the printer answers the fence at once and, once A has printed, A's owed +// answer and B's ready answer back to back. Both are dropped, and B waits +// for its own confirmation. +func TestSendAfterAnUnconfirmedJobStillPrinting(t *testing.T) { + answer := make(chan struct{}) + var conns atomic.Int32 + addr := fakePrinter(t, func(conn net.Conn) { + if conns.Add(1) == 1 { + if answerReady(conn) != nil { + return + } + _, _ = readJob(conn) + _, _ = io.ReadAll(conn) + return + } + if readFence(conn) != nil { + return + } + _, _ = conn.Write([]byte{0x12}) + time.Sleep(400 * time.Millisecond) + _, _ = conn.Write([]byte{0x00}) + time.Sleep(2 * time.Millisecond) + _, _ = conn.Write([]byte{0x00}) + if _, err := readJob(conn); err != nil { + return + } + <-answer + _, _ = conn.Write([]byte{0x00}) + _, _ = io.ReadAll(conn) + }) + client := printer.NewClient(addr, time.Second, 500*time.Millisecond, printer.Confirm(true)) + var unconfirmed *printer.UnconfirmedError + if err := client.Send(context.Background(), []byte("A"), nil); !errors.As(err, &unconfirmed) { + t.Fatalf("first Send = %v, want an UnconfirmedError", err) + } + client = printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) + sendUntilAnswered(t, client, []byte("B"), answer) +} + +// The case the client leaves open: an answer still queued in the printer +// when the fence arrived, then a pause of 250 ms, while the printer answers +// DLE EOT 1 as online, before the ready answer. The pause outlasts the +// settle and the read after the online check, so the ready answer +// confirms the job before it has printed. +func TestSendResidualPauseBetweenQueuedAnswers(t *testing.T) { + answer := make(chan struct{}) + addr := fakePrinter(t, func(conn net.Conn) { + if readFence(conn) != nil { + return + } + _, _ = conn.Write([]byte{0x12}) + time.Sleep(50 * time.Millisecond) + _, _ = conn.Write([]byte{0x00}) + ready := time.AfterFunc(250*time.Millisecond, func() { _, _ = conn.Write([]byte{0x00}) }) + defer ready.Stop() + if _, err := readJob(conn); err != nil { + return + } + <-answer + _, _ = conn.Write([]byte{0x00}) + _, _ = io.ReadAll(conn) + }) + client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) + sendResidual(t, client, []byte("job"), answer) +} + +// The fence's answer comes inside an automatic status block on this +// connection, should a printer ever put one between a block's bytes. It is +// read as a block byte, the fence is missed, and Send gives up at the +// deadline with nothing of the job written. +func TestSendFenceAnswerInsideABlock(t *testing.T) { + rest := make(chan []byte, 1) + addr := fakePrinter(t, func(conn net.Conn) { + if readFence(conn) != nil { + rest <- nil + return + } + _, _ = conn.Write([]byte{0x10, 0x00, 0x12, 0x00, 0x00}) + time.Sleep(20 * time.Millisecond) + _, _ = conn.Write([]byte{0x00}) + data, _ := io.ReadAll(conn) + rest <- data + }) + client := printer.NewClient(addr, time.Second, 500*time.Millisecond, printer.Confirm(true)) + if err := client.Send(context.Background(), []byte("job"), nil); err == nil { + t.Error("Send = nil, want an error: the fence was never seen") + } + if got := <-rest; len(got) != 0 { + t.Errorf("printer got % X after the fence request", got) + } +} + +// The case the client leaves open, should a printer ever put the fence's +// answer between the last bytes of a block whose header went to an +// earlier connection: the bytes after it count as answers, and the ready +// answer, 300 ms later, confirms the job before it has printed. +func TestSendResidualFenceAnswerBetweenTailBytes(t *testing.T) { + answer := make(chan struct{}) + addr := fakePrinter(t, func(conn net.Conn) { + if readFence(conn) != nil { + return + } + _, _ = conn.Write([]byte{0x00, 0x12, 0x00, 0x00}) + ready := time.AfterFunc(300*time.Millisecond, func() { _, _ = conn.Write([]byte{0x00}) }) + defer ready.Stop() + if _, err := readJob(conn); err != nil { + return + } + <-answer + _, _ = conn.Write([]byte{0x00}) + _, _ = io.ReadAll(conn) + }) + client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) + sendResidual(t, client, []byte("job"), answer) +} + +// A printer that never answers the fence but floods bytes that are not +// answers to DLE EOT: Send gives up at its deadline, and a cancellation +// stops it at once. +func TestSendBoundedByAFloodBeforeTheFence(t *testing.T) { + addr := fakePrinter(t, func(conn net.Conn) { + if readFence(conn) != nil { + return + } + go func() { _, _ = io.Copy(io.Discard, conn) }() + chunk := []byte{0x00, 0x10, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00} + for { + if _, err := conn.Write(chunk); err != nil { + return + } + } + }) + client := printer.NewClient(addr, time.Second, 500*time.Millisecond, printer.Confirm(true)) + start := time.Now() + err := client.Send(context.Background(), []byte("job"), nil) + if took := time.Since(start); err == nil || took > 700*time.Millisecond { + t.Errorf("Send = %v after %v, want an error within 700 ms", err, took) + } + + ctx, cancel := context.WithCancel(context.Background()) + time.AfterFunc(100*time.Millisecond, cancel) + client = printer.NewClient(addr, time.Second, 3*time.Second, printer.Confirm(true)) + start = time.Now() + err = client.Send(ctx, []byte("job"), nil) + if took := time.Since(start); !errors.Is(err, context.Canceled) || took > 300*time.Millisecond { + t.Errorf("cancelled Send = %v after %v, want context.Canceled within 300 ms", err, took) + } +} + +// After the fence the printer sends a byte like an answer to GS r every +// 20 ms, so the answers never settle; a cancellation stops the wait at +// once. +func TestSendCancelledDuringSteadyAnswers(t *testing.T) { + addr := fakePrinter(t, func(conn net.Conn) { + if readFence(conn) != nil { + return + } + go func() { _, _ = io.Copy(io.Discard, conn) }() + if _, err := conn.Write([]byte{0x12}); err != nil { + return + } + for { + if _, err := conn.Write([]byte{0x00}); err != nil { + return + } + time.Sleep(20 * time.Millisecond) + } + }) + var worst time.Duration + for i := range 10 { + after := time.Duration(50+i*7) * time.Millisecond + client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) + ctx, cancel := context.WithCancel(context.Background()) + time.AfterFunc(after, cancel) + start := time.Now() + _ = client.Send(ctx, []byte("job"), nil) + cancel() + worst = max(worst, time.Since(start)-after) + } + if worst > 150*time.Millisecond { + t.Errorf("a cancellation took %v to stop the wait", worst) + } +} + +// After the fence the printer floods bytes like answers to GS r. A +// cancellation stops the wait at once, even one that lands between a read +// and the reset of the read deadline after it. +func TestSendCancelledDuringAnswerFlood(t *testing.T) { + addr := fakePrinter(t, func(conn net.Conn) { + if readFence(conn) != nil { + return + } + go func() { _, _ = io.Copy(io.Discard, conn) }() + if _, err := conn.Write([]byte{0x12}); err != nil { + return + } + chunk := make([]byte, 16) + for { + if _, err := conn.Write(chunk); err != nil { + return + } + } + }) + for i := range 5 { + client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) + ctx, cancel := context.WithCancel(context.Background()) + time.AfterFunc(time.Duration(50+i*7)*time.Millisecond, cancel) + start := time.Now() + err := client.Send(ctx, []byte("job"), nil) + cancel() + if took := time.Since(start); !errors.Is(err, context.Canceled) || took > 500*time.Millisecond { + t.Errorf("trial %d: Send = %v after %v, want context.Canceled within 500 ms", i, err, took) + } + } +} + // A dial that fails never calls beforeWrite. func TestSendDialFailureSkipsBeforeWrite(t *testing.T) { ln, err := net.Listen("tcp", "127.0.0.1:0") @@ -237,6 +1662,51 @@ func TestStatus(t *testing.T) { } } +// A printer that answers DLE EOT with bytes that are not DLE EOT answers +// gets ErrStatusUnsupported without Status waiting out its timeout: at +// once for a byte that fits no answer, and within 100 ms for one that +// looks like an answer to GS r, which a late answer could be. +func TestStatusOnAnswersThatAreNotRealTime(t *testing.T) { + for name, tt := range map[string]struct { + answer byte + within time.Duration + }{ + "a byte like a GS r answer": {0x00, 500 * time.Millisecond}, + "a byte that fits no answer": {0x80, 80 * time.Millisecond}, + } { + t.Run(name, func(t *testing.T) { + addr := statusPrinter(t, map[byte]byte{1: tt.answer, 2: tt.answer, 3: tt.answer, 4: tt.answer}) + start := time.Now() + _, err := printer.NewClient(addr, time.Second, time.Second).Status(context.Background()) + if took := time.Since(start); !errors.Is(err, printer.ErrStatusUnsupported) || took > tt.within { + t.Errorf("Status = %v after %v, want ErrStatusUnsupported within %v", err, took, tt.within) + } + }) + } +} + +// A late answer to an earlier GS r 1 and an automatic status block, sent +// before the answers to DLE EOT, are passed over. +func TestStatusSkipsStrayBytes(t *testing.T) { + addr := fakePrinter(t, func(conn net.Conn) { + _, _ = conn.Write([]byte{0x00, 0x10, 0x00, 0x00, 0x00}) + req := make([]byte, 3) + for { + if _, err := io.ReadFull(conn, req); err != nil { + return + } + _, _ = conn.Write([]byte{0x12}) + } + }) + status, err := printer.NewClient(addr, time.Second, time.Second).Status(context.Background()) + if err != nil { + t.Fatal(err) + } + if want := (escpos.Status{Online: true}); status != want { + t.Errorf("status = %+v, want %+v", status, want) + } +} + func TestStatusUnsupported(t *testing.T) { addr := fakePrinter(t, func(conn net.Conn) { _, _ = io.Copy(io.Discard, conn) // a printer that never answers