Fix /healthz false alarms; default to 512-dot TM-T88 profile
CI / Lint, test and scan (push) Successful in 1m42s

Hardware testing on the real printer (an Epson TM-T88IV, not a TM-T20II)
turned up two problems, and an adversarial review found three more.

Printer status
- Treat DLE EOT 2 bits (cover open, paper-end stop) as offline causes:
  Status.Normalized clears them while DLE EOT 1 reports the printer
  online. The TM-T88IV reported online + cover open while printing and
  cutting a long receipt, which made /healthz return 503.
- PaperOut now comes only from the DLE EOT 4 roll-paper sensor; the
  paper-end stop is reported separately as PaperEndStop.
- /healthz re-reads a printer that looks not ready after 750 ms and only
  reports a problem that is still there.
- A status read cut short by the caller's deadline now returns
  context.DeadlineExceeded (503 "timeout") instead of
  ErrStatusUnsupported, which /healthz reported as 200 "unknown" and
  could hide an offline printer.

Printer profiles
- Default model is now tm-t88 (512 dots, 42/56 columns). A profile wider
  than the printer makes it break words mid-line; a narrower one only
  shortens lines.
- Add tm-m50 (TM-m50/II) and document TM-T88IV-VII, 58 mm paper on
  180-dpi printers, and that the TM-T88VII does not report paper near-end
  through real-time status.
- README example banner shortened to 42 characters to fit the default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-29 21:51:12 -06:00
1 parent 6502d9551d
commit afcf96431f
12 files changed
+328 -69

No files matched your search

