- Printing
- Android
- Reliability
Printing in a kitchen: ESC/POS, KOTs and an Android print bridge
A kitchen order ticket that does not print is a dish that does not get cooked. Kitchen printers live on flaky Bluetooth links, behind consumer routers, next to fryers, and get switched off at night. Cloud printing has to cope with all of that without a person standing over it. This is how ours works.
A queue per printer
Fravolo never pushes bytes to a printer from the cloud. Printers sit on restaurant networks that we cannot — and should not — reach into. Instead, every printer has a queue of jobs on the server, and something on the restaurant’s side pulls from it. That something is one of three things:
- The Android app, which talks to printers over Bluetooth, USB or the LAN and runs as a background service.
- A small print bridge — a single Go binary for Windows, macOS or a Raspberry Pi — that sits on the LAN and prints to network printers.
- A browser print station: a Chrome tab in kiosk-printing mode that prints whatever arrives, for restaurants with a PC and a USB printer.
All three connect outwards to the API. The bridge and the Android app authenticate with a device key that is shown once at pairing, stored only as a hash, bound to one restaurant and outlet, and revocable; the browser station uses the signed-in staff session. Nothing opens a port in the restaurant.
What prints where
Each printer says what it is for: kitchen tickets, bills, or both, and optionally which menu categories it handles — tandoor, bar, desserts. When a KOT is sent, it becomes one job per kitchen printer, each with only the lines that printer claims. Bills go to bill printers, and a new online order prints a slip at the counter so nobody misses it even with the alert muted.
One rule here came straight from a real kitchen: a dish no station claims prints on every kitchen printer. Two slips are a minor annoyance; a dish nobody cooks is a refund.
A job stores the finished slip — a list of typed rows (text, label-and-amount pairs, columns, rules, gaps and QR codes) with centring, bold, large and inverse flags — not a reference to the order. What was sent to the kitchen is what prints, even if the order is edited a second later, and a reprint is the same slip.
Claim, lease, confirm
A client claims the oldest waiting job for the printers it serves with a single atomic find-and-update that marks it sent, records who claimed it and when, and counts the attempt. It then prints and reports done or failed. Only the claimer can do either.
The important part is what counts as “waiting”. A job that was claimed but never confirmed becomes claimable again after thirty seconds. That is a lease, expressed as nothing more than a query:
// waiting matches jobs a client may take: queued and due, or claimed
// so long ago that the claimer must have died. That is the lease.
func waiting(printers bson.A, now time.Time) bson.M {
return bson.M{"printer_id": bson.M{"$in": printers}, "$or": bson.A{
bson.M{"status": JobQueued, "not_before": bson.M{"$lte": now}},
bson.M{"status": JobSent, "claimed_at": bson.M{"$lt": now.Add(-claimTimeout)}},
}}
}
func (s *Service) Claim(ctx context.Context, claimer string, printers []Printer) (*Claimed, error) {
// ... mark the printers as seen; clear any "not printing" alert ...
for range maxAttempts + 1 {
var j Job
err := s.db.On(ctx, "print_jobs").FindOneAndUpdate(ctx, waiting(ids, now),
bson.M{"$set": bson.M{"status": JobSent, "claimed_by": claimer, "claimed_at": now},
"$inc": bson.M{"attempts": 1}},
options.FindOneAndUpdate().SetSort(bson.D{{Key: "created_at", Value: 1}}),
).Decode(&j)
// ... a job past its attempts is failed and the loop takes the next ...
}
}That gives at-least-once printing. A phone that loses Wi-Fi after printing but before confirming will cause one duplicate slip thirty seconds later. A phone that dies mid-print will not lose the ticket. In a kitchen that is exactly the right way round.
A failure re-queues the job with a growing delay. Every claim counts as an attempt, including ones whose lease simply expired, so a job that keeps being claimed and never confirmed is eventually marked failed — with a reason — and an owner or manager can retry it from the printers screen. Jobs expire from the database after a week through a TTL index.
Long-polling without holding a job
Clients wait for work with a long poll of up to twenty seconds. The subtle design choice is what the server does when work arrives during the wait: it answers “ready” without handing over the job, and the client immediately claims with a fresh request.
func (h *Handler) claim(c *fiber.Ctx) error {
if job, err := h.svc.Claim(ctx, printers, device); err == nil {
return c.JSON(job) // work was already waiting
}
deadline := time.Now().Add(clampWait(c.QueryInt("wait"))) // at most 20 s
for time.Now().Before(deadline) {
time.Sleep(pollEvery)
if h.svc.Ready(ctx, printers) {
// Don't hand the job over on a connection that may be dead.
return c.JSON(fiber.Map{"ready": true})
}
}
return c.SendStatus(fiber.StatusNoContent)
}Why the extra round trip? A connection that has been open for fifteen seconds over restaurant Wi-Fi may already be dead, and the server cannot tell. If it put a job on that connection, the job would sit leased to a client that never saw it until the lease expired. Answering “ready” costs one request; it means a job is only ever handed over on a request the client has just made.
The bridge and the app back off when the server is unreachable. The app stops for good when its key is revoked; the bridge keeps asking, slowly, until it is paired again; the station stops when its sign-in ends. The Android service restarts itself after a reboot or an app update.
Noticing a dead printer
Every claim request marks the printer as recently seen. A job in the one-minute loop — like every job there, on its own goroutine under a deadline — looks for printers with jobs waiting longer than a few minutes, publishes printer.stuck on the live bus and pushes it to the owner, managers, the counter and the kitchen, on devices that asked for printer alerts. The alert has a cooldown and stops after a few repeats, so a printer switched off for the night does not page anyone until morning, and the next claim request from that printer’s device resets it.
One slip, three renderers
ESC/POS text
ESC/POS is the command language almost every thermal receipt printer speaks: a handful of escape sequences for initialise, alignment, bold, double size, inverse, feed and cut, plus the printer’s own QR encoder. Our Go encoder for the bridge — with a Kotlin port in the Android app for its text mode — is a short table of those commands and a loop over laid-out lines: 48 columns for 80 mm paper and 32 for 58 mm, large text taking half the width, centring done with spaces, and the whole slip repeated per copy.
var (
cmdInit = []byte{0x1b, 0x40} // ESC @
cmdCodePage = []byte{0x1b, 0x74, 0x00} // ESC t 0: PC437
cmdBoldOn = []byte{0x1b, 0x45, 0x01} // ESC E 1
cmdBigOn = []byte{0x1d, 0x21, 0x11} // GS ! 0x11: double width and height
cmdInvertOn = []byte{0x1d, 0x42, 0x01} // GS B 1
cmdFeedCut = []byte{0x1b, 0x64, 0x04, 0x1d, 0x56, 0x42, 0x00} // feed 4, partial cut
)
lines := Layout(asciiRows, Chars(paperMM)) // 48 or 32 columns
buf.Write(cmdInit)
buf.Write(cmdCodePage)
for _, l := range lines {
if l.Bold { buf.Write(cmdBoldOn) }
if l.Big { buf.Write(cmdBigOn) }
if l.Invert { buf.Write(cmdInvertOn) }
buf.WriteString(l.Text + "
")
// ... and switched off again after the line ...
}
buf.Write(cmdFeedCut)The catch is the character set. Most printers ship with a Western code page and no Indic glyphs, so text mode is ASCII only: the rupee sign becomes “Rs.”, smart quotes become straight ones, and anything else becomes a question mark. That is fine for “2 × Paneer Tikka”. It is not fine for a menu written in Hindi.
Raster images on Android
So the Android app’s default is image mode. It draws the slip onto a bitmap the width of the print head — 576 dots for 80 mm, 384 for 58 mm — using a monospace font sized to one cell per character. Each run of text is placed at its own column, so a proportional Devanagari name cannot push the prices out of line. The bitmap is thresholded to black and white and sent as raster bands. Android draws the glyphs, so the rupee sign and Indic scripts print exactly as they look on screen.
Image mode costs bandwidth, which matters on slow Bluetooth printers; restaurants that print only Latin text can switch a connection to text mode. Over Bluetooth the app writes in chunks and waits briefly before closing the socket — some printers cut off the end of a slip if you hang up the moment the last byte is written.
Trade-offs
- At-least-once means occasional duplicates. We chose a duplicate KOT over a lost one. Idempotent printing does not exist on hardware with no memory of what it printed.
- The long poll polls. While a client waits, the server checks the queue every second and a half. That is simple and cheap at our scale; a change stream or a pub/sub wake-up would remove the polling, and the bus we already have is the obvious way to do it.
- Queueing runs inside the request. Creating print jobs is a few inserts in the KOT request; a failure is logged and never fails the KOT. The cost is that a KOT can, in a rare failure, exist without a print job. An alert on that case is on our list.
- Right-to-left scripts are not handled yet. Image mode lays columns out left to right. Android can draw Arabic glyphs, but proper bidirectional layout is work we have to do before we call Arabic slips finished.
- Two HTML renderers. The print station renders the queued slip, while the manual 80 mm print pages render from the order. Their wording is kept in step by hand; one renderer for both is the cleaner design.