Files
uberbringer/internal/pkg/printer/printer.go
T
57_WolveandClaude Opus 5.5 9376653e1a Let the printer client wait for the printer to confirm a job
A write to the printer's socket returns once the operating system holds
the bytes, not once the printer has them. On the TM-T88IV with its cover
open, Windows took all of a 128 KB receipt into its send buffer at once,
so the job read done; once the cover closed, only its first third
printed, without its cut, and the printer was left inside the image
command, waiting for the rest.

With the new option printer.Confirm(true), 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:

- Before beforeWrite, it sends DLE EOT 1, GS a 0 and GS r 1 in one
  write. 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, and Send drops it.
  That takes care of answers owed to requests the printer ran on an
  earlier connection or for an earlier run of the daemon, of the last
  bytes of a status block whose header went to an earlier connection,
  and of late DLE EOT answers, however long a lost segment holds the
  request back. Send waits for the fence until the write timeout or
  the context's deadline, then for an answer to GS r 1 after it.
  Without them, as with the cover open, no paper, or a printer stuck
  inside an earlier job, Send returns a plain error with nothing of
  the job written, as after a failed dial. Requests still queued in the
  printer ahead of this one are answered after the fence too, and
  answers carry nothing that tells them apart, so the wait reads every
  answer until 100 ms have passed since the last and drops them all,
  and none can be taken for a later job's confirmation. Each job waits
  those 100 ms. Only answers keep the wait open, so status blocks
  cannot, and a wait that the deadline or the connection's end cuts
  short counts as not ready, as one without an answer does. A printer
  may run GS r 1 while offline, so Send then asks DLE EOT 1 again, for
  up to 2 s, and writes the job only if the printer answers that it is
  online. Last, it reads on for 100 ms. Once the answers have settled
  none is owed, so an answer to GS r 1 during the online check or after
  it means one taken for the ready answer was not, as when a late
  DLE EOT answer from an earlier connection stood in for the fence and
  an owed answer followed it; Send then returns a plain error with
  nothing written, and the job is tried again. A cancellation stops the
  wait at once: it sets a flag that every reset of the read deadline
  checks, and the wait returns only once a cancellation that raced its
  end has finished with the connection.
- After the job, it sends GS a 0 and GS r 1 again and returns once the
  answer arrives. If it does not arrive before the write deadline, or
  the connection fails or closes after the job was written in full,
  Send returns an *UnconfirmedError: the job may have printed in full,
  in part or not at all. The error has an Unconfirmed method, so the
  queue can tell it apart without importing the package.

Automatic status blocks are what GS a 0 is for. The UB-E02 and UB-E03
boards turn them on at power-on, and a job's own ESC @ does not turn
them off on a TM-T88VII with DIP switch 2-1 on. A block's last three
bytes have an answer's fixed bits (bits 4 and 7 clear), and the board
can send them on the next connection, where they would stand for the
ready answer. The printer runs GS a 0 in order, so no block follows the
answer to a GS r 1 sent after it. Blocks that come before it are passed
over by their header's fixed bits: each connection keeps its place in a
block across reads, and once Send has the confirmation it reads on for
up to 100 ms for the rest of a block it ended inside. A block cut short
ends with its connection, and last bytes that still begin a connection,
before the first job after a power-on has turned blocks off, come before
the fence's answer and are dropped.

Status sends no GS a 0, which the printer does not run while it is
offline. It passes over blocks, answers to DLE EOT n that a job's own
bytes hold, and a late answer to GS r 1, and before it closes it reads
what has come, to the end of any block, so that the next connection
gets none of it. It returns ErrStatusUnsupported at once on a byte that
fits no answer, and within 100 ms when a byte like an answer to GS r is
not followed by an answer to DLE EOT, rather than after its 2 s. The
printers plan and the job-store plan say so. The TM-T88IV answered
GS r 1 with 0x00 within 4 ms when asked on its own. Nothing turns the
option on yet.

