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

+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)
}
}