package printer_test import ( "bytes" "context" "errors" "fmt" "io" "net" "slices" "sync/atomic" "testing" "time" "uberbringer/internal/pkg/escpos" "uberbringer/internal/pkg/printer" ) // fakePrinter accepts one connection per handle call. func fakePrinter(t *testing.T, handle func(net.Conn)) string { t.Helper() ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = ln.Close() }) go func() { for { conn, err := ln.Accept() if err != nil { return } go func() { defer conn.Close() handle(conn) }() } }() return ln.Addr().String() } func TestSend(t *testing.T) { received := make(chan []byte, 1) addr := fakePrinter(t, func(conn net.Conn) { data, _ := io.ReadAll(conn) received <- data }) client := printer.NewClient(addr, time.Second, time.Second) if err := client.Send(context.Background(), []byte("receipt"), nil); err != nil { t.Fatal(err) } select { case got := <-received: if !bytes.Equal(got, []byte("receipt")) { t.Errorf("printer got %q", got) } case <-time.After(2 * time.Second): t.Fatal("printer received nothing") } } // beforeWrite runs once the connection is open and before the first byte; // when it fails, the printer receives nothing and Send returns its error. func TestSendCallsBeforeWrite(t *testing.T) { accepted := make(chan struct{}, 2) firstByte := make(chan struct{}, 2) received := make(chan []byte, 2) addr := fakePrinter(t, func(conn net.Conn) { accepted <- struct{}{} first := make([]byte, 1) if _, err := io.ReadFull(conn, first); err != nil { received <- nil return } firstByte <- struct{}{} rest, _ := io.ReadAll(conn) received <- append(first, rest...) }) client := printer.NewClient(addr, time.Second, time.Second) var calls int err := client.Send(context.Background(), []byte("receipt"), func() error { calls++ select { case <-accepted: case <-time.After(2 * time.Second): t.Error("the printer never accepted the connection") } select { case <-firstByte: t.Error("the printer got a byte before beforeWrite returned") case <-time.After(50 * time.Millisecond): } return nil }) if err != nil || calls != 1 { t.Fatalf("Send = %v after %d calls, want nil after 1", err, calls) } if got := <-received; !bytes.Equal(got, []byte("receipt")) { t.Errorf("printer got %q", got) } refused := errors.New("not recorded") if err := client.Send(context.Background(), []byte("receipt"), func() error { return refused }); !errors.Is(err, refused) { t.Errorf("Send = %v, want the error beforeWrite returned", err) } select { case got := <-received: if len(got) != 0 { t.Errorf("printer got %q after beforeWrite failed, want nothing", got) } case <-time.After(2 * time.Second): t.Fatal("the connection was not closed after beforeWrite failed") } } // readJob reads from conn until the bytes end with GS r 1, which Send asks // before a job and again after it, and returns the bytes before it without // the GS a 0 that Send sends before each GS r 1. On the way it answers a // DLE EOT 1 that begins what it reads, as an online printer does: Send asks // one at the start of a connection, and another once the printer is ready. func readJob(conn net.Conn) ([]byte, error) { var got []byte buf := make([]byte, 256) online := escpos.StatusRequest(escpos.StatusPrinter) for !bytes.HasSuffix(got, escpos.TransmitStatusRequest()) { n, err := conn.Read(buf) got = append(got, buf[:n]...) if bytes.HasPrefix(got, online) { got = got[len(online):] if _, err := conn.Write([]byte{0x12}); err != nil { return got, err } } if err != nil { return got, err } } got = bytes.TrimSuffix(got, escpos.TransmitStatusRequest()) return bytes.TrimSuffix(got, escpos.AutomaticStatusOff()), nil } // answerReady reads the DLE EOT 1, GS a 0 and GS r 1 that Send sends before // a job, answers the DLE EOT 1 and the GS r 1, then answers the DLE EOT 1 // that follows, as an online printer that can print does. func answerReady(conn net.Conn) error { before, err := readJob(conn) if err != nil { return err } if len(before) != 0 { return fmt.Errorf("got % X before the ready request", before) } if _, err := conn.Write([]byte{0x00}); err != nil { return err } req := make([]byte, 3) if _, err := io.ReadFull(conn, req); err != nil { return err } if !bytes.Equal(req, escpos.StatusRequest(escpos.StatusPrinter)) { return fmt.Errorf("got % X after the ready answer, want DLE EOT 1", req) } _, err = conn.Write([]byte{0x12}) return err } // With Confirm, Send asks whether the printer is ready before the job, and // returns only once the printer answers the GS r 1 after it, passing over // the bytes before the answer: an automatic status block, whose last bytes // look like the answer, and an answer to a DLE EOT in the job. func TestSendWaitsForConfirmation(t *testing.T) { job := make(chan []byte, 1) answer := make(chan struct{}) addr := fakePrinter(t, func(conn net.Conn) { if err := answerReady(conn); err != nil { job <- nil return } data, err := readJob(conn) job <- data if err != nil { return } _, _ = conn.Write([]byte{0x10, 0x00, 0x00, 0x00, 0x16}) <-answer _, _ = conn.Write([]byte{0x00}) _, _ = io.ReadAll(conn) }) client := printer.NewClient(addr, time.Second, 5*time.Second, printer.Confirm(true)) sent := make(chan error, 1) go func() { sent <- client.Send(context.Background(), []byte("receipt"), nil) }() if got := <-job; !bytes.Equal(got, []byte("receipt")) { t.Errorf("printer got %q, then GS r 1", got) } select { case err := <-sent: t.Fatalf("Send returned %v before the printer answered", err) case <-time.After(300 * time.Millisecond): } close(answer) select { case err := <-sent: if err != nil { t.Errorf("Send = %v, want nil once the printer answered", err) } case <-time.After(5 * time.Second): t.Fatal("Send did not return after the printer answered") } } // With Confirm, a job written in full that the printer does not confirm, // because it never answers or closes the connection first, gives an // UnconfirmedError; the printer has every byte. func TestSendUnconfirmed(t *testing.T) { for name, after := range map[string]func(net.Conn){ "no answer before the deadline": func(conn net.Conn) { _, _ = io.ReadAll(conn) }, "the connection closed": func(net.Conn) {}, } { t.Run(name, func(t *testing.T) { job := make(chan []byte, 1) addr := fakePrinter(t, func(conn net.Conn) { if err := answerReady(conn); err != nil { job <- nil return } data, _ := readJob(conn) job <- data after(conn) }) client := printer.NewClient(addr, time.Second, 300*time.Millisecond, printer.Confirm(true)) err := client.Send(context.Background(), []byte("receipt"), nil) var unconfirmed *printer.UnconfirmedError if !errors.As(err, &unconfirmed) || !unconfirmed.Unconfirmed() { t.Errorf("Send = %v, want an UnconfirmedError", err) } if got := <-job; !bytes.Equal(got, []byte("receipt")) { t.Errorf("printer got %q", got) } }) } } // With Confirm, a printer that does not answer the ready request, as with // its cover open, gets nothing of the job: Send returns a plain error // without calling beforeWrite. func TestSendToAPrinterNotReady(t *testing.T) { received := make(chan []byte, 1) addr := fakePrinter(t, func(conn net.Conn) { data, _ := io.ReadAll(conn) received <- data }) client := printer.NewClient(addr, time.Second, 300*time.Millisecond, printer.Confirm(true)) called := false err := client.Send(context.Background(), []byte("receipt"), func() error { called = true; return nil }) var unconfirmed *printer.UnconfirmedError if err == nil || errors.As(err, &unconfirmed) { t.Errorf("Send = %v, want a plain error", err) } if called { t.Error("beforeWrite ran although the printer was not ready") } if got, want := <-received, slices.Concat(escpos.StatusRequest(escpos.StatusPrinter), escpos.AutomaticStatusOff(), escpos.TransmitStatusRequest()); !bytes.Equal(got, want) { t.Errorf("printer got % X, want only the ready request, % X", got, want) } } // After a job the printer did not confirm, its answer can still come, late, // on the next connection, or never. Either way it never confirms the next // job: the ready request before it reads and drops the late answer. func TestSendDropsALateAnswer(t *testing.T) { for name, late := range map[string][]byte{"the late answer comes": {0x00}, "it never comes": nil} { t.Run(name, func(t *testing.T) { answer := make(chan struct{}) var conns atomic.Int32 addr := fakePrinter(t, func(conn net.Conn) { if conns.Add(1) == 1 { if answerReady(conn) == nil { _, _ = readJob(conn) } return } _, _ = conn.Write(late) if answerReady(conn) != nil { return } if _, err := readJob(conn); err != nil { return } <-answer _, _ = conn.Write([]byte{0x00}) _, _ = io.ReadAll(conn) }) client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) var unconfirmed *printer.UnconfirmedError if err := client.Send(context.Background(), []byte("first"), nil); !errors.As(err, &unconfirmed) { t.Fatalf("first Send = %v, want an UnconfirmedError", err) } sent := make(chan error, 1) go func() { sent <- client.Send(context.Background(), []byte("second"), nil) }() select { case err := <-sent: t.Fatalf("second Send returned %v before the printer confirmed it", err) case <-time.After(500 * time.Millisecond): } close(answer) if err := <-sent; err != nil { t.Errorf("second Send = %v, want nil once the printer confirmed it", err) } }) } } // sendUntilAnswered sends data and checks that Send returns nil, and not // before answer is closed, which the fake printer waits on before it // confirms the job. func sendUntilAnswered(t *testing.T, client *printer.Client, data []byte, answer chan struct{}) { t.Helper() sent := make(chan error, 1) go func() { sent <- client.Send(context.Background(), data, nil) }() select { case err := <-sent: close(answer) t.Errorf("Send returned %v before the printer confirmed the job", err) return case <-time.After(500 * time.Millisecond): } close(answer) if err := <-sent; err != nil { t.Errorf("Send = %v once the printer confirmed the job", err) } } // An answer the printer owes to a request this Client never sent, as from // an earlier run of the daemon, comes before the answer to the ready // request, in a read of its own. The ready wait drops both, so neither // confirms the job. func TestSendDropsAnAnswerOwedToAnEarlierRun(t *testing.T) { answer := make(chan struct{}) addr := fakePrinter(t, func(conn net.Conn) { if _, err := readJob(conn); err != nil { return } _, _ = conn.Write([]byte{0x00}) time.Sleep(20 * time.Millisecond) _, _ = conn.Write([]byte{0x00}) if _, err := readJob(conn); err != nil { return } <-answer _, _ = conn.Write([]byte{0x00}) _, _ = io.ReadAll(conn) }) client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) sendUntilAnswered(t, client, []byte("job"), answer) } // A job whose own bytes hold GS r 1 is confirmed by that request's answer, // and the answer to the request after it comes on the next connection. It // never confirms the next job. func TestSendDropsTheAnswerOwedAfterAJobsOwnRequest(t *testing.T) { var conns atomic.Int32 answer := make(chan struct{}) raw := append(append([]byte("before "), escpos.TransmitStatusRequest()...), []byte(" after")...) addr := fakePrinter(t, func(conn net.Conn) { if conns.Add(1) == 1 { if answerReady(conn) != nil { return } buf := make([]byte, len(raw)+len(escpos.AutomaticStatusOff())+len(escpos.TransmitStatusRequest())) if _, err := io.ReadFull(conn, buf); err != nil { return } _, _ = conn.Write([]byte{0x00}) _, _ = io.ReadAll(conn) return } if _, err := readJob(conn); err != nil { return } _, _ = conn.Write([]byte{0x00}) time.Sleep(20 * time.Millisecond) _, _ = conn.Write([]byte{0x00}) if _, err := readJob(conn); err != nil { return } <-answer _, _ = conn.Write([]byte{0x00}) _, _ = io.ReadAll(conn) }) client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) if err := client.Send(context.Background(), raw, nil); err != nil { t.Fatalf("first Send = %v", err) } sendUntilAnswered(t, client, []byte("second"), answer) } // An automatic status block whose header comes in the read with the ready // answer, and whose last bytes come in the next, is passed over. func TestSendSkipsAStatusBlockSplitAcrossReads(t *testing.T) { answer := make(chan struct{}) addr := fakePrinter(t, func(conn net.Conn) { if _, err := readJob(conn); err != nil { return } _, _ = conn.Write([]byte{0x00, 0x10}) time.Sleep(20 * time.Millisecond) _, _ = conn.Write([]byte{0x00, 0x00, 0x00}) if _, err := readJob(conn); err != nil { return } <-answer _, _ = conn.Write([]byte{0x00}) _, _ = io.ReadAll(conn) }) client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) sendUntilAnswered(t, client, []byte("job"), answer) } // firstJobThen serves the first connection as a printer that answers the // ready request, reads the job and its confirmation request, writes // confirmation, then calls after with the connection, if not nil, and holds // it until the client closes it. Every later connection goes to later. func firstJobThen(t *testing.T, confirmation []byte, after, later func(net.Conn)) string { t.Helper() var conns atomic.Int32 return fakePrinter(t, func(conn net.Conn) { if conns.Add(1) == 1 { if answerReady(conn) != nil { return } if _, err := readJob(conn); err != nil { return } _, _ = conn.Write(confirmation) if after != nil { after(conn) } _, _ = io.ReadAll(conn) return } later(conn) }) } // A job's confirmation comes with an automatic status block's header, and // the block's last three bytes follow 50 ms later on whichever connection // is open. Send keeps the connection open until they come, so they are read // as the block's on that connection, and none is taken for an answer to the // next job's ready request, which the printer sends only later. func TestSendReadsAStatusBlockTailBeforeClosing(t *testing.T) { var current atomic.Pointer[net.Conn] answer := make(chan struct{}) addr := firstJobThen(t, []byte{0x00, 0x10}, func(conn net.Conn) { current.CompareAndSwap(nil, &conn) time.Sleep(50 * time.Millisecond) _, _ = (*current.Load()).Write([]byte{0x00, 0x00, 0x00}) }, func(conn net.Conn) { current.Store(&conn) if _, err := readJob(conn); err != nil { return } time.Sleep(300 * time.Millisecond) _, _ = conn.Write([]byte{0x00}) if _, err := readJob(conn); err != nil { return } <-answer _, _ = conn.Write([]byte{0x00}) _, _ = io.ReadAll(conn) }) client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) if err := client.Send(context.Background(), []byte("first"), nil); err != nil { t.Fatalf("first Send = %v", err) } sendUntilAnswered(t, client, []byte("second"), answer) } // A job's confirmation comes with an automatic status block's header, and // the rest of the block never comes, as when the printer is switched off. // The next connections start afresh: the next jobs' ready answers and the // status answers count. func TestSendForgetsAStatusBlockCutShort(t *testing.T) { var statusConns atomic.Bool addr := firstJobThen(t, []byte{0x00, 0x10}, nil, func(conn net.Conn) { if statusConns.Load() { req := make([]byte, 3) for { if _, err := io.ReadFull(conn, req); err != nil { return } _, _ = conn.Write([]byte{0x12}) } } if answerReady(conn) != nil { return } if _, err := readJob(conn); err != nil { return } _, _ = conn.Write([]byte{0x00}) _, _ = io.ReadAll(conn) }) client := printer.NewClient(addr, time.Second, 500*time.Millisecond, printer.Confirm(true)) if err := client.Send(context.Background(), []byte("first"), nil); err != nil { t.Fatalf("first Send = %v", err) } for i := 2; i <= 4; i++ { if err := client.Send(context.Background(), []byte("next"), nil); err != nil { t.Errorf("Send %d = %v, want nil: the printer answered and confirmed", i, err) } } statusConns.Store(true) if status, err := client.Status(context.Background()); err != nil || !status.Online { t.Errorf("Status = %+v, %v, want online", status, err) } } // A printer with its cover open sends an automatic status block saying so // and does not answer the ready request, whether or not the last job's // confirmation came with a header whose block was cut short. Nothing of // the next job is written, and Send fails. func TestSendToAPrinterReportingItsCoverOpen(t *testing.T) { for name, confirmation := range map[string][]byte{ "after a block cut short": {0x00, 0x10}, "after a plain answer": {0x00}, } { t.Run(name, func(t *testing.T) { written := make(chan []byte, 1) closeCover := make(chan struct{}) addr := firstJobThen(t, confirmation, nil, func(conn net.Conn) { if before, err := readJob(conn); err != nil || len(before) != 0 { written <- nil return } _, _ = conn.Write([]byte{0x38, 0x00, 0x00, 0x00}) job, err := readJob(conn) if err != nil { written <- nil return } written <- job <-closeCover _, _ = conn.Write([]byte{0x10, 0x00, 0x00, 0x00, 0x00}) _, _ = io.ReadAll(conn) }) client := printer.NewClient(addr, time.Second, 600*time.Millisecond, printer.Confirm(true)) if err := client.Send(context.Background(), []byte("first"), nil); err != nil { t.Fatalf("first Send = %v", err) } sent := make(chan error, 1) go func() { sent <- client.Send(context.Background(), []byte("second"), nil) }() select { case job := <-written: if job != nil { t.Errorf("printer with its cover open got %q", job) } case <-time.After(3 * time.Second): t.Fatal("fake printer saw neither a job nor a close") } close(closeCover) if err := <-sent; err == nil { t.Error("second Send = nil, want an error: the printer never answered") } }) } } // An answer owed to the last job's confirmation request comes just before // the ready wait's deadline, and the answer to the ready request just after // it. The deadline cuts the wait short, so the printer is not ready and // nothing is written; the late ready answer is never taken for the job's. func TestSendNotReadyWhenTheDeadlineCutsTheWait(t *testing.T) { var conns atomic.Int32 written := make(chan []byte, 1) addr := fakePrinter(t, func(conn net.Conn) { if conns.Add(1) == 1 { if answerReady(conn) != nil { return } _, _ = readJob(conn) _, _ = io.ReadAll(conn) return } if _, err := readJob(conn); err != nil { return } time.Sleep(560 * time.Millisecond) _, _ = conn.Write([]byte{0x00}) time.Sleep(60 * time.Millisecond) _, _ = conn.Write([]byte{0x00}) job, _ := io.ReadAll(conn) written <- job }) client := printer.NewClient(addr, time.Second, 600*time.Millisecond, printer.Confirm(true)) var unconfirmed *printer.UnconfirmedError if err := client.Send(context.Background(), []byte("first"), nil); !errors.As(err, &unconfirmed) { t.Fatalf("first Send = %v, want an UnconfirmedError", err) } called := false err := client.Send(context.Background(), []byte("second"), func() error { called = true; return nil }) if err == nil || errors.As(err, &unconfirmed) || called { t.Errorf("second Send = %v, beforeWrite called %v; want a plain error before beforeWrite", err, called) } if got := <-written; len(got) != 0 { t.Errorf("printer got % X after the ready request", got) } } // After the ready answer the printer sends an automatic status block every // 50 ms. Only answers keep the ready wait open, so Send writes the job and // returns on its confirmation, and a cancelled one returns at once. func TestSendOnALineFullOfStatusBlocks(t *testing.T) { addr := fakePrinter(t, func(conn net.Conn) { if answerReady(conn) != nil { return } stop := make(chan struct{}) defer close(stop) go func() { for { select { case <-stop: return case <-time.After(50 * time.Millisecond): if _, err := conn.Write([]byte{0x10, 0x00, 0x00, 0x00}); err != nil { return } } } }() if _, err := readJob(conn); err != nil { return } _, _ = conn.Write([]byte{0x00}) _, _ = io.ReadAll(conn) }) client := printer.NewClient(addr, time.Second, 700*time.Millisecond, printer.Confirm(true)) start := time.Now() if err := client.Send(context.Background(), []byte("job"), nil); err != nil { t.Errorf("Send = %v, want nil", err) } if took := time.Since(start); took > 500*time.Millisecond { t.Errorf("Send took %v", took) } ctx, cancel := context.WithCancel(context.Background()) time.AfterFunc(50*time.Millisecond, cancel) start = time.Now() err := client.Send(ctx, []byte("job"), func() error { return errors.New("beforeWrite called") }) if err == nil { t.Error("cancelled Send = nil") } if took := time.Since(start); took > 500*time.Millisecond { t.Errorf("cancelled Send took %v", took) } } // With Confirm, Send sends DLE EOT 1, GS a 0 and GS r 1, DLE EOT 1 again // once they are answered, then the job with GS a 0 and GS r 1 after it, and // nothing else. func TestSendWithConfirmSendsTheseBytes(t *testing.T) { received := make(chan []byte, 1) addr := fakePrinter(t, func(conn net.Conn) { var all []byte defer func() { received <- all }() for _, step := range []struct { read int answer []byte }{{9, []byte{0x12, 0x00}}, {3, []byte{0x12}}, {len("receipt") + 6, []byte{0x00}}} { buf := make([]byte, step.read) n, err := io.ReadFull(conn, buf) all = append(all, buf[:n]...) if err != nil { return } if _, err := conn.Write(step.answer); err != nil { return } } rest, _ := io.ReadAll(conn) all = append(all, rest...) }) client := printer.NewClient(addr, time.Second, time.Second, printer.Confirm(true)) if err := client.Send(context.Background(), []byte("receipt"), nil); err != nil { t.Fatalf("Send = %v", err) } want := []byte("\x10\x04\x01\x1Da\x00\x1Dr\x01\x10\x04\x01receipt\x1Da\x00\x1Dr\x01") if got := <-received; !bytes.Equal(got, want) { t.Errorf("printer got % X\nwant % X", got, want) } } // With Confirm, a printer that answers the ready request but reports // itself offline to DLE EOT 1 gets nothing of the job: Send returns a plain // error without calling beforeWrite. func TestSendToAnOfflinePrinter(t *testing.T) { rest := make(chan []byte, 1) addr := fakePrinter(t, func(conn net.Conn) { if _, err := readJob(conn); err != nil { rest <- nil return } _, _ = conn.Write([]byte{0x00}) req := make([]byte, 3) if _, err := io.ReadFull(conn, req); err != nil { rest <- nil return } _, _ = conn.Write([]byte{0x1A}) data, _ := io.ReadAll(conn) rest <- data }) client := printer.NewClient(addr, time.Second, time.Second, printer.Confirm(true)) called := false err := client.Send(context.Background(), []byte("receipt"), func() error { called = true; return nil }) var unconfirmed *printer.UnconfirmedError if err == nil || errors.As(err, &unconfirmed) || called { t.Errorf("Send = %v, beforeWrite called %v; want a plain error before beforeWrite", err, called) } if got := <-rest; len(got) != 0 { t.Errorf("printer got % X after DLE EOT 1", got) } } // tailBoard is a fake printer whose output goes to whichever connection is // open, as a print server board can route it. The first connection goes to // first, every later one to later. The tail func first gets writes bytes to // the next connection once it is accepted, or after 90 ms to the first, so // a block's last bytes always come within 100 ms of its header. func tailBoard(t *testing.T, first func(conn net.Conn, tail func([]byte)), later func(net.Conn)) string { t.Helper() var conns atomic.Int32 next := make(chan net.Conn, 1) return fakePrinter(t, func(conn net.Conn) { if conns.Add(1) == 1 { first(conn, func(b []byte) { select { case c := <-next: _, _ = c.Write(b) case <-time.After(90 * time.Millisecond): _, _ = conn.Write(b) } }) _, _ = io.ReadAll(conn) return } select { case next <- conn: default: } later(conn) }) } // coverOpen serves a connection as a printer with its cover open: it // answers nothing, and reports on written everything it was sent. func coverOpen(written chan<- []byte) func(net.Conn) { return func(conn net.Conn) { data, _ := io.ReadAll(conn) written <- data } } // expectNoJob checks that Send failed and that the printer got nothing on // written but the requests Send asks before a job. func expectNoJob(t *testing.T, written <-chan []byte, err error) { t.Helper() select { case got := <-written: for _, request := range [][]byte{ escpos.AutomaticStatusOff(), escpos.TransmitStatusRequest(), escpos.StatusRequest(escpos.StatusPrinter), } { got = bytes.ReplaceAll(got, request, nil) } if len(got) != 0 { t.Errorf("printer with its cover open got %q; Send = %v", got, err) } case <-time.After(3 * time.Second): t.Fatal("the fake printer saw no second connection end") } if err == nil { t.Error("Send = nil, though the printer never answered") } } // The cover opens as Status reads its last answer: an automatic status // block's header follows that answer, and its last bytes come 90 ms later. // Status reads them before it closes the connection, so the next job's // connection, on which the printer answers nothing until the job is // written, gets none, and nothing of the job is written. func TestStatusReadsTheBlockAfterItsLastAnswer(t *testing.T) { for name, later := range map[string]func(chan<- []byte) func(net.Conn){ "the cover stays open": coverOpen, "the cover closes once the job is written": func(written chan<- []byte) func(net.Conn) { return func(conn net.Conn) { if _, err := readJob(conn); err != nil { written <- nil return } job, err := readJob(conn) written <- job if err != nil { return } _, _ = conn.Write([]byte{0x00}) _, _ = io.ReadAll(conn) } }, } { t.Run(name, func(t *testing.T) { written := make(chan []byte, 1) addr := tailBoard(t, func(conn net.Conn, tail func([]byte)) { req := make([]byte, 3) for kind := 1; kind <= 4; kind++ { if _, err := io.ReadFull(conn, req); err != nil { return } answer := []byte{0x12} if kind == 4 { answer = []byte{0x12, 0x38} } _, _ = conn.Write(answer) } tail([]byte{0x00, 0x00, 0x00}) }, later(written)) client := printer.NewClient(addr, time.Second, 400*time.Millisecond, printer.Confirm(true)) if status, err := client.Status(context.Background()); err != nil { t.Fatalf("Status = %+v, %v", status, err) } err := client.Send(context.Background(), []byte("second"), nil) expectNoJob(t, written, err) }) } } // An automatic status block's header comes on one connection and its last // bytes on the next, which reaches a printer with its cover open. They look // like answers to the ready request, but the printer does not answer DLE // EOT 1 as online, so nothing of the job is written. func TestSendToACoverOpenPrinterAfterABlockCutShort(t *testing.T) { tests := []struct { name string writeTimeout time.Duration first func(conn net.Conn, tail func([]byte)) firstSend func(error) bool }{ { name: "a header just after the confirmation", writeTimeout: 400 * time.Millisecond, first: func(conn net.Conn, tail func([]byte)) { if answerReady(conn) != nil { return } if _, err := readJob(conn); err != nil { return } _, _ = conn.Write([]byte{0x00}) time.Sleep(5 * time.Millisecond) _, _ = conn.Write([]byte{0x38}) tail([]byte{0x00, 0x00, 0x00}) }, firstSend: func(err error) bool { return err == nil }, }, { name: "a header just before the confirmation deadline", writeTimeout: 500 * time.Millisecond, first: func(conn net.Conn, tail func([]byte)) { if answerReady(conn) != nil { return } if _, err := readJob(conn); err != nil { return } time.Sleep(450 * time.Millisecond) _, _ = conn.Write([]byte{0x38}) tail([]byte{0x00, 0x00, 0x00}) }, firstSend: func(err error) bool { var unconfirmed *printer.UnconfirmedError return errors.As(err, &unconfirmed) }, }, { name: "the confirmation and a header just before the write deadline", writeTimeout: 600 * time.Millisecond, first: func(conn net.Conn, tail func([]byte)) { if answerReady(conn) != nil { return } if _, err := readJob(conn); err != nil { return } time.Sleep(520 * time.Millisecond) _, _ = conn.Write([]byte{0x00, 0x38}) tail([]byte{0x00, 0x00, 0x00}) }, firstSend: func(err error) bool { return err == nil }, }, { name: "a header just before the ready deadline", writeTimeout: 500 * time.Millisecond, first: func(conn net.Conn, tail func([]byte)) { if _, err := readJob(conn); err != nil { return } time.Sleep(450 * time.Millisecond) _, _ = conn.Write([]byte{0x38}) tail([]byte{0x00, 0x03, 0x00}) }, firstSend: func(err error) bool { return err != nil }, }, { name: "a whole block after the confirmation", writeTimeout: 400 * time.Millisecond, first: func(conn net.Conn, _ func([]byte)) { if answerReady(conn) != nil { return } if _, err := readJob(conn); err != nil { return } _, _ = conn.Write([]byte{0x00, 0x38, 0x00, 0x00, 0x00}) }, firstSend: func(err error) bool { return err == nil }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { written := make(chan []byte, 1) addr := tailBoard(t, tt.first, coverOpen(written)) client := printer.NewClient(addr, time.Second, tt.writeTimeout, printer.Confirm(true)) if err := client.Send(context.Background(), []byte("first"), nil); !tt.firstSend(err) { t.Fatalf("first Send = %v", err) } err := client.Send(context.Background(), []byte("second"), nil) expectNoJob(t, written, err) }) } } // Owed answers with an automatic status block among them, whole or split // across reads, are all dropped, and the job waits for its own // confirmation. func TestSendDropsOwedAnswersAroundAStatusBlock(t *testing.T) { for name, seq := range map[string][][]byte{ "a whole block": {{0x00}, {0x10, 0x00, 0x00, 0x00}, {0x00}, {0x00}}, "a split block": {{0x00}, {0x10}, {0x00, 0x00, 0x00}, {0x00}, {0x00}}, "a header with an owed answer": {{0x00, 0x10}, {0x00}, {0x00, 0x00}, {0x00}}, } { t.Run(name, func(t *testing.T) { answer := make(chan struct{}) addr := fakePrinter(t, func(conn net.Conn) { if _, err := readJob(conn); err != nil { return } for _, b := range seq { _, _ = conn.Write(b) time.Sleep(25 * time.Millisecond) } if _, err := readJob(conn); err != nil { return } <-answer _, _ = conn.Write([]byte{0x00}) _, _ = io.ReadAll(conn) }) client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) sendUntilAnswered(t, client, []byte("job"), answer) }) } } // readFence reads the DLE EOT 1, GS a 0 and GS r 1 that Send sends at the // start of a connection. func readFence(conn net.Conn) error { want := slices.Concat(escpos.StatusRequest(escpos.StatusPrinter), escpos.AutomaticStatusOff(), escpos.TransmitStatusRequest()) got := make([]byte, len(want)) if _, err := io.ReadFull(conn, got); err != nil { return err } if !bytes.Equal(got, want) { return fmt.Errorf("got % X at the start of the connection, want % X", got, want) } return nil } // An answer owed to a request the printer ran earlier comes at the start of // the connection, and the requests reach the printer 150 ms later, as after // a lost segment. The answer comes before the fence's, so it is dropped, // and the job waits for its own confirmation, whether the ready answer // comes with the fence's or 150 ms after it. func TestSendDropsAnOwedAnswerBeforeTheFence(t *testing.T) { for name, readyAfter := range map[string]time.Duration{ "the ready answer with the fence's": 0, "the ready answer 150 ms later": 150 * time.Millisecond, } { t.Run(name, func(t *testing.T) { answer := make(chan struct{}) addr := fakePrinter(t, func(conn net.Conn) { _, _ = conn.Write([]byte{0x00}) time.Sleep(150 * time.Millisecond) if readFence(conn) != nil { return } _, _ = conn.Write([]byte{0x12}) time.Sleep(readyAfter) _, _ = conn.Write([]byte{0x00}) if _, err := readJob(conn); err != nil { return } <-answer _, _ = conn.Write([]byte{0x00}) _, _ = io.ReadAll(conn) }) client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) sendUntilAnswered(t, client, []byte("job"), answer) }) } } // An owed answer at the start of the connection, while the cover is open; // the cover closes, and the printer answers every DLE EOT 1 at once as // online but runs GS r 1 only 300 ms later, as after a feed and cut at // cover close. The owed answer comes before the fence's and is dropped, so // the job waits for the late ready answer and then for its own // confirmation. func TestSendAfterAnOwedAnswerAndACoverClosing(t *testing.T) { answer := make(chan struct{}) addr := fakePrinter(t, func(conn net.Conn) { _, _ = conn.Write([]byte{0x00}) if readFence(conn) != nil { return } _, _ = conn.Write([]byte{0x12}) ready := time.AfterFunc(300*time.Millisecond, func() { _, _ = conn.Write([]byte{0x00}) }) defer ready.Stop() if _, err := readJob(conn); err != nil { return } <-answer _, _ = conn.Write([]byte{0x00}) _, _ = io.ReadAll(conn) }) client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) sendUntilAnswered(t, client, []byte("job"), answer) } // A block's header comes just after a job's confirmation and its last bytes // begin the next connection, ahead of the fence's answer. The printer is // online but answers the ready request only 300 ms later, still busy. The // last bytes are dropped with everything before the fence, so the job waits // for the ready answer, and that answer never confirms it. func TestSendDropsABlockTailBeforeTheFence(t *testing.T) { answer := make(chan struct{}) addr := tailBoard(t, func(conn net.Conn, tail func([]byte)) { if answerReady(conn) != nil { return } if _, err := readJob(conn); err != nil { return } _, _ = conn.Write([]byte{0x00}) time.Sleep(5 * time.Millisecond) _, _ = conn.Write([]byte{0x38}) tail([]byte{0x00, 0x00, 0x00}) }, func(conn net.Conn) { time.Sleep(20 * time.Millisecond) if readFence(conn) != nil { return } _, _ = conn.Write([]byte{0x12}) ready := time.AfterFunc(300*time.Millisecond, func() { _, _ = conn.Write([]byte{0x00}) }) defer ready.Stop() if _, err := readJob(conn); err != nil { return } <-answer _, _ = conn.Write([]byte{0x00}) _, _ = io.ReadAll(conn) }) client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) if err := client.Send(context.Background(), []byte("first"), nil); err != nil { t.Fatalf("first Send = %v", err) } sendUntilAnswered(t, client, []byte("second"), answer) } // The answer owed to an unconfirmed job comes after the fence's; then the // cover opens before the ready request runs, and the printer answers the // online check as offline. Nothing of the job is written. func TestSendAfterAnOwedAnswerAndACoverOpening(t *testing.T) { rest := make(chan []byte, 1) var conns atomic.Int32 addr := fakePrinter(t, func(conn net.Conn) { if conns.Add(1) == 1 { if answerReady(conn) != nil { return } _, _ = readJob(conn) _, _ = io.ReadAll(conn) return } if readFence(conn) != nil { rest <- nil return } _, _ = conn.Write([]byte{0x12, 0x00}) req := make([]byte, 3) if _, err := io.ReadFull(conn, req); err != nil { rest <- nil return } _, _ = conn.Write([]byte{0x3A}) data, _ := io.ReadAll(conn) rest <- data }) client := printer.NewClient(addr, time.Second, 500*time.Millisecond, printer.Confirm(true)) var unconfirmed *printer.UnconfirmedError if err := client.Send(context.Background(), []byte("first"), nil); !errors.As(err, &unconfirmed) { t.Fatalf("first Send = %v, want an UnconfirmedError", err) } err := client.Send(context.Background(), []byte("second"), nil) if got := <-rest; len(got) != 0 { t.Errorf("printer with its cover open got %q", got) } if err == nil { t.Error("second Send = nil, want an error: the printer reported itself offline") } } // After the ready answer the printer floods bytes like answers to GS r and // never answers the online check: Send gives up within its bounds, with // nothing of the job written. func TestSendBoundedByAFloodDuringTheOnlineCheck(t *testing.T) { rest := make(chan []byte, 1) addr := fakePrinter(t, func(conn net.Conn) { if readFence(conn) != nil { rest <- nil return } _, _ = conn.Write([]byte{0x12, 0x00}) online := make([]byte, 3) if _, err := io.ReadFull(conn, online); err != nil { rest <- nil return } stop := make(chan struct{}) go func() { for { select { case <-stop: return default: } if _, err := conn.Write([]byte{0x00}); err != nil { return } time.Sleep(time.Millisecond) } }() data, _ := io.ReadAll(conn) close(stop) rest <- data }) client := printer.NewClient(addr, time.Second, 5*time.Second, printer.Confirm(true)) start := time.Now() err := client.Send(context.Background(), []byte("job"), nil) if took := time.Since(start); err == nil || took > 6*time.Second { t.Errorf("Send = %v after %v, want an error within 6 s", err, took) } if got := bytes.ReplaceAll(<-rest, escpos.StatusRequest(escpos.StatusPrinter), nil); len(got) != 0 { t.Errorf("printer got % X after the online check", got) } } // With Confirm off, Send writes the job's bytes alone, whatever the // printer sends back. func TestSendWithConfirmOffSendsOnlyTheJob(t *testing.T) { job := []byte("\x1b@receipt\x1dr\x01") received := make(chan []byte, 1) addr := fakePrinter(t, func(conn net.Conn) { got := make([]byte, len(job)) n, _ := io.ReadFull(conn, got) _, _ = conn.Write([]byte{0x00, 0x10, 0x00, 0x00, 0x00, 0x12}) extra, _ := io.ReadAll(conn) received <- append(got[:n], extra...) }) client := printer.NewClient(addr, time.Second, time.Second, printer.Confirm(false)) if err := client.Send(context.Background(), job, nil); err != nil { t.Fatal(err) } if got := <-received; !bytes.Equal(got, job) { t.Errorf("printer got % X", got) } } // Status against a printer that sends an automatic status block every 5 ms, // before and after its answers, returns within its bounds. func TestStatusBoundedByAFloodOfBlocks(t *testing.T) { addr := fakePrinter(t, func(conn net.Conn) { stop := make(chan struct{}) defer close(stop) go func() { for { select { case <-stop: return case <-time.After(5 * time.Millisecond): if _, err := conn.Write([]byte{0x10, 0x00, 0x00, 0x00}); err != nil { return } } } }() req := make([]byte, 3) for { if _, err := io.ReadFull(conn, req); err != nil { return } _, _ = conn.Write([]byte{0x12}) } }) start := time.Now() status, err := printer.NewClient(addr, time.Second, time.Second).Status(context.Background()) if took := time.Since(start); err != nil || !status.Online || took > time.Second { t.Errorf("Status = %+v, %v after %v, want online within 1 s", status, err, took) } } // sendResidual sends data as sendUntilAnswered does, but only logs a Send // that returns before answer is closed: the case is one the client leaves // open, and the test shows how it ends. func sendResidual(t *testing.T, client *printer.Client, data []byte, answer chan struct{}) { t.Helper() sent := make(chan error, 1) go func() { sent <- client.Send(context.Background(), data, nil) }() select { case err := <-sent: close(answer) t.Logf("RESIDUAL: Send returned %v before the printer confirmed the job", err) return case <-time.After(500 * time.Millisecond): } close(answer) t.Logf("Send = %v once the printer confirmed the job", <-sent) } // A late answer to an earlier connection's DLE EOT and an owed answer to // GS r reach this connection at once, while its own requests are held back // 300 ms, as by a lost segment. The late answer stands in for the fence and // the owed one for the ready answer; then this connection's own answers // come, in either order, or a GS r answer comes during the online check. // An answer to GS r after the answers settled makes the printer not ready, // and nothing of the job is written. func TestSendRefusesAnAnswerAfterAFakeFence(t *testing.T) { for name, answers := range map[string][]byte{ "fence, ready, online": {0x12, 0x00, 0x12}, "fence, online, ready": {0x12, 0x12, 0x00}, "an answer during the online check": {0x00, 0x12}, } { t.Run(name, func(t *testing.T) { rest := make(chan []byte, 1) addr := fakePrinter(t, func(conn net.Conn) { _, _ = conn.Write([]byte{0x12, 0x00}) time.Sleep(300 * time.Millisecond) if readFence(conn) != nil { rest <- nil return } online := make([]byte, 3) if _, err := io.ReadFull(conn, online); err != nil { rest <- nil return } _, _ = conn.Write(answers) data, _ := io.ReadAll(conn) rest <- data }) client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) called := false err := client.Send(context.Background(), []byte("job"), func() error { called = true; return nil }) var unconfirmed *printer.UnconfirmedError if err == nil || errors.As(err, &unconfirmed) || called { t.Errorf("Send = %v, beforeWrite called %v; want a plain error before beforeWrite", err, called) } if got := <-rest; len(got) != 0 { t.Errorf("printer got % X after the online check", got) } }) } } // A late answer to an earlier connection's DLE EOT alone, with no answer to // GS r owed after it, stands in for the fence harmlessly: nothing is // counted before this connection's own ready answer. func TestSendAfterALateFenceAnswerAlone(t *testing.T) { answer := make(chan struct{}) addr := fakePrinter(t, func(conn net.Conn) { _, _ = conn.Write([]byte{0x12}) time.Sleep(300 * time.Millisecond) if readFence(conn) != nil { return } _, _ = conn.Write([]byte{0x12, 0x00}) if _, err := readJob(conn); err != nil { return } <-answer _, _ = conn.Write([]byte{0x00}) _, _ = io.ReadAll(conn) }) client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) sendUntilAnswered(t, client, []byte("job"), answer) } // Job A is unconfirmed, the printer still printing it. On B's connection // the printer answers the fence at once and, once A has printed, A's owed // answer and B's ready answer back to back. Both are dropped, and B waits // for its own confirmation. func TestSendAfterAnUnconfirmedJobStillPrinting(t *testing.T) { answer := make(chan struct{}) var conns atomic.Int32 addr := fakePrinter(t, func(conn net.Conn) { if conns.Add(1) == 1 { if answerReady(conn) != nil { return } _, _ = readJob(conn) _, _ = io.ReadAll(conn) return } if readFence(conn) != nil { return } _, _ = conn.Write([]byte{0x12}) time.Sleep(400 * time.Millisecond) _, _ = conn.Write([]byte{0x00}) time.Sleep(2 * time.Millisecond) _, _ = conn.Write([]byte{0x00}) if _, err := readJob(conn); err != nil { return } <-answer _, _ = conn.Write([]byte{0x00}) _, _ = io.ReadAll(conn) }) client := printer.NewClient(addr, time.Second, 500*time.Millisecond, printer.Confirm(true)) var unconfirmed *printer.UnconfirmedError if err := client.Send(context.Background(), []byte("A"), nil); !errors.As(err, &unconfirmed) { t.Fatalf("first Send = %v, want an UnconfirmedError", err) } client = printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) sendUntilAnswered(t, client, []byte("B"), answer) } // The case the client leaves open: an answer still queued in the printer // when the fence arrived, then a pause of 250 ms, while the printer answers // DLE EOT 1 as online, before the ready answer. The pause outlasts the // settle and the read after the online check, so the ready answer // confirms the job before it has printed. func TestSendResidualPauseBetweenQueuedAnswers(t *testing.T) { answer := make(chan struct{}) addr := fakePrinter(t, func(conn net.Conn) { if readFence(conn) != nil { return } _, _ = conn.Write([]byte{0x12}) time.Sleep(50 * time.Millisecond) _, _ = conn.Write([]byte{0x00}) ready := time.AfterFunc(250*time.Millisecond, func() { _, _ = conn.Write([]byte{0x00}) }) defer ready.Stop() if _, err := readJob(conn); err != nil { return } <-answer _, _ = conn.Write([]byte{0x00}) _, _ = io.ReadAll(conn) }) client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) sendResidual(t, client, []byte("job"), answer) } // The fence's answer comes inside an automatic status block on this // connection, should a printer ever put one between a block's bytes. It is // read as a block byte, the fence is missed, and Send gives up at the // deadline with nothing of the job written. func TestSendFenceAnswerInsideABlock(t *testing.T) { rest := make(chan []byte, 1) addr := fakePrinter(t, func(conn net.Conn) { if readFence(conn) != nil { rest <- nil return } _, _ = conn.Write([]byte{0x10, 0x00, 0x12, 0x00, 0x00}) time.Sleep(20 * time.Millisecond) _, _ = conn.Write([]byte{0x00}) data, _ := io.ReadAll(conn) rest <- data }) client := printer.NewClient(addr, time.Second, 500*time.Millisecond, printer.Confirm(true)) if err := client.Send(context.Background(), []byte("job"), nil); err == nil { t.Error("Send = nil, want an error: the fence was never seen") } if got := <-rest; len(got) != 0 { t.Errorf("printer got % X after the fence request", got) } } // The case the client leaves open, should a printer ever put the fence's // answer between the last bytes of a block whose header went to an // earlier connection: the bytes after it count as answers, and the ready // answer, 300 ms later, confirms the job before it has printed. func TestSendResidualFenceAnswerBetweenTailBytes(t *testing.T) { answer := make(chan struct{}) addr := fakePrinter(t, func(conn net.Conn) { if readFence(conn) != nil { return } _, _ = conn.Write([]byte{0x00, 0x12, 0x00, 0x00}) ready := time.AfterFunc(300*time.Millisecond, func() { _, _ = conn.Write([]byte{0x00}) }) defer ready.Stop() if _, err := readJob(conn); err != nil { return } <-answer _, _ = conn.Write([]byte{0x00}) _, _ = io.ReadAll(conn) }) client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) sendResidual(t, client, []byte("job"), answer) } // A printer that never answers the fence but floods bytes that are not // answers to DLE EOT: Send gives up at its deadline, and a cancellation // stops it at once. func TestSendBoundedByAFloodBeforeTheFence(t *testing.T) { addr := fakePrinter(t, func(conn net.Conn) { if readFence(conn) != nil { return } go func() { _, _ = io.Copy(io.Discard, conn) }() chunk := []byte{0x00, 0x10, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00} for { if _, err := conn.Write(chunk); err != nil { return } } }) client := printer.NewClient(addr, time.Second, 500*time.Millisecond, printer.Confirm(true)) start := time.Now() err := client.Send(context.Background(), []byte("job"), nil) if took := time.Since(start); err == nil || took > 700*time.Millisecond { t.Errorf("Send = %v after %v, want an error within 700 ms", err, took) } ctx, cancel := context.WithCancel(context.Background()) time.AfterFunc(100*time.Millisecond, cancel) client = printer.NewClient(addr, time.Second, 3*time.Second, printer.Confirm(true)) start = time.Now() err = client.Send(ctx, []byte("job"), nil) if took := time.Since(start); !errors.Is(err, context.Canceled) || took > 300*time.Millisecond { t.Errorf("cancelled Send = %v after %v, want context.Canceled within 300 ms", err, took) } } // After the fence the printer sends a byte like an answer to GS r every // 20 ms, so the answers never settle; a cancellation stops the wait at // once. func TestSendCancelledDuringSteadyAnswers(t *testing.T) { addr := fakePrinter(t, func(conn net.Conn) { if readFence(conn) != nil { return } go func() { _, _ = io.Copy(io.Discard, conn) }() if _, err := conn.Write([]byte{0x12}); err != nil { return } for { if _, err := conn.Write([]byte{0x00}); err != nil { return } time.Sleep(20 * time.Millisecond) } }) var worst time.Duration for i := range 10 { after := time.Duration(50+i*7) * time.Millisecond client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) ctx, cancel := context.WithCancel(context.Background()) time.AfterFunc(after, cancel) start := time.Now() _ = client.Send(ctx, []byte("job"), nil) cancel() worst = max(worst, time.Since(start)-after) } if worst > 150*time.Millisecond { t.Errorf("a cancellation took %v to stop the wait", worst) } } // After the fence the printer floods bytes like answers to GS r. A // cancellation stops the wait at once, even one that lands between a read // and the reset of the read deadline after it. func TestSendCancelledDuringAnswerFlood(t *testing.T) { addr := fakePrinter(t, func(conn net.Conn) { if readFence(conn) != nil { return } go func() { _, _ = io.Copy(io.Discard, conn) }() if _, err := conn.Write([]byte{0x12}); err != nil { return } chunk := make([]byte, 16) for { if _, err := conn.Write(chunk); err != nil { return } } }) for i := range 5 { client := printer.NewClient(addr, time.Second, 2*time.Second, printer.Confirm(true)) ctx, cancel := context.WithCancel(context.Background()) time.AfterFunc(time.Duration(50+i*7)*time.Millisecond, cancel) start := time.Now() err := client.Send(ctx, []byte("job"), nil) cancel() if took := time.Since(start); !errors.Is(err, context.Canceled) || took > 500*time.Millisecond { t.Errorf("trial %d: Send = %v after %v, want context.Canceled within 500 ms", i, err, took) } } } // A dial that fails never calls beforeWrite. func TestSendDialFailureSkipsBeforeWrite(t *testing.T) { ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } addr := ln.Addr().String() _ = ln.Close() client := printer.NewClient(addr, 500*time.Millisecond, time.Second) called := false if err := client.Send(context.Background(), []byte("x"), func() error { called = true; return nil }); err == nil { t.Fatal("expected a connection error") } if called { t.Error("beforeWrite ran although the dial failed") } } func TestSendUnreachable(t *testing.T) { ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } addr := ln.Addr().String() _ = ln.Close() // nothing listens here now client := printer.NewClient(addr, 500*time.Millisecond, time.Second) if err := client.Send(context.Background(), []byte("x"), nil); err == nil { t.Fatal("expected a connection error") } } func TestSendRespectsCancelledContextWhileBusy(t *testing.T) { accepted := make(chan struct{}, 1) release := make(chan struct{}) addr := fakePrinter(t, func(conn net.Conn) { accepted <- struct{}{} <-release _, _ = io.Copy(io.Discard, conn) }) t.Cleanup(func() { close(release) }) client := printer.NewClient(addr, time.Second, 5*time.Second) // Hold the single connection slot with a status query that never gets // an answer, then try to send with a short deadline. The client takes // the slot before it dials, so once the printer has accepted the status // query's connection the slot is held. go func() { _, _ = client.Status(context.Background()) }() select { case <-accepted: case <-time.After(5 * time.Second): t.Fatal("the status query never connected") } ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) defer cancel() if err := client.Send(ctx, []byte("x"), nil); !errors.Is(err, context.DeadlineExceeded) { t.Errorf("err = %v, want context.DeadlineExceeded", err) } } // 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) { 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]]}) } }) client := printer.NewClient(addr, time.Second, time.Second) status, err := client.Status(context.Background()) if err != nil { t.Fatal(err) } if want := (escpos.Status{Online: true, PaperNearEnd: true}); status != want { t.Errorf("status = %+v, want %+v", status, want) } } // A printer that answers DLE EOT with bytes that are not DLE EOT answers // gets ErrStatusUnsupported without Status waiting out its timeout: at // once for a byte that fits no answer, and within 100 ms for one that // looks like an answer to GS r, which a late answer could be. func TestStatusOnAnswersThatAreNotRealTime(t *testing.T) { for name, tt := range map[string]struct { answer byte within time.Duration }{ "a byte like a GS r answer": {0x00, 500 * time.Millisecond}, "a byte that fits no answer": {0x80, 80 * time.Millisecond}, } { t.Run(name, func(t *testing.T) { addr := statusPrinter(t, map[byte]byte{1: tt.answer, 2: tt.answer, 3: tt.answer, 4: tt.answer}) start := time.Now() _, err := printer.NewClient(addr, time.Second, time.Second).Status(context.Background()) if took := time.Since(start); !errors.Is(err, printer.ErrStatusUnsupported) || took > tt.within { t.Errorf("Status = %v after %v, want ErrStatusUnsupported within %v", err, took, tt.within) } }) } } // A late answer to an earlier GS r 1 and an automatic status block, sent // before the answers to DLE EOT, are passed over. func TestStatusSkipsStrayBytes(t *testing.T) { addr := fakePrinter(t, func(conn net.Conn) { _, _ = conn.Write([]byte{0x00, 0x10, 0x00, 0x00, 0x00}) req := make([]byte, 3) for { if _, err := io.ReadFull(conn, req); err != nil { return } _, _ = conn.Write([]byte{0x12}) } }) status, err := printer.NewClient(addr, time.Second, time.Second).Status(context.Background()) if err != nil { t.Fatal(err) } if want := (escpos.Status{Online: true}); status != want { t.Errorf("status = %+v, want %+v", status, want) } } func TestStatusUnsupported(t *testing.T) { addr := fakePrinter(t, func(conn net.Conn) { _, _ = io.Copy(io.Discard, conn) // a printer that never answers }) client := printer.NewClient(addr, time.Second, time.Second) // 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. It answers only // once the test is over, after the caller's deadline has passed. late := make(chan struct{}) t.Cleanup(func() { close(late) }) addr := fakePrinter(t, func(conn net.Conn) { req := make([]byte, 3) for { if _, err := io.ReadFull(conn, req); err != nil { return } <-late _, _ = 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) } }