+43 -6
View File
@@ -12,6 +12,7 @@ import (
"github.com/gofiber/fiber/v3"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printer"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
@@ -139,7 +140,8 @@ func (s *Server) handleJob(c fiber.Ctx) error {
// printerHealth is the printer part of the /healthz response.
type printerHealth struct {
Reachable bool `json:"reachable"`
// Reachable is omitted when it is unknown, e.g. after a timeout.
Reachable *bool `json:"reachable,omitempty"`
Status string `json:"status"`
Online *bool `json:"online,omitempty"`
CoverOpen *bool `json:"cover_open,omitempty"`
@@ -165,26 +167,34 @@ func (s *Server) handleHealth(c fiber.Ctx) error {
resp.Queue.Pending = s.jobs.Pending()
httpStatus := fiber.StatusOK
st, err := s.printer.Status(ctx)
st, err := s.settledPrinterStatus(ctx)
switch {
case errors.Is(err, printer.ErrStatusUnsupported):
resp.Status = "ok"
resp.Printer = printerHealth{Reachable: true, Status: "unknown"}
resp.Printer = printerHealth{Reachable: boolPtr(true), Status: "unknown"}
case errors.Is(err, context.DeadlineExceeded):
// The printer did not answer within healthTimeout, typically because
// it is still taking in a large job. Its state is unknown, so do not
// claim it is healthy.
s.logger.Warn("printer health check timed out", "err", err)
resp.Status = "unavailable"
resp.Printer = printerHealth{Status: "timeout"}
httpStatus = fiber.StatusServiceUnavailable
case err != nil:
s.logger.Warn("printer health check failed", "err", err)
resp.Status = "unavailable"
resp.Printer = printerHealth{Reachable: false, Status: "unreachable"}
resp.Printer = printerHealth{Reachable: boolPtr(false), Status: "unreachable"}
httpStatus = fiber.StatusServiceUnavailable
default:
paper := "ok"
switch {
case st.PaperOut:
case st.PaperOut || st.PaperEndStop:
paper = "out"
case st.PaperNearEnd:
paper = "near_end"
}
resp.Printer = printerHealth{
Reachable: true,
Reachable: boolPtr(true),
Status: "ready",
Online: &st.Online,
CoverOpen: &st.CoverOpen,
@@ -202,3 +212,30 @@ func (s *Server) handleHealth(c fiber.Ctx) error {
}
return c.Status(httpStatus).JSON(resp)
}
func boolPtr(b bool) *bool { return &b }
// settledPrinterStatus reads the printer status and, if the printer looks not
// ready, reads it once more after HealthRecheckDelay. A printer that is busy
// feeding or cutting can report a problem for a moment; only one that is
// still there on the second reading is reported, so monitors do not see an
// outage every time a long receipt prints.
func (s *Server) settledPrinterStatus(ctx context.Context) (escpos.Status, error) {
st, err := s.printer.Status(ctx)
if err != nil || st.Ready() {
return st, err
}
timer := time.NewTimer(s.config.HealthRecheckDelay)
defer timer.Stop()
select {
case <-timer.C:
case <-ctx.Done():
return st, nil // no time left to re-check; report what was seen
}
again, err := s.printer.Status(ctx)
if err != nil {
// The second reading failed; the first one is still a real answer.
return st, nil
}
return again, nil
}
+11
View File
@@ -66,8 +66,16 @@ type Config struct {
// RequestID generates request IDs.
RequestID func() string
// HealthRecheckDelay is how long /healthz waits before re-reading a
// printer that looked not ready. Zero means defaultHealthRecheckDelay.
HealthRecheckDelay time.Duration
}
// defaultHealthRecheckDelay is long enough for a cut or paper feed to finish
// and short enough to stay well inside healthTimeout.
const defaultHealthRecheckDelay = 750 * time.Millisecond
// Server is the HTTP API.
type Server struct {
app *fiber.App
@@ -87,6 +95,9 @@ func New(config Config, jobs Jobs, printer Printer, logger *slog.Logger) *Server
case config.RequestID == nil:
panic("server.New: RequestID must not be nil")
}
if config.HealthRecheckDelay <= 0 {
config.HealthRecheckDelay = defaultHealthRecheckDelay
}
s := &Server{config: config, jobs: jobs, printer: printer, logger: logger}
s.app = fiber.New(fiber.Config{
+52 -22
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
@@ -55,12 +56,29 @@ func (f *fakeJobs) Status(id printqueue.JobID) (printqueue.Status, error) {
func (f *fakeJobs) Pending() int { return 0 }
// fakePrinter returns statuses in order, repeating the last one, or err.
type fakePrinter struct {
status escpos.Status
err error
mu sync.Mutex
statuses []escpos.Status
err error
calls int
}
func (f fakePrinter) Status(context.Context) (escpos.Status, error) { return f.status, f.err }
func (f *fakePrinter) Status(context.Context) (escpos.Status, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.calls++
if f.err != nil || len(f.statuses) == 0 {
return escpos.Status{}, f.err
}
return f.statuses[min(f.calls, len(f.statuses))-1], nil
}
func (f *fakePrinter) Calls() int {
f.mu.Lock()
defer f.mu.Unlock()
return f.calls
}
func newJobID(t *testing.T) printqueue.JobID {
t.Helper()
@@ -88,6 +106,8 @@ func newTestServer(t *testing.T, jobs *fakeJobs, p Printer) *Server {
WriteTimeout: time.Second,
IdleTimeout: time.Second,
RequestID: func() string { return "req_test" },
HealthRecheckDelay: time.Millisecond,
}, jobs, p, slog.New(slog.NewTextHandler(io.Discard, nil)))
}
@@ -152,7 +172,7 @@ func TestPrintAuth(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, fakePrinter{})
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
resp, body := do(t, s, printRequest(t, validJob, tt.auth))
if resp.StatusCode != tt.want {
t.Fatalf("status = %d, want %d (%v)", resp.StatusCode, tt.want, body)
@@ -165,7 +185,7 @@ func TestPrintAuth(t *testing.T) {
}
func TestPrintQueryTokenIsNotAccepted(t *testing.T) {
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, fakePrinter{})
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
req := httptest.NewRequest(http.MethodPost, "/api/v1/print?token="+validToken(t), strings.NewReader(validJob))
if resp, _ := do(t, s, req); resp.StatusCode != http.StatusUnauthorized {
t.Errorf("status = %d, want 401", resp.StatusCode)
@@ -174,7 +194,7 @@ func TestPrintQueryTokenIsNotAccepted(t *testing.T) {
func TestPrintAccepted(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t)}
s := newTestServer(t, jobs, fakePrinter{})
s := newTestServer(t, jobs, &fakePrinter{})
resp, body := do(t, s, printRequest(t, validJob, "Bearer "+validToken(t)))
if resp.StatusCode != http.StatusAccepted {
t.Fatalf("status = %d (%v)", resp.StatusCode, body)
@@ -203,7 +223,7 @@ func TestPrintBadRequests(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t)}
s := newTestServer(t, jobs, fakePrinter{})
s := newTestServer(t, jobs, &fakePrinter{})
resp, body := do(t, s, printRequest(t, tt.body, "Bearer "+validToken(t)))
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("status = %d, want 400 (%v)", resp.StatusCode, body)
@@ -219,7 +239,7 @@ func TestPrintBadRequests(t *testing.T) {
}
func TestPrintValidationDetails(t *testing.T) {
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, fakePrinter{})
s := newTestServer(t, &fakeJobs{nextID: newJobID(t)}, &fakePrinter{})
_, body := do(t, s, printRequest(t, `{"elements":[{"type":"text","size":12},{"type":"qr"}]}`, "Bearer "+validToken(t)))
details, _ := body["details"].([]any)
if len(details) != 2 {
@@ -228,7 +248,7 @@ func TestPrintValidationDetails(t *testing.T) {
}
func TestPrintQueueFull(t *testing.T) {
s := newTestServer(t, &fakeJobs{submitErr: printqueue.ErrQueueFull}, fakePrinter{})
s := newTestServer(t, &fakeJobs{submitErr: printqueue.ErrQueueFull}, &fakePrinter{})
resp, _ := do(t, s, printRequest(t, validJob, "Bearer "+validToken(t)))
if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") == "" {
t.Errorf("status = %d, Retry-After = %q", resp.StatusCode, resp.Header.Get("Retry-After"))
@@ -240,7 +260,7 @@ func TestJobStatus(t *testing.T) {
jobs := &fakeJobs{statuses: map[printqueue.JobID]printqueue.Status{
id: {ID: id, State: printqueue.StateDone, Attempts: 1},
}}
s := newTestServer(t, jobs, fakePrinter{})
s := newTestServer(t, jobs, &fakePrinter{})
auth := "Bearer " + validToken(t)
tests := []struct {
@@ -270,27 +290,37 @@ func TestJobStatus(t *testing.T) {
}
func TestHealth(t *testing.T) {
ready := escpos.Status{Online: true}
coverOpen := escpos.Status{CoverOpen: true}
tests := []struct {
name string
printer fakePrinter
printer *fakePrinter
want int
wantStatus string
wantPrinter string
wantPaper string
wantReachable bool
wantReachable any // nil when the field must be absent
wantCalls int
}{
{"ready", fakePrinter{status: escpos.Status{Online: true}}, 200, "ok", "ready", "ok", true},
{"paper low still ok", fakePrinter{status: escpos.Status{Online: true, PaperNearEnd: true}}, 200, "ok", "ready", "near_end", true},
{"paper out", fakePrinter{status: escpos.Status{PaperOut: true}}, 503, "degraded", "not_ready", "out", true},
{"no status support", fakePrinter{err: printer.ErrStatusUnsupported}, 200, "ok", "unknown", "", true},
{"unreachable", fakePrinter{err: errors.New("dial tcp: timeout")}, 503, "unavailable", "unreachable", "", false},
{"ready", &fakePrinter{statuses: []escpos.Status{ready}}, 200, "ok", "ready", "ok", true, 1},
{"paper low still ok", &fakePrinter{statuses: []escpos.Status{{Online: true, PaperNearEnd: true}}}, 200, "ok", "ready", "near_end", true, 1},
{"paper out", &fakePrinter{statuses: []escpos.Status{{PaperOut: true}}}, 503, "degraded", "not_ready", "out", true, 2},
{"paper end stop", &fakePrinter{statuses: []escpos.Status{{PaperEndStop: true}}}, 503, "degraded", "not_ready", "out", true, 2},
{"cover open on both readings", &fakePrinter{statuses: []escpos.Status{coverOpen}}, 503, "degraded", "not_ready", "ok", true, 2},
{"brief problem while printing", &fakePrinter{statuses: []escpos.Status{coverOpen, ready}}, 200, "ok", "ready", "ok", true, 2},
{"no status support", &fakePrinter{err: printer.ErrStatusUnsupported}, 200, "ok", "unknown", "", true, 1},
{"unreachable", &fakePrinter{err: errors.New("connection refused")}, 503, "unavailable", "unreachable", "", false, 1},
{"status timed out", &fakePrinter{err: fmt.Errorf("reading printer status: %w", context.DeadlineExceeded)}, 503, "unavailable", "timeout", "", nil, 1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := newTestServer(t, &fakeJobs{}, tt.printer)
resp, body := do(t, s, httptest.NewRequest(http.MethodGet, "/healthz", nil))
if resp.StatusCode != tt.want {
t.Fatalf("status = %d, want %d", resp.StatusCode, tt.want)
t.Fatalf("status = %d, want %d (%v)", resp.StatusCode, tt.want, body)
}
if got := tt.printer.Calls(); got != tt.wantCalls {
t.Errorf("printer queried %d times, want %d", got, tt.wantCalls)
}
p, _ := body["printer"].(map[string]any)
if body["status"] != tt.wantStatus || p["status"] != tt.wantPrinter || p["reachable"] != tt.wantReachable {
@@ -299,15 +329,15 @@ func TestHealth(t *testing.T) {
if paper, _ := p["paper"].(string); paper != tt.wantPaper {
t.Errorf("paper = %q, want %q", paper, tt.wantPaper)
}
if _, leaked := p["error"].(string); leaked && !tt.wantReachable {
t.Error("unreachable printer error text must not be exposed publicly")
if _, leaked := p["error"].(string); leaked && tt.wantReachable != true {
t.Error("connection error text must not be exposed publicly")
}
})
}
}
func TestIndexAndRobotsAndNotFound(t *testing.T) {
s := newTestServer(t, &fakeJobs{}, fakePrinter{})
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
resp, body := do(t, s, httptest.NewRequest(http.MethodGet, "/", nil))
if resp.StatusCode != 200 || body["Project"] != "Überbringer" || body["Version"] != "test" {
t.Errorf("index = %d %v", resp.StatusCode, body)
@@ -335,7 +365,7 @@ func TestRateLimitPerClientBehindProxy(t *testing.T) {
WriteTimeout: time.Second,
IdleTimeout: time.Second,
RequestID: func() string { return "req_test" },
}, jobs, fakePrinter{}, slog.New(slog.NewTextHandler(io.Discard, nil)))
}, jobs, &fakePrinter{}, slog.New(slog.NewTextHandler(io.Discard, nil)))
send := func(clientIP string) int {
req := printRequest(t, validJob, "Bearer "+validToken(t))
+6 -3
View File
@@ -69,7 +69,7 @@ type PrinterConfig struct {
Address string `toml:"address"`
Port int `toml:"port"`
// Model selects a printer profile, e.g. "tm-t20" or "generic-58mm".
// Model selects a printer profile, e.g. "tm-t88" or "generic-58mm".
Model string `toml:"model"`
// CodePage is the character table text is transcoded to, e.g. "cp437".
@@ -152,8 +152,11 @@ func Default() Config {
IdleTimeout: 60 * time.Second,
},
Printer: PrinterConfig{
Port: 9100,
Model: "tm-t20",
Port: 9100,
// The narrower 512-dot profile is the safe default: on a wider
// printer lines are just shorter, while a profile wider than the
// printer makes it break words at the right edge.
Model: "tm-t88",
CodePage: "cp437",
DialTimeout: 5 * time.Second,
WriteTimeout: 30 * time.Second,
+1 -1
View File
@@ -39,7 +39,7 @@ func TestLoadLegacyConfigGetsDefaults(t *testing.T) {
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Printer.Port != 9100 || cfg.Printer.Model != "tm-t20" || cfg.Printer.CodePage != "cp437" {
if cfg.Printer.Port != 9100 || cfg.Printer.Model != "tm-t88" || cfg.Printer.CodePage != "cp437" {
t.Errorf("printer defaults not applied: %+v", cfg.Printer)
}
if cfg.WebServer.RateWindow != time.Minute || cfg.Queue.Size != 100 {
+48 -1
View File
@@ -361,7 +361,14 @@ func TestStatusApply(t *testing.T) {
{
name: "paper out",
resps: map[escpos.StatusKind]byte{1: 0x1A, 2: 0x32, 3: 0x12, 4: 0x72},
want: escpos.Status{PaperOut: true},
want: escpos.Status{PaperEndStop: true, PaperOut: true},
},
{
// The reading a TM-T88IV gave mid-print: online, yet DLE EOT 2
// claims the cover is open. Apply keeps the raw bits.
name: "online with stale cover bit",
resps: map[escpos.StatusKind]byte{1: 0x12, 2: 0x16, 3: 0x12, 4: 0x12},
want: escpos.Status{Online: true, CoverOpen: true},
},
{
name: "cutter error",
@@ -387,6 +394,43 @@ func TestStatusApply(t *testing.T) {
}
}
func TestStatusNormalized(t *testing.T) {
tests := []struct {
name string
in escpos.Status
want escpos.Status
ready bool
}{
{
name: "online clears stale offline causes",
in: escpos.Status{Online: true, CoverOpen: true, PaperEndStop: true},
want: escpos.Status{Online: true},
ready: true,
},
{
name: "offline keeps the cover open cause",
in: escpos.Status{CoverOpen: true},
want: escpos.Status{CoverOpen: true},
},
{
name: "online keeps sensor and error bits",
in: escpos.Status{Online: true, PaperOut: true, CutterError: true},
want: escpos.Status{Online: true, PaperOut: true, CutterError: true},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := tt.in.Normalized()
if got != tt.want {
t.Errorf("Normalized() = %+v, want %+v", got, tt.want)
}
if got.Ready() != tt.ready {
t.Errorf("Ready() = %v, want %v", got.Ready(), tt.ready)
}
})
}
}
func TestStatusApplyRejectsGarbage(t *testing.T) {
var s escpos.Status
if err := s.Apply(escpos.StatusPrinter, 'H'); !errors.Is(err, escpos.ErrInvalidArgument) {
@@ -408,6 +452,9 @@ func TestLookupProfile(t *testing.T) {
}{
{"tm-t20ii", "tm-t20", 48, 64},
{"TM-T88V", "tm-t88", 42, 56},
{"tm-t88iv", "tm-t88", 42, 56},
{"tm-t88vii", "tm-t88", 42, 56},
{"tm-m50ii", "tm-m50", 42, 56},
{"generic-58mm", "generic-58mm", 32, 42},
}
for _, tt := range tests {
+10 -6
View File
@@ -19,23 +19,27 @@ type Profile struct {
FontBWidth int
}
// LookupProfile returns the profile for a model name such as "tm-t20". Common
// model variants (e.g. "tm-t20ii") resolve to their family.
// LookupProfile returns the profile for a model name such as "tm-t88". Common
// model variants (e.g. "tm-t88vii") resolve to their family.
func LookupProfile(model string) (Profile, error) {
switch strings.ToLower(strings.TrimSpace(model)) {
case "tm-t20", "tm-t20ii", "tm-t20iii", "tm-t20iv":
// 80 mm paper at 203 dpi: 48 columns of Font A, 64 of Font B.
return Profile{Name: "tm-t20", DotsPerLine: 576, FontAWidth: 12, FontBWidth: 9}, nil
case "tm-t88", "tm-t88iv", "tm-t88v", "tm-t88vi", "tm-t88vii":
// 80 mm paper at 180 dpi: 42 columns of Font A, 56 of Font B.
return Profile{Name: "tm-t88", DotsPerLine: 512, FontAWidth: 12, FontBWidth: 9}, nil
case "tm-m50", "tm-m50ii":
// 80 mm paper at 180 dpi: 42 columns of Font A, 56 of Font B.
return Profile{Name: "tm-m50", DotsPerLine: 512, FontAWidth: 12, FontBWidth: 9}, nil
case "tm-t20", "tm-t20ii", "tm-t20iii", "tm-t20iv":
// 80 mm paper at 203 dpi: 48 columns of Font A, 64 of Font B.
return Profile{Name: "tm-t20", DotsPerLine: 576, FontAWidth: 12, FontBWidth: 9}, nil
case "generic-80mm":
return Profile{Name: "generic-80mm", DotsPerLine: 576, FontAWidth: 12, FontBWidth: 9}, nil
case "generic-58mm":
// 58 mm paper at 203 dpi: 32 columns of Font A.
return Profile{Name: "generic-58mm", DotsPerLine: 384, FontAWidth: 12, FontBWidth: 9}, nil
}
return Profile{}, fmt.Errorf("%w: unknown printer model %q (want tm-t20, tm-t88, generic-80mm or generic-58mm)",
return Profile{}, fmt.Errorf(
"%w: unknown printer model %q (want tm-t88, tm-m50, tm-t20, generic-80mm or generic-58mm)",
ErrInvalidArgument, model)
}
+31 -7
View File
@@ -20,10 +20,20 @@ func StatusKinds() []StatusKind {
// Status is the printer state decoded from DLE EOT responses.
type Status struct {
Online bool
CoverOpen bool
PaperNearEnd bool
PaperOut bool
Online bool
// CoverOpen and PaperEndStop come from DLE EOT 2, which reports why the
// printer is offline. They only mean something while Online is false;
// see Normalized.
CoverOpen bool
PaperEndStop bool
// PaperNearEnd and PaperOut come from the roll paper sensors (DLE EOT 4).
// The TM-T88VII does not support the near-end bits, so PaperNearEnd is
// always false on that model.
PaperNearEnd bool
PaperOut bool
CutterError bool
Unrecoverable bool
// AutoRecoverable reports an error the printer clears by itself, such as
@@ -33,7 +43,21 @@ type Status struct {
// Ready reports whether the printer can print right now.
func (s Status) Ready() bool {
return s.Online && !s.CoverOpen && !s.PaperOut && !s.CutterError && !s.Unrecoverable && !s.AutoRecoverable
return s.Online && !s.CoverOpen && !s.PaperEndStop && !s.PaperOut &&
!s.CutterError && !s.Unrecoverable && !s.AutoRecoverable
}
// Normalized returns s with the offline causes cleared when the printer
// reports itself online. Epson printers always go offline while the cover is
// open or printing has stopped at the paper end, so an online printer cannot
// have either cause; a TM-T88IV has been seen to report a stale cover-open
// bit while busy printing and cutting a long receipt.
func (s Status) Normalized() Status {
if s.Online {
s.CoverOpen = false
s.PaperEndStop = false
}
return s
}
// StatusRequest returns the real-time DLE EOT n command for kind. Real-time
@@ -60,14 +84,14 @@ func (s *Status) Apply(kind StatusKind, resp byte) error {
s.Online = !bit(3)
case StatusOffline:
s.CoverOpen = bit(2)
s.PaperOut = s.PaperOut || bit(5)
s.PaperEndStop = bit(5)
case StatusError:
s.CutterError = bit(3)
s.Unrecoverable = bit(5)
s.AutoRecoverable = bit(6)
case StatusPaper:
s.PaperNearEnd = bit(2) && bit(3)
s.PaperOut = s.PaperOut || (bit(5) && bit(6))
s.PaperOut = bit(5) && bit(6)
default:
return fmt.Errorf("%w: unknown status kind %d", ErrInvalidArgument, kind)
}
+17 -9
View File
@@ -64,7 +64,8 @@ func (c *Client) Send(ctx context.Context, data []byte) error {
}
defer release()
if err := conn.SetWriteDeadline(c.deadline(ctx, c.writeTimeout)); err != nil {
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 {
@@ -73,8 +74,11 @@ func (c *Client) Send(ctx context.Context, data []byte) error {
return nil
}
// Status queries the printer's real-time status. It returns
// ErrStatusUnsupported when the printer is reachable but does not answer.
// 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.
func (c *Client) Status(ctx context.Context) (escpos.Status, error) {
var status escpos.Status
conn, release, err := c.connect(ctx)
@@ -85,7 +89,7 @@ func (c *Client) Status(ctx context.Context) (escpos.Status, error) {
resp := make([]byte, 1)
for _, kind := range escpos.StatusKinds() {
deadline := c.deadline(ctx, statusTimeout)
deadline, fromContext := c.deadline(ctx, statusTimeout)
if err := conn.SetDeadline(deadline); err != nil {
return status, fmt.Errorf("setting printer deadline: %w", err)
}
@@ -95,6 +99,9 @@ func (c *Client) Status(ctx context.Context) (escpos.Status, error) {
if _, err := conn.Read(resp); 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)
}
return status, ErrStatusUnsupported
}
return status, fmt.Errorf("reading printer status: %w", err)
@@ -103,7 +110,7 @@ func (c *Client) Status(ctx context.Context) (escpos.Status, error) {
return status, ErrStatusUnsupported
}
}
return status, nil
return status.Normalized(), nil
}
// connect waits for the connection slot and dials the printer. The returned
@@ -128,11 +135,12 @@ func (c *Client) connect(ctx context.Context) (net.Conn, func(), error) {
return conn, release, nil
}
// deadline returns now+d, or the context deadline if that is sooner.
func (c *Client) deadline(ctx context.Context, d time.Duration) time.Time {
// 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
return ctxDeadline, true
}
return deadline
return deadline, false
}
+64 -3
View File
@@ -91,6 +91,46 @@ func TestSendRespectsCancelledContextWhileBusy(t *testing.T) {
}
}
// statusPrinter answers DLE EOT requests from answers, keyed by kind.
func statusPrinter(t *testing.T, answers map[byte]byte) string {
t.Helper()
return fakePrinter(t, func(conn net.Conn) {
req := make([]byte, 3)
for {
if _, err := io.ReadFull(conn, req); err != nil {
return
}
if req[0] != 0x10 || req[1] != 0x04 {
return
}
_, _ = conn.Write([]byte{answers[req[2]]})
}
})
}
func TestStatusIgnoresStaleCoverBitWhileOnline(t *testing.T) {
// The exact reading a TM-T88IV gave while printing a long receipt.
addr := statusPrinter(t, map[byte]byte{1: 0x12, 2: 0x16, 3: 0x12, 4: 0x12})
status, err := printer.NewClient(addr, time.Second, time.Second).Status(context.Background())
if err != nil {
t.Fatal(err)
}
if status.CoverOpen || !status.Ready() {
t.Errorf("status = %+v, want ready with the cover reported closed", status)
}
}
func TestStatusReportsCoverOpenWhenOffline(t *testing.T) {
addr := statusPrinter(t, map[byte]byte{1: 0x1A, 2: 0x16, 3: 0x12, 4: 0x12})
status, err := printer.NewClient(addr, time.Second, time.Second).Status(context.Background())
if err != nil {
t.Fatal(err)
}
if !status.CoverOpen || status.Online || status.Ready() {
t.Errorf("status = %+v, want offline with the cover open", status)
}
}
func TestStatus(t *testing.T) {
answers := map[byte]byte{1: 0x12, 2: 0x12, 3: 0x12, 4: 0x1E} // paper near end
addr := fakePrinter(t, func(conn net.Conn) {
@@ -120,9 +160,30 @@ func TestStatusUnsupported(t *testing.T) {
_, _ = io.Copy(io.Discard, conn) // a printer that never answers
})
client := printer.NewClient(addr, time.Second, time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
defer cancel()
if _, err := client.Status(ctx); !errors.Is(err, printer.ErrStatusUnsupported) {
// No context deadline: the client's own status timeout (2s) must expire.
if _, err := client.Status(context.Background()); !errors.Is(err, printer.ErrStatusUnsupported) {
t.Errorf("err = %v, want ErrStatusUnsupported", err)
}
}
func TestStatusContextDeadlineIsNotUnsupported(t *testing.T) {
// A printer that answers, just later than the caller is willing to wait,
// e.g. while it works through a large buffered image.
addr := fakePrinter(t, func(conn net.Conn) {
req := make([]byte, 3)
for {
if _, err := io.ReadFull(conn, req); err != nil {
return
}
time.Sleep(300 * time.Millisecond)
_, _ = conn.Write([]byte{0x1A}) // offline
}
})
client := printer.NewClient(addr, time.Second, time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
_, err := client.Status(ctx)
if !errors.Is(err, context.DeadlineExceeded) || errors.Is(err, printer.ErrStatusUnsupported) {
t.Errorf("err = %v, want context.DeadlineExceeded and not ErrStatusUnsupported", err)
}
}