Refactor to Go standards; add print queue and own ESC/POS library
CI / Lint, test and scan (push) Successful in 1m41s

Restructure the daemon to follow the project's Go coding standards and
expand its features.

Layout and tooling
- cmd/uberbringer/main.go is now thin; all logic lives under internal/.
- Module path is git.anomalous.dev/57_Wolve/uberbringer, go 1.26, every
  dependency upgraded, vendor/ removed.
- staticcheck, govulncheck and goimports pinned as go tools; add a
  Makefile, CI workflow, goreleaser v2 config and Alpine Dockerfile.

Features
- Background print queue with job status (GET /api/v1/jobs/:id), send
  retries with backoff, and graceful shutdown.
- New {"elements": [...]} job format on POST /api/v1/print. Breaking:
  replaces {"data": [...]}, and the response is now JSON 202.
- In-house ESC/POS library replacing justinmichaelvieira/escpos: sizes
  1-8, Font B, CODE39/CODE128, QR, banded raster images, DLE EOT status.
- UTF-8 text transcoded to CP437 (configurable) with word-aware wrapping.
- Images from URL or base64, scaled and dithered; URL fetches refuse
  internal addresses (SSRF guard).
- Fiber v3 HTTP server, TypeID (UUIDv7) job and request IDs, /healthz
  with live printer status, `secret` and `token` subcommands.

Fixes
- Jobs are validated before anything is sent; a failed printer dial no
  longer panics.
- Request logs never contain tokens; Sentry no longer receives the
  Authorization header or print contents.
- Rate limiting is per client behind nginx (X-Real-IP).
- install.sh writes the [printer] section, runs the service as a
  dedicated user and uses a current nginx TLS config.

config.toml is no longer tracked; start from configs/config.example.toml.

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:17:16 -06:00
1 parent bb73348433
commit 6502d9551d
807 files changed
+6659 -500291

No files matched your search

