Fix /healthz false alarms; default to 512-dot TM-T88 profile
CI / Lint, test and scan (push) Successful in 1m42s
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:
1 parent
6502d9551d
commit
afcf96431f
12 files changed
+322
-63
No files matched your search
@@ -82,7 +82,7 @@ curl -X POST https://printer.example.com/api/v1/print \
|
|||||||
-H "Content-Type: application/json" \
|
-H "Content-Type: application/json" \
|
||||||
-d '{
|
-d '{
|
||||||
"elements": [
|
"elements": [
|
||||||
{"type": "text", "text": "▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓"},
|
{"type": "text", "text": "▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓"},
|
||||||
{"type": "text", "text": "┌─────────────────────┐\n│ !!! ACHTUNG !!! │\n└─────────────────────┘", "align": "center"},
|
{"type": "text", "text": "┌─────────────────────┐\n│ !!! ACHTUNG !!! │\n└─────────────────────┘", "align": "center"},
|
||||||
{"type": "text", "text": "Überbringer", "size": 2, "bold": true, "align": "center"},
|
{"type": "text", "text": "Überbringer", "size": 2, "bold": true, "align": "center"},
|
||||||
{"type": "feed"},
|
{"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
|
A printer that accepts connections but does not answer status requests is
|
||||||
reported as `"status": "unknown"` with HTTP `200`.
|
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
|
||||||
|
|
||||||
Errors are JSON: `{"error": "message", "details": ["..."]}`.
|
Errors are JSON: `{"error": "message", "details": ["..."]}`.
|
||||||
@@ -169,7 +184,7 @@ element is already a `cut`.
|
|||||||
| `bold` | `false` | |
|
| `bold` | `false` | |
|
||||||
| `underline` | `0` | 0, 1 (thin) or 2 (thick) |
|
| `underline` | `0` | 0, 1 (thin) or 2 (thick) |
|
||||||
| `invert` | `false` | white on black |
|
| `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` |
|
| `align` | `left` | `left`, `center`, `right` |
|
||||||
| `newline` | `true` | `false` keeps the next element on the same line |
|
| `newline` | `true` | `false` keeps the next element on the same line |
|
||||||
| `wrap` | `true` | `false` sends the text as-is and lets the printer wrap |
|
| `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.
|
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
|
**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
|
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
|
renderer tracks the position across `"newline": false` elements, so mixed
|
||||||
sizes on one line still wrap correctly.
|
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` |
|
| `url` | | `http`/`https` URL, or use `base64` |
|
||||||
| `base64` | | Image data, or a `data:image/png;base64,...` URI |
|
| `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` | |
|
| `align` | `left` | |
|
||||||
|
|
||||||
PNG, JPEG, GIF and WebP are supported. Images wider than the paper are scaled
|
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:
|
Settings worth knowing:
|
||||||
|
|
||||||
- `printer.model`: `tm-t20` (default), `tm-t88`, `generic-80mm` or
|
- `printer.model` sets the print width and characters per line:
|
||||||
`generic-58mm`. It sets the paper width and characters per line.
|
|
||||||
`paper_width` and `columns` override it.
|
| 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
|
- `printer.codepage`: `cp437` (default), `cp850`, `cp858` (has €) or
|
||||||
`cp1252`.
|
`cp1252`.
|
||||||
- `webserver.trusted_proxies` / `proxy_header`: the real client IP for
|
- `webserver.trusted_proxies` / `proxy_header`: the real client IP for
|
||||||
|
|||||||
@@ -32,15 +32,21 @@
|
|||||||
address = "" # printer IP or hostname, e.g. "192.168.1.245"
|
address = "" # printer IP or hostname, e.g. "192.168.1.245"
|
||||||
port = 9100
|
port = 9100
|
||||||
|
|
||||||
# tm-t20 (TM-T20/II/III), tm-t88 (TM-T88IV-VII), generic-80mm, generic-58mm
|
# Sets the print width and characters per line:
|
||||||
model = "tm-t20"
|
# 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,
|
# Character table that text is transcoded to: cp437 (Epson default,
|
||||||
# box-drawing and shading), cp850, cp858 (adds €) or cp1252.
|
# box-drawing and shading), cp850, cp858 (adds €) or cp1252.
|
||||||
codepage = "cp437"
|
codepage = "cp437"
|
||||||
|
|
||||||
# paper_width = 576 # printable dots; overrides the model
|
# paper_width = 512 # printable dots; overrides the model
|
||||||
# columns = 48 # Font A characters per line for word wrap
|
# columns = 42 # Font A characters per line for word wrap
|
||||||
|
|
||||||
dial_timeout = "5s"
|
dial_timeout = "5s"
|
||||||
write_timeout = "30s"
|
write_timeout = "30s"
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
|
|
||||||
"github.com/gofiber/fiber/v3"
|
"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/printer"
|
||||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
|
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/printqueue"
|
||||||
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/receipt"
|
"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.
|
// printerHealth is the printer part of the /healthz response.
|
||||||
type printerHealth struct {
|
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"`
|
Status string `json:"status"`
|
||||||
Online *bool `json:"online,omitempty"`
|
Online *bool `json:"online,omitempty"`
|
||||||
CoverOpen *bool `json:"cover_open,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()
|
resp.Queue.Pending = s.jobs.Pending()
|
||||||
httpStatus := fiber.StatusOK
|
httpStatus := fiber.StatusOK
|
||||||
|
|
||||||
st, err := s.printer.Status(ctx)
|
st, err := s.settledPrinterStatus(ctx)
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, printer.ErrStatusUnsupported):
|
case errors.Is(err, printer.ErrStatusUnsupported):
|
||||||
resp.Status = "ok"
|
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:
|
case err != nil:
|
||||||
s.logger.Warn("printer health check failed", "err", err)
|
s.logger.Warn("printer health check failed", "err", err)
|
||||||
resp.Status = "unavailable"
|
resp.Status = "unavailable"
|
||||||
resp.Printer = printerHealth{Reachable: false, Status: "unreachable"}
|
resp.Printer = printerHealth{Reachable: boolPtr(false), Status: "unreachable"}
|
||||||
httpStatus = fiber.StatusServiceUnavailable
|
httpStatus = fiber.StatusServiceUnavailable
|
||||||
default:
|
default:
|
||||||
paper := "ok"
|
paper := "ok"
|
||||||
switch {
|
switch {
|
||||||
case st.PaperOut:
|
case st.PaperOut || st.PaperEndStop:
|
||||||
paper = "out"
|
paper = "out"
|
||||||
case st.PaperNearEnd:
|
case st.PaperNearEnd:
|
||||||
paper = "near_end"
|
paper = "near_end"
|
||||||
}
|
}
|
||||||
resp.Printer = printerHealth{
|
resp.Printer = printerHealth{
|
||||||
Reachable: true,
|
Reachable: boolPtr(true),
|
||||||
Status: "ready",
|
Status: "ready",
|
||||||
Online: &st.Online,
|
Online: &st.Online,
|
||||||
CoverOpen: &st.CoverOpen,
|
CoverOpen: &st.CoverOpen,
|
||||||
@@ -202,3 +212,30 @@ func (s *Server) handleHealth(c fiber.Ctx) error {
|
|||||||
}
|
}
|
||||||
return c.Status(httpStatus).JSON(resp)
|
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
|
||||||
|
}
|
||||||
@@ -66,8 +66,16 @@ type Config struct {
|
|||||||
|
|
||||||
// RequestID generates request IDs.
|
// RequestID generates request IDs.
|
||||||
RequestID func() string
|
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.
|
// Server is the HTTP API.
|
||||||
type Server struct {
|
type Server struct {
|
||||||
app *fiber.App
|
app *fiber.App
|
||||||
@@ -87,6 +95,9 @@ func New(config Config, jobs Jobs, printer Printer, logger *slog.Logger) *Server
|
|||||||
case config.RequestID == nil:
|
case config.RequestID == nil:
|
||||||
panic("server.New: RequestID must not be 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 := &Server{config: config, jobs: jobs, printer: printer, logger: logger}
|
||||||
|
|
||||||
s.app = fiber.New(fiber.Config{
|
s.app = fiber.New(fiber.Config{
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -55,12 +56,29 @@ func (f *fakeJobs) Status(id printqueue.JobID) (printqueue.Status, error) {
|
|||||||
|
|
||||||
func (f *fakeJobs) Pending() int { return 0 }
|
func (f *fakeJobs) Pending() int { return 0 }
|
||||||
|
|
||||||
|
// fakePrinter returns statuses in order, repeating the last one, or err.
|
||||||
type fakePrinter struct {
|
type fakePrinter struct {
|
||||||
status escpos.Status
|
mu sync.Mutex
|
||||||
|
statuses []escpos.Status
|
||||||
err error
|
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 {
|
func newJobID(t *testing.T) printqueue.JobID {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
@@ -88,6 +106,8 @@ func newTestServer(t *testing.T, jobs *fakeJobs, p Printer) *Server {
|
|||||||
WriteTimeout: time.Second,
|
WriteTimeout: time.Second,
|
||||||
IdleTimeout: time.Second,
|
IdleTimeout: time.Second,
|
||||||
RequestID: func() string { return "req_test" },
|
RequestID: func() string { return "req_test" },
|
||||||
|
|
||||||
|
HealthRecheckDelay: time.Millisecond,
|
||||||
}, jobs, p, slog.New(slog.NewTextHandler(io.Discard, nil)))
|
}, jobs, p, slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,7 +172,7 @@ func TestPrintAuth(t *testing.T) {
|
|||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
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))
|
resp, body := do(t, s, printRequest(t, validJob, tt.auth))
|
||||||
if resp.StatusCode != tt.want {
|
if resp.StatusCode != tt.want {
|
||||||
t.Fatalf("status = %d, want %d (%v)", resp.StatusCode, tt.want, body)
|
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) {
|
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))
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/print?token="+validToken(t), strings.NewReader(validJob))
|
||||||
if resp, _ := do(t, s, req); resp.StatusCode != http.StatusUnauthorized {
|
if resp, _ := do(t, s, req); resp.StatusCode != http.StatusUnauthorized {
|
||||||
t.Errorf("status = %d, want 401", resp.StatusCode)
|
t.Errorf("status = %d, want 401", resp.StatusCode)
|
||||||
@@ -174,7 +194,7 @@ func TestPrintQueryTokenIsNotAccepted(t *testing.T) {
|
|||||||
|
|
||||||
func TestPrintAccepted(t *testing.T) {
|
func TestPrintAccepted(t *testing.T) {
|
||||||
jobs := &fakeJobs{nextID: newJobID(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)))
|
resp, body := do(t, s, printRequest(t, validJob, "Bearer "+validToken(t)))
|
||||||
if resp.StatusCode != http.StatusAccepted {
|
if resp.StatusCode != http.StatusAccepted {
|
||||||
t.Fatalf("status = %d (%v)", resp.StatusCode, body)
|
t.Fatalf("status = %d (%v)", resp.StatusCode, body)
|
||||||
@@ -203,7 +223,7 @@ func TestPrintBadRequests(t *testing.T) {
|
|||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
jobs := &fakeJobs{nextID: newJobID(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)))
|
resp, body := do(t, s, printRequest(t, tt.body, "Bearer "+validToken(t)))
|
||||||
if resp.StatusCode != http.StatusBadRequest {
|
if resp.StatusCode != http.StatusBadRequest {
|
||||||
t.Fatalf("status = %d, want 400 (%v)", resp.StatusCode, body)
|
t.Fatalf("status = %d, want 400 (%v)", resp.StatusCode, body)
|
||||||
@@ -219,7 +239,7 @@ func TestPrintBadRequests(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestPrintValidationDetails(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)))
|
_, body := do(t, s, printRequest(t, `{"elements":[{"type":"text","size":12},{"type":"qr"}]}`, "Bearer "+validToken(t)))
|
||||||
details, _ := body["details"].([]any)
|
details, _ := body["details"].([]any)
|
||||||
if len(details) != 2 {
|
if len(details) != 2 {
|
||||||
@@ -228,7 +248,7 @@ func TestPrintValidationDetails(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestPrintQueueFull(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)))
|
resp, _ := do(t, s, printRequest(t, validJob, "Bearer "+validToken(t)))
|
||||||
if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") == "" {
|
if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") == "" {
|
||||||
t.Errorf("status = %d, Retry-After = %q", resp.StatusCode, 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{
|
jobs := &fakeJobs{statuses: map[printqueue.JobID]printqueue.Status{
|
||||||
id: {ID: id, State: printqueue.StateDone, Attempts: 1},
|
id: {ID: id, State: printqueue.StateDone, Attempts: 1},
|
||||||
}}
|
}}
|
||||||
s := newTestServer(t, jobs, fakePrinter{})
|
s := newTestServer(t, jobs, &fakePrinter{})
|
||||||
auth := "Bearer " + validToken(t)
|
auth := "Bearer " + validToken(t)
|
||||||
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
@@ -270,27 +290,37 @@ func TestJobStatus(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestHealth(t *testing.T) {
|
func TestHealth(t *testing.T) {
|
||||||
|
ready := escpos.Status{Online: true}
|
||||||
|
coverOpen := escpos.Status{CoverOpen: true}
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
printer fakePrinter
|
printer *fakePrinter
|
||||||
want int
|
want int
|
||||||
wantStatus string
|
wantStatus string
|
||||||
wantPrinter string
|
wantPrinter string
|
||||||
wantPaper 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},
|
{"ready", &fakePrinter{statuses: []escpos.Status{ready}}, 200, "ok", "ready", "ok", true, 1},
|
||||||
{"paper low still ok", fakePrinter{status: escpos.Status{Online: true, PaperNearEnd: true}}, 200, "ok", "ready", "near_end", true},
|
{"paper low still ok", &fakePrinter{statuses: []escpos.Status{{Online: true, PaperNearEnd: true}}}, 200, "ok", "ready", "near_end", true, 1},
|
||||||
{"paper out", fakePrinter{status: escpos.Status{PaperOut: true}}, 503, "degraded", "not_ready", "out", true},
|
{"paper out", &fakePrinter{statuses: []escpos.Status{{PaperOut: true}}}, 503, "degraded", "not_ready", "out", true, 2},
|
||||||
{"no status support", fakePrinter{err: printer.ErrStatusUnsupported}, 200, "ok", "unknown", "", true},
|
{"paper end stop", &fakePrinter{statuses: []escpos.Status{{PaperEndStop: true}}}, 503, "degraded", "not_ready", "out", true, 2},
|
||||||
{"unreachable", fakePrinter{err: errors.New("dial tcp: timeout")}, 503, "unavailable", "unreachable", "", false},
|
{"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 {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
s := newTestServer(t, &fakeJobs{}, tt.printer)
|
s := newTestServer(t, &fakeJobs{}, tt.printer)
|
||||||
resp, body := do(t, s, httptest.NewRequest(http.MethodGet, "/healthz", nil))
|
resp, body := do(t, s, httptest.NewRequest(http.MethodGet, "/healthz", nil))
|
||||||
if resp.StatusCode != tt.want {
|
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)
|
p, _ := body["printer"].(map[string]any)
|
||||||
if body["status"] != tt.wantStatus || p["status"] != tt.wantPrinter || p["reachable"] != tt.wantReachable {
|
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 {
|
if paper, _ := p["paper"].(string); paper != tt.wantPaper {
|
||||||
t.Errorf("paper = %q, want %q", paper, tt.wantPaper)
|
t.Errorf("paper = %q, want %q", paper, tt.wantPaper)
|
||||||
}
|
}
|
||||||
if _, leaked := p["error"].(string); leaked && !tt.wantReachable {
|
if _, leaked := p["error"].(string); leaked && tt.wantReachable != true {
|
||||||
t.Error("unreachable printer error text must not be exposed publicly")
|
t.Error("connection error text must not be exposed publicly")
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestIndexAndRobotsAndNotFound(t *testing.T) {
|
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))
|
resp, body := do(t, s, httptest.NewRequest(http.MethodGet, "/", nil))
|
||||||
if resp.StatusCode != 200 || body["Project"] != "Überbringer" || body["Version"] != "test" {
|
if resp.StatusCode != 200 || body["Project"] != "Überbringer" || body["Version"] != "test" {
|
||||||
t.Errorf("index = %d %v", resp.StatusCode, body)
|
t.Errorf("index = %d %v", resp.StatusCode, body)
|
||||||
@@ -335,7 +365,7 @@ func TestRateLimitPerClientBehindProxy(t *testing.T) {
|
|||||||
WriteTimeout: time.Second,
|
WriteTimeout: time.Second,
|
||||||
IdleTimeout: time.Second,
|
IdleTimeout: time.Second,
|
||||||
RequestID: func() string { return "req_test" },
|
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 {
|
send := func(clientIP string) int {
|
||||||
req := printRequest(t, validJob, "Bearer "+validToken(t))
|
req := printRequest(t, validJob, "Bearer "+validToken(t))
|
||||||
|
|||||||
@@ -69,7 +69,7 @@ type PrinterConfig struct {
|
|||||||
Address string `toml:"address"`
|
Address string `toml:"address"`
|
||||||
Port int `toml:"port"`
|
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"`
|
Model string `toml:"model"`
|
||||||
|
|
||||||
// CodePage is the character table text is transcoded to, e.g. "cp437".
|
// CodePage is the character table text is transcoded to, e.g. "cp437".
|
||||||
@@ -153,7 +153,10 @@ func Default() Config {
|
|||||||
},
|
},
|
||||||
Printer: PrinterConfig{
|
Printer: PrinterConfig{
|
||||||
Port: 9100,
|
Port: 9100,
|
||||||
Model: "tm-t20",
|
// 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",
|
CodePage: "cp437",
|
||||||
DialTimeout: 5 * time.Second,
|
DialTimeout: 5 * time.Second,
|
||||||
WriteTimeout: 30 * time.Second,
|
WriteTimeout: 30 * time.Second,
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ func TestLoadLegacyConfigGetsDefaults(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Load: %v", err)
|
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)
|
t.Errorf("printer defaults not applied: %+v", cfg.Printer)
|
||||||
}
|
}
|
||||||
if cfg.WebServer.RateWindow != time.Minute || cfg.Queue.Size != 100 {
|
if cfg.WebServer.RateWindow != time.Minute || cfg.Queue.Size != 100 {
|
||||||
|
|||||||
@@ -361,7 +361,14 @@ func TestStatusApply(t *testing.T) {
|
|||||||
{
|
{
|
||||||
name: "paper out",
|
name: "paper out",
|
||||||
resps: map[escpos.StatusKind]byte{1: 0x1A, 2: 0x32, 3: 0x12, 4: 0x72},
|
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",
|
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) {
|
func TestStatusApplyRejectsGarbage(t *testing.T) {
|
||||||
var s escpos.Status
|
var s escpos.Status
|
||||||
if err := s.Apply(escpos.StatusPrinter, 'H'); !errors.Is(err, escpos.ErrInvalidArgument) {
|
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-t20ii", "tm-t20", 48, 64},
|
||||||
{"TM-T88V", "tm-t88", 42, 56},
|
{"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},
|
{"generic-58mm", "generic-58mm", 32, 42},
|
||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
|
|||||||
@@ -19,23 +19,27 @@ type Profile struct {
|
|||||||
FontBWidth int
|
FontBWidth int
|
||||||
}
|
}
|
||||||
|
|
||||||
// LookupProfile returns the profile for a model name such as "tm-t20". Common
|
// LookupProfile returns the profile for a model name such as "tm-t88". Common
|
||||||
// model variants (e.g. "tm-t20ii") resolve to their family.
|
// model variants (e.g. "tm-t88vii") resolve to their family.
|
||||||
func LookupProfile(model string) (Profile, error) {
|
func LookupProfile(model string) (Profile, error) {
|
||||||
switch strings.ToLower(strings.TrimSpace(model)) {
|
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":
|
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.
|
// 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
|
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":
|
case "generic-80mm":
|
||||||
return Profile{Name: "generic-80mm", DotsPerLine: 576, FontAWidth: 12, FontBWidth: 9}, nil
|
return Profile{Name: "generic-80mm", DotsPerLine: 576, FontAWidth: 12, FontBWidth: 9}, nil
|
||||||
case "generic-58mm":
|
case "generic-58mm":
|
||||||
// 58 mm paper at 203 dpi: 32 columns of Font A.
|
// 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{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)
|
ErrInvalidArgument, model)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -21,9 +21,19 @@ func StatusKinds() []StatusKind {
|
|||||||
// Status is the printer state decoded from DLE EOT responses.
|
// Status is the printer state decoded from DLE EOT responses.
|
||||||
type Status struct {
|
type Status struct {
|
||||||
Online 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
|
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
|
PaperNearEnd bool
|
||||||
PaperOut bool
|
PaperOut bool
|
||||||
|
|
||||||
CutterError bool
|
CutterError bool
|
||||||
Unrecoverable bool
|
Unrecoverable bool
|
||||||
// AutoRecoverable reports an error the printer clears by itself, such as
|
// 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.
|
// Ready reports whether the printer can print right now.
|
||||||
func (s Status) Ready() bool {
|
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
|
// 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)
|
s.Online = !bit(3)
|
||||||
case StatusOffline:
|
case StatusOffline:
|
||||||
s.CoverOpen = bit(2)
|
s.CoverOpen = bit(2)
|
||||||
s.PaperOut = s.PaperOut || bit(5)
|
s.PaperEndStop = bit(5)
|
||||||
case StatusError:
|
case StatusError:
|
||||||
s.CutterError = bit(3)
|
s.CutterError = bit(3)
|
||||||
s.Unrecoverable = bit(5)
|
s.Unrecoverable = bit(5)
|
||||||
s.AutoRecoverable = bit(6)
|
s.AutoRecoverable = bit(6)
|
||||||
case StatusPaper:
|
case StatusPaper:
|
||||||
s.PaperNearEnd = bit(2) && bit(3)
|
s.PaperNearEnd = bit(2) && bit(3)
|
||||||
s.PaperOut = s.PaperOut || (bit(5) && bit(6))
|
s.PaperOut = bit(5) && bit(6)
|
||||||
default:
|
default:
|
||||||
return fmt.Errorf("%w: unknown status kind %d", ErrInvalidArgument, kind)
|
return fmt.Errorf("%w: unknown status kind %d", ErrInvalidArgument, kind)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -64,7 +64,8 @@ func (c *Client) Send(ctx context.Context, data []byte) error {
|
|||||||
}
|
}
|
||||||
defer release()
|
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)
|
return fmt.Errorf("setting printer write deadline: %w", err)
|
||||||
}
|
}
|
||||||
if _, err := conn.Write(data); err != nil {
|
if _, err := conn.Write(data); err != nil {
|
||||||
@@ -73,8 +74,11 @@ func (c *Client) Send(ctx context.Context, data []byte) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Status queries the printer's real-time status. It returns
|
// Status queries the printer's real-time status, normalized so that offline
|
||||||
// ErrStatusUnsupported when the printer is reachable but does not answer.
|
// 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) {
|
func (c *Client) Status(ctx context.Context) (escpos.Status, error) {
|
||||||
var status escpos.Status
|
var status escpos.Status
|
||||||
conn, release, err := c.connect(ctx)
|
conn, release, err := c.connect(ctx)
|
||||||
@@ -85,7 +89,7 @@ func (c *Client) Status(ctx context.Context) (escpos.Status, error) {
|
|||||||
|
|
||||||
resp := make([]byte, 1)
|
resp := make([]byte, 1)
|
||||||
for _, kind := range escpos.StatusKinds() {
|
for _, kind := range escpos.StatusKinds() {
|
||||||
deadline := c.deadline(ctx, statusTimeout)
|
deadline, fromContext := c.deadline(ctx, statusTimeout)
|
||||||
if err := conn.SetDeadline(deadline); err != nil {
|
if err := conn.SetDeadline(deadline); err != nil {
|
||||||
return status, fmt.Errorf("setting printer deadline: %w", err)
|
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 {
|
if _, err := conn.Read(resp); err != nil {
|
||||||
var netErr net.Error
|
var netErr net.Error
|
||||||
if errors.As(err, &netErr) && netErr.Timeout() {
|
if errors.As(err, &netErr) && netErr.Timeout() {
|
||||||
|
if fromContext {
|
||||||
|
return status, fmt.Errorf("reading printer status: %w", context.DeadlineExceeded)
|
||||||
|
}
|
||||||
return status, ErrStatusUnsupported
|
return status, ErrStatusUnsupported
|
||||||
}
|
}
|
||||||
return status, fmt.Errorf("reading printer status: %w", err)
|
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, ErrStatusUnsupported
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return status, nil
|
return status.Normalized(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// connect waits for the connection slot and dials the printer. The returned
|
// 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
|
return conn, release, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// deadline returns now+d, or the context deadline if that is sooner.
|
// deadline returns now+d, or the context deadline if that is sooner, and
|
||||||
func (c *Client) deadline(ctx context.Context, d time.Duration) time.Time {
|
// 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)
|
deadline := time.Now().Add(d)
|
||||||
if ctxDeadline, ok := ctx.Deadline(); ok && ctxDeadline.Before(deadline) {
|
if ctxDeadline, ok := ctx.Deadline(); ok && ctxDeadline.Before(deadline) {
|
||||||
return ctxDeadline
|
return ctxDeadline, true
|
||||||
}
|
}
|
||||||
return deadline
|
return deadline, false
|
||||||
}
|
}
|
||||||
@@ -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) {
|
func TestStatus(t *testing.T) {
|
||||||
answers := map[byte]byte{1: 0x12, 2: 0x12, 3: 0x12, 4: 0x1E} // paper near end
|
answers := map[byte]byte{1: 0x12, 2: 0x12, 3: 0x12, 4: 0x1E} // paper near end
|
||||||
addr := fakePrinter(t, func(conn net.Conn) {
|
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
|
_, _ = io.Copy(io.Discard, conn) // a printer that never answers
|
||||||
})
|
})
|
||||||
client := printer.NewClient(addr, time.Second, time.Second)
|
client := printer.NewClient(addr, time.Second, time.Second)
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
|
// No context deadline: the client's own status timeout (2s) must expire.
|
||||||
defer cancel()
|
if _, err := client.Status(context.Background()); !errors.Is(err, printer.ErrStatusUnsupported) {
|
||||||
if _, err := client.Status(ctx); !errors.Is(err, printer.ErrStatusUnsupported) {
|
|
||||||
t.Errorf("err = %v, want ErrStatusUnsupported", err)
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user