Tests pin the bytes Send sends with the option on, refuse a printer that
answers DLE EOT 1 as offline, put an owed answer, a block's last bytes
or both before the fence and delay the ready answer behind it, as after
a lost segment or while the printer feeds and cuts at cover close,
answer the ready request after an answer owed to an earlier run, and
after one owed since a job's own GS r 1,
split a status block across reads and across a confirmation and the
50 ms after it, and put owed answers around a block; in each, Send
waits for the job's own answer. Others cut a block short and find the
next jobs and Status unharmed, send a cover-open block in place of the
ready answer, start a connection with the last bytes of a block whose
header came after a confirmation, before the confirmation's deadline,
with the confirmation at the write deadline, before the ready deadline
or after Status's last answer, and find nothing written to a printer
with its cover open. Others cut the ready wait short by its deadline and
find nothing written, send status blocks every 50 ms and find the job
sent and confirmed, and answer DLE EOT with bytes that are not DLE EOT
answers and find Status unsupported within 100 ms. Others flood the
online check with bytes like answers and Status with status blocks, and
find both bounded, and turn the option off and find the job's bytes
sent alone. Others put a late DLE EOT answer and an owed answer ahead of
a held-back request, or an answer during the online check, and find
nothing written; cancel during a steady stream and a flood of answers
and find the wait stops at once; and play two cases the client leaves
open, a long pause between queued answers and a fence answer between a
block's last bytes, logging how they end.

Part of stage 1d of docs/plans/job-store.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 21:28:37 -06:00

621 lines
22 KiB
Go

// Package printer talks to a network receipt printer over a raw TCP socket
// (the "port 9100" / JetDirect protocol).
package printer
import (
"context"
"errors"
"fmt"
"net"
"slices"
"sync/atomic"
"time"
"uberbringer/internal/pkg/escpos"
)
// statusTimeout bounds how long the printer may take to answer one real-time
// status request.
const statusTimeout = 2 * time.Second
// ErrStatusUnsupported is returned by Status when the printer accepts the
// 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.
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
// context cancellation, unlike a mutex.
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, 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")
}
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.
func (c *Client) Addr() string {
return c.addr
}
// Send writes data to the printer in one connection. Once the connection
// is open, and before the first byte is written, it calls beforeWrite, if
// not nil; an error from it closes the connection with nothing written and
// is returned. The write deadline starts after beforeWrite returns, so a
// 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 {
return err
}
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
}
}
writeDeadline, _ := c.deadline(ctx, c.writeTimeout)
if err := conn.SetWriteDeadline(writeDeadline); err != nil {
return fmt.Errorf("setting printer write deadline: %w", err)
}
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, 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)
if err != nil {
return status, err
}
defer release()
l := &line{conn: conn}
for _, kind := range escpos.StatusKinds() {
deadline, fromContext := c.deadline(ctx, statusTimeout)
if err := conn.SetDeadline(deadline); err != nil {
return status, fmt.Errorf("setting printer deadline: %w", err)
}
if _, err := conn.Write(escpos.StatusRequest(kind)); err != nil {
return status, fmt.Errorf("requesting printer status: %w", err)
}
resp, err := l.realTimeAnswer(deadline)
if err != nil {
var netErr net.Error
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); 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) {
select {
case c.slot <- struct{}{}:
case <-ctx.Done():
return nil, nil, fmt.Errorf("waiting for printer %s: %w", c.addr, ctx.Err())
}
conn, err := c.dialer.DialContext(ctx, "tcp", c.addr)
if err != nil {
<-c.slot
return nil, nil, fmt.Errorf("connecting to printer %s: %w", c.addr, err)
}
release := func() {
// Close errors after a completed write carry no information the
// caller can act on: the data has already been handed to the OS.
_ = conn.Close()
<-c.slot
}
return conn, release, nil
}
// deadline returns now+d, or the context deadline if that is sooner, and
// whether the context deadline was the one chosen.
func (c *Client) deadline(ctx context.Context, d time.Duration) (time.Time, bool) {
deadline := time.Now().Add(d)
if ctxDeadline, ok := ctx.Deadline(); ok && ctxDeadline.Before(deadline) {
return ctxDeadline, true
}
return deadline, false
}