//! ESC/POS thermal printing for captured photos. //! //! Configuration (environment variables or the committed `.env`; read once at //! startup): //! - `PHOTOBOOTH_PRINTER`: where to send print data. Either a device path such as //! `/dev/usb/lp0` (USB printer class) or a raw network printer as //! `tcp://host[:port]` (port defaults to 9100). Defaults to `/dev/usb/lp0`; //! set it to an empty value to disable printing. //! - `PHOTOBOOTH_PRINTER_DOTS`: printable width in dots, rounded down to a multiple //! of 8. Defaults to 576 (80 mm paper); use 384 for 58 mm paper. //! - `PHOTOBOOTH_PRINTER_GAMMA`: mid-tone brightening applied before dithering //! to offset the dot gain of thermal paper (`out = in^(1/gamma)`). Defaults to //! 2.7; typical values are 1.8-3.0, and 1 disables it. //! - `PHOTOBOOTH_PRINTER_DENSITY`: thermal head energy in percent of the rated //! energy, 70-130 (SII `DC2 ~ n`). Unset by default. //! - `PHOTOBOOTH_PRINTER_SPEED`: `quality` (120 mm/s), `low` (150 mm/s), //! `silent` (180 mm/s) or `high` (200 mm/s) (SII `GS s n`). Unset by default. //! //! Both head settings belong to the SII RP-D10 command set and are only sent //! when configured, because a printer that does not implement them loses sync //! and prints the raster data that follows as text - metres of it. The tested //! Birch 0CP-Q3 does exactly that with either command, so leave both unset //! unless the printer is known to understand them. They are sent with every //! band and are not stored by the printer (no memory switch writes). //! //! Each photo is captioned with the event name and place above it, and a //! keepsake line, the capture date and time and one of `QUOTES` below it. The //! captions are in German with the English directly underneath, the quotes in //! English only. Christmas pixel art (see `artwork`) frames the photo: fir //! trees and presents in the snow above it and ornaments hanging below it, //! arranged differently on every slip. The timestamp is the system clock in //! local time, so the booth's clock has to be right for it to mean anything. //! Text goes out in the printer's own code page (PC437), since it prints UTF-8 //! bytes as separate glyphs; see `code_page`. //! //! Each photo is converted to gray, resized to the exact dot width, contrast //! equalized (CLAHE), slightly sharpened, gamma brightened and finally Atkinson //! dithered, in that order: scaling a dithered image would ruin the pattern. //! //! Serial printers must have their baud rate set beforehand (for example with //! `stty -F /dev/ttyUSB0 9600`); this module only writes bytes. use std::{ fs::OpenOptions, io::Write, net::{TcpStream, ToSocketAddrs}, path::PathBuf, time::Duration, }; use chrono::Local; use opencv::{ core::{self, Mat, Size}, imgproc, prelude::*, }; use crate::{ artwork::{self, CELLS_ACROSS, ROWS}, quotes::QUOTES, }; const DEFAULT_PRINTER: &str = "/dev/usb/lp0"; const DEFAULT_DOTS: usize = 576; const DEFAULT_GAMMA: f32 = 2.7; const DENSITY_RANGE: std::ops::RangeInclusive = 70..=130; /// CLAHE settings: contrast limit and tiles across the image. const CLAHE_CLIP_LIMIT: f64 = 2.0; const CLAHE_TILES: i32 = 8; /// Unsharp mask: blur radius in dots and how much of the detail to add back. const SHARPEN_SIGMA: f64 = 1.0; const SHARPEN_AMOUNT: f64 = 0.5; const DEFAULT_NETWORK_PORT: u16 = 9100; const NETWORK_TIMEOUT: Duration = Duration::from_secs(5); /// Raster rows per `GS v 0` command, 4.5 KiB per band at 576 dots. const BAND_ROWS: usize = 64; const FEED_LINES: u8 = 4; /// Caption printed around every photo. const EVENT_TITLE: &str = "WINFNACHTEN"; const EVENT_PLACE: &str = "WINF Treitlstraße 3"; const KEEPSAKE_DE: &str = "Ich war dabei!"; const KEEPSAKE_EN: &str = "I was there!"; /// Capture time, written the German way and the same in both languages. const STAMP_FORMAT: &str = "%d.%m.%Y, %H:%M"; /// Pause between writes, leaving the head time to drain a band (8 mm of paper) /// before the next one arrives. const PACE: Duration = Duration::from_millis(100); #[derive(Debug, PartialEq)] enum Target { Device(PathBuf), Network(String), } impl Target { fn parse(value: &str) -> Option { let value = value.trim(); if value.is_empty() { return None; } Some(match value.strip_prefix("tcp://") { Some(address) if address.contains(':') => Self::Network(address.to_owned()), Some(address) => Self::Network(format!("{address}:{DEFAULT_NETWORK_PORT}")), None => Self::Device(PathBuf::from(value)), }) } } /// Maximum print speeds of the SII `GS s n` command. #[derive(Clone, Copy, Debug, PartialEq)] enum Speed { High, Quality, Low, Silent, } impl Speed { fn parse(value: &str) -> Option { match value.trim().to_ascii_lowercase().as_str() { "high" => Some(Self::High), "quality" => Some(Self::Quality), "low" => Some(Self::Low), "silent" => Some(Self::Silent), _ => None, } } fn code(self) -> u8 { match self { Self::High => 0, Self::Quality => 1, Self::Low => 2, Self::Silent => 3, } } } /// Head settings sent before each job; `None` leaves the printer's own setting. #[derive(Debug, Default, PartialEq)] struct Head { density: Option, speed: Option, } impl Head { /// Either command is sent only when its variable holds a valid value, so /// that printers which do not implement them never see them. fn from_values(density: Option<&str>, speed: Option<&str>) -> Self { Self { density: density .and_then(|value| value.trim().parse::().ok()) .filter(|density| DENSITY_RANGE.contains(density)), speed: speed.and_then(Speed::parse), } } fn commands(&self) -> Vec { let mut bytes = Vec::new(); if let Some(density) = self.density { bytes.extend([0x12, b'~', density]); // DC2 ~ n: print density in % } if let Some(speed) = self.speed { bytes.extend([0x1D, b's', speed.code()]); // GS s n: print speed } bytes } } #[derive(Debug)] pub struct Printer { target: Target, dots: usize, gamma: f32, head: Head, } impl Printer { /// Returns `None` only when `PHOTOBOOTH_PRINTER` is explicitly empty. pub fn from_env() -> Option { Self::from_values( std::env::var("PHOTOBOOTH_PRINTER").ok().as_deref(), std::env::var("PHOTOBOOTH_PRINTER_DOTS").ok().as_deref(), std::env::var("PHOTOBOOTH_PRINTER_GAMMA").ok().as_deref(), ) .map(|printer| Self { head: Head::from_values( std::env::var("PHOTOBOOTH_PRINTER_DENSITY").ok().as_deref(), std::env::var("PHOTOBOOTH_PRINTER_SPEED").ok().as_deref(), ), ..printer }) } fn from_values(printer: Option<&str>, dots: Option<&str>, gamma: Option<&str>) -> Option { let target = Target::parse(printer.unwrap_or(DEFAULT_PRINTER))?; let dots = dots .and_then(|value| value.trim().parse::().ok()) .map_or(DEFAULT_DOTS, |dots| dots / 8 * 8) .max(8); let gamma = gamma .and_then(|value| value.trim().parse::().ok()) .filter(|gamma| gamma.is_finite() && *gamma > 0.0) .unwrap_or(DEFAULT_GAMMA); Some(Self { target, dots, gamma, head: Head::from_values(None, None), }) } /// Prints `copies` identical cut-separated copies of the (BGR) frame. pub fn print(&self, frame: &Mat, copies: usize) -> Result<(), String> { if copies == 0 { return Ok(()); } let bitmap = render(frame, self.dots, self.gamma).map_err(|error| format!("render: {error}"))?; let stamp = Local::now().format(STAMP_FORMAT).to_string(); self.send(&encode( &bitmap, &self.head, copies, &stamp, first_quote(), clock_seed(), )) } /// Sends the job one write at a time, pacing them to the print head. fn send(&self, job: &[Vec]) -> Result<(), String> { let mut sink: Box = match &self.target { Target::Device(path) => Box::new( // Opened per job so an unplugged and re-attached printer recovers. OpenOptions::new() .write(true) .open(path) .map_err(|error| format!("open {}: {error}", path.display()))?, ), Target::Network(address) => { let socket = address .to_socket_addrs() .map_err(|error| format!("resolve {address}: {error}"))? .next() .ok_or_else(|| format!("resolve {address}: no address"))?; let stream = TcpStream::connect_timeout(&socket, NETWORK_TIMEOUT) .map_err(|error| format!("connect {address}: {error}"))?; stream .set_write_timeout(Some(NETWORK_TIMEOUT * 2)) .map_err(|error| format!("configure {address}: {error}"))?; Box::new(stream) } }; for (index, write) in job.iter().enumerate() { if index > 0 { std::thread::sleep(PACE); } sink.write_all(write) .and_then(|()| sink.flush()) .map_err(|error| format!("write: {error}"))?; } Ok(()) } } /// 1-bit bitmap, row-major, most significant bit first; a set bit is a black dot. struct Bitmap { width_bytes: usize, data: Vec, } fn render(frame: &Mat, dots: usize, gamma: f32) -> opencv::Result { let rows = (frame.rows() as usize * dots / frame.cols().max(1) as usize).max(1); let mut gray = Mat::default(); imgproc::cvt_color_def(frame, &mut gray, imgproc::COLOR_BGR2GRAY)?; // Resize to the exact head width first; everything after works per dot. let mut resized = Mat::default(); imgproc::resize( &gray, &mut resized, Size::new(dots as i32, rows as i32), 0.0, 0.0, imgproc::INTER_AREA, )?; // Local contrast equalization keeps faces from sinking into the shadows. let mut equalized = Mat::default(); imgproc::create_clahe(CLAHE_CLIP_LIMIT, Size::new(CLAHE_TILES, CLAHE_TILES))? .apply(&resized, &mut equalized)?; // Unsharp mask: original + amount * (original - blurred). let mut blurred = Mat::default(); imgproc::gaussian_blur_def(&equalized, &mut blurred, Size::new(0, 0), SHARPEN_SIGMA)?; let mut sharpened = Mat::default(); core::add_weighted_def( &equalized, 1.0 + SHARPEN_AMOUNT, &blurred, -SHARPEN_AMOUNT, 0.0, &mut sharpened, )?; let sharpened = sharpened.try_clone()?; // contiguous bytes let curve = gamma_curve(gamma); let brightened: Vec = sharpened .data_bytes()? .iter() .map(|&value| curve[usize::from(value)]) .collect(); Ok(Bitmap { width_bytes: dots / 8, data: dither(&brightened, dots, rows), }) } /// Lookup table lifting mid-tones, since thermal dot gain darkens them again. fn gamma_curve(gamma: f32) -> [u8; 256] { std::array::from_fn(|value| (255.0 * (value as f32 / 255.0).powf(1.0 / gamma)).round() as u8) } /// Atkinson error diffusion: thermal heads only print black or nothing. /// /// Only 6/8 of the error is passed on, which keeps highlights open and gives /// the lighter look that suits thermal paper better than Floyd-Steinberg. fn dither(gray: &[u8], width: usize, rows: usize) -> Vec { let stride = width / 8; let mut packed = vec![0u8; stride * rows]; // Error rows are padded (one cell left, two right) to avoid edge branches; // cell `x + 1` belongs to pixel `x`. let mut errors = [(); 3].map(|()| vec![0f32; width + 3]); for y in 0..rows { for x in 0..width { let wanted = f32::from(gray[y * width + x]) + errors[0][x + 1]; let black = wanted < 128.0; if black { packed[y * stride + x / 8] |= 0x80 >> (x % 8); } let share = (wanted - if black { 0.0 } else { 255.0 }) / 8.0; errors[0][x + 2] += share; errors[0][x + 3] += share; errors[1][x] += share; errors[1][x + 1] += share; errors[1][x + 2] += share; errors[2][x + 1] += share; } errors.rotate_left(1); errors[2].fill(0.0); } packed } /// Encodes the job as a sequence of writes: one per raster band, then one feed /// and cut per copy. /// /// Every band is re-initialized and carries exactly one raster command. The /// tested Birch 0CP-Q3 only keeps sync when `GS v 0` follows `ESC @` directly: /// given several bands in one initialized stream it abandons the image and /// prints the remaining dot data as text, about two metres of it per photo. fn encode( bitmap: &Bitmap, head: &Head, copies: usize, stamp: &str, first_quote: usize, seed: u64, ) -> Vec> { let mut job = Vec::new(); for copy in 0..copies { // A scene above the photo and ornaments below it, new for every copy. let dots = bitmap.width_bytes * 8; let seed = seed.wrapping_add(2 * copy as u64); job.push(header(head)); raster_bands(&mut job, &pixel_strip(dots, seed, Side::Above), head); raster_bands(&mut job, bitmap, head); raster_bands( &mut job, &pixel_strip(dots, seed.wrapping_add(1), Side::Below), head, ); job.push(footer( head, stamp, "ES[(first_quote + copy) % QUOTES.len()], )); job.push(finish(head)); } job } /// Appends the bitmap as one write per band of `BAND_ROWS` rows. fn raster_bands(job: &mut Vec>, bitmap: &Bitmap, head: &Head) { for band in bitmap.data.chunks(BAND_ROWS * bitmap.width_bytes) { let rows = band.len() / bitmap.width_bytes; let mut write = vec![0x1B, b'@']; // ESC @: initialize write.extend(head.commands()); write.extend([0x1D, b'v', b'0', 0]); // GS v 0: raster image, normal density write.extend((bitmap.width_bytes as u16).to_le_bytes()); write.extend((rows as u16).to_le_bytes()); write.extend(band); job.push(write); } } /// Which side of the photo a pixel strip goes on. #[derive(Clone, Copy)] enum Side { /// Trees and presents standing on the snow, the strip's bottom line. Above, /// Ornaments hanging from the strip's solid top line. Below, } /// The random Christmas pixel strip across the whole paper, `ROWS` lines of /// pixels with the solid line next to the photo. Pixels are 6 dots on 80 mm /// paper and 4 on 58 mm. fn pixel_strip(dots: usize, seed: u64, side: Side) -> Bitmap { let cell = (dots / CELLS_ACROSS).max(1); let columns = dots / cell; let left = (dots - columns * cell) / 2; let stride = dots / 8; let lines = match side { Side::Above => artwork::scenery(seed, columns), Side::Below => artwork::ornaments(seed, columns), }; let mut data = vec![0u8; stride * ROWS * cell]; for y in 0..ROWS * cell { for x in 0..columns * cell { if lines[y / cell][x / cell] { let dot = left + x; data[y * stride + dot / 8] |= 0x80 >> (dot % 8); } } } Bitmap { width_bytes: stride, data, } } /// The German letters and the middle dot in the captions as single PC437 bytes, /// the code page the booth's printer starts in. Anything else non-ASCII would /// need a wider table or `ESC t`, so a test keeps the printed text within this /// set. fn code_page(character: char) -> Option { Some(match character { 'ä' => 0x84, 'ö' => 0x94, 'ü' => 0x81, 'Ä' => 0x8E, 'Ö' => 0x99, 'Ü' => 0x9A, 'ß' => 0xE1, '·' => 0xFA, ascii if ascii.is_ascii() => ascii as u8, _ => return None, }) } /// Appends one line of text, encoded for the printer. fn text_line(write: &mut Vec, line: &str) { write.extend( line.chars() .map(|character| code_page(character).unwrap_or(b'?')), ); write.push(b'\n'); } /// Starts a write with `ESC @` and the head settings, then centres the text. fn centered(head: &Head) -> Vec { let mut write = vec![0x1B, b'@']; // ESC @: initialize write.extend(head.commands()); write.extend([0x1B, b'a', 1]); // ESC a n: centre the following lines write } /// Emphasizes the next line: double width and height, bold. const LARGE: [u8; 6] = [0x1D, b'!', 0x11, 0x1B, b'E', 1]; // GS ! n, ESC E n const SMALL: [u8; 6] = [0x1D, b'!', 0x00, 0x1B, b'E', 0]; fn header(head: &Head) -> Vec { let mut write = centered(head); write.extend(LARGE); text_line(&mut write, EVENT_TITLE); write.extend(SMALL); text_line(&mut write, EVENT_PLACE); write.extend([0x1B, b'd', 1]); // a blank line between caption and photo write } /// Which quote the next slip gets. The clock is random enough for a joke, and /// saves pulling in a generator. fn first_quote() -> usize { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |since| since.subsec_nanos() as usize) % QUOTES.len() } /// Seed for the pixel strips of one job, from the clock like the quote. fn clock_seed() -> u64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |since| since.as_nanos() as u64) } fn footer(head: &Head, stamp: &str, quote: &[&str]) -> Vec { let mut write = centered(head); write.extend([0x1B, b'd', 1]); write.extend(LARGE); text_line(&mut write, KEEPSAKE_DE); write.extend(SMALL); text_line(&mut write, KEEPSAKE_EN); write.extend([0x1B, b'd', 1]); text_line(&mut write, stamp); write.extend([0x1B, b'd', 1]); for line in quote { text_line(&mut write, line); } write } /// Feeds the slip past the cutter and cuts it. fn finish(head: &Head) -> Vec { let mut write = vec![0x1B, b'@']; // ESC @: initialize write.extend(head.commands()); write.extend([0x1B, b'd', FEED_LINES]); // ESC d n: feed n lines write.extend([0x1D, b'V', 66, 3]); // GS V 66 n: feed and partial cut write } #[cfg(test)] mod tests { use super::*; const STAMP: &str = "14.11.2026, 15:42"; /// Every line the booth prints, large or small. fn printed_lines() -> impl Iterator { [EVENT_TITLE, EVENT_PLACE, KEEPSAKE_DE, KEEPSAKE_EN, STAMP] .into_iter() .chain(QUOTES.iter().flat_map(|quote| quote.iter().copied())) } fn contains_line(write: &[u8], line: &str) -> bool { let mut needle = Vec::new(); text_line(&mut needle, line); write.windows(needle.len()).any(|window| window == needle) } #[test] fn printed_lines_fit_an_80_mm_line() { // Font A is 12 dots wide, so 48 columns; the large lines take two each. let columns = DEFAULT_DOTS / 12; for line in [EVENT_TITLE, KEEPSAKE_DE] { assert!(line.chars().count() <= columns / 2, "{line}"); } for line in printed_lines().filter(|line| ![EVENT_TITLE, KEEPSAKE_DE].contains(line)) { assert!(line.chars().count() <= columns, "{line}"); } } #[test] fn german_text_is_sent_in_the_printers_code_page() { let mut write = Vec::new(); text_line(&mut write, "schönste Prüfung, Fächer, Straße"); assert_eq!(write, b"sch\x94nste Pr\x81fung, F\x84cher, Stra\xE1e\n"); // No printed line needs a character the code page lacks. for line in printed_lines() { assert!( line.chars().all(|character| code_page(character).is_some()), "{line}" ); } } #[test] fn quotes_are_picked_from_the_list_and_vary() { let picked: std::collections::BTreeSet = (0..1000).map(|_| first_quote()).collect(); assert!(picked.last().is_some_and(|last| *last < QUOTES.len())); // Not all of them on a coarse clock, but a slip must not be predictable. assert!(picked.len() > 1, "{picked:?}"); } #[test] fn parses_device_and_network_targets() { assert_eq!(Target::parse(" "), None); assert_eq!( Target::parse("/dev/usb/lp0"), Some(Target::Device("/dev/usb/lp0".into())) ); assert_eq!( Target::parse("tcp://192.168.0.5"), Some(Target::Network("192.168.0.5:9100".into())) ); assert_eq!( Target::parse("tcp://printer.local:9101"), Some(Target::Network("printer.local:9101".into())) ); } #[test] fn unset_variables_fall_back_to_80mm_usb_printer() { let printer = Printer::from_values(None, None, None).unwrap(); assert_eq!(printer.target, Target::Device("/dev/usb/lp0".into())); assert_eq!(printer.dots, 576); assert_eq!(printer.gamma, 2.7); // Unparsable widths fall back; valid ones are rounded to whole bytes. let dots = |value| Printer::from_values(None, Some(value), None).unwrap().dots; assert_eq!(dots("wide"), 576); assert_eq!(dots(" 390 "), 384); // Gamma must be a positive number. let gamma = |value| Printer::from_values(None, None, Some(value)).unwrap().gamma; assert_eq!(gamma(" 2.4 "), 2.4); assert_eq!(gamma("0"), 2.7); assert_eq!(gamma("bright"), 2.7); // An explicitly empty printer disables printing. assert!(Printer::from_values(Some(""), None, None).is_none()); } #[test] fn head_commands_are_sent_only_when_configured() { // Unset, empty, out-of-range and unknown values all send nothing. for (density, speed) in [ (None, None), (Some(""), Some(" ")), (Some("140"), Some("fast")), ] { let head = Head::from_values(density, speed); assert_eq!(head, Head::default(), "{density:?} {speed:?}"); assert!(head.commands().is_empty(), "{density:?} {speed:?}"); } // Valid values are sent as the SII commands. let head = Head::from_values(Some(" 70 "), Some("Low")); assert_eq!(head.commands(), [0x12, b'~', 70, 0x1D, b's', 2]); } #[test] fn configured_head_settings_precede_every_raster_band() { let bitmap = Bitmap { width_bytes: 1, data: vec![0; BAND_ROWS + 1], }; let head = Head::from_values(Some("85"), Some("quality")); let job = encode(&bitmap, &head, 1, STAMP, 0, 0); // Strip, the two photo bands and the other strip. for band in &job[1..5] { assert_eq!( &band[..12], [ 0x1B, b'@', 0x12, b'~', 85, 0x1D, b's', 1, 0x1D, b'v', b'0', 0 ] ); } } #[test] fn gamma_curve_lifts_mid_tones_and_keeps_endpoints() { let curve = gamma_curve(2.0); assert_eq!((curve[0], curve[255]), (0, 255)); assert_eq!(curve[64], 128); // sqrt(0.25) = 0.5 assert!(curve.windows(2).all(|pair| pair[0] <= pair[1])); assert_eq!(gamma_curve(1.0), std::array::from_fn(|value| value as u8)); } #[test] fn dithers_extremes_and_packs_msb_first() { assert_eq!(dither(&[0; 16], 16, 1), vec![0xFF, 0xFF]); assert_eq!(dither(&[255; 16], 16, 1), vec![0x00, 0x00]); let mut half = [255u8; 8]; half[0] = 0; assert_eq!(dither(&half, 8, 1), vec![0x80]); } #[test] fn mid_gray_prints_roughly_half_the_dots() { let packed = dither(&[128; 64 * 64], 64, 64); let black: u32 = packed.iter().map(|byte| byte.count_ones()).sum(); assert!((1800..2300).contains(&black), "black dots: {black}"); } #[test] fn encodes_one_initialized_raster_command_per_write() { let bitmap = Bitmap { width_bytes: 2, data: vec![0xAA; 2 * (BAND_ROWS + 1)], }; let job = encode(&bitmap, &Head::default(), 2, STAMP, 0, 0); // Per copy: the caption, a pixel strip, the photo's full band and // leftover row, a pixel strip, the footer and the cut. assert_eq!(job.len(), 2 * 7); for copy in job.chunks(7) { assert_eq!( ©[2][..10], [0x1B, b'@', 0x1D, b'v', b'0', 0, 2, 0, BAND_ROWS as u8, 0] ); assert_eq!(copy[2].len(), 10 + 2 * BAND_ROWS); assert_eq!( copy[3], [ vec![0x1B, b'@', 0x1D, b'v', b'0', 0, 2, 0, 1, 0], vec![0xAA; 2] ] .concat() ); } // Every write initializes first, so no dot data is read as commands. assert!(job.iter().all(|write| write.starts_with(&[0x1B, b'@']))); } #[test] fn frames_the_photo_with_christmas_pixel_art() { for dots in [384, 576] { let cell = dots / CELLS_ACROSS; for side in [Side::Above, Side::Below] { let strip = pixel_strip(dots, 42, side); assert_eq!(strip.width_bytes, dots / 8); assert_eq!(strip.data.len(), dots / 8 * ROWS * cell); let lit = |row: usize, dot: usize| { strip.data[row * strip.width_bytes + dot / 8] & (0x80 >> (dot % 8)) != 0 }; // Dots lit in each line of pixels, from the photo outward. let mut counts: Vec = (0..ROWS) .map(|line| (0..dots).filter(|dot| lit(line * cell, *dot)).count()) .collect(); if matches!(side, Side::Above) { counts.reverse(); } // The line next to the photo spans the paper, and there is // more than that line. assert_eq!(counts[0], dots); assert!(counts[1..].iter().all(|count| *count < dots), "{counts:?}"); assert!(counts[1..].iter().sum::() > dots, "{counts:?}"); // Pixels are solid squares: every dot row of a line is the same. for line in 0..ROWS { for dot_row in 1..cell { for dot in 0..dots { assert_eq!(lit(line * cell, dot), lit(line * cell + dot_row, dot)); } } } } } // Caption, strip, photo, strip, footer, cut. At 576 dots each strip is // 72 rows, a full band and 8 more, around the photo's single row. let bitmap = Bitmap { width_bytes: 72, data: vec![0xFF; 72], }; let job = encode(&bitmap, &Head::default(), 1, STAMP, 0, 5); assert_eq!(job.len(), 8); let raster = |rows: u8| [0x1B, b'@', 0x1D, b'v', b'0', 0, 72, 0, rows, 0]; for strip in [1, 4] { assert!(job[strip].starts_with(&raster(BAND_ROWS as u8))); assert!(job[strip + 1].starts_with(&raster(8))); } assert_eq!(&job[3][..10], raster(1)); assert!(job[7].ends_with(&[0x1D, b'V', 66, 3])); // Nothing is printed after the quote but the feed and the cut. assert!(job[6].windows(2).all(|pair| pair != [0x1D, b'v'])); // The next copy gets a different scene. let two = encode(&bitmap, &Head::default(), 2, STAMP, 0, 5); assert_ne!(two[1], two[9]); assert_ne!(two[4], two[12]); } #[test] fn captions_the_photo_and_cuts_once_per_copy() { let bitmap = Bitmap { width_bytes: 1, data: vec![0; 1], }; let last = QUOTES.len() - 1; let job = encode(&bitmap, &Head::default(), 2, STAMP, last, 0); assert!(contains_line(&job[0], EVENT_TITLE) && contains_line(&job[0], EVENT_PLACE)); assert!(contains_line(&job[4], KEEPSAKE_DE) && contains_line(&job[4], KEEPSAKE_EN)); assert!(contains_line(&job[4], STAMP)); // Consecutive copies get consecutive quotes, wrapping round the list. assert!(QUOTES[last].iter().all(|line| contains_line(&job[4], line))); assert!(QUOTES[0].iter().all(|line| contains_line(&job[10], line))); assert!(job[4].ends_with(&footer(&Head::default(), STAMP, QUOTES[last])[1..])); // The real stamp is as wide as the one used here. let now = Local::now().format(STAMP_FORMAT).to_string(); assert!(now.is_ascii() && now.len() == STAMP.len(), "{now}"); let cuts = job .iter() .filter(|write| write.ends_with(&[0x1D, b'V', 66, 3])) .count(); assert_eq!(cuts, 2); } }