Public Access
Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8664a1dd13 | ||
|
|
cdc1bc4264 | ||
|
|
a9e07b324d | ||
|
|
2a62450238 | ||
|
|
a77d42a1e4 | ||
|
|
1a94c33304 | ||
|
|
cb7bcff93e | ||
|
|
8d2111ff41 | ||
|
|
b4001c97c8 | ||
|
|
851e021fc2 | ||
|
|
abb752c3ef | ||
|
|
52eb0147fd | ||
|
|
0c1ef93552 | ||
|
|
26701d0d3b | ||
|
|
1b4b9d662a | ||
|
|
28b52145eb | ||
|
|
511929d579 |
@@ -179,10 +179,16 @@ the widest roll it will accept — the console warns you if you enter anything w
|
|||||||
| DK-11208 | 38 × 90 mm die-cut | Narrower; turn the photo off |
|
| DK-11208 | 38 × 90 mm die-cut | Narrower; turn the photo off |
|
||||||
| DK-11209 | 29 × 62 mm die-cut | Name and host only |
|
| DK-11209 | 29 × 62 mm die-cut | Name and host only |
|
||||||
|
|
||||||
|
**Tell it which roll is loaded.** *Roll loaded in the printer* under **Sites → Edit → Printer**
|
||||||
|
must match what is physically in the machine. A two-colour job sent to a plain roll is refused
|
||||||
|
outright: the printer shows **Wrong Roll Type** and nothing comes out. The setting is separate
|
||||||
|
from the red styling option on purpose — a design choice should not silently change the media
|
||||||
|
type the printer is told to expect.
|
||||||
|
|
||||||
**The red option.** Tick *Print the heading and the no-check warning in red* and the site name
|
**The red option.** Tick *Print the heading and the no-check warning in red* and the site name
|
||||||
and the **No WWCC / VIT** box print red instead of black, which makes a visitor without a check
|
and the **No WWCC / VIT** box print red instead of black, which makes a visitor without a check
|
||||||
obvious across a room. It only works on a DK-22251 roll — on any other roll the printer renders
|
obvious across a room. It needs the roll setting above to be the DK-22251; with a plain roll
|
||||||
it as grey. Two-colour printing is also far slower than black alone (Brother rate it at roughly
|
selected the badge is drawn in black instead and the console says so. Two-colour printing is also far slower than black alone (Brother rate it at roughly
|
||||||
15 labels a minute against 110), which is irrelevant for one badge at a time but worth knowing.
|
15 labels a minute against 110), which is irrelevant for one badge at a time but worth knowing.
|
||||||
|
|
||||||
### Printing from the server
|
### Printing from the server
|
||||||
@@ -271,9 +277,25 @@ HOST_PORT=8443
|
|||||||
HTTPS_PUBLIC_PORT=8443
|
HTTPS_PUBLIC_PORT=8443
|
||||||
```
|
```
|
||||||
|
|
||||||
An address that isn't listed produces a browser warning. Change the list and restart; the
|
An address that isn't listed produces a browser warning.
|
||||||
certificate reissues itself automatically, and devices that already trust the authority accept
|
|
||||||
it without any further work.
|
After changing anything in `.env`, bring the container back with **`docker compose up -d`**, not
|
||||||
|
`docker compose restart`. Restart reuses the running container along with the environment it
|
||||||
|
started with, so the edit appears to do nothing; `up -d` recreates it and picks the new values
|
||||||
|
up. Confirm with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose exec visitor-signin printenv HTTPS_HOSTNAMES
|
||||||
|
docker compose logs --tail=20 visitor-signin | grep tls
|
||||||
|
```
|
||||||
|
|
||||||
|
The log should say `renewing the server certificate: HTTPS_HOSTNAMES changed` and then list every
|
||||||
|
name it now covers. If it lists only `localhost`, `visitors.local` and a `172.x` address, the
|
||||||
|
variable never reached the container — those are the defaults plus the container's own docker
|
||||||
|
bridge address.
|
||||||
|
|
||||||
|
Reissuing does **not** touch the certificate authority, so devices that already trust it keep
|
||||||
|
working and no MDM profile needs redeploying.
|
||||||
|
|
||||||
The kiosk is then at `https://visitors.local:8443`, admin at `https://visitors.local:8443/admin`.
|
The kiosk is then at `https://visitors.local:8443`, admin at `https://visitors.local:8443/admin`.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
# Badge printing
|
||||||
|
|
||||||
|
The app renders the badge and sends it to the Brother QL-820NWB over TCP port
|
||||||
|
9100, speaking Brother's raster command language directly. No CUPS, no driver,
|
||||||
|
no print dialog, and no Python.
|
||||||
|
|
||||||
|
## Why not AirPrint
|
||||||
|
|
||||||
|
AirPrint from the kiosk browser means iPadOS renders the badge from print CSS
|
||||||
|
and picks the page geometry from what the printer advertises. That costs exact
|
||||||
|
control of the 60.96 mm print width, makes two-colour DK-22251 output
|
||||||
|
impossible, and cannot suppress the print dialog — so a staff member has to tap
|
||||||
|
"Print" for every visitor. Fine for a staffed desk, useless for unattended
|
||||||
|
sign-in.
|
||||||
|
|
||||||
|
Doing it server-side also means the kiosk device stops mattering. An iPad, an
|
||||||
|
old Android tablet, a browser on a NUC: they all just POST.
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
```
|
||||||
|
src/printing/
|
||||||
|
ql-raster.js command language: media, cut, expanded mode, bit packing
|
||||||
|
ql-status.js decoder for the 32-byte status frames
|
||||||
|
ql-transport.js TCP client for port 9100
|
||||||
|
ql-print.js printPng / printerHealth, plus the serial queue
|
||||||
|
src/printer.js badge layout and rendering (unchanged by this work)
|
||||||
|
```
|
||||||
|
|
||||||
|
Protocol details follow Brother's *Raster Command Reference, QL-800/810W/820NWB
|
||||||
|
v1.01*. Where that manual and pklaus/brother_ql disagree, the manual wins;
|
||||||
|
brother_ql targets older models and several of its defaults are wrong for this
|
||||||
|
hardware (200-byte invalidate instead of 400, the print-quality bit set during
|
||||||
|
two-colour jobs, the media-length valid bit asserted for continuous tape).
|
||||||
|
|
||||||
|
## The roll setting is not cosmetic
|
||||||
|
|
||||||
|
`sites.printer_label` must match the roll physically in the machine:
|
||||||
|
|
||||||
|
| Roll | Setting |
|
||||||
|
|---|---|
|
||||||
|
| DK-22205, 62 mm white | `62` |
|
||||||
|
| DK-22251, 62 mm black/red | `62red` |
|
||||||
|
|
||||||
|
This is enforced by the printer, not by us. A monochrome job sent to a
|
||||||
|
black/red roll is refused outright, and vice versa. It applies even when the
|
||||||
|
badge has no red on it — with `62red` set, every job is built as two-colour and
|
||||||
|
the red plane is simply empty.
|
||||||
|
|
||||||
|
The printer's own error message is misleading here. It says "change it to
|
||||||
|
Monochrome media", which points at a driver setting that doesn't exist in this
|
||||||
|
setup. The fix is the roll dropdown in the admin console, or swapping the roll.
|
||||||
|
|
||||||
|
## Status, and why there isn't much
|
||||||
|
|
||||||
|
Manual section 5.9: over a network connection the print data is sent as-is and
|
||||||
|
nothing comes back. Status frames only arrive over USB. brother_ql documents the
|
||||||
|
same limitation for its network backend.
|
||||||
|
|
||||||
|
So `printerHealth` returns a tri-state `ready`:
|
||||||
|
|
||||||
|
- `true` — the printer answered and everything is fine
|
||||||
|
- `false` — it answered and something is wrong
|
||||||
|
- `null` — reachable, but it won't say
|
||||||
|
|
||||||
|
`null` is the normal answer here. Show it as amber/unknown in the admin console;
|
||||||
|
colouring it green claims something we don't know. Likewise `printPng` returns
|
||||||
|
`confirmed: false` when no status came back: the bytes were delivered, but
|
||||||
|
whether paper moved is unknown.
|
||||||
|
|
||||||
|
Consequence worth accepting: a jammed or empty printer cannot be detected. The
|
||||||
|
practical signal is a visitor saying no badge appeared. That is tolerable
|
||||||
|
because the evacuation record is written before printing is attempted. If real
|
||||||
|
roll monitoring is ever needed, the lead to follow is SNMP — the Brother Status
|
||||||
|
Monitor on Windows gets roll state over the network somehow, and it is not
|
||||||
|
using port 9100.
|
||||||
|
|
||||||
|
## Concurrency
|
||||||
|
|
||||||
|
The QL accepts one TCP connection at a time and has no job spooler worth the
|
||||||
|
name. Two visitors signing in together would otherwise produce a refused
|
||||||
|
connection, half a label, or both. Every job goes through a serial queue keyed
|
||||||
|
on printer host, in `ql-print.js`.
|
||||||
|
|
||||||
|
That queue is in-process. Running more than one app instance against one printer
|
||||||
|
would need a lock in SQLite instead.
|
||||||
|
|
||||||
|
## Geometry
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
| Print head | 720 pins, 60.96 mm at 300 dpi |
|
||||||
|
| 62 mm roll printable | 696 pins, 58.9 mm |
|
||||||
|
| Margins | 12 pins each side |
|
||||||
|
| Feed margin | 35 dots (3 mm), the documented minimum |
|
||||||
|
| Length | 150 to 11811 raster lines (12.7 mm to 1 m) |
|
||||||
|
|
||||||
|
Every raster line sent is the full 90 bytes regardless of the roll. Narrower
|
||||||
|
media just means more pins miss the paper.
|
||||||
|
|
||||||
|
## Diagnostics
|
||||||
|
|
||||||
|
Reachability and roll state:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose exec visitor-signin node -e "
|
||||||
|
import('./src/printing/ql-print.js').then(async m =>
|
||||||
|
console.log(await m.printerHealth({ host: '10.142.177.169', label: '62red' })));
|
||||||
|
"
|
||||||
|
```
|
||||||
|
|
||||||
|
If a label never appears, work down this list:
|
||||||
|
|
||||||
|
**Nothing at all, `Cannot reach printer`.** Routing or firewall between the
|
||||||
|
container and the printer. Try `nc -vz IP 9100` from the Ubuntu host; if that
|
||||||
|
works but the container doesn't, it is Docker networking.
|
||||||
|
|
||||||
|
**Connects but silent.** Normal. See above.
|
||||||
|
|
||||||
|
**Media mismatch error.** The roll setting and the physical roll disagree.
|
||||||
|
|
||||||
|
**Labels come out blank.** Roll in backwards, or a non-Brother roll with no end
|
||||||
|
sensor. The printer reports no error for this.
|
||||||
|
|
||||||
|
**Everything mirrored.** The bit packing is wrong. The head clocks each raster
|
||||||
|
line out right-to-left; see `packRow`.
|
||||||
|
|
||||||
|
**First label after a power cycle is misaligned.** Feed one label from the front
|
||||||
|
panel before the first sign-in of the day.
|
||||||
|
|
||||||
|
## Known rough edge
|
||||||
|
|
||||||
|
Photos are not dithered. `drawBadge` draws them straight and the plane
|
||||||
|
conversion thresholds at luminance 180. A thermal head has no grey, so faces
|
||||||
|
come out blotchy. The fix is Floyd–Steinberg on the photo region before it goes
|
||||||
|
on the canvas, inside `drawBadge`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Created by: Jess Rogerson (yelling commands at Claude.AI)
|
||||||
+42
-5
@@ -702,9 +702,9 @@ async function loadSites() {
|
|||||||
<dt>Printer</dt>
|
<dt>Printer</dt>
|
||||||
<dd>${
|
<dd>${
|
||||||
s.printer.enabled && s.printer.host
|
s.printer.enabled && s.printer.host
|
||||||
? `${esc(s.printer.model)} at ${esc(s.printer.host)}:${s.printer.port}${
|
? `${esc(s.printer.model)} at ${esc(s.printer.host)}:${s.printer.port}, ${
|
||||||
s.printer.rotate ? `, rotated ${s.printer.rotate}°` : ''
|
s.printer.label === '62red' ? 'black and red roll' : 'black roll'
|
||||||
}${
|
}${s.printer.rotate ? `, rotated ${s.printer.rotate}°` : ''}${
|
||||||
s.printerStatus
|
s.printerStatus
|
||||||
? s.printerStatus.ok
|
? s.printerStatus.ok
|
||||||
? ` <span class="pill">last print ok, ${stamp(s.printerStatus.at)}</span>`
|
? ` <span class="pill">last print ok, ${stamp(s.printerStatus.at)}</span>`
|
||||||
@@ -799,14 +799,21 @@ function openSiteModal(site) {
|
|||||||
<p class="hint" id="badge-warning" hidden></p>
|
<p class="hint" id="badge-warning" hidden></p>
|
||||||
<label class="inline"><input type="checkbox" name="showPhoto" id="badge-photo" ${site.badge.showPhoto ? 'checked' : ''}> Include the visitor's photo</label>
|
<label class="inline"><input type="checkbox" name="showPhoto" id="badge-photo" ${site.badge.showPhoto ? 'checked' : ''}> Include the visitor's photo</label>
|
||||||
<label class="inline"><input type="checkbox" name="accent" id="badge-accent" ${site.badge.accent ? 'checked' : ''}> Print the heading and the no-check warning in red</label>
|
<label class="inline"><input type="checkbox" name="accent" id="badge-accent" ${site.badge.accent ? 'checked' : ''}> Print the heading and the no-check warning in red</label>
|
||||||
<p class="hint">Red needs a two-colour roll such as the Brother DK-22251. On any other
|
<p class="hint" id="accent-note"></p>
|
||||||
roll it prints as grey. Two-colour printing is also much slower than black alone.</p>
|
<p class="hint">Two-colour printing is much slower than black alone.</p>
|
||||||
<h4 class="modal-section">Printer</h4>
|
<h4 class="modal-section">Printer</h4>
|
||||||
<label class="inline"><input type="checkbox" name="printerEnabled" ${site.printer.enabled ? 'checked' : ''}> Print from the server, straight to a network printer</label>
|
<label class="inline"><input type="checkbox" name="printerEnabled" ${site.printer.enabled ? 'checked' : ''}> Print from the server, straight to a network printer</label>
|
||||||
<div class="modal-row">
|
<div class="modal-row">
|
||||||
${field('Printer IP address', 'printerHost', site.printer.host, 'text')}
|
${field('Printer IP address', 'printerHost', site.printer.host, 'text')}
|
||||||
${field('Port', 'printerPort', site.printer.port, 'number')}
|
${field('Port', 'printerPort', site.printer.port, 'number')}
|
||||||
</div>
|
</div>
|
||||||
|
<label class="modal-field"><span>Roll loaded in the printer</span>
|
||||||
|
<select name="printerLabel">
|
||||||
|
<option value="62" ${site.printer.label !== '62red' ? 'selected' : ''}>62 mm continuous, black only</option>
|
||||||
|
<option value="62red" ${site.printer.label === '62red' ? 'selected' : ''}>62 mm continuous, black and red (DK-22251)</option>
|
||||||
|
</select></label>
|
||||||
|
<p class="hint">This must match the roll actually in the machine. Send a two-colour job to a
|
||||||
|
plain roll and the printer answers <em>Wrong Roll Type</em> and prints nothing.</p>
|
||||||
<div class="modal-row">
|
<div class="modal-row">
|
||||||
${field('Model', 'printerModel', site.printer.model)}
|
${field('Model', 'printerModel', site.printer.model)}
|
||||||
<label class="modal-field"><span>Rotation</span>
|
<label class="modal-field"><span>Rotation</span>
|
||||||
@@ -883,6 +890,7 @@ function openSiteModal(site) {
|
|||||||
port: Number(data.printerPort) || 9100,
|
port: Number(data.printerPort) || 9100,
|
||||||
model: data.printerModel,
|
model: data.printerModel,
|
||||||
rotate: Number(data.printerRotate) || 0,
|
rotate: Number(data.printerRotate) || 0,
|
||||||
|
label: data.printerLabel,
|
||||||
},
|
},
|
||||||
branding: {
|
branding: {
|
||||||
brand: data.brand || null,
|
brand: data.brand || null,
|
||||||
@@ -992,6 +1000,35 @@ function wireBannerEditor() {
|
|||||||
[pageInput, textInput].forEach((el) => el.addEventListener('input', showContrast));
|
[pageInput, textInput].forEach((el) => el.addEventListener('input', showContrast));
|
||||||
showContrast();
|
showContrast();
|
||||||
|
|
||||||
|
// Red is only possible on the two-colour roll, so say so as the two settings change.
|
||||||
|
const accentBox = $('#badge-accent');
|
||||||
|
const rollSelect = $('#modal-form [name="printerLabel"]');
|
||||||
|
const accentNote = $('#accent-note');
|
||||||
|
|
||||||
|
const showAccentNote = () => {
|
||||||
|
if (!accentNote) return;
|
||||||
|
if (!accentBox?.checked) {
|
||||||
|
accentNote.hidden = false;
|
||||||
|
accentNote.className = 'hint';
|
||||||
|
accentNote.textContent = 'Everything prints black.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (rollSelect?.value === '62red') {
|
||||||
|
accentNote.hidden = false;
|
||||||
|
accentNote.className = 'hint';
|
||||||
|
accentNote.textContent = 'The heading and the no-check warning will print red.';
|
||||||
|
} else {
|
||||||
|
accentNote.hidden = false;
|
||||||
|
accentNote.className = 'hint warn';
|
||||||
|
accentNote.textContent =
|
||||||
|
'The roll selected below cannot print red, so these will come out black. Load a DK-22251 and change the roll setting to use colour.';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
accentBox?.addEventListener('change', showAccentNote);
|
||||||
|
rollSelect?.addEventListener('change', showAccentNote);
|
||||||
|
showAccentNote();
|
||||||
|
|
||||||
$('#banner-file').addEventListener('change', (event) => {
|
$('#banner-file').addEventListener('change', (event) => {
|
||||||
const file = event.target.files[0];
|
const file = event.target.files[0];
|
||||||
if (!file) return;
|
if (!file) return;
|
||||||
|
|||||||
@@ -0,0 +1,98 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* One-shot patch: dither visitor photos before they go on the badge canvas.
|
||||||
|
*
|
||||||
|
* node scripts/dither-badge-photos.mjs # patch
|
||||||
|
* node scripts/dither-badge-photos.mjs --check # report only
|
||||||
|
*
|
||||||
|
* A thermal head has no grey. Drawn straight, a photo gets thresholded by the
|
||||||
|
* plane conversion and most of a face lands on one side of that threshold, so
|
||||||
|
* it prints as a solid black mass. This inserts a Floyd-Steinberg pass at
|
||||||
|
* exactly the size the photo will occupy.
|
||||||
|
*
|
||||||
|
* Idempotent, writes printer.js.bak, refuses to run if the anchor is missing.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
const target = path.resolve(here, '..', 'src', 'printer.js');
|
||||||
|
const checkOnly = process.argv.includes('--check');
|
||||||
|
|
||||||
|
function fail(message) {
|
||||||
|
console.error(`\n FAILED: ${message}\n`);
|
||||||
|
console.error(' Nothing was changed.\n');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!fs.existsSync(target)) fail(`${target} does not exist. Run this from the repo root.`);
|
||||||
|
|
||||||
|
let source = fs.readFileSync(target, 'utf8');
|
||||||
|
const original = source;
|
||||||
|
|
||||||
|
if (source.includes('ditherPhoto(')) {
|
||||||
|
console.log('\n Already patched — printer.js dithers photos. Nothing to do.\n');
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
const changes = [];
|
||||||
|
|
||||||
|
/* -- 1. Import ---------------------------------------------------- */
|
||||||
|
|
||||||
|
const importAnchor = "import { photoAbsolutePath } from './photos.js';";
|
||||||
|
if (!source.includes(importAnchor)) fail('could not find the photos.js import');
|
||||||
|
|
||||||
|
source = source.replace(
|
||||||
|
importAnchor,
|
||||||
|
`${importAnchor}\nimport { ditherPhoto } from './printing/dither.js';`
|
||||||
|
);
|
||||||
|
changes.push('added the ditherPhoto import');
|
||||||
|
|
||||||
|
/* -- 2. Dither once, at final size, before either draw site ------- */
|
||||||
|
|
||||||
|
// Matches the existing line regardless of the exact multipliers, so tweaking
|
||||||
|
// the photo size later doesn't break this patch.
|
||||||
|
const sizeAnchor = /const photoSize = photo \? Math\.round\([^;]+\) : 0;/;
|
||||||
|
const match = source.match(sizeAnchor);
|
||||||
|
if (!match) fail('could not find the photoSize calculation in drawBadge');
|
||||||
|
|
||||||
|
const insertion = `${match[0]}
|
||||||
|
|
||||||
|
// Thermal heads print pure black or nothing, so a photo has to be reduced to
|
||||||
|
// 1-bit before it lands on the canvas — otherwise the plane conversion
|
||||||
|
// thresholds it into a solid blob. Done once here rather than at each draw
|
||||||
|
// site, and at exactly photoSize: rescaling a dithered image resamples the
|
||||||
|
// dot pattern back into greys and undoes the whole thing.
|
||||||
|
//
|
||||||
|
// Skipped on the measuring pass, which never paints.
|
||||||
|
if (photo && photoSize > 0 && startY !== null) {
|
||||||
|
photo = ditherPhoto(photo, photoSize);
|
||||||
|
}`;
|
||||||
|
|
||||||
|
source = source.replace(sizeAnchor, insertion);
|
||||||
|
changes.push('drawBadge dithers the photo at its final size');
|
||||||
|
|
||||||
|
/* -- 3. Sanity check ---------------------------------------------- */
|
||||||
|
|
||||||
|
if (!/let photo = null;/.test(source)) {
|
||||||
|
fail('photo is not declared with let — it cannot be reassigned. Patch by hand.');
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('\n Changes to src/printer.js:');
|
||||||
|
for (const c of changes) console.log(` - ${c}`);
|
||||||
|
|
||||||
|
if (checkOnly) {
|
||||||
|
console.log('\n --check given, nothing written.\n');
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (source === original) fail('nothing actually changed');
|
||||||
|
|
||||||
|
fs.writeFileSync(`${target}.bak`, original);
|
||||||
|
fs.writeFileSync(target, source);
|
||||||
|
|
||||||
|
console.log(`\n Wrote ${target}`);
|
||||||
|
console.log(` Backup at ${target}.bak`);
|
||||||
|
console.log('\n Next: docker compose build && docker compose up -d\n');
|
||||||
+4
-2
@@ -25,8 +25,10 @@ fi
|
|||||||
|
|
||||||
if docker compose ps --status running 2>/dev/null | grep -q visitor-signin; then
|
if docker compose ps --status running 2>/dev/null | grep -q visitor-signin; then
|
||||||
docker compose exec -T visitor-signin node scripts/make-cert.mjs $FORCE
|
docker compose exec -T visitor-signin node scripts/make-cert.mjs $FORCE
|
||||||
echo "Restarting so the new certificate is served..."
|
echo "Recreating the container so the new certificate is served..."
|
||||||
docker compose restart visitor-signin
|
# up -d rather than restart: restart keeps the environment the container was
|
||||||
|
# started with, so an edited .env would be ignored.
|
||||||
|
docker compose up -d visitor-signin
|
||||||
else
|
else
|
||||||
node scripts/make-cert.mjs $FORCE
|
node scripts/make-cert.mjs $FORCE
|
||||||
fi
|
fi
|
||||||
|
|||||||
@@ -0,0 +1,171 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* One-shot patch: point printer.js at the native QL protocol module instead of
|
||||||
|
* shelling out to the Python brother_ql CLI.
|
||||||
|
*
|
||||||
|
* node scripts/wire-native-printing.mjs # patch
|
||||||
|
* node scripts/wire-native-printing.mjs --check # report only, change nothing
|
||||||
|
*
|
||||||
|
* Safe to run twice — it detects an already-patched file and stops.
|
||||||
|
* Writes printer.js.bak next to the original before touching anything.
|
||||||
|
*
|
||||||
|
* Only the imports and the two functions at the bottom change. The badge
|
||||||
|
* layout (drawBadge / renderBadgePng) is left exactly as it is.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
const target = path.resolve(here, '..', 'src', 'printer.js');
|
||||||
|
const checkOnly = process.argv.includes('--check');
|
||||||
|
|
||||||
|
function fail(message) {
|
||||||
|
console.error(`\n FAILED: ${message}\n`);
|
||||||
|
console.error(' Nothing was changed. Patch printer.js by hand instead.\n');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find a top-level function and return its full text by matching braces.
|
||||||
|
* Formatting-independent, unlike matching the whole body literally.
|
||||||
|
*/
|
||||||
|
function extractFunction(source, signature) {
|
||||||
|
const start = source.indexOf(signature);
|
||||||
|
if (start === -1) return null;
|
||||||
|
|
||||||
|
let depth = 0;
|
||||||
|
let i = source.indexOf('{', start);
|
||||||
|
if (i === -1) return null;
|
||||||
|
|
||||||
|
for (; i < source.length; i++) {
|
||||||
|
if (source[i] === '{') depth++;
|
||||||
|
else if (source[i] === '}') {
|
||||||
|
depth--;
|
||||||
|
if (depth === 0) {
|
||||||
|
return { start, end: i + 1, text: source.slice(start, i + 1) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!fs.existsSync(target)) fail(`${target} does not exist. Run this from the repo root.`);
|
||||||
|
|
||||||
|
let source = fs.readFileSync(target, 'utf8');
|
||||||
|
const original = source;
|
||||||
|
|
||||||
|
if (source.includes("from './printing/ql-print.js'")) {
|
||||||
|
console.log('\n Already patched — printer.js imports the native module. Nothing to do.\n');
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
const changes = [];
|
||||||
|
|
||||||
|
/* -- 1. Import the native module ---------------------------------- */
|
||||||
|
|
||||||
|
const importAnchor = "import { photoAbsolutePath } from './photos.js';";
|
||||||
|
if (!source.includes(importAnchor)) fail('could not find the photos.js import');
|
||||||
|
|
||||||
|
source = source.replace(
|
||||||
|
importAnchor,
|
||||||
|
`${importAnchor}\nimport { printPng, printerHealth } from './printing/ql-print.js';`
|
||||||
|
);
|
||||||
|
changes.push('added the ql-print import');
|
||||||
|
|
||||||
|
/* -- 2. Replace printBadge ---------------------------------------- */
|
||||||
|
|
||||||
|
const printBadge = extractFunction(source, 'export async function printBadge(visit, site)');
|
||||||
|
if (!printBadge) fail('could not locate printBadge');
|
||||||
|
if (!printBadge.text.includes('runBrotherQl')) {
|
||||||
|
fail('printBadge does not call runBrotherQl — it may already have been changed');
|
||||||
|
}
|
||||||
|
|
||||||
|
const newPrintBadge = `export async function printBadge(visit, site) {
|
||||||
|
if (!isConfigured(site)) throw new Error('Server printing is not turned on for this site.');
|
||||||
|
|
||||||
|
const png = await renderBadgePng(visit, site);
|
||||||
|
const port = Number(site.printer_port) || 9100;
|
||||||
|
const target = \`tcp://\${site.printer_host}:\${port}\`;
|
||||||
|
|
||||||
|
// The roll decides whether the job is two-colour, not the accent setting.
|
||||||
|
// A DK-22251 roll refuses a monochrome job even when the badge has no red
|
||||||
|
// on it, so labelFor() is passed straight through and ql-print maps it.
|
||||||
|
const result = await printPng(png, {
|
||||||
|
host: site.printer_host,
|
||||||
|
port,
|
||||||
|
label: labelFor(site),
|
||||||
|
});
|
||||||
|
|
||||||
|
note(site.id, result.ok, result.message);
|
||||||
|
if (!result.ok) throw new Error(result.message);
|
||||||
|
|
||||||
|
// confirmed is false when the printer accepted the bytes but never said the
|
||||||
|
// label came out. Over the network that is the normal case, not a fault.
|
||||||
|
return { ok: true, confirmed: Boolean(result.confirmed), target };
|
||||||
|
}`;
|
||||||
|
|
||||||
|
source =
|
||||||
|
source.slice(0, printBadge.start) + newPrintBadge + source.slice(printBadge.end);
|
||||||
|
changes.push('printBadge now uses printPng');
|
||||||
|
|
||||||
|
/* -- 3. Replace available ----------------------------------------- */
|
||||||
|
|
||||||
|
const available = extractFunction(source, 'export function available()');
|
||||||
|
if (available) {
|
||||||
|
const newAvailable = `export function available() {
|
||||||
|
// Kept for callers that only ask "can this server print at all?". The
|
||||||
|
// external brother_ql binary is no longer involved, so the answer is always
|
||||||
|
// yes; use health(site) to ask about a specific printer.
|
||||||
|
return Promise.resolve(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reachability and, where the printer will say, roll state.
|
||||||
|
*
|
||||||
|
* ready is tri-state: true, false, or null meaning "reachable but it won't
|
||||||
|
* tell us". Null is the normal answer over the network — show it as unknown
|
||||||
|
* in the admin console rather than green or red.
|
||||||
|
*/
|
||||||
|
export function health(site) {
|
||||||
|
return printerHealth({
|
||||||
|
host: site?.printer_host,
|
||||||
|
port: Number(site?.printer_port) || 9100,
|
||||||
|
label: labelFor(site),
|
||||||
|
});
|
||||||
|
}`;
|
||||||
|
|
||||||
|
source =
|
||||||
|
source.slice(0, available.start) + newAvailable + source.slice(available.end);
|
||||||
|
changes.push('available() no longer probes for a binary; added health(site)');
|
||||||
|
} else {
|
||||||
|
console.warn(' note: available() not found, skipping that step');
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -- 4. Flag the now-dead subprocess code ------------------------- */
|
||||||
|
|
||||||
|
for (const name of ['function explainPrintError', 'function runBrotherQl']) {
|
||||||
|
if (source.includes(name)) {
|
||||||
|
changes.push(`${name.split(' ')[1]}() is now unused and can be deleted`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* -- Report / write ----------------------------------------------- */
|
||||||
|
|
||||||
|
console.log('\n Changes to src/printer.js:');
|
||||||
|
for (const c of changes) console.log(` - ${c}`);
|
||||||
|
|
||||||
|
if (checkOnly) {
|
||||||
|
console.log('\n --check given, nothing written.\n');
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (source === original) fail('nothing actually changed');
|
||||||
|
|
||||||
|
fs.writeFileSync(`${target}.bak`, original);
|
||||||
|
fs.writeFileSync(target, source);
|
||||||
|
|
||||||
|
console.log(`\n Wrote ${target}`);
|
||||||
|
console.log(` Backup at ${target}.bak`);
|
||||||
|
console.log('\n Next: docker compose build && docker compose up -d\n');
|
||||||
@@ -27,6 +27,7 @@ CREATE TABLE IF NOT EXISTS sites (
|
|||||||
printer_port INTEGER NOT NULL DEFAULT 9100,
|
printer_port INTEGER NOT NULL DEFAULT 9100,
|
||||||
printer_model TEXT NOT NULL DEFAULT 'QL-820NWB',
|
printer_model TEXT NOT NULL DEFAULT 'QL-820NWB',
|
||||||
printer_rotate INTEGER NOT NULL DEFAULT 0,
|
printer_rotate INTEGER NOT NULL DEFAULT 0,
|
||||||
|
printer_label TEXT NOT NULL DEFAULT '62',
|
||||||
banner_path TEXT,
|
banner_path TEXT,
|
||||||
banner_height INTEGER NOT NULL DEFAULT 64,
|
banner_height INTEGER NOT NULL DEFAULT 64,
|
||||||
banner_align TEXT NOT NULL DEFAULT 'left',
|
banner_align TEXT NOT NULL DEFAULT 'left',
|
||||||
@@ -183,6 +184,10 @@ addColumn('sites', 'printer_host', 'TEXT');
|
|||||||
addColumn('sites', 'printer_port', 'INTEGER NOT NULL DEFAULT 9100');
|
addColumn('sites', 'printer_port', 'INTEGER NOT NULL DEFAULT 9100');
|
||||||
addColumn('sites', 'printer_model', "TEXT NOT NULL DEFAULT 'QL-820NWB'");
|
addColumn('sites', 'printer_model', "TEXT NOT NULL DEFAULT 'QL-820NWB'");
|
||||||
addColumn('sites', 'printer_rotate', 'INTEGER NOT NULL DEFAULT 0');
|
addColumn('sites', 'printer_rotate', 'INTEGER NOT NULL DEFAULT 0');
|
||||||
|
// Which roll is physically loaded. Kept separate from the red styling option:
|
||||||
|
// the printer refuses a two-colour job on a plain roll, so guessing the media
|
||||||
|
// from a design setting means a wrong-roll error nobody can explain.
|
||||||
|
addColumn('sites', 'printer_label', "TEXT NOT NULL DEFAULT '62'");
|
||||||
addColumn('frequent_visitors', 'company', 'TEXT');
|
addColumn('frequent_visitors', 'company', 'TEXT');
|
||||||
|
|
||||||
db.exec('CREATE INDEX IF NOT EXISTS idx_visits_site ON visits(site_id, signed_out_at)');
|
db.exec('CREATE INDEX IF NOT EXISTS idx_visits_site ON visits(site_id, signed_out_at)');
|
||||||
|
|||||||
+70
-29
@@ -6,6 +6,8 @@ import { execFile } from 'node:child_process';
|
|||||||
import { createCanvas, loadImage, GlobalFonts } from '@napi-rs/canvas';
|
import { createCanvas, loadImage, GlobalFonts } from '@napi-rs/canvas';
|
||||||
import config from './config.js';
|
import config from './config.js';
|
||||||
import { photoAbsolutePath } from './photos.js';
|
import { photoAbsolutePath } from './photos.js';
|
||||||
|
import { ditherPhoto } from './printing/dither.js';
|
||||||
|
import { printPng, printerHealth } from './printing/ql-print.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Printing happens on the server, not in the kiosk browser.
|
* Printing happens on the server, not in the kiosk browser.
|
||||||
@@ -41,9 +43,26 @@ export function isConfigured(site) {
|
|||||||
return Boolean(site?.printer_enabled && site?.printer_host);
|
return Boolean(site?.printer_enabled && site?.printer_host);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** brother_ql's label id. The two-colour roll is a different label to the plain one. */
|
/**
|
||||||
|
* brother_ql's media id for the roll that is actually loaded.
|
||||||
|
*
|
||||||
|
* This is set explicitly rather than inferred from the red styling option. A
|
||||||
|
* two-colour job sent to a plain roll is rejected by the printer with "Wrong
|
||||||
|
* Roll Type", which gives no clue that a colour checkbox caused it.
|
||||||
|
*/
|
||||||
|
export const ROLL_TYPES = {
|
||||||
|
'62': '62 mm continuous, black only',
|
||||||
|
'62red': '62 mm continuous, black and red (DK-22251)',
|
||||||
|
};
|
||||||
|
|
||||||
export function labelFor(site) {
|
export function labelFor(site) {
|
||||||
return site?.badge_accent ? '62red' : '62';
|
const label = site?.printer_label;
|
||||||
|
return Object.hasOwn(ROLL_TYPES, label) ? label : '62';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Red ink only exists on the two-colour roll; anywhere else it prints dark grey. */
|
||||||
|
export function accentWillPrintRed(site) {
|
||||||
|
return Boolean(site?.badge_accent) && labelFor(site) === '62red';
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------------ rendering */
|
/* ------------------------------------------------------------ rendering */
|
||||||
@@ -96,6 +115,17 @@ async function drawBadge(ctx, widthDots, heightDots, visit, site, accent, startY
|
|||||||
}
|
}
|
||||||
|
|
||||||
const photoSize = photo ? Math.round(unit * (portrait ? 0.52 : 0.5)) : 0;
|
const photoSize = photo ? Math.round(unit * (portrait ? 0.52 : 0.5)) : 0;
|
||||||
|
|
||||||
|
// Thermal heads print pure black or nothing, so a photo has to be reduced to
|
||||||
|
// 1-bit before it lands on the canvas — otherwise the plane conversion
|
||||||
|
// thresholds it into a solid blob. Done once here rather than at each draw
|
||||||
|
// site, and at exactly photoSize: rescaling a dithered image resamples the
|
||||||
|
// dot pattern back into greys and undoes the whole thing.
|
||||||
|
//
|
||||||
|
// Skipped on the measuring pass, which never paints.
|
||||||
|
if (photo && photoSize > 0 && startY !== null) {
|
||||||
|
photo = ditherPhoto(photo, photoSize);
|
||||||
|
}
|
||||||
let cursorY = startY === null ? pad : startY;
|
let cursorY = startY === null ? pad : startY;
|
||||||
let textLeft = pad;
|
let textLeft = pad;
|
||||||
let textWidth = widthDots - pad * 2;
|
let textWidth = widthDots - pad * 2;
|
||||||
@@ -223,7 +253,8 @@ export async function renderBadgePng(visit, site) {
|
|||||||
|
|
||||||
const design = createCanvas(designW, designH);
|
const design = createCanvas(designW, designH);
|
||||||
const ctx = design.getContext('2d');
|
const ctx = design.getContext('2d');
|
||||||
const accent = Boolean(site.badge_accent);
|
// Only paint red when the loaded roll can actually print it.
|
||||||
|
const accent = accentWillPrintRed(site);
|
||||||
|
|
||||||
// Measure first, then draw the block centred down the label. Without this the
|
// Measure first, then draw the block centred down the label. Without this the
|
||||||
// content hugs the top and leaves a wide blank strip at the bottom of every badge.
|
// content hugs the top and leaves a wide blank strip at the bottom of every badge.
|
||||||
@@ -273,6 +304,9 @@ function explainPrintError(output, host) {
|
|||||||
if (/Unknown label|label/i.test(last) && /identifier/i.test(last)) {
|
if (/Unknown label|label/i.test(last) && /identifier/i.test(last)) {
|
||||||
return 'The printer rejected the label size. Check the roll loaded matches the badge settings.';
|
return 'The printer rejected the label size. Check the roll loaded matches the badge settings.';
|
||||||
}
|
}
|
||||||
|
if (/wrong roll|WrongMedia|media/i.test(last)) {
|
||||||
|
return 'The printer says the roll is wrong. Check "Roll loaded in the printer" matches what is actually in the machine — a black and red job is refused on a plain roll.';
|
||||||
|
}
|
||||||
return last || 'The printer did not accept the job.';
|
return last || 'The printer did not accept the job.';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -309,33 +343,24 @@ export async function printBadge(visit, site) {
|
|||||||
if (!isConfigured(site)) throw new Error('Server printing is not turned on for this site.');
|
if (!isConfigured(site)) throw new Error('Server printing is not turned on for this site.');
|
||||||
|
|
||||||
const png = await renderBadgePng(visit, site);
|
const png = await renderBadgePng(visit, site);
|
||||||
const file = path.join(os.tmpdir(), `badge-${crypto.randomBytes(6).toString('hex')}.png`);
|
|
||||||
fs.writeFileSync(file, png);
|
|
||||||
|
|
||||||
const port = Number(site.printer_port) || 9100;
|
const port = Number(site.printer_port) || 9100;
|
||||||
const target = `tcp://${site.printer_host}:${port}`;
|
const target = `tcp://${site.printer_host}:${port}`;
|
||||||
|
|
||||||
try {
|
// The roll decides whether the job is two-colour, not the accent setting.
|
||||||
await runBrotherQl(
|
// A DK-22251 roll refuses a monochrome job even when the badge has no red
|
||||||
[
|
// on it, so labelFor() is passed straight through and ql-print maps it.
|
||||||
'--backend', 'network',
|
const result = await printPng(png, {
|
||||||
'--model', site.printer_model || 'QL-820NWB',
|
host: site.printer_host,
|
||||||
'--printer', target,
|
port,
|
||||||
'print',
|
label: labelFor(site),
|
||||||
'--label', labelFor(site),
|
});
|
||||||
file,
|
|
||||||
],
|
note(site.id, result.ok, result.message);
|
||||||
config.printing.timeoutMs
|
if (!result.ok) throw new Error(result.message);
|
||||||
);
|
|
||||||
note(site.id, true, `Printed to ${site.printer_host}`);
|
// confirmed is false when the printer accepted the bytes but never said the
|
||||||
return { ok: true, target };
|
// label came out. Over the network that is the normal case, not a fault.
|
||||||
} catch (err) {
|
return { ok: true, confirmed: Boolean(result.confirmed), target };
|
||||||
const friendly = explainPrintError(err.message, site.printer_host);
|
|
||||||
note(site.id, false, friendly);
|
|
||||||
throw new Error(friendly);
|
|
||||||
} finally {
|
|
||||||
fs.rm(file, { force: true }, () => {});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A sample badge, for checking the printer and the layout without a real visit. */
|
/** A sample badge, for checking the printer and the layout without a real visit. */
|
||||||
@@ -354,7 +379,23 @@ export function sampleVisit(site) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function available() {
|
export function available() {
|
||||||
return new Promise((resolve) => {
|
// Kept for callers that only ask "can this server print at all?". The
|
||||||
execFile(config.printing.command, ['--version'], (err) => resolve(!err));
|
// external brother_ql binary is no longer involved, so the answer is always
|
||||||
|
// yes; use health(site) to ask about a specific printer.
|
||||||
|
return Promise.resolve(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reachability and, where the printer will say, roll state.
|
||||||
|
*
|
||||||
|
* ready is tri-state: true, false, or null meaning "reachable but it won't
|
||||||
|
* tell us". Null is the normal answer over the network — show it as unknown
|
||||||
|
* in the admin console rather than green or red.
|
||||||
|
*/
|
||||||
|
export function health(site) {
|
||||||
|
return printerHealth({
|
||||||
|
host: site?.printer_host,
|
||||||
|
port: Number(site?.printer_port) || 9100,
|
||||||
|
label: labelFor(site),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,234 @@
|
|||||||
|
import { createCanvas } from '@napi-rs/canvas';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reduce a photo to pure black and white for a thermal print head.
|
||||||
|
*
|
||||||
|
* The head has no grey: every dot is burnt or not. Sending a photo straight
|
||||||
|
* through means the plane conversion thresholds it, and since most of a face
|
||||||
|
* sits on one side of any threshold you get a solid blob. Floyd-Steinberg
|
||||||
|
* error diffusion trades spatial resolution for apparent tone instead, which
|
||||||
|
* is what makes a photo readable at 300 dpi.
|
||||||
|
*
|
||||||
|
* Three things matter for this to look like a face rather than noise:
|
||||||
|
*
|
||||||
|
* 1. Dither at the exact pixel size the photo will occupy. Rescaling a
|
||||||
|
* dithered image resamples the dot pattern back into greys, and the later
|
||||||
|
* threshold turns those into the same blob we were avoiding.
|
||||||
|
*
|
||||||
|
* 2. Stretch the levels first. Webcam captures under office lighting are
|
||||||
|
* usually squeezed into the middle of the range; dithering that directly
|
||||||
|
* produces flat mush. Normalising to the full range first gives the error
|
||||||
|
* diffusion something to work with.
|
||||||
|
*
|
||||||
|
* 3. Aim for a fixed ink coverage. Thermal dots spread as the paper heats, so
|
||||||
|
* they come out fatter on the label than they look on screen, and a
|
||||||
|
* digitally "correct" image prints muddy. Targeting coverage also makes
|
||||||
|
* every badge print at the same density regardless of how the visitor
|
||||||
|
* happened to be lit.
|
||||||
|
*
|
||||||
|
* Text is deliberately NOT dithered anywhere — dithered glyph edges look furry
|
||||||
|
* at this resolution. Only photographs go through here.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Rec. 601 luma, which matches how the eye weights these channels. */
|
||||||
|
function luminance(r, g, b) {
|
||||||
|
return 0.299 * r + 0.587 * g + 0.114 * b;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stretch contrast so the darkest few percent land near black and the
|
||||||
|
* lightest few near white.
|
||||||
|
*
|
||||||
|
* Percentiles rather than absolute min/max, so one bright window or one dark
|
||||||
|
* shadow doesn't waste the whole range.
|
||||||
|
*/
|
||||||
|
function autoLevels(grey, { lowPercentile = 0.02, highPercentile = 0.98 } = {}) {
|
||||||
|
const histogram = new Uint32Array(256);
|
||||||
|
for (let i = 0; i < grey.length; i++) histogram[grey[i] | 0]++;
|
||||||
|
|
||||||
|
const lowTarget = grey.length * lowPercentile;
|
||||||
|
const highTarget = grey.length * highPercentile;
|
||||||
|
|
||||||
|
let low = 0;
|
||||||
|
let high = 255;
|
||||||
|
let seen = 0;
|
||||||
|
for (let v = 0; v < 256; v++) {
|
||||||
|
seen += histogram[v];
|
||||||
|
if (seen >= lowTarget) { low = v; break; }
|
||||||
|
}
|
||||||
|
seen = 0;
|
||||||
|
for (let v = 255; v >= 0; v--) {
|
||||||
|
seen += histogram[v];
|
||||||
|
if (seen >= grey.length - highTarget) { high = v; break; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// A nearly flat image would blow up into noise; leave it alone.
|
||||||
|
if (high - low < 24) return;
|
||||||
|
|
||||||
|
const scale = 255 / (high - low);
|
||||||
|
for (let i = 0; i < grey.length; i++) {
|
||||||
|
grey[i] = Math.min(255, Math.max(0, (grey[i] - low) * scale));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Floyd-Steinberg error diffusion over a luminance buffer, in place.
|
||||||
|
*
|
||||||
|
* Serpentine scanning: alternating direction per row avoids the diagonal
|
||||||
|
* banding a plain left-to-right pass leaves in smooth gradients like skin.
|
||||||
|
*/
|
||||||
|
function floydSteinberg(grey, width, height) {
|
||||||
|
const at = (x, y) => y * width + x;
|
||||||
|
|
||||||
|
for (let y = 0; y < height; y++) {
|
||||||
|
const leftToRight = y % 2 === 0;
|
||||||
|
const from = leftToRight ? 0 : width - 1;
|
||||||
|
const to = leftToRight ? width : -1;
|
||||||
|
const step = leftToRight ? 1 : -1;
|
||||||
|
|
||||||
|
for (let x = from; x !== to; x += step) {
|
||||||
|
const p = at(x, y);
|
||||||
|
const old = grey[p];
|
||||||
|
const next = old < 128 ? 0 : 255;
|
||||||
|
grey[p] = next;
|
||||||
|
const error = old - next;
|
||||||
|
|
||||||
|
const ahead = x + step;
|
||||||
|
const behind = x - step;
|
||||||
|
|
||||||
|
if (ahead >= 0 && ahead < width) grey[at(ahead, y)] += error * (7 / 16);
|
||||||
|
if (y + 1 < height) {
|
||||||
|
if (behind >= 0 && behind < width) grey[at(behind, y + 1)] += error * (3 / 16);
|
||||||
|
grey[at(x, y + 1)] += error * (5 / 16);
|
||||||
|
if (ahead >= 0 && ahead < width) grey[at(ahead, y + 1)] += error * (1 / 16);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Add a constant to every sample, clamped to the printable range. */
|
||||||
|
function applyShift(grey, shift) {
|
||||||
|
if (!shift) return;
|
||||||
|
for (let p = 0; p < grey.length; p++) {
|
||||||
|
grey[p] = Math.min(255, Math.max(0, grey[p] + shift));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fraction of dots that would burn, for a given luminance buffer. */
|
||||||
|
function coverageOf(grey, width, height) {
|
||||||
|
const trial = Float32Array.from(grey);
|
||||||
|
floydSteinberg(trial, width, height);
|
||||||
|
let black = 0;
|
||||||
|
for (let p = 0; p < trial.length; p++) if (trial[p] < 128) black++;
|
||||||
|
return black / trial.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find the brightness offset that lands the dithered result on a given ink
|
||||||
|
* coverage.
|
||||||
|
*
|
||||||
|
* Error diffusion preserves mean tone, so coverage is roughly 1 - mean/255 and
|
||||||
|
* the first guess can be computed directly rather than searched for. Clipping
|
||||||
|
* at the ends of the range spoils that slightly, so up to three cheap
|
||||||
|
* correction passes follow. Each pass is one dither over a few tens of
|
||||||
|
* thousands of samples — the whole thing runs in about 6 ms for a 24 mm photo.
|
||||||
|
*
|
||||||
|
* Capped at +/-120 so a very dark or very bright capture degrades into
|
||||||
|
* something faint rather than a blank square.
|
||||||
|
*/
|
||||||
|
function solveShiftForCoverage(grey, width, height, target, maxPasses = 3) {
|
||||||
|
const clamp = (v) => Math.min(120, Math.max(-120, v));
|
||||||
|
|
||||||
|
let mean = 0;
|
||||||
|
for (let p = 0; p < grey.length; p++) mean += grey[p];
|
||||||
|
mean /= grey.length;
|
||||||
|
|
||||||
|
let shift = clamp(255 * (1 - target) - mean);
|
||||||
|
|
||||||
|
for (let pass = 0; pass < maxPasses; pass++) {
|
||||||
|
const trial = Float32Array.from(grey);
|
||||||
|
applyShift(trial, shift);
|
||||||
|
const actual = coverageOf(trial, width, height);
|
||||||
|
const error = actual - target;
|
||||||
|
if (Math.abs(error) < 0.005) break;
|
||||||
|
// Coverage moves roughly linearly with the offset over this range.
|
||||||
|
shift = clamp(shift + error * 255);
|
||||||
|
}
|
||||||
|
|
||||||
|
return shift;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Dither a photo to 1-bit at a given square size.
|
||||||
|
*
|
||||||
|
* @param {import('@napi-rs/canvas').Image} image Loaded photo
|
||||||
|
* @param {number} size Final size in printer dots — must match the size it
|
||||||
|
* will be drawn at, or the dither is destroyed
|
||||||
|
* @param {Object} [options]
|
||||||
|
* @param {boolean} [options.levels=true] Stretch contrast first
|
||||||
|
* @param {number} [options.brightness=0] -100..100, nudge before dithering.
|
||||||
|
* Negative darkens.
|
||||||
|
* @param {number} [options.targetCoverage=0.333]
|
||||||
|
* Fraction of dots to burn, 0..1. The brightness needed to hit it is
|
||||||
|
* solved for, so every photo prints at the same density however it was
|
||||||
|
* lit. Raise it for a heavier print, lower it for a lighter one. Pass
|
||||||
|
* null to leave density alone and print whatever the photo gives.
|
||||||
|
* @returns {import('@napi-rs/canvas').Canvas} ready to pass to drawImage
|
||||||
|
*/
|
||||||
|
export function ditherPhoto(image, size, options = {}) {
|
||||||
|
const { levels = true, brightness = 0, targetCoverage = 0.333 } = options;
|
||||||
|
|
||||||
|
const canvas = createCanvas(size, size);
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
|
||||||
|
ctx.fillStyle = '#ffffff';
|
||||||
|
ctx.fillRect(0, 0, size, size);
|
||||||
|
|
||||||
|
// Cover-fit rather than stretch, so a non-square capture isn't distorted.
|
||||||
|
const scale = Math.max(size / image.width, size / image.height);
|
||||||
|
const drawWidth = image.width * scale;
|
||||||
|
const drawHeight = image.height * scale;
|
||||||
|
ctx.drawImage(
|
||||||
|
image,
|
||||||
|
(size - drawWidth) / 2,
|
||||||
|
(size - drawHeight) / 2,
|
||||||
|
drawWidth,
|
||||||
|
drawHeight
|
||||||
|
);
|
||||||
|
|
||||||
|
const pixels = ctx.getImageData(0, 0, size, size);
|
||||||
|
const { data } = pixels;
|
||||||
|
const grey = new Float32Array(size * size);
|
||||||
|
|
||||||
|
for (let p = 0, i = 0; p < grey.length; p++, i += 4) {
|
||||||
|
const a = data[i + 3] / 255;
|
||||||
|
grey[p] = luminance(
|
||||||
|
data[i] * a + 255 * (1 - a),
|
||||||
|
data[i + 1] * a + 255 * (1 - a),
|
||||||
|
data[i + 2] * a + 255 * (1 - a)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (levels) autoLevels(grey);
|
||||||
|
|
||||||
|
if (brightness !== 0) applyShift(grey, (brightness / 100) * 255);
|
||||||
|
|
||||||
|
if (targetCoverage != null) {
|
||||||
|
applyShift(grey, solveShiftForCoverage(grey, size, size, targetCoverage));
|
||||||
|
}
|
||||||
|
|
||||||
|
floydSteinberg(grey, size, size);
|
||||||
|
|
||||||
|
for (let p = 0, i = 0; p < grey.length; p++, i += 4) {
|
||||||
|
const v = grey[p] < 128 ? 0 : 255;
|
||||||
|
data[i] = v;
|
||||||
|
data[i + 1] = v;
|
||||||
|
data[i + 2] = v;
|
||||||
|
data[i + 3] = 255;
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.putImageData(pixels, 0, 0);
|
||||||
|
return canvas;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ditherPhoto;
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
import { createCanvas, loadImage } from '@napi-rs/canvas';
|
||||||
|
|
||||||
|
import { getMedia, buildJob, PIXEL_WIDTH } from './ql-raster.js';
|
||||||
|
import { probeStatus, sendJob, DEFAULT_PORT } from './ql-transport.js';
|
||||||
|
import { describeProblem, checkMediaMatches } from './ql-status.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends a rendered badge to a Brother QL over the network, speaking the
|
||||||
|
* printer's raster protocol directly.
|
||||||
|
*
|
||||||
|
* This is the drop-in replacement for shelling out to the Python brother_ql
|
||||||
|
* CLI in printer.js. Same job, minus a Python runtime in the image and minus
|
||||||
|
* writing every badge to a temp file.
|
||||||
|
*
|
||||||
|
* What it does NOT buy us is reliable printer state. The QL-820NWB accepts
|
||||||
|
* jobs on port 9100 but stays silent over TCP; status frames only come back
|
||||||
|
* over USB. So roll type, roll level and cover state are unknowable from here,
|
||||||
|
* exactly as they were with brother_ql. Status handling below is best effort:
|
||||||
|
* used when offered, never required.
|
||||||
|
*
|
||||||
|
* Input is the PNG renderBadgePng() already produces, so the badge layout,
|
||||||
|
* rotation and vertical centring are untouched.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Maps the site's printer_label value onto a media definition. */
|
||||||
|
const LABEL_TO_MEDIA = {
|
||||||
|
62: { media: '62', red: false },
|
||||||
|
'62red': { media: '62', red: true },
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The QL accepts one TCP connection at a time and has no job spooler worth the
|
||||||
|
* name. Two visitors signing in together would otherwise collide: a refused
|
||||||
|
* connection, a half-printed label, or both. One queue per printer host.
|
||||||
|
*
|
||||||
|
* Note this is in-process. If the app is ever scaled past one instance against
|
||||||
|
* a single printer, this needs to become a lock in SQLite instead.
|
||||||
|
*/
|
||||||
|
const queues = new Map();
|
||||||
|
|
||||||
|
function enqueue(host, task) {
|
||||||
|
const previous = queues.get(host) || Promise.resolve();
|
||||||
|
// Swallow the previous failure so one bad job doesn't poison the queue.
|
||||||
|
const next = previous.catch(() => {}).then(task);
|
||||||
|
queues.set(
|
||||||
|
host,
|
||||||
|
next.catch(() => {})
|
||||||
|
);
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decode a PNG into the black and red ink maps the printer wants.
|
||||||
|
*
|
||||||
|
* The renderer draws accent elements as pure #ff0000, so red separation is
|
||||||
|
* just a colour test. A dot never lands in both planes; the printer would burn
|
||||||
|
* it twice and the result is muddy brown.
|
||||||
|
*/
|
||||||
|
async function pngToPlanes(png, media, { red, threshold = 180 }) {
|
||||||
|
const image = await loadImage(png);
|
||||||
|
const width = image.width;
|
||||||
|
const height = image.height;
|
||||||
|
|
||||||
|
if (width > media.printableDots) {
|
||||||
|
throw new Error(
|
||||||
|
`Badge is ${width} dots wide but ${media.label} only prints ${media.printableDots}.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const canvas = createCanvas(width, height);
|
||||||
|
const ctx = canvas.getContext('2d');
|
||||||
|
ctx.fillStyle = '#ffffff';
|
||||||
|
ctx.fillRect(0, 0, width, height);
|
||||||
|
ctx.drawImage(image, 0, 0);
|
||||||
|
const { data } = ctx.getImageData(0, 0, width, height);
|
||||||
|
|
||||||
|
// Inset so the image lands on the paper rather than off the head's edge.
|
||||||
|
const xOffset = PIXEL_WIDTH - width - media.offsetR;
|
||||||
|
const size = PIXEL_WIDTH * height;
|
||||||
|
const black = new Uint8Array(size);
|
||||||
|
const redPlane = red ? new Uint8Array(size) : null;
|
||||||
|
|
||||||
|
for (let y = 0; y < height; y++) {
|
||||||
|
const srcRow = y * width * 4;
|
||||||
|
const dstRow = y * PIXEL_WIDTH + xOffset;
|
||||||
|
|
||||||
|
for (let x = 0; x < width; x++) {
|
||||||
|
const i = srcRow + x * 4;
|
||||||
|
const a = data[i + 3] / 255;
|
||||||
|
const r = data[i] * a + 255 * (1 - a);
|
||||||
|
const g = data[i + 1] * a + 255 * (1 - a);
|
||||||
|
const b = data[i + 2] * a + 255 * (1 - a);
|
||||||
|
|
||||||
|
if (red && r >= 90 && r - Math.max(g, b) >= 60) {
|
||||||
|
redPlane[dstRow + x] = 1;
|
||||||
|
} else if (0.299 * r + 0.587 * g + 0.114 * b <= threshold) {
|
||||||
|
black[dstRow + x] = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { width: PIXEL_WIDTH, height, black, red: redPlane };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Print one badge.
|
||||||
|
*
|
||||||
|
* @param {Buffer} png Output of renderBadgePng()
|
||||||
|
* @param {Object} options
|
||||||
|
* @param {string} options.host
|
||||||
|
* @param {number} [options.port=9100]
|
||||||
|
* @param {string} [options.label='62'] The site's printer_label value
|
||||||
|
* @param {boolean} [options.cut=true]
|
||||||
|
* @param {number} [options.threshold] Luminance cutover, 0-255; higher is bolder
|
||||||
|
* @param {boolean} [options.checkMedia=true] Best effort; skipped if the printer is mute
|
||||||
|
* @returns {Promise<{ok: boolean, confirmed?: boolean, message: string}>}
|
||||||
|
*/
|
||||||
|
export async function printPng(png, options = {}) {
|
||||||
|
const {
|
||||||
|
host,
|
||||||
|
port = DEFAULT_PORT,
|
||||||
|
label = '62',
|
||||||
|
cut = true,
|
||||||
|
threshold,
|
||||||
|
checkMedia = true,
|
||||||
|
compress = false,
|
||||||
|
} = options;
|
||||||
|
|
||||||
|
if (!host) return { ok: false, message: 'No printer host is configured for this site.' };
|
||||||
|
|
||||||
|
const mapping = LABEL_TO_MEDIA[label] || LABEL_TO_MEDIA['62'];
|
||||||
|
const media = getMedia(mapping.media);
|
||||||
|
|
||||||
|
return enqueue(host, async () => {
|
||||||
|
try {
|
||||||
|
if (checkMedia) {
|
||||||
|
const probe = await probeStatus(host, { port });
|
||||||
|
if (!probe.reachable) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
message: probe.error || `Cannot reach printer at ${host}:${port}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// A silent printer is the normal case over TCP, so absent status must
|
||||||
|
// never block the job — the visitor is already signed in and waiting.
|
||||||
|
if (probe.status) {
|
||||||
|
const problem =
|
||||||
|
describeProblem(probe.status) || checkMediaMatches(probe.status, media);
|
||||||
|
if (problem) return { ok: false, message: problem };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const page = await pngToPlanes(png, media, { red: mapping.red, threshold });
|
||||||
|
const job = buildJob([page], { media: media.id, cut, compress });
|
||||||
|
|
||||||
|
const result = await sendJob(host, job, { port });
|
||||||
|
const last = result.frames[result.frames.length - 1];
|
||||||
|
const problem = last ? describeProblem(last) : null;
|
||||||
|
|
||||||
|
if (problem) return { ok: false, message: problem };
|
||||||
|
|
||||||
|
// Without status frames, "delivered" is as strong a claim as we can make.
|
||||||
|
// Don't dress that up as confirmation the label physically came out.
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
confirmed: result.statusAvailable,
|
||||||
|
message: result.statusAvailable
|
||||||
|
? `Printed to ${host}`
|
||||||
|
: `Sent to ${host} (this printer does not confirm over the network)`,
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
return { ok: false, message: err.message };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ask the printer how it is, without printing.
|
||||||
|
*
|
||||||
|
* `ready` is tri-state: true, false, or null for "reachable but it won't say",
|
||||||
|
* which is the normal answer over the network. Treat null as unknown in the
|
||||||
|
* admin console rather than colouring it green or red.
|
||||||
|
*/
|
||||||
|
export async function printerHealth({ host, port = DEFAULT_PORT, label = '62' }) {
|
||||||
|
if (!host) return { online: false, ready: false, message: 'No printer configured' };
|
||||||
|
|
||||||
|
const mapping = LABEL_TO_MEDIA[label] || LABEL_TO_MEDIA['62'];
|
||||||
|
const media = getMedia(mapping.media);
|
||||||
|
|
||||||
|
const probe = await probeStatus(host, { port });
|
||||||
|
|
||||||
|
if (!probe.reachable) {
|
||||||
|
return { online: false, ready: false, message: probe.error || 'Printer did not answer' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// The usual case on this hardware: reachable, but mute. Report that honestly
|
||||||
|
// rather than dressing silence up as either health or failure.
|
||||||
|
if (!probe.status) {
|
||||||
|
return {
|
||||||
|
online: true,
|
||||||
|
ready: null,
|
||||||
|
message:
|
||||||
|
'Reachable. This printer does not report status over the network, so ' +
|
||||||
|
'roll type, roll level and cover state cannot be checked from here.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const problem = describeProblem(probe.status) || checkMediaMatches(probe.status, media);
|
||||||
|
return {
|
||||||
|
online: true,
|
||||||
|
ready: !problem,
|
||||||
|
message: problem || 'Ready',
|
||||||
|
mediaWidthMm: probe.status.mediaWidthMm,
|
||||||
|
mediaType: probe.status.mediaType,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export { LABEL_TO_MEDIA };
|
||||||
@@ -0,0 +1,378 @@
|
|||||||
|
/**
|
||||||
|
* Brother QL-8xx raster command builder.
|
||||||
|
*
|
||||||
|
* Byte-level command sequence follows Brother's "Raster Command Reference,
|
||||||
|
* QL-800/810W/820NWB, Version 1.01". Where that manual and the reference
|
||||||
|
* implementation in pklaus/brother_ql disagree, the manual wins — brother_ql
|
||||||
|
* targets older models and its defaults are not correct for this hardware.
|
||||||
|
*
|
||||||
|
* The QL-820NWB print head is 720 dots wide (60.96 mm at 300 dpi). Every
|
||||||
|
* raster line transmitted is therefore exactly 90 bytes before compression,
|
||||||
|
* regardless of the media loaded. Narrower media just means more of those
|
||||||
|
* dots fall outside the paper.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const PIXEL_WIDTH = 720;
|
||||||
|
const BYTES_PER_ROW = PIXEL_WIDTH / 8; // 90
|
||||||
|
|
||||||
|
// Manual section 2.1: "Sends a 400-byte invalidate command". brother_ql sends
|
||||||
|
// 200, which works on older models but is not what this hardware documents.
|
||||||
|
const INVALIDATE_BYTES = 400;
|
||||||
|
|
||||||
|
// Manual section 2.3.4. Continuous media outside this range is rejected.
|
||||||
|
const MIN_LENGTH_DOTS = 150; // 12.7 mm
|
||||||
|
const MAX_LENGTH_DOTS = 11811; // 1000 mm
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Media definitions, from manual sections 2.3.2 and 2.3.5.
|
||||||
|
*
|
||||||
|
* `printableDots` is how many of the 720 head pins land on the label;
|
||||||
|
* `offsetR` is the number of right-margin pins. For 62 mm continuous the
|
||||||
|
* manual gives 12 left / 696 print area / 12 right.
|
||||||
|
*/
|
||||||
|
const MEDIA = {
|
||||||
|
// DK-22205 (62 mm white) and DK-22251 (62 mm black/red) — continuous.
|
||||||
|
'62': {
|
||||||
|
id: '62',
|
||||||
|
label: '62 mm continuous',
|
||||||
|
dieCut: false,
|
||||||
|
widthMm: 62,
|
||||||
|
lengthMm: 0,
|
||||||
|
printableDots: 696,
|
||||||
|
offsetR: 12,
|
||||||
|
feedMargin: 35, // 3 mm, the documented minimum for continuous tape
|
||||||
|
},
|
||||||
|
// Die-cut sizes, kept for completeness.
|
||||||
|
'62x29': {
|
||||||
|
id: '62x29',
|
||||||
|
label: '62 mm x 29 mm die-cut',
|
||||||
|
dieCut: true,
|
||||||
|
widthMm: 62,
|
||||||
|
lengthMm: 29,
|
||||||
|
printableDots: 696,
|
||||||
|
lengthDots: 271,
|
||||||
|
offsetR: 12,
|
||||||
|
feedMargin: 0, // must be 0 for die-cut
|
||||||
|
},
|
||||||
|
'62x100': {
|
||||||
|
id: '62x100',
|
||||||
|
label: '62 mm x 100 mm die-cut',
|
||||||
|
dieCut: true,
|
||||||
|
widthMm: 62,
|
||||||
|
lengthMm: 100,
|
||||||
|
printableDots: 696,
|
||||||
|
lengthDots: 1109,
|
||||||
|
offsetR: 12,
|
||||||
|
feedMargin: 0,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
function getMedia(id) {
|
||||||
|
const media = MEDIA[id];
|
||||||
|
if (!media) {
|
||||||
|
throw new Error(
|
||||||
|
`Unknown media "${id}". Known media: ${Object.keys(MEDIA).join(', ')}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return media;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ *
|
||||||
|
* Bit packing
|
||||||
|
* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pack one row of the ink map into the 90 bytes the printer expects.
|
||||||
|
*
|
||||||
|
* The printer clocks each raster line out starting from the far side of the
|
||||||
|
* head, so the first transmitted bit is the RIGHTMOST dot. brother_ql achieves
|
||||||
|
* this by mirroring the image before packing; we do the same thing directly
|
||||||
|
* with an index flip, which avoids materialising a mirrored copy.
|
||||||
|
*
|
||||||
|
* Get this wrong and every label prints mirrored. See the byte-order tests.
|
||||||
|
*
|
||||||
|
* @param {Uint8Array} ink Full-image ink map, 1 byte per dot, 1 = burn.
|
||||||
|
* @param {number} rowStart Offset of this row within `ink`.
|
||||||
|
* @returns {Buffer} 90 bytes.
|
||||||
|
*/
|
||||||
|
function packRow(ink, rowStart) {
|
||||||
|
const out = Buffer.alloc(BYTES_PER_ROW);
|
||||||
|
for (let x = 0; x < PIXEL_WIDTH; x++) {
|
||||||
|
if (ink[rowStart + x] === 0) continue;
|
||||||
|
const i = PIXEL_WIDTH - 1 - x;
|
||||||
|
out[i >> 3] |= 0x80 >> (i & 7);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TIFF PackBits encoder, as used by the QL compression mode.
|
||||||
|
* Worst case for 90 bytes of input is 91 bytes out, so the result always
|
||||||
|
* fits the single-byte length field.
|
||||||
|
*/
|
||||||
|
function packBits(input) {
|
||||||
|
const out = [];
|
||||||
|
let i = 0;
|
||||||
|
const n = input.length;
|
||||||
|
|
||||||
|
while (i < n) {
|
||||||
|
// Look for a run of 3+ identical bytes.
|
||||||
|
let runEnd = i + 1;
|
||||||
|
while (runEnd < n && input[runEnd] === input[i] && runEnd - i < 128) runEnd++;
|
||||||
|
const runLength = runEnd - i;
|
||||||
|
|
||||||
|
if (runLength >= 3) {
|
||||||
|
out.push(257 - runLength, input[i]);
|
||||||
|
i = runEnd;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otherwise accumulate a literal run, stopping before any 3-byte run.
|
||||||
|
let litStart = i;
|
||||||
|
let litEnd = i;
|
||||||
|
while (litEnd < n && litEnd - litStart < 128) {
|
||||||
|
if (
|
||||||
|
litEnd + 2 < n &&
|
||||||
|
input[litEnd] === input[litEnd + 1] &&
|
||||||
|
input[litEnd] === input[litEnd + 2]
|
||||||
|
) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
litEnd++;
|
||||||
|
}
|
||||||
|
const litLength = litEnd - litStart;
|
||||||
|
out.push(litLength - 1);
|
||||||
|
for (let k = litStart; k < litEnd; k++) out.push(input[k]);
|
||||||
|
i = litEnd;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Buffer.from(out);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ *
|
||||||
|
* Command primitives
|
||||||
|
* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
const CMD = {
|
||||||
|
invalidate: () => Buffer.alloc(INVALIDATE_BYTES, 0x00),
|
||||||
|
initialize: () => Buffer.from([0x1b, 0x40]), // ESC @
|
||||||
|
statusRequest: () => Buffer.from([0x1b, 0x69, 0x53]), // ESC i S
|
||||||
|
switchToRaster: () => Buffer.from([0x1b, 0x69, 0x61, 0x01]), // ESC i a 1
|
||||||
|
|
||||||
|
/** ESC i ! — automatic status notification. 0 = notify, 1 = stay quiet. */
|
||||||
|
statusNotification: (notify) =>
|
||||||
|
Buffer.from([0x1b, 0x69, 0x21, notify ? 0x00 : 0x01]),
|
||||||
|
|
||||||
|
/** ESC i z — media type, width, length, raster count, page flag. */
|
||||||
|
mediaAndQuality({ media, rasterLines, firstPage, highQuality, twoColour }) {
|
||||||
|
let flags = 0x80; // printer recovery always on
|
||||||
|
flags |= 0x02; // media type valid
|
||||||
|
flags |= 0x04; // media width valid
|
||||||
|
|
||||||
|
// Only meaningful for die-cut stock. Brother's own driver sends 0x86 for
|
||||||
|
// continuous tape — no length bit — and the manual warns that asserting a
|
||||||
|
// valid flag the loaded media doesn't match returns a "replace media"
|
||||||
|
// error (error information 2, bit 0).
|
||||||
|
if (media.dieCut) flags |= 0x08;
|
||||||
|
|
||||||
|
// The manual marks the print-quality bit as invalid for two-colour work.
|
||||||
|
if (highQuality && !twoColour) flags |= 0x40;
|
||||||
|
|
||||||
|
const buf = Buffer.alloc(13);
|
||||||
|
buf[0] = 0x1b;
|
||||||
|
buf[1] = 0x69;
|
||||||
|
buf[2] = 0x7a;
|
||||||
|
buf[3] = flags;
|
||||||
|
buf[4] = media.dieCut ? 0x0b : 0x0a;
|
||||||
|
buf[5] = media.widthMm & 0xff;
|
||||||
|
buf[6] = media.dieCut ? media.lengthMm & 0xff : 0x00;
|
||||||
|
// For two-colour, one raster line is the whole 186-byte packet
|
||||||
|
// ('w' 01 90 <90> 'w' 02 90 <90>), so this stays a line count either way.
|
||||||
|
buf.writeUInt32LE(rasterLines >>> 0, 7);
|
||||||
|
buf[11] = firstPage ? 0x00 : 0x01;
|
||||||
|
buf[12] = 0x00;
|
||||||
|
return buf;
|
||||||
|
},
|
||||||
|
|
||||||
|
/** ESC i M — auto cut on/off (bit 6). */
|
||||||
|
autoCut: (enabled) => Buffer.from([0x1b, 0x69, 0x4d, enabled ? 0x40 : 0x00]),
|
||||||
|
|
||||||
|
/** ESC i A — cut every n labels. */
|
||||||
|
cutEvery: (n) => Buffer.from([0x1b, 0x69, 0x41, n & 0xff]),
|
||||||
|
|
||||||
|
/** ESC i K — bit 0 two-colour, bit 3 cut at end, bit 6 600 dpi. */
|
||||||
|
expandedMode({ twoColour, cutAtEnd, dpi600 }) {
|
||||||
|
let flags = 0x00;
|
||||||
|
if (twoColour) flags |= 1 << 0;
|
||||||
|
if (cutAtEnd) flags |= 1 << 3;
|
||||||
|
if (dpi600) flags |= 1 << 6;
|
||||||
|
return Buffer.from([0x1b, 0x69, 0x4b, flags]);
|
||||||
|
},
|
||||||
|
|
||||||
|
/** ESC i d — feed / margin amount in dots. */
|
||||||
|
margins(dots) {
|
||||||
|
const buf = Buffer.alloc(5);
|
||||||
|
buf[0] = 0x1b;
|
||||||
|
buf[1] = 0x69;
|
||||||
|
buf[2] = 0x64;
|
||||||
|
buf.writeUInt16LE(dots & 0xffff, 3);
|
||||||
|
return buf;
|
||||||
|
},
|
||||||
|
|
||||||
|
/** M — compression mode (2 = PackBits). Not supported on the QL-800. */
|
||||||
|
compression: (enabled) => Buffer.from([0x4d, enabled ? 0x02 : 0x00]),
|
||||||
|
|
||||||
|
/** 0x1A ends the last page, 0x0C ends an intermediate page. */
|
||||||
|
print: (lastPage) => Buffer.from([lastPage ? 0x1a : 0x0c]),
|
||||||
|
};
|
||||||
|
|
||||||
|
/* ------------------------------------------------------------------ *
|
||||||
|
* Job assembly
|
||||||
|
* ------------------------------------------------------------------ */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @typedef {Object} Plane
|
||||||
|
* @property {number} width Must be 720.
|
||||||
|
* @property {number} height Raster lines.
|
||||||
|
* @property {Uint8Array} black 1 byte per dot, non-zero = burn black.
|
||||||
|
* @property {Uint8Array} [red] Same shape; omit for monochrome.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the complete byte stream for one or more pages.
|
||||||
|
*
|
||||||
|
* @param {Plane[]} pages
|
||||||
|
* @param {Object} [options]
|
||||||
|
* @param {string} [options.media='62']
|
||||||
|
* @param {boolean} [options.cut=true] Cut after the last label.
|
||||||
|
* @param {number} [options.cutEvery=1]
|
||||||
|
* @param {boolean} [options.highQuality=true]
|
||||||
|
* @param {boolean} [options.compress=false]
|
||||||
|
* @returns {Buffer}
|
||||||
|
*/
|
||||||
|
function buildJob(pages, options = {}) {
|
||||||
|
const {
|
||||||
|
media: mediaId = '62',
|
||||||
|
cut = true,
|
||||||
|
cutEvery = 1,
|
||||||
|
highQuality = true,
|
||||||
|
compress = false,
|
||||||
|
} = options;
|
||||||
|
|
||||||
|
const media = getMedia(mediaId);
|
||||||
|
if (!Array.isArray(pages) || pages.length === 0) {
|
||||||
|
throw new Error('buildJob requires at least one page');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialisation commands, once per job (manual section 2.1).
|
||||||
|
const chunks = [CMD.invalidate(), CMD.initialize()];
|
||||||
|
|
||||||
|
pages.forEach((page, index) => {
|
||||||
|
validatePage(page, media);
|
||||||
|
|
||||||
|
const twoColour = Boolean(page.red);
|
||||||
|
const isFirst = index === 0;
|
||||||
|
const isLast = index === pages.length - 1;
|
||||||
|
|
||||||
|
// Control codes, repeated for every page, in the manual's documented order.
|
||||||
|
chunks.push(CMD.switchToRaster());
|
||||||
|
chunks.push(CMD.statusNotification(true));
|
||||||
|
chunks.push(
|
||||||
|
CMD.mediaAndQuality({
|
||||||
|
media,
|
||||||
|
rasterLines: page.height,
|
||||||
|
firstPage: isFirst,
|
||||||
|
highQuality,
|
||||||
|
twoColour,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
chunks.push(CMD.autoCut(cut));
|
||||||
|
chunks.push(CMD.cutEvery(cutEvery));
|
||||||
|
chunks.push(CMD.expandedMode({ twoColour, cutAtEnd: cut, dpi600: false }));
|
||||||
|
chunks.push(CMD.margins(media.feedMargin));
|
||||||
|
if (compress) chunks.push(CMD.compression(true));
|
||||||
|
|
||||||
|
chunks.push(encodeRasterData(page, compress));
|
||||||
|
chunks.push(CMD.print(isLast));
|
||||||
|
});
|
||||||
|
|
||||||
|
return Buffer.concat(chunks);
|
||||||
|
}
|
||||||
|
|
||||||
|
function validatePage(page, media) {
|
||||||
|
if (page.width !== PIXEL_WIDTH) {
|
||||||
|
throw new Error(
|
||||||
|
`Page width must be ${PIXEL_WIDTH} dots, got ${page.width}. ` +
|
||||||
|
`Pad the ${media.printableDots}-dot printable area out to the full head width.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!media.dieCut) {
|
||||||
|
if (page.height < MIN_LENGTH_DOTS) {
|
||||||
|
throw new Error(
|
||||||
|
`Page is ${page.height} dots long; continuous media needs at least ${MIN_LENGTH_DOTS}.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (page.height > MAX_LENGTH_DOTS) {
|
||||||
|
throw new Error(
|
||||||
|
`Page is ${page.height} dots long; the maximum is ${MAX_LENGTH_DOTS}.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else if (page.height !== media.lengthDots) {
|
||||||
|
throw new Error(
|
||||||
|
`Die-cut media ${media.id} needs exactly ${media.lengthDots} raster lines, got ${page.height}.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const expected = page.width * page.height;
|
||||||
|
if (page.black.length !== expected) {
|
||||||
|
throw new Error(
|
||||||
|
`Black plane is ${page.black.length} bytes, expected ${expected}.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (page.red && page.red.length !== expected) {
|
||||||
|
throw new Error(`Red plane is ${page.red.length} bytes, expected ${expected}.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeRasterData(page, compress) {
|
||||||
|
const chunks = [];
|
||||||
|
const twoColour = Boolean(page.red);
|
||||||
|
|
||||||
|
for (let y = 0; y < page.height; y++) {
|
||||||
|
const rowStart = y * page.width;
|
||||||
|
const planes = twoColour
|
||||||
|
? [packRow(page.black, rowStart), packRow(page.red, rowStart)]
|
||||||
|
: [packRow(page.black, rowStart)];
|
||||||
|
|
||||||
|
planes.forEach((row, planeIndex) => {
|
||||||
|
const payload = compress ? packBits(row) : row;
|
||||||
|
// 'w' 0x01 = first colour (high energy, black), 'w' 0x02 = second colour
|
||||||
|
// (low energy, red). 'g' 0x00 is the monochrome transfer.
|
||||||
|
const header = twoColour
|
||||||
|
? Buffer.from([0x77, planeIndex === 0 ? 0x01 : 0x02, payload.length])
|
||||||
|
: Buffer.from([0x67, 0x00, payload.length]);
|
||||||
|
chunks.push(header, payload);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return Buffer.concat(chunks);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Bytes that ask the printer for a status frame and nothing else. */
|
||||||
|
function buildStatusRequest() {
|
||||||
|
return Buffer.concat([CMD.invalidate(), CMD.initialize(), CMD.statusRequest()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
PIXEL_WIDTH,
|
||||||
|
BYTES_PER_ROW,
|
||||||
|
INVALIDATE_BYTES,
|
||||||
|
MIN_LENGTH_DOTS,
|
||||||
|
MAX_LENGTH_DOTS,
|
||||||
|
MEDIA,
|
||||||
|
getMedia,
|
||||||
|
buildJob,
|
||||||
|
buildStatusRequest,
|
||||||
|
packBits,
|
||||||
|
packRow,
|
||||||
|
CMD,
|
||||||
|
};
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
/**
|
||||||
|
* Decoder for the 32-byte status frame the QL series sends back.
|
||||||
|
*
|
||||||
|
* Field layout and every code below is from Brother's "Raster Command
|
||||||
|
* Reference, QL-800/810W/820NWB v1.01", section 4, "Status information
|
||||||
|
* request".
|
||||||
|
*
|
||||||
|
* Note this is only useful over USB. Manual section 5.9 shows the network
|
||||||
|
* flow: over a TCP/IP port the print data is simply sent as-is and no status
|
||||||
|
* comes back. See probeStatus in ql-transport.js.
|
||||||
|
*
|
||||||
|
* 0 print head mark (0x80)
|
||||||
|
* 1 size (0x20)
|
||||||
|
* 2 fixed 'B' (0x42)
|
||||||
|
* 3 series code, fixed '4' (0x34)
|
||||||
|
* 4 model code
|
||||||
|
* 5-7 fixed
|
||||||
|
* 8 error information 1
|
||||||
|
* 9 error information 2
|
||||||
|
* 10 media width in mm
|
||||||
|
* 11 media type
|
||||||
|
* 12-13 fixed
|
||||||
|
* 14 fixed 0x3F
|
||||||
|
* 15 mode
|
||||||
|
* 16 fixed
|
||||||
|
* 17 media length in mm
|
||||||
|
* 18 status type
|
||||||
|
* 19 phase type
|
||||||
|
* 20-21 phase number (big endian)
|
||||||
|
* 22 notification number
|
||||||
|
* 23-31 reserved
|
||||||
|
*/
|
||||||
|
|
||||||
|
const FRAME_LENGTH = 32;
|
||||||
|
|
||||||
|
const ERROR_BITS_1 = [
|
||||||
|
[0x01, 'No media loaded'],
|
||||||
|
[0x02, 'End of media reached'],
|
||||||
|
[0x04, 'Cutter jam'],
|
||||||
|
[0x10, 'Printer busy'],
|
||||||
|
[0x20, 'Printer turned off'],
|
||||||
|
[0x40, 'High-voltage adapter fault'],
|
||||||
|
[0x80, 'Fan motor fault'],
|
||||||
|
];
|
||||||
|
|
||||||
|
const ERROR_BITS_2 = [
|
||||||
|
[
|
||||||
|
0x01,
|
||||||
|
'Media mismatch — the loaded roll does not match the job. A black/red ' +
|
||||||
|
'roll rejects a monochrome job, and vice versa.',
|
||||||
|
],
|
||||||
|
[0x02, 'Expansion buffer full'],
|
||||||
|
[0x04, 'Communication error'],
|
||||||
|
[0x08, 'Communication buffer full'],
|
||||||
|
[0x10, 'Cover is open'],
|
||||||
|
[0x20, 'Cancelled at the printer'],
|
||||||
|
[0x40, 'Media cannot be fed, or the end of the media was detected'],
|
||||||
|
[0x80, 'System error'],
|
||||||
|
];
|
||||||
|
|
||||||
|
const STATUS_TYPES = {
|
||||||
|
0x00: 'reply',
|
||||||
|
0x01: 'printing_completed',
|
||||||
|
0x02: 'error',
|
||||||
|
0x04: 'turned_off',
|
||||||
|
0x05: 'notification',
|
||||||
|
0x06: 'phase_change',
|
||||||
|
};
|
||||||
|
|
||||||
|
const PHASE_TYPES = {
|
||||||
|
0x00: 'waiting_to_receive',
|
||||||
|
0x01: 'printing',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Notification numbers. Cooling pauses printing but is not a failure. */
|
||||||
|
const NOTIFICATIONS = {
|
||||||
|
0x00: null,
|
||||||
|
0x03: 'Print head cooling (started)',
|
||||||
|
0x04: 'Print head cooling (finished)',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Byte 4 of the status frame. */
|
||||||
|
const MODEL_CODES = {
|
||||||
|
0x38: 'QL-800',
|
||||||
|
0x39: 'QL-810W',
|
||||||
|
0x41: 'QL-820NWB',
|
||||||
|
};
|
||||||
|
|
||||||
|
const MEDIA_TYPES = {
|
||||||
|
0x00: 'none',
|
||||||
|
0x0a: 'continuous',
|
||||||
|
0x0b: 'die_cut',
|
||||||
|
0x4a: 'continuous',
|
||||||
|
0x4b: 'die_cut',
|
||||||
|
0xff: 'incompatible',
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decode a status frame.
|
||||||
|
* @param {Buffer} buf
|
||||||
|
* @returns {Object|null} null if the buffer isn't a recognisable frame.
|
||||||
|
*/
|
||||||
|
function decodeStatus(buf) {
|
||||||
|
if (!buf || buf.length < FRAME_LENGTH) return null;
|
||||||
|
if (buf[0] !== 0x80 || buf[1] !== 0x20) return null;
|
||||||
|
|
||||||
|
const errors = [];
|
||||||
|
for (const [bit, message] of ERROR_BITS_1) {
|
||||||
|
if (buf[8] & bit) errors.push(message);
|
||||||
|
}
|
||||||
|
for (const [bit, message] of ERROR_BITS_2) {
|
||||||
|
if (buf[9] & bit) errors.push(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
const statusType = STATUS_TYPES[buf[18]] || `unknown_0x${buf[18].toString(16)}`;
|
||||||
|
|
||||||
|
return {
|
||||||
|
model: MODEL_CODES[buf[4]] || `unknown_0x${buf[4].toString(16)}`,
|
||||||
|
errors,
|
||||||
|
hasError: errors.length > 0 || buf[18] === 0x02,
|
||||||
|
mediaWidthMm: buf[10],
|
||||||
|
mediaLengthMm: buf[17],
|
||||||
|
mediaType: MEDIA_TYPES[buf[11]] || `unknown_0x${buf[11].toString(16)}`,
|
||||||
|
mediaLoaded: buf[11] !== 0x00,
|
||||||
|
statusType,
|
||||||
|
phaseType: PHASE_TYPES[buf[19]] || `unknown_0x${buf[19].toString(16)}`,
|
||||||
|
phaseNumber: buf.readUInt16BE(20),
|
||||||
|
notification: NOTIFICATIONS[buf[22]] ?? `unknown_0x${buf[22].toString(16)}`,
|
||||||
|
cooling: buf[22] === 0x03,
|
||||||
|
raw: Buffer.from(buf.subarray(0, FRAME_LENGTH)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Split a stream of concatenated frames. The printer often sends several
|
||||||
|
* (phase change, then printing completed) in one go.
|
||||||
|
* @param {Buffer} buf
|
||||||
|
* @returns {Object[]}
|
||||||
|
*/
|
||||||
|
function decodeAll(buf) {
|
||||||
|
const out = [];
|
||||||
|
for (let offset = 0; offset + FRAME_LENGTH <= buf.length; offset += FRAME_LENGTH) {
|
||||||
|
const frame = decodeStatus(buf.subarray(offset, offset + FRAME_LENGTH));
|
||||||
|
if (frame) out.push(frame);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Turn a decoded frame into something worth showing a receptionist.
|
||||||
|
* Returns null when nothing is wrong.
|
||||||
|
*/
|
||||||
|
function describeProblem(status) {
|
||||||
|
if (!status) return null;
|
||||||
|
if (status.errors.length > 0) return status.errors.join('; ');
|
||||||
|
if (status.statusType === 'error') return 'The printer reported an unspecified error';
|
||||||
|
if (status.statusType === 'turned_off') return 'The printer is turning off';
|
||||||
|
if (!status.mediaLoaded) return 'No label roll detected';
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check the loaded roll matches what the job expects.
|
||||||
|
*
|
||||||
|
* Worth doing before sending where status is available: a monochrome job on a
|
||||||
|
* black/red roll is refused outright, and the printer's own message ("change
|
||||||
|
* it to Monochrome media") points at the driver rather than at the roll
|
||||||
|
* setting, which sends people the wrong way.
|
||||||
|
*
|
||||||
|
* @returns {string|null} a problem description, or null if it matches.
|
||||||
|
*/
|
||||||
|
function checkMediaMatches(status, media) {
|
||||||
|
if (!status) return null;
|
||||||
|
if (!status.mediaLoaded) return 'No label roll is loaded';
|
||||||
|
if (status.mediaWidthMm !== media.widthMm) {
|
||||||
|
return `Wrong roll loaded: printer reports ${status.mediaWidthMm} mm, job needs ${media.widthMm} mm`;
|
||||||
|
}
|
||||||
|
const wantDieCut = Boolean(media.dieCut);
|
||||||
|
const isDieCut = status.mediaType === 'die_cut';
|
||||||
|
if (wantDieCut !== isDieCut) {
|
||||||
|
return wantDieCut
|
||||||
|
? 'Job needs die-cut labels but continuous tape is loaded'
|
||||||
|
: 'Job needs continuous tape but die-cut labels are loaded';
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
FRAME_LENGTH,
|
||||||
|
MODEL_CODES,
|
||||||
|
decodeStatus,
|
||||||
|
decodeAll,
|
||||||
|
describeProblem,
|
||||||
|
checkMediaMatches,
|
||||||
|
};
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
import net from 'node:net';
|
||||||
|
|
||||||
|
import { decodeAll, FRAME_LENGTH } from './ql-status.js';
|
||||||
|
import { buildStatusRequest } from './ql-raster.js';
|
||||||
|
|
||||||
|
const DEFAULT_PORT = 9100;
|
||||||
|
const DEFAULT_CONNECT_TIMEOUT = 5000;
|
||||||
|
const DEFAULT_JOB_TIMEOUT = 30000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Open a socket, run `handler`, and always clean up afterwards.
|
||||||
|
* The QL only accepts one connection at a time, so every helper here
|
||||||
|
* connects, does its work, and disconnects.
|
||||||
|
*/
|
||||||
|
function withSocket(host, port, connectTimeout, handler) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const socket = new net.Socket();
|
||||||
|
let settled = false;
|
||||||
|
|
||||||
|
const finish = (err, value) => {
|
||||||
|
if (settled) return;
|
||||||
|
settled = true;
|
||||||
|
socket.removeAllListeners();
|
||||||
|
socket.destroy();
|
||||||
|
if (err) reject(err);
|
||||||
|
else resolve(value);
|
||||||
|
};
|
||||||
|
|
||||||
|
socket.setTimeout(connectTimeout);
|
||||||
|
socket.once('timeout', () =>
|
||||||
|
finish(new Error(`Timed out connecting to ${host}:${port}`))
|
||||||
|
);
|
||||||
|
socket.once('error', (err) =>
|
||||||
|
finish(new Error(`Cannot reach printer at ${host}:${port} — ${err.message}`))
|
||||||
|
);
|
||||||
|
|
||||||
|
socket.connect(port, host, () => {
|
||||||
|
socket.setTimeout(0);
|
||||||
|
handler(socket, finish);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Probe the printer.
|
||||||
|
*
|
||||||
|
* Never throws for the "connected but silent" case, because that is the normal
|
||||||
|
* result on this hardware: the QL-820NWB accepts jobs on port 9100 but does not
|
||||||
|
* report state back over TCP — status frames only come back over USB. brother_ql
|
||||||
|
* documents the same limitation for its network backend. A silent printer is
|
||||||
|
* therefore reachable-and-probably-fine, not broken, and callers must treat a
|
||||||
|
* null status as "unknown" rather than "bad".
|
||||||
|
*
|
||||||
|
* @returns {Promise<{reachable: boolean, status: Object|null, error: string|null}>}
|
||||||
|
*/
|
||||||
|
async function probeStatus(host, options = {}) {
|
||||||
|
const {
|
||||||
|
port = DEFAULT_PORT,
|
||||||
|
connectTimeout = DEFAULT_CONNECT_TIMEOUT,
|
||||||
|
replyTimeout = 2000,
|
||||||
|
} = options;
|
||||||
|
|
||||||
|
try {
|
||||||
|
return await withSocket(host, port, connectTimeout, (socket, finish) => {
|
||||||
|
let received = Buffer.alloc(0);
|
||||||
|
|
||||||
|
// No reply is the expected outcome over the network, so this timer is the
|
||||||
|
// normal path rather than an error path. Keep it short.
|
||||||
|
const timer = setTimeout(
|
||||||
|
() => finish(null, { reachable: true, status: null, error: null }),
|
||||||
|
replyTimeout
|
||||||
|
);
|
||||||
|
|
||||||
|
socket.on('data', (chunk) => {
|
||||||
|
received = Buffer.concat([received, chunk]);
|
||||||
|
if (received.length >= FRAME_LENGTH) {
|
||||||
|
clearTimeout(timer);
|
||||||
|
const frames = decodeAll(received);
|
||||||
|
finish(null, {
|
||||||
|
reachable: true,
|
||||||
|
status: frames.length ? frames[frames.length - 1] : null,
|
||||||
|
error: null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.write(buildStatusRequest(), (err) => {
|
||||||
|
if (err) {
|
||||||
|
clearTimeout(timer);
|
||||||
|
finish(null, { reachable: false, status: null, error: err.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
return { reachable: false, status: null, error: err.message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a prepared job.
|
||||||
|
*
|
||||||
|
* Completion is signalled by the write flushing and the socket closing, NOT by
|
||||||
|
* a status frame — see probeStatus. If the printer does happen to answer, the
|
||||||
|
* frames come back as a bonus and a reported error is treated as authoritative.
|
||||||
|
*
|
||||||
|
* The write is followed by end(), not destroy(). destroy() can discard data
|
||||||
|
* still sitting in the kernel send buffer, which for a ~190 KB label job means
|
||||||
|
* a silently truncated print.
|
||||||
|
*
|
||||||
|
* @returns {Promise<{frames: Object[], completed: boolean, statusAvailable: boolean}>}
|
||||||
|
*/
|
||||||
|
async function sendJob(host, job, options = {}) {
|
||||||
|
const {
|
||||||
|
port = DEFAULT_PORT,
|
||||||
|
connectTimeout = DEFAULT_CONNECT_TIMEOUT,
|
||||||
|
jobTimeout = DEFAULT_JOB_TIMEOUT,
|
||||||
|
graceMs = 3000,
|
||||||
|
} = options;
|
||||||
|
|
||||||
|
return withSocket(host, port, connectTimeout, (socket, finish) => {
|
||||||
|
let received = Buffer.alloc(0);
|
||||||
|
const frames = [];
|
||||||
|
let sawCompleted = false;
|
||||||
|
let flushed = false;
|
||||||
|
|
||||||
|
const done = () =>
|
||||||
|
finish(null, {
|
||||||
|
frames,
|
||||||
|
completed: sawCompleted || flushed,
|
||||||
|
statusAvailable: frames.length > 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
finish(
|
||||||
|
new Error(
|
||||||
|
`Printer at ${host}:${port} did not accept the whole job within ${jobTimeout} ms`
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}, jobTimeout);
|
||||||
|
|
||||||
|
socket.on('data', (chunk) => {
|
||||||
|
received = Buffer.concat([received, chunk]);
|
||||||
|
while (received.length >= FRAME_LENGTH) {
|
||||||
|
const [frame] = decodeAll(received.subarray(0, FRAME_LENGTH));
|
||||||
|
received = received.subarray(FRAME_LENGTH);
|
||||||
|
if (!frame) continue;
|
||||||
|
frames.push(frame);
|
||||||
|
|
||||||
|
if (frame.hasError) {
|
||||||
|
clearTimeout(timer);
|
||||||
|
finish(null, { frames, completed: false, statusAvailable: true });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (frame.statusType === 'printing_completed') sawCompleted = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Peer closed and our data has gone out: the job is delivered.
|
||||||
|
socket.once('close', () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
done();
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.write(job, (err) => {
|
||||||
|
if (err) {
|
||||||
|
clearTimeout(timer);
|
||||||
|
finish(err);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
flushed = true;
|
||||||
|
// Half-close: flushes everything queued, then sends FIN.
|
||||||
|
socket.end();
|
||||||
|
|
||||||
|
// Some units never close their half of the connection. Once our data is
|
||||||
|
// out the job is delivered, so don't hold the queue open waiting on a FIN
|
||||||
|
// that may never arrive.
|
||||||
|
setTimeout(() => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
done();
|
||||||
|
}, graceMs);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export { DEFAULT_PORT, probeStatus, sendJob };
|
||||||
+5
-2
@@ -397,7 +397,7 @@ router.patch('/sites/:id', (req, res) => {
|
|||||||
badge_height_mm = ?, badge_show_photo = ?, badge_accent = ?, badge_note = ?,
|
badge_height_mm = ?, badge_show_photo = ?, badge_accent = ?, badge_note = ?,
|
||||||
colour_brand = ?, colour_signout = ?, colour_page = ?, colour_text = ?,
|
colour_brand = ?, colour_signout = ?, colour_page = ?, colour_text = ?,
|
||||||
banner_height = ?, banner_align = ?, printer_enabled = ?, printer_host = ?,
|
banner_height = ?, banner_align = ?, printer_enabled = ?, printer_host = ?,
|
||||||
printer_port = ?, printer_model = ?, printer_rotate = ? WHERE id = ?`
|
printer_port = ?, printer_model = ?, printer_rotate = ?, printer_label = ? WHERE id = ?`
|
||||||
).run(
|
).run(
|
||||||
clean(req.body?.name ?? site.name, 100) || site.name,
|
clean(req.body?.name ?? site.name, 100) || site.name,
|
||||||
req.body?.slug ? uniqueSlug(req.body.slug, site.id) : site.slug,
|
req.body?.slug ? uniqueSlug(req.body.slug, site.id) : site.slug,
|
||||||
@@ -432,7 +432,10 @@ router.patch('/sites/:id', (req, res) => {
|
|||||||
printerCfg.model !== undefined ? clean(printerCfg.model, 40) || 'QL-820NWB' : site.printer_model,
|
printerCfg.model !== undefined ? clean(printerCfg.model, 40) || 'QL-820NWB' : site.printer_model,
|
||||||
printerCfg.rotate !== undefined
|
printerCfg.rotate !== undefined
|
||||||
? ([0, 90, 180, 270].includes(Number(printerCfg.rotate)) ? Number(printerCfg.rotate) : 0)
|
? ([0, 90, 180, 270].includes(Number(printerCfg.rotate)) ? Number(printerCfg.rotate) : 0)
|
||||||
: site.printer_rotate
|
: site.printer_rotate,
|
||||||
|
printerCfg.label !== undefined
|
||||||
|
? (Object.hasOwn(printer.ROLL_TYPES, printerCfg.label) ? printerCfg.label : '62')
|
||||||
|
: site.printer_label
|
||||||
, site.id);
|
, site.id);
|
||||||
|
|
||||||
res.json(shapeSite(db.prepare('SELECT * FROM sites WHERE id = ?').get(site.id)));
|
res.json(shapeSite(db.prepare('SELECT * FROM sites WHERE id = ?').get(site.id)));
|
||||||
|
|||||||
@@ -65,6 +65,7 @@ export function shapeSite(site) {
|
|||||||
port: site.printer_port || 9100,
|
port: site.printer_port || 9100,
|
||||||
model: site.printer_model || 'QL-820NWB',
|
model: site.printer_model || 'QL-820NWB',
|
||||||
rotate: site.printer_rotate || 0,
|
rotate: site.printer_rotate || 0,
|
||||||
|
label: site.printer_label || '62',
|
||||||
},
|
},
|
||||||
badge: {
|
badge: {
|
||||||
enabled: Boolean(site.badge_enabled),
|
enabled: Boolean(site.badge_enabled),
|
||||||
|
|||||||
+12
@@ -194,6 +194,18 @@ export function ensureCertificates({ force = false } = {}) {
|
|||||||
fs.writeFileSync(p.names, JSON.stringify(config.https.hostnames));
|
fs.writeFileSync(p.names, JSON.stringify(config.https.hostnames));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A very common mistake is editing .env and then using `docker compose restart`,
|
||||||
|
// which reuses the old environment. The symptom is a certificate covering only
|
||||||
|
// the defaults, so say so rather than letting it fail later in a browser.
|
||||||
|
const configured = config.https.hostnames;
|
||||||
|
if (configured.length === 1 && configured[0] === 'visitors.local') {
|
||||||
|
console.warn(
|
||||||
|
'[tls] HTTPS_HOSTNAMES is at its default. If you set it in .env, bring the container\n' +
|
||||||
|
' back with "docker compose up -d" rather than "docker compose restart" — restart\n' +
|
||||||
|
' keeps the environment the container started with.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
key: fs.readFileSync(p.key),
|
key: fs.readFileSync(p.key),
|
||||||
cert: fs.readFileSync(p.cert),
|
cert: fs.readFileSync(p.cert),
|
||||||
|
|||||||
Reference in New Issue
Block a user