diff --git a/README.md b/README.md index 0cc1802..e3cc1d3 100644 --- a/README.md +++ b/README.md @@ -82,7 +82,7 @@ curl -X POST https://printer.example.com/api/v1/print \ -H "Content-Type: application/json" \ -d '{ "elements": [ - {"type": "text", "text": "▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓"}, + {"type": "text", "text": "▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓"}, {"type": "text", "text": "┌─────────────────────┐\n│ !!! ACHTUNG !!! │\n└─────────────────────┘", "align": "center"}, {"type": "text", "text": "Überbringer", "size": 2, "bold": true, "align": "center"}, {"type": "feed"}, @@ -136,6 +136,21 @@ curl -H "Authorization: Bearer $TOKEN" https://printer.example.com/api/v1/jobs/j A printer that accepts connections but does not answer status requests is reported as `"status": "unknown"` with HTTP `200`. +Details: + +- **Brief problems are re-checked.** A printer that looks not ready is read + again 750 ms later, and only a problem that is still there gives `503`. + While cutting or feeding, a printer can report a problem for a moment. +- **Timeouts.** The printer accepts one connection at a time. While it is still + taking in a large job, the 3-second health check can run out of time. That + gives `503` with printer status `"timeout"`, because the printer's state is + unknown. +- **The cover flag** is only reported while the printer is offline. Epson + printers always go offline when the cover opens. +- **Paper low on the TM-T88VII.** That model does not report paper near-end + through real-time status, so `"near_end"` never appears for it; paper out + is still reported. + ### Errors Errors are JSON: `{"error": "message", "details": ["..."]}`. @@ -169,7 +184,7 @@ element is already a `cut`. | `bold` | `false` | | | `underline` | `0` | 0, 1 (thin) or 2 (thick) | | `invert` | `false` | white on black | -| `font` | `a` | `a` (48 columns on 80 mm) or `b` (64 columns, smaller) | +| `font` | `a` | `a`, or `b` (smaller: 56 instead of 42 columns on a TM-T88) | | `align` | `left` | `left`, `center`, `right` | | `newline` | `true` | `false` keeps the next element on the same line | | `wrap` | `true` | `false` sends the text as-is and lets the printer wrap | @@ -179,7 +194,7 @@ default. Characters the code page lacks, such as emoji, print as `?`. Control characters are removed so text can never be read as printer commands. **Word wrap.** The line width comes from the printer model and the character -size: 48 characters at size 1, 24 at size 2, and so on. Lines break at spaces, +size: on a TM-T88, 42 characters at size 1, 21 at size 2, and so on. Lines break at spaces, and only a word longer than a whole line (a long URL, say) is split. The renderer tracks the position across `"newline": false` elements, so mixed sizes on one line still wrap correctly. @@ -216,7 +231,7 @@ sizes on one line still wrap correctly. |----------|---------|--------| | `url` | | `http`/`https` URL, or use `base64` | | `base64` | | Image data, or a `data:image/png;base64,...` URI | -| `width` | natural | Target width in dots, up to the paper width (576 on 80 mm) | +| `width` | natural | Target width in dots, up to the model's print width (512 on a TM-T88) | | `align` | `left` | | PNG, JPEG, GIF and WebP are supported. Images wider than the paper are scaled @@ -269,9 +284,22 @@ errors, so a typo can't silently fall back to a default. Settings worth knowing: -- `printer.model`: `tm-t20` (default), `tm-t88`, `generic-80mm` or - `generic-58mm`. It sets the paper width and characters per line. - `paper_width` and `columns` override it. +- `printer.model` sets the print width and characters per line: + + | Model | Printers | Width | Font A / B columns | + |-------|----------|-------|--------------------| + | `tm-t88` (default) | TM-T88IV, V, VI, VII | 512 dots (180 dpi) | 42 / 56 | + | `tm-m50` | TM-m50, TM-m50II | 512 dots (180 dpi) | 42 / 56 | + | `tm-t20` | TM-T20, II, III | 576 dots (203 dpi) | 48 / 64 | + | `generic-80mm` | other 80 mm, 203 dpi | 576 dots | 48 / 64 | + | `generic-58mm` | 58 mm paper, 203 dpi | 384 dots | 32 / 42 | + + For 58 mm paper on a 180-dpi printer (TM-T88VII, TM-m50II), use a + `tm-t88` or `tm-m50` model with `paper_width = 360` (30 Font A columns). + + If words break at the right edge (for example `seve` on one line and `ral` + on the next), the model is wider than the printer. `paper_width` (dots) and + `columns` (Font A characters per line) override the model. - `printer.codepage`: `cp437` (default), `cp850`, `cp858` (has €) or `cp1252`. - `webserver.trusted_proxies` / `proxy_header`: the real client IP for diff --git a/configs/config.example.toml b/configs/config.example.toml index 04b714e..1fc74d3 100644 --- a/configs/config.example.toml +++ b/configs/config.example.toml @@ -32,15 +32,21 @@ address = "" # printer IP or hostname, e.g. "192.168.1.245" port = 9100 - # tm-t20 (TM-T20/II/III), tm-t88 (TM-T88IV-VII), generic-80mm, generic-58mm - model = "tm-t20" + # Sets the print width and characters per line: + # tm-t88 TM-T88IV/V/VI/VII 512 dots, 42 columns (180 dpi) + # tm-m50 TM-m50/II 512 dots, 42 columns (180 dpi) + # tm-t20 TM-T20/II/III 576 dots, 48 columns (203 dpi) + # generic-80mm 576 dots, 48 columns + # generic-58mm 384 dots, 32 columns + # If words break at the right edge, the model is wider than the printer. + model = "tm-t88" # Character table that text is transcoded to: cp437 (Epson default, # box-drawing and shading), cp850, cp858 (adds €) or cp1252. codepage = "cp437" - # paper_width = 576 # printable dots; overrides the model - # columns = 48 # Font A characters per line for word wrap + # paper_width = 512 # printable dots; overrides the model + # columns = 42 # Font A characters per line for word wrap dial_timeout = "5s" write_timeout = "30s" diff --git a/internal/app/uberbringer/server/handlers.go b/internal/app/uberbringer/server/handlers.go index 1eddaa3..674858e 100644 --- a/internal/app/uberbringer/server/handlers.go +++ b/internal/app/uberbringer/server/handlers.go @@ -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 +} diff --git a/internal/app/uberbringer/server/server.go b/internal/app/uberbringer/server/server.go index b6e08d7..a87d7bb 100644 --- a/internal/app/uberbringer/server/server.go +++ b/internal/app/uberbringer/server/server.go @@ -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{ diff --git a/internal/app/uberbringer/server/server_test.go b/internal/app/uberbringer/server/server_test.go index b405acd..531df0b 100644 --- a/internal/app/uberbringer/server/server_test.go +++ b/internal/app/uberbringer/server/server_test.go @@ -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)) diff --git a/internal/pkg/config/config.go b/internal/pkg/config/config.go index 09a0509..4a7954c 100644 --- a/internal/pkg/config/config.go +++ b/internal/pkg/config/config.go @@ -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, diff --git a/internal/pkg/config/config_test.go b/internal/pkg/config/config_test.go index d1e2ff6..66fd42c 100644 --- a/internal/pkg/config/config_test.go +++ b/internal/pkg/config/config_test.go @@ -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 { diff --git a/internal/pkg/escpos/escpos_test.go b/internal/pkg/escpos/escpos_test.go index 9c49740..bb385db 100644 --- a/internal/pkg/escpos/escpos_test.go +++ b/internal/pkg/escpos/escpos_test.go @@ -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 { diff --git a/internal/pkg/escpos/profile.go b/internal/pkg/escpos/profile.go index fa9c496..bec785e 100644 --- a/internal/pkg/escpos/profile.go +++ b/internal/pkg/escpos/profile.go @@ -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) } diff --git a/internal/pkg/escpos/status.go b/internal/pkg/escpos/status.go index c091261..f33b76b 100644 --- a/internal/pkg/escpos/status.go +++ b/internal/pkg/escpos/status.go @@ -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) } diff --git a/internal/pkg/printer/printer.go b/internal/pkg/printer/printer.go index ec897e5..9e906c6 100644 --- a/internal/pkg/printer/printer.go +++ b/internal/pkg/printer/printer.go @@ -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 } diff --git a/internal/pkg/printer/printer_test.go b/internal/pkg/printer/printer_test.go index a7e0b75..fded0bb 100644 --- a/internal/pkg/printer/printer_test.go +++ b/internal/pkg/printer/printer_test.go @@ -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) + } +}