+211
View File
@@ -0,0 +1,211 @@
package escpos
import (
"fmt"
"strings"
)
// Symbology identifies a one-dimensional barcode type. Values are the GS k
// function B type codes.
type Symbology byte
// Supported barcode symbologies.
const (
UPCA Symbology = 65
UPCE Symbology = 66
EAN13 Symbology = 67
EAN8 Symbology = 68
CODE39 Symbology = 69
CODE128 Symbology = 73
)
// HRIPosition places the human-readable interpretation (the digits) relative
// to a barcode.
type HRIPosition byte
// HRIPosition values for GS H.
const (
HRINone HRIPosition = 0
HRIAbove HRIPosition = 1
HRIBelow HRIPosition = 2
HRIBoth HRIPosition = 3
)
// Barcode module width limits for GS w.
const (
MinBarcodeWidth = 2
MaxBarcodeWidth = 6
)
const code39Charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ -.$/+%"
// ParseSymbology returns the symbology named by name, e.g. "ean13".
func ParseSymbology(name string) (Symbology, error) {
switch strings.ToLower(strings.TrimSpace(name)) {
case "upca", "upc-a":
return UPCA, nil
case "upce", "upc-e":
return UPCE, nil
case "ean13", "ean-13", "jan13":
return EAN13, nil
case "ean8", "ean-8", "jan8":
return EAN8, nil
case "code39", "code-39":
return CODE39, nil
case "code128", "code-128":
return CODE128, nil
}
return 0, fmt.Errorf("%w: unknown barcode symbology %q", ErrInvalidArgument, name)
}
// String returns the canonical symbology name.
func (s Symbology) String() string {
switch s {
case UPCA:
return "upca"
case UPCE:
return "upce"
case EAN13:
return "ean13"
case EAN8:
return "ean8"
case CODE39:
return "code39"
case CODE128:
return "code128"
}
return fmt.Sprintf("Symbology(%d)", byte(s))
}
// ValidateBarcode reports whether data can be encoded as sym. Where data
// includes the check digit, the check digit is verified.
func ValidateBarcode(sym Symbology, data string) error {
invalid := func(format string, args ...any) error {
return fmt.Errorf("%w: %s: "+format, append([]any{ErrInvalidArgument, sym}, args...)...)
}
switch sym {
case UPCA:
if !isDigits(data) || (len(data) != 11 && len(data) != 12) {
return invalid("want 11 or 12 digits")
}
if len(data) == 12 && !validCheckDigit(data) {
return invalid("check digit is wrong")
}
case UPCE:
switch {
case !isDigits(data):
return invalid("want digits only")
case len(data) >= 6 && len(data) <= 8:
case (len(data) == 11 || len(data) == 12) && data[0] == '0':
default:
return invalid("want 6-8 digits, or 11-12 digits starting with 0")
}
case EAN13:
if !isDigits(data) || (len(data) != 12 && len(data) != 13) {
return invalid("want 12 or 13 digits")
}
if len(data) == 13 && !validCheckDigit(data) {
return invalid("check digit is wrong")
}
case EAN8:
if !isDigits(data) || (len(data) != 7 && len(data) != 8) {
return invalid("want 7 or 8 digits")
}
if len(data) == 8 && !validCheckDigit(data) {
return invalid("check digit is wrong")
}
case CODE39:
if len(data) < 1 || len(data) > 255 {
return invalid("want 1-255 characters")
}
for _, r := range data {
if !strings.ContainsRune(code39Charset, r) {
return invalid("character %q not allowed (use 0-9, A-Z, space and -.$/+%%)", r)
}
}
case CODE128:
if len(data) < 1 {
return invalid("data is empty")
}
for _, r := range data {
if r < 0x20 || r > 0x7E {
return invalid("character %q not allowed (printable ASCII only)", r)
}
}
if len(code128Payload(data)) > 255 {
return invalid("data is too long")
}
default:
return fmt.Errorf("%w: unknown barcode symbology %d", ErrInvalidArgument, byte(sym))
}
return nil
}
// BarcodeHeight sets the barcode height in dots (GS h n).
func (b *Builder) BarcodeHeight(dots uint8) {
b.buf.Write([]byte{gs, 'h', dots})
}
// BarcodeWidth sets the barcode module width, [MinBarcodeWidth] to
// [MaxBarcodeWidth] (GS w n).
func (b *Builder) BarcodeWidth(module int) error {
if module < MinBarcodeWidth || module > MaxBarcodeWidth {
return fmt.Errorf("%w: barcode width %d must be within %d-%d",
ErrInvalidArgument, module, MinBarcodeWidth, MaxBarcodeWidth)
}
b.buf.Write([]byte{gs, 'w', byte(module)})
return nil
}
// BarcodeHRI sets where the human-readable digits are printed (GS H n).
func (b *Builder) BarcodeHRI(pos HRIPosition) {
b.buf.Write([]byte{gs, 'H', byte(pos)})
}
// Barcode validates data and appends a barcode (GS k m n d1...dn). CODE128
// data is printed in code set B, so callers pass plain text.
func (b *Builder) Barcode(sym Symbology, data string) error {
if err := ValidateBarcode(sym, data); err != nil {
return err
}
payload := []byte(data)
if sym == CODE128 {
payload = code128Payload(data)
}
b.buf.Write([]byte{gs, 'k', byte(sym), byte(len(payload))})
b.buf.Write(payload)
return nil
}
// code128Payload selects code set B and escapes '{', which the printer
// treats as the start of a code set or function character.
func code128Payload(data string) []byte {
return []byte("{B" + strings.ReplaceAll(data, "{", "{{"))
}
func isDigits(s string) bool {
if s == "" {
return false
}
for i := range len(s) {
if s[i] < '0' || s[i] > '9' {
return false
}
}
return true
}
// validCheckDigit verifies the GS1 mod-10 check digit in the last position of
// a UPC-A, EAN-13 or EAN-8 number.
func validCheckDigit(code string) bool {
sum := 0
body := code[:len(code)-1]
for i := range len(body) {
digit := int(body[len(body)-1-i] - '0')
if i%2 == 0 {
digit *= 3
}
sum += digit
}
return (10-sum%10)%10 == int(code[len(code)-1]-'0')
}
+181
View File
@@ -0,0 +1,181 @@
// Package escpos builds Epson ESC/POS command streams for thermal receipt
// printers.
//
// A [Builder] accumulates commands in memory. Callers send [Builder.Bytes] to
// the printer in a single write, so an invalid element never leaves a
// half-printed receipt. Commands follow the Epson ESC/POS Application
// Programming Guide; byte values are named by the control characters the
// specification uses (ESC, GS, DLE).
package escpos
import (
"bytes"
"errors"
"fmt"
)
// Control characters that introduce ESC/POS commands.
const (
ht byte = 0x09
lf byte = 0x0A
dle byte = 0x10
eot byte = 0x04
esc byte = 0x1B
gs byte = 0x1D
)
// MaxCharacterScale is the largest character width or height multiplier
// supported by GS !.
const MaxCharacterScale = 8
// ErrInvalidArgument is wrapped by every validation error the package
// returns.
var ErrInvalidArgument = errors.New("escpos: invalid argument")
// Justification aligns text, barcodes and QR codes on the line.
type Justification byte
// Justification values for ESC a.
const (
JustifyLeft Justification = 0
JustifyCenter Justification = 1
JustifyRight Justification = 2
)
// Font selects one of the printer's built-in character fonts.
type Font byte
// Font values for ESC M.
const (
FontA Font = 0
FontB Font = 1
)
// Underline selects the underline thickness.
type Underline byte
// Underline values for ESC -.
const (
UnderlineNone Underline = 0
UnderlineThin Underline = 1
UnderlineThick Underline = 2
)
// CutMode selects a full or partial paper cut.
type CutMode byte
// CutMode values for GS V function B, which feeds the paper to the cutting
// position before cutting so the last printed line is not lost.
const (
CutFull CutMode = 65
CutPartial CutMode = 66
)
// Builder accumulates an ESC/POS command stream. The zero value is ready to
// use. A Builder is not safe for concurrent use.
type Builder struct {
buf bytes.Buffer
}
// Bytes returns the accumulated command stream. The slice aliases the
// Builder's buffer and is valid until the next write.
func (b *Builder) Bytes() []byte {
return b.buf.Bytes()
}
// Len returns the number of accumulated bytes.
func (b *Builder) Len() int {
return b.buf.Len()
}
// Raw appends p unchanged. It is the escape hatch for commands the Builder
// does not model.
func (b *Builder) Raw(p []byte) {
b.buf.Write(p)
}
// Text appends already-encoded character data. Use [CodePage.Encode] to
// convert UTF-8 text first.
func (b *Builder) Text(encoded []byte) {
b.buf.Write(encoded)
}
// Initialize resets the printer to its power-on settings (ESC @).
func (b *Builder) Initialize() {
b.buf.Write([]byte{esc, '@'})
}
// LineFeed prints the line buffer and advances one line (LF).
func (b *Builder) LineFeed() {
b.buf.WriteByte(lf)
}
// Feed prints the line buffer and advances lines lines (ESC d n).
func (b *Builder) Feed(lines uint8) {
b.buf.Write([]byte{esc, 'd', lines})
}
// LineSpacing sets the line spacing in motion units (ESC 3 n).
func (b *Builder) LineSpacing(units uint8) {
b.buf.Write([]byte{esc, '3', units})
}
// DefaultLineSpacing restores the default line spacing (ESC 2).
func (b *Builder) DefaultLineSpacing() {
b.buf.Write([]byte{esc, '2'})
}
// Bold turns emphasized printing on or off (ESC E n).
func (b *Builder) Bold(on bool) {
b.buf.Write([]byte{esc, 'E', boolByte(on)})
}
// Underline sets the underline mode (ESC - n).
func (b *Builder) Underline(u Underline) {
b.buf.Write([]byte{esc, '-', byte(u)})
}
// Reverse turns white-on-black printing on or off (GS B n).
func (b *Builder) Reverse(on bool) {
b.buf.Write([]byte{gs, 'B', boolByte(on)})
}
// Justify sets the alignment (ESC a n). It takes effect at the start of the
// next line.
func (b *Builder) Justify(j Justification) {
b.buf.Write([]byte{esc, 'a', byte(j)})
}
// Font selects the character font (ESC M n).
func (b *Builder) Font(f Font) {
b.buf.Write([]byte{esc, 'M', byte(f)})
}
// Size sets the character width and height multipliers, each 1 to
// [MaxCharacterScale] (GS ! n).
func (b *Builder) Size(width, height int) error {
if width < 1 || width > MaxCharacterScale || height < 1 || height > MaxCharacterScale {
return fmt.Errorf("%w: character size %dx%d must be within 1-%d",
ErrInvalidArgument, width, height, MaxCharacterScale)
}
b.buf.Write([]byte{gs, '!', byte(width-1)<<4 | byte(height-1)})
return nil
}
// SelectCodePage selects the character table used to print text (ESC t n).
func (b *Builder) SelectCodePage(cp CodePage) {
b.buf.Write([]byte{esc, 't', cp.table()})
}
// Cut feeds the paper to the cutter plus feed motion units and cuts it
// (GS V m n).
func (b *Builder) Cut(mode CutMode, feed uint8) {
b.buf.Write([]byte{gs, 'V', byte(mode), feed})
}
func boolByte(on bool) byte {
if on {
return 1
}
return 0
}
+112
View File
@@ -0,0 +1,112 @@
package escpos
import (
"fmt"
"strings"
"unicode/utf8"
"golang.org/x/text/encoding/charmap"
)
// CodePage is a printer character table. It ties the ESC t table number the
// printer understands to the character map used to transcode UTF-8 text, so
// the two can never disagree.
type CodePage int
// Supported code pages. CodePage437 is the Epson factory default.
const (
CodePage437 CodePage = iota + 1
CodePage850
CodePage858
CodePage1252
)
// ParseCodePage returns the code page named by name, e.g. "cp437".
func ParseCodePage(name string) (CodePage, error) {
switch strings.ToLower(strings.TrimSpace(name)) {
case "cp437", "437", "pc437":
return CodePage437, nil
case "cp850", "850", "pc850":
return CodePage850, nil
case "cp858", "858", "pc858":
return CodePage858, nil
case "cp1252", "1252", "wpc1252", "windows-1252":
return CodePage1252, nil
}
return 0, fmt.Errorf("%w: unknown code page %q (want cp437, cp850, cp858 or cp1252)",
ErrInvalidArgument, name)
}
// String returns the canonical code page name.
func (cp CodePage) String() string {
switch cp {
case CodePage437:
return "cp437"
case CodePage850:
return "cp850"
case CodePage858:
return "cp858"
case CodePage1252:
return "cp1252"
}
return fmt.Sprintf("CodePage(%d)", int(cp))
}
// table returns the ESC t table number for cp.
func (cp CodePage) table() byte {
switch cp {
case CodePage850:
return 2
case CodePage858:
return 19
case CodePage1252:
return 16
}
return 0 // PC437, also the fallback for an invalid CodePage.
}
func (cp CodePage) charmap() *charmap.Charmap {
switch cp {
case CodePage850:
return charmap.CodePage850
case CodePage858:
return charmap.CodePage858
case CodePage1252:
return charmap.Windows1252
}
return charmap.CodePage437
}
// Encode transcodes UTF-8 text to cp, one byte per rune. Runes the code page
// cannot represent become '?'. Control characters other than newline and tab
// are dropped, because the printer would interpret them as commands.
func (cp CodePage) Encode(s string) []byte {
cm := cp.charmap()
out := make([]byte, 0, len(s))
for _, r := range s {
switch {
case r == '\n' || r == '\t':
out = append(out, byte(r))
case IsControl(r):
// Dropped: control bytes would be read as printer commands.
case r < utf8.RuneSelf:
out = append(out, byte(r))
default:
c, ok := cm.EncodeRune(r)
if !ok || c < 0x20 || c == 0x7F {
c = '?'
}
out = append(out, c)
}
}
return out
}
// IsControl reports whether r is a control character that [CodePage.Encode]
// drops. Newline and tab are not reported.
func IsControl(r rune) bool {
if r == '\n' || r == '\t' {
return false
}
return r < 0x20 || r == 0x7F || (r >= 0x80 && r < 0xA0) || r == utf8.RuneError
}
+426
View File
@@ -0,0 +1,426 @@
package escpos_test
import (
"bytes"
"errors"
"image"
"image/color"
"strings"
"testing"
"git.anomalous.dev/57_Wolve/uberbringer/internal/pkg/escpos"
)
// Byte-exact checks against the Epson ESC/POS command reference.
func TestCommands(t *testing.T) {
tests := []struct {
name string
build func(b *escpos.Builder)
want []byte
}{
{"initialize", func(b *escpos.Builder) { b.Initialize() }, []byte{0x1B, 0x40}},
{"line feed", func(b *escpos.Builder) { b.LineFeed() }, []byte{0x0A}},
{"feed 3", func(b *escpos.Builder) { b.Feed(3) }, []byte{0x1B, 0x64, 3}},
{"line spacing", func(b *escpos.Builder) { b.LineSpacing(30) }, []byte{0x1B, 0x33, 30}},
{"default line spacing", func(b *escpos.Builder) { b.DefaultLineSpacing() }, []byte{0x1B, 0x32}},
{"bold on", func(b *escpos.Builder) { b.Bold(true) }, []byte{0x1B, 0x45, 1}},
{"bold off", func(b *escpos.Builder) { b.Bold(false) }, []byte{0x1B, 0x45, 0}},
{"underline thick", func(b *escpos.Builder) { b.Underline(escpos.UnderlineThick) }, []byte{0x1B, 0x2D, 2}},
{"reverse", func(b *escpos.Builder) { b.Reverse(true) }, []byte{0x1D, 0x42, 1}},
{"justify center", func(b *escpos.Builder) { b.Justify(escpos.JustifyCenter) }, []byte{0x1B, 0x61, 1}},
{"font b", func(b *escpos.Builder) { b.Font(escpos.FontB) }, []byte{0x1B, 0x4D, 1}},
{"code page 437", func(b *escpos.Builder) { b.SelectCodePage(escpos.CodePage437) }, []byte{0x1B, 0x74, 0}},
{"code page 850", func(b *escpos.Builder) { b.SelectCodePage(escpos.CodePage850) }, []byte{0x1B, 0x74, 2}},
{"code page 858", func(b *escpos.Builder) { b.SelectCodePage(escpos.CodePage858) }, []byte{0x1B, 0x74, 19}},
{"code page 1252", func(b *escpos.Builder) { b.SelectCodePage(escpos.CodePage1252) }, []byte{0x1B, 0x74, 16}},
{"partial cut", func(b *escpos.Builder) { b.Cut(escpos.CutPartial, 0) }, []byte{0x1D, 0x56, 66, 0}},
{"full cut", func(b *escpos.Builder) { b.Cut(escpos.CutFull, 5) }, []byte{0x1D, 0x56, 65, 5}},
{"barcode height", func(b *escpos.Builder) { b.BarcodeHeight(80) }, []byte{0x1D, 0x68, 80}},
{"barcode hri", func(b *escpos.Builder) { b.BarcodeHRI(escpos.HRIBelow) }, []byte{0x1D, 0x48, 2}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var b escpos.Builder
tt.build(&b)
if !bytes.Equal(b.Bytes(), tt.want) {
t.Errorf("got % X, want % X", b.Bytes(), tt.want)
}
})
}
}
func TestSize(t *testing.T) {
tests := []struct {
width, height int
want byte
wantErr bool
}{
{1, 1, 0x00, false},
{2, 2, 0x11, false},
{8, 8, 0x77, false},
{3, 1, 0x20, false},
{1, 4, 0x03, false},
{0, 1, 0, true},
{9, 1, 0, true},
{1, 9, 0, true},
}
for _, tt := range tests {
var b escpos.Builder
err := b.Size(tt.width, tt.height)
if tt.wantErr {
if !errors.Is(err, escpos.ErrInvalidArgument) || b.Len() != 0 {
t.Errorf("Size(%d,%d): err=%v len=%d, want ErrInvalidArgument and nothing written",
tt.width, tt.height, err, b.Len())
}
continue
}
want := []byte{0x1D, 0x21, tt.want}
if err != nil || !bytes.Equal(b.Bytes(), want) {
t.Errorf("Size(%d,%d) = % X, %v; want % X", tt.width, tt.height, b.Bytes(), err, want)
}
}
}
func TestBarcodeWidthUsesWidthCommand(t *testing.T) {
var b escpos.Builder
if err := b.BarcodeWidth(3); err != nil {
t.Fatal(err)
}
if want := []byte{0x1D, 0x77, 3}; !bytes.Equal(b.Bytes(), want) {
t.Errorf("got % X, want % X", b.Bytes(), want)
}
if err := b.BarcodeWidth(7); !errors.Is(err, escpos.ErrInvalidArgument) {
t.Errorf("BarcodeWidth(7) err = %v, want ErrInvalidArgument", err)
}
}
func TestBarcode(t *testing.T) {
tests := []struct {
name string
sym escpos.Symbology
data string
want []byte
wantErr bool
}{
{name: "ean13 with check digit", sym: escpos.EAN13, data: "4006381333931",
want: append([]byte{0x1D, 0x6B, 67, 13}, "4006381333931"...)},
{name: "ean13 without check digit", sym: escpos.EAN13, data: "400638133393",
want: append([]byte{0x1D, 0x6B, 67, 12}, "400638133393"...)},
{name: "ean13 wrong check digit", sym: escpos.EAN13, data: "4006381333932", wantErr: true},
{name: "ean13 letters", sym: escpos.EAN13, data: "40063813339A", wantErr: true},
{name: "ean8", sym: escpos.EAN8, data: "96385074",
want: append([]byte{0x1D, 0x6B, 68, 8}, "96385074"...)},
{name: "ean8 wrong length", sym: escpos.EAN8, data: "123", wantErr: true},
{name: "upca", sym: escpos.UPCA, data: "036000291452",
want: append([]byte{0x1D, 0x6B, 65, 12}, "036000291452"...)},
{name: "upce short", sym: escpos.UPCE, data: "123456",
want: append([]byte{0x1D, 0x6B, 66, 6}, "123456"...)},
{name: "upce long must start with 0", sym: escpos.UPCE, data: "12345678901", wantErr: true},
{name: "code39", sym: escpos.CODE39, data: "ABC-123",
want: append([]byte{0x1D, 0x6B, 69, 7}, "ABC-123"...)},
{name: "code39 lowercase", sym: escpos.CODE39, data: "abc", wantErr: true},
{name: "code128 code set B", sym: escpos.CODE128, data: "Hello-1",
want: append([]byte{0x1D, 0x6B, 73, 9}, "{BHello-1"...)},
{name: "code128 escapes brace", sym: escpos.CODE128, data: "a{b",
want: append([]byte{0x1D, 0x6B, 73, 6}, "{Ba{{b"...)},
{name: "code128 non-ascii", sym: escpos.CODE128, data: "Grüße", wantErr: true},
{name: "code128 too long", sym: escpos.CODE128, data: strings.Repeat("x", 254), wantErr: true},
{name: "empty", sym: escpos.CODE128, data: "", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var b escpos.Builder
err := b.Barcode(tt.sym, tt.data)
if tt.wantErr {
if !errors.Is(err, escpos.ErrInvalidArgument) || b.Len() != 0 {
t.Fatalf("err=%v len=%d, want ErrInvalidArgument and nothing written", err, b.Len())
}
return
}
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(b.Bytes(), tt.want) {
t.Errorf("got % X, want % X", b.Bytes(), tt.want)
}
})
}
}
func TestQRCode(t *testing.T) {
var b escpos.Builder
if err := b.QRCode([]byte("hi"), 6, escpos.QRCorrectionM); err != nil {
t.Fatal(err)
}
want := []byte{
0x1D, 0x28, 0x6B, 4, 0, 0x31, 0x41, 0x32, 0, // model 2
0x1D, 0x28, 0x6B, 3, 0, 0x31, 0x43, 6, // module size
0x1D, 0x28, 0x6B, 3, 0, 0x31, 0x45, 49, // correction M
0x1D, 0x28, 0x6B, 5, 0, 0x31, 0x50, 0x30, 'h', 'i', // store
0x1D, 0x28, 0x6B, 3, 0, 0x31, 0x51, 0x30, // print
}
if !bytes.Equal(b.Bytes(), want) {
t.Errorf("got % X\nwant % X", b.Bytes(), want)
}
}
func TestQRCodeStoreLengthUsesHighByte(t *testing.T) {
var b escpos.Builder
data := bytes.Repeat([]byte{'x'}, 300)
if err := b.QRCode(data, 4, escpos.QRCorrectionL); err != nil {
t.Fatal(err)
}
store := []byte{0x1D, 0x28, 0x6B, byte(303 & 0xFF), byte(303 >> 8), 0x31, 0x50, 0x30}
if !bytes.Contains(b.Bytes(), store) {
t.Errorf("store header % X not found", store)
}
}
func TestQRCodeRejects(t *testing.T) {
tests := map[string]func(b *escpos.Builder) error{
"empty": func(b *escpos.Builder) error { return b.QRCode(nil, 4, escpos.QRCorrectionM) },
"too long": func(b *escpos.Builder) error {
return b.QRCode(make([]byte, escpos.MaxQRData+1), 4, escpos.QRCorrectionM)
},
"module too big": func(b *escpos.Builder) error { return b.QRCode([]byte("x"), 17, escpos.QRCorrectionM) },
"bad correction": func(b *escpos.Builder) error { return b.QRCode([]byte("x"), 4, 47) },
"module too small": func(b *escpos.Builder) error { return b.QRCode([]byte("x"), 0, escpos.QRCorrectionM) },
}
for name, call := range tests {
t.Run(name, func(t *testing.T) {
var b escpos.Builder
if err := call(&b); !errors.Is(err, escpos.ErrInvalidArgument) || b.Len() != 0 {
t.Errorf("err=%v len=%d, want ErrInvalidArgument and nothing written", err, b.Len())
}
})
}
}
func TestEncodeCodePage437(t *testing.T) {
tests := []struct {
name string
in string
want []byte
}{
{"ascii", "Hello, World!", []byte("Hello, World!")},
{"box drawing", "┌─┐│└┘", []byte{0xDA, 0xC4, 0xBF, 0xB3, 0xC0, 0xD9}},
{"shading", "░▒▓█", []byte{0xB0, 0xB1, 0xB2, 0xDB}},
{"double box", "╔═╗", []byte{0xC9, 0xCD, 0xBB}},
{"umlauts", "Über ä ö", []byte{0x9A, 'b', 'e', 'r', ' ', 0x84, ' ', 0x94}},
{"symbols", "£°±", []byte{0x9C, 0xF8, 0xF1}},
{"unmappable emoji", "hi 🎉", []byte("hi ?")},
{"keeps newline and tab", "a\nb\tc", []byte("a\nb\tc")},
// ESC is dropped, so the '@' that followed it is harmless text.
{"drops control characters", "a\x1b@b\x00c\r", []byte("a@bc")},
{"smiley maps below 0x20 so becomes ?", "☺", []byte("?")},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := escpos.CodePage437.Encode(tt.in)
if !bytes.Equal(got, tt.want) {
t.Errorf("Encode(%q) = % X, want % X", tt.in, got, tt.want)
}
})
}
}
func TestEncodeOtherCodePages(t *testing.T) {
if got := escpos.CodePage858.Encode("€"); !bytes.Equal(got, []byte{0xD5}) {
t.Errorf("cp858 € = % X, want D5", got)
}
if got := escpos.CodePage1252.Encode("ێ"); !bytes.Equal(got, []byte{0x80, 0xE9}) {
t.Errorf("cp1252 ێ = % X, want 80 E9", got)
}
if got := escpos.CodePage850.Encode("é"); !bytes.Equal(got, []byte{0x82}) {
t.Errorf("cp850 é = % X, want 82", got)
}
}
func TestParseCodePage(t *testing.T) {
for _, name := range []string{"cp437", "CP437", "437"} {
if cp, err := escpos.ParseCodePage(name); err != nil || cp != escpos.CodePage437 {
t.Errorf("ParseCodePage(%q) = %v, %v", name, cp, err)
}
}
if _, err := escpos.ParseCodePage("ebcdic"); !errors.Is(err, escpos.ErrInvalidArgument) {
t.Errorf("ParseCodePage(ebcdic) err = %v", err)
}
}
func TestRasterImagePacksBitsAndPadsWidth(t *testing.T) {
// 10x2 image: row 0 is black at x=0 and x=9, row 1 is all white.
img := image.NewGray(image.Rect(0, 0, 10, 2))
for i := range img.Pix {
img.Pix[i] = 0xFF
}
img.SetGray(0, 0, color.Gray{})
img.SetGray(9, 0, color.Gray{})
var b escpos.Builder
if err := b.RasterImage(img); err != nil {
t.Fatal(err)
}
want := []byte{
0x1D, 0x76, 0x30, 0, 2, 0, 2, 0, // 2 bytes wide, 2 rows
0x80, 0x40, // row 0: bit for x=0, bit for x=9
0x00, 0x00, // row 1: padding stays white
}
if !bytes.Equal(b.Bytes(), want) {
t.Errorf("got % X, want % X", b.Bytes(), want)
}
}
func TestRasterImageRespectsBoundsOrigin(t *testing.T) {
// A sub-image whose bounds do not start at (0,0).
full := image.NewGray(image.Rect(0, 0, 16, 4))
for i := range full.Pix {
full.Pix[i] = 0xFF
}
full.SetGray(8, 2, color.Gray{})
sub := full.SubImage(image.Rect(8, 2, 16, 3))
var b escpos.Builder
if err := b.RasterImage(sub); err != nil {
t.Fatal(err)
}
want := []byte{0x1D, 0x76, 0x30, 0, 1, 0, 1, 0, 0x80}
if !bytes.Equal(b.Bytes(), want) {
t.Errorf("got % X, want % X", b.Bytes(), want)
}
}
func TestRasterImageBandsTallImages(t *testing.T) {
img := image.NewGray(image.Rect(0, 0, 8, 600))
var b escpos.Builder
if err := b.RasterImage(img); err != nil {
t.Fatal(err)
}
headers := []([]byte){
{0x1D, 0x76, 0x30, 0, 1, 0, 0x00, 0x01}, // 256 rows
{0x1D, 0x76, 0x30, 0, 1, 0, 0x00, 0x01}, // 256 rows
{0x1D, 0x76, 0x30, 0, 1, 0, 88, 0}, // 88 rows
}
out := b.Bytes()
for i, h := range headers {
if !bytes.HasPrefix(out, h) {
t.Fatalf("band %d header = % X, want % X", i, out[:min(8, len(out))], h)
}
rows := int(h[6]) | int(h[7])<<8
out = out[8+rows:]
}
if len(out) != 0 {
t.Errorf("%d trailing bytes", len(out))
}
}
func TestRasterImageTransparentIsWhite(t *testing.T) {
img := image.NewNRGBA(image.Rect(0, 0, 8, 1))
img.SetNRGBA(0, 0, color.NRGBA{A: 0}) // transparent black: paper shows
img.SetNRGBA(1, 0, color.NRGBA{A: 255}) // opaque black
img.SetNRGBA(2, 0, color.NRGBA{R: 255, G: 255, B: 255, A: 255})
var b escpos.Builder
if err := b.RasterImage(img); err != nil {
t.Fatal(err)
}
if got := b.Bytes()[8]; got != 0x40 {
t.Errorf("row byte = %08b, want 01000000", got)
}
}
func TestRasterImageEmpty(t *testing.T) {
var b escpos.Builder
if err := b.RasterImage(image.NewGray(image.Rect(0, 0, 0, 0))); !errors.Is(err, escpos.ErrInvalidArgument) {
t.Errorf("err = %v, want ErrInvalidArgument", err)
}
}
func TestStatusApply(t *testing.T) {
tests := []struct {
name string
resps map[escpos.StatusKind]byte
want escpos.Status
ready bool
}{
{
name: "healthy",
resps: map[escpos.StatusKind]byte{1: 0x12, 2: 0x12, 3: 0x12, 4: 0x12},
want: escpos.Status{Online: true},
ready: true,
},
{
name: "cover open",
resps: map[escpos.StatusKind]byte{1: 0x1A, 2: 0x16, 3: 0x12, 4: 0x12},
want: escpos.Status{CoverOpen: true},
},
{
name: "paper near end",
resps: map[escpos.StatusKind]byte{1: 0x12, 2: 0x12, 3: 0x12, 4: 0x1E},
want: escpos.Status{Online: true, PaperNearEnd: true},
ready: true,
},
{
name: "paper out",
resps: map[escpos.StatusKind]byte{1: 0x1A, 2: 0x32, 3: 0x12, 4: 0x72},
want: escpos.Status{PaperOut: true},
},
{
name: "cutter error",
resps: map[escpos.StatusKind]byte{1: 0x1A, 2: 0x52, 3: 0x1A, 4: 0x12},
want: escpos.Status{CutterError: true},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var s escpos.Status
for _, kind := range escpos.StatusKinds() {
if err := s.Apply(kind, tt.resps[kind]); err != nil {
t.Fatal(err)
}
}
if s != tt.want {
t.Errorf("status = %+v, want %+v", s, tt.want)
}
if s.Ready() != tt.ready {
t.Errorf("Ready() = %v, want %v", s.Ready(), tt.ready)
}
})
}
}
func TestStatusApplyRejectsGarbage(t *testing.T) {
var s escpos.Status
if err := s.Apply(escpos.StatusPrinter, 'H'); !errors.Is(err, escpos.ErrInvalidArgument) {
t.Errorf("err = %v, want ErrInvalidArgument", err)
}
}
func TestStatusRequest(t *testing.T) {
if got := escpos.StatusRequest(escpos.StatusPaper); !bytes.Equal(got, []byte{0x10, 0x04, 4}) {
t.Errorf("got % X", got)
}
}
func TestLookupProfile(t *testing.T) {
tests := []struct {
model string
wantName string
colsA, colsB int
}{
{"tm-t20ii", "tm-t20", 48, 64},
{"TM-T88V", "tm-t88", 42, 56},
{"generic-58mm", "generic-58mm", 32, 42},
}
for _, tt := range tests {
p, err := escpos.LookupProfile(tt.model)
if err != nil {
t.Fatalf("LookupProfile(%q): %v", tt.model, err)
}
if p.Name != tt.wantName || p.Columns(escpos.FontA) != tt.colsA || p.Columns(escpos.FontB) != tt.colsB {
t.Errorf("%q: name=%s cols=%d/%d, want %s %d/%d", tt.model, p.Name,
p.Columns(escpos.FontA), p.Columns(escpos.FontB), tt.wantName, tt.colsA, tt.colsB)
}
}
if _, err := escpos.LookupProfile("sol-802"); !errors.Is(err, escpos.ErrInvalidArgument) {
t.Errorf("unknown model err = %v", err)
}
}
+53
View File
@@ -0,0 +1,53 @@
package escpos
import (
"fmt"
"strings"
)
// Profile describes the printable area and fonts of a printer model.
type Profile struct {
// Name is the canonical model name.
Name string
// DotsPerLine is the printable width in dots.
DotsPerLine int
// FontAWidth and FontBWidth are the glyph widths in dots, including
// default character spacing, at scale 1.
FontAWidth int
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.
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 "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)",
ErrInvalidArgument, model)
}
// GlyphWidth returns the width in dots of one character in font f at scale 1.
func (p Profile) GlyphWidth(f Font) int {
if f == FontB {
return p.FontBWidth
}
return p.FontAWidth
}
// Columns returns how many characters of font f at scale 1 fit on a line.
func (p Profile) Columns(f Font) int {
return p.DotsPerLine / p.GlyphWidth(f)
}
+70
View File
@@ -0,0 +1,70 @@
package escpos
import (
"fmt"
"strings"
)
// QRCorrection is the QR code error correction level. Higher levels survive
// more damage at the cost of a denser code.
type QRCorrection byte
// QRCorrection values for GS ( k function 169.
const (
QRCorrectionL QRCorrection = 48 // about 7% recovery
QRCorrectionM QRCorrection = 49 // about 15% recovery
QRCorrectionQ QRCorrection = 50 // about 25% recovery
QRCorrectionH QRCorrection = 51 // about 30% recovery
)
// QR code limits.
const (
MaxQRData = 7089 // bytes the printer's symbol storage accepts
MinQRModuleSize = 1
MaxQRModuleSize = 16
)
// ParseQRCorrection returns the correction level named by name: L, M, Q or H.
func ParseQRCorrection(name string) (QRCorrection, error) {
switch strings.ToUpper(strings.TrimSpace(name)) {
case "L":
return QRCorrectionL, nil
case "M":
return QRCorrectionM, nil
case "Q":
return QRCorrectionQ, nil
case "H":
return QRCorrectionH, nil
}
return 0, fmt.Errorf("%w: unknown QR correction level %q (want L, M, Q or H)", ErrInvalidArgument, name)
}
// QRCode appends a model 2 QR code holding data, printed with square modules
// moduleSize dots wide.
func (b *Builder) QRCode(data []byte, moduleSize int, level QRCorrection) error {
switch {
case len(data) == 0:
return fmt.Errorf("%w: QR data is empty", ErrInvalidArgument)
case len(data) > MaxQRData:
return fmt.Errorf("%w: QR data is %d bytes, limit is %d", ErrInvalidArgument, len(data), MaxQRData)
case moduleSize < MinQRModuleSize || moduleSize > MaxQRModuleSize:
return fmt.Errorf("%w: QR module size %d must be within %d-%d",
ErrInvalidArgument, moduleSize, MinQRModuleSize, MaxQRModuleSize)
case level < QRCorrectionL || level > QRCorrectionH:
return fmt.Errorf("%w: unknown QR correction level %d", ErrInvalidArgument, byte(level))
}
// Function 165: select model 2.
b.buf.Write([]byte{gs, '(', 'k', 4, 0, '1', 'A', '2', 0})
// Function 167: module size.
b.buf.Write([]byte{gs, '(', 'k', 3, 0, '1', 'C', byte(moduleSize)})
// Function 169: error correction level.
b.buf.Write([]byte{gs, '(', 'k', 3, 0, '1', 'E', byte(level)})
// Function 180: store data. The length covers cn, fn, m and the data.
n := len(data) + 3
b.buf.Write([]byte{gs, '(', 'k', byte(n), byte(n >> 8), '1', 'P', '0'})
b.buf.Write(data)
// Function 181: print the stored symbol.
b.buf.Write([]byte{gs, '(', 'k', 3, 0, '1', 'Q', '0'})
return nil
}
+83
View File
@@ -0,0 +1,83 @@
package escpos
import (
"fmt"
"image"
"image/color"
)
// rasterBandHeight is the number of rows sent per GS v 0 command. Splitting
// tall images keeps every command within the height limits of all supported
// models (TM-T20 accepts up to 2303 rows).
const rasterBandHeight = 256
// maxRasterWidthBytes bounds the image width so xL/xH stay meaningful.
const maxRasterWidthBytes = 0xFFFF
// RasterImage appends img as one or more GS v 0 raster bit images. Pixels
// darker than 50% luminance, after compositing onto white paper, print black.
// Dither images first (see the raster package) for photographic content. The
// width is padded with white up to a multiple of 8 dots.
func (b *Builder) RasterImage(img image.Image) error {
bounds := img.Bounds()
width, height := bounds.Dx(), bounds.Dy()
if width <= 0 || height <= 0 {
return fmt.Errorf("%w: image is empty", ErrInvalidArgument)
}
widthBytes := (width + 7) / 8
if widthBytes > maxRasterWidthBytes {
return fmt.Errorf("%w: image is %d dots wide", ErrInvalidArgument, width)
}
dark := darkFunc(img)
row := make([]byte, widthBytes)
for top := 0; top < height; top += rasterBandHeight {
rows := min(rasterBandHeight, height-top)
b.buf.Write([]byte{gs, 'v', '0', 0,
byte(widthBytes), byte(widthBytes >> 8),
byte(rows), byte(rows >> 8)})
for y := top; y < top+rows; y++ {
clear(row)
for x := range width {
if dark(bounds.Min.X+x, bounds.Min.Y+y) {
row[x/8] |= 0x80 >> (x % 8)
}
}
b.buf.Write(row)
}
}
return nil
}
// darkFunc returns a pixel test for img, with fast paths for the image types
// the raster package produces.
func darkFunc(img image.Image) func(x, y int) bool {
switch m := img.(type) {
case *image.Paletted:
dark := make([]bool, len(m.Palette))
for i, c := range m.Palette {
dark[i] = isDark(c)
}
return func(x, y int) bool {
idx := m.ColorIndexAt(x, y)
return int(idx) < len(dark) && dark[idx]
}
case *image.Gray:
return func(x, y int) bool {
return m.GrayAt(x, y).Y < 0x80
}
}
return func(x, y int) bool {
return isDark(img.At(x, y))
}
}
// isDark composites c onto white and reports whether its luminance is below
// 50%. RGBA returns alpha-premultiplied values, so adding the uncovered
// fraction of white is enough to composite.
func isDark(c color.Color) bool {
r, g, bl, a := c.RGBA()
white := 0xFFFF - a
luma := (299*(r+white) + 587*(g+white) + 114*(bl+white)) / 1000
return luma < 0x8000
}
+75
View File
@@ -0,0 +1,75 @@
package escpos
import "fmt"
// StatusKind selects which real-time status byte DLE EOT requests.
type StatusKind byte
// StatusKind values for DLE EOT n.
const (
StatusPrinter StatusKind = 1
StatusOffline StatusKind = 2
StatusError StatusKind = 3
StatusPaper StatusKind = 4
)
// StatusKinds lists every status kind in the order a full query sends them.
func StatusKinds() []StatusKind {
return []StatusKind{StatusPrinter, StatusOffline, StatusError, StatusPaper}
}
// Status is the printer state decoded from DLE EOT responses.
type Status struct {
Online bool
CoverOpen bool
PaperNearEnd bool
PaperOut bool
CutterError bool
Unrecoverable bool
// AutoRecoverable reports an error the printer clears by itself, such as
// a print head that is too hot.
AutoRecoverable bool
}
// 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
}
// StatusRequest returns the real-time DLE EOT n command for kind. Real-time
// commands are executed immediately, even while the printer is busy.
func StatusRequest(kind StatusKind) []byte {
return []byte{dle, eot, byte(kind)}
}
// statusFixedMask and statusFixedBits describe the bits every DLE EOT
// response has fixed: bits 0 and 7 are 0, bits 1 and 4 are 1.
const (
statusFixedMask byte = 0x93
statusFixedBits byte = 0x12
)
// Apply decodes resp, the printer's answer to StatusRequest(kind), into s.
func (s *Status) Apply(kind StatusKind, resp byte) error {
if resp&statusFixedMask != statusFixedBits {
return fmt.Errorf("%w: 0x%02X is not a DLE EOT %d response", ErrInvalidArgument, resp, kind)
}
bit := func(n uint) bool { return resp&(1<<n) != 0 }
switch kind {
case StatusPrinter:
s.Online = !bit(3)
case StatusOffline:
s.CoverOpen = bit(2)
s.PaperOut = s.PaperOut || 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))
default:
return fmt.Errorf("%w: unknown status kind %d", ErrInvalidArgument, kind)
}
return nil
}