use std::sync::RwLock;
use std::sync::atomic::{AtomicU8, Ordering};
use crate::codepage::CodePage;
use crate::command::{
Alignment, BarcodeData, BarcodeSystem, Command, CutMode, DrawerPin, FontFamily, ImageData,
PrintDensity, QrCorrectionLevel, QrData, UnderlineMode,
};
use crate::dialect::Dialect;
use crate::error::{PapermintError, Result};
use crate::status::{CoverStatus, DrawerStatus, PaperStatus, PrinterStatus};
const LF: u8 = 0x0A; const DLE: u8 = 0x10; const EOT: u8 = 0x04; const ESC: u8 = 0x1B; const GS: u8 = 0x1D;
#[derive(Debug)]
pub struct EscPos {
char_size_mask: AtomicU8,
active_codepage: RwLock<CodePage>,
}
impl Default for EscPos {
fn default() -> Self {
Self::new()
}
}
impl EscPos {
#[must_use]
pub fn new() -> Self {
Self {
char_size_mask: AtomicU8::new(0),
active_codepage: RwLock::new(CodePage::Pc437),
}
}
fn encode_barcode(&self, data: &BarcodeData, buf: &mut Vec<u8>) -> Result<()> {
let payload = data.data.as_bytes();
let system_code = match data.system {
BarcodeSystem::UpcA => 65,
BarcodeSystem::UpcE => 66,
BarcodeSystem::Ean13 => 67,
BarcodeSystem::Ean8 => 68,
BarcodeSystem::Code39 => 69,
BarcodeSystem::Itf => 70,
BarcodeSystem::Codabar => 71,
BarcodeSystem::Code93 => 72,
BarcodeSystem::Code128 => 73,
};
let (prefix, payload_bytes) = match data.system {
BarcodeSystem::Code128
if !payload.starts_with(b"{A")
&& !payload.starts_with(b"{B")
&& !payload.starts_with(b"{C") =>
{
(&b"{B"[..], payload)
}
_ => (&[][..], payload),
};
let total_len = prefix.len() + payload_bytes.len();
let len = u8::try_from(total_len).map_err(|_| {
PapermintError::InvalidCommand(format!(
"barcode data too long: {} bytes (max 255)",
total_len
))
})?;
let height = if data.height == 0 { 64 } else { data.height };
buf.extend_from_slice(&[GS, b'h', height]);
let width = data.width.clamp(2, 6);
buf.extend_from_slice(&[GS, b'w', width]);
buf.extend_from_slice(&[GS, b'k', system_code, len]);
buf.extend_from_slice(prefix);
buf.extend_from_slice(payload_bytes);
Ok(())
}
fn encode_qr(&self, data: &QrData, buf: &mut Vec<u8>) -> Result<()> {
let payload = data.data.as_bytes();
let payload_len = payload.len();
let store_len = payload_len.checked_add(3).ok_or_else(|| {
PapermintError::InvalidCommand("QR code payload too large".to_string())
})?;
let (p_l, p_h) = if store_len <= 0xFFFF {
let p_l = u8::try_from(store_len & 0xFF).unwrap_or(0);
let p_h = u8::try_from((store_len >> 8) & 0xFF).unwrap_or(0);
(p_l, p_h)
} else {
return Err(PapermintError::InvalidCommand(
"QR code data exceeds 65535 bytes".to_string(),
));
};
let model = if data.model == 1 { 49 } else { 50 }; buf.extend_from_slice(&[GS, b'(', b'k', 4, 0, 49, 65, model, 0]);
let cell_size = data.cell_size.clamp(1, 16);
buf.extend_from_slice(&[GS, b'(', b'k', 3, 0, 49, 67, cell_size]);
let ec_code = match data.correction {
QrCorrectionLevel::L => 48,
QrCorrectionLevel::M => 49,
QrCorrectionLevel::Q => 50,
QrCorrectionLevel::H => 51,
};
buf.extend_from_slice(&[GS, b'(', b'k', 3, 0, 49, 69, ec_code]);
buf.extend_from_slice(&[GS, b'(', b'k', p_l, p_h, 49, 80, 48]);
buf.extend_from_slice(payload);
buf.extend_from_slice(&[GS, b'(', b'k', 3, 0, 49, 81, 48]);
Ok(())
}
fn encode_image(&self, img: &ImageData, buf: &mut Vec<u8>) -> Result<()> {
if img.width == 0 || img.height == 0 {
return Ok(());
}
let width_bytes = img.width.div_ceil(8) as usize;
let expected_len = width_bytes
.checked_mul(img.height as usize)
.ok_or_else(|| {
PapermintError::InvalidCommand(
"image dimensions cause integer overflow".to_string(),
)
})?;
if img.pixels.len() < expected_len {
return Err(PapermintError::InvalidCommand(format!(
"image pixel buffer length ({}) is less than expected ({}) for {}x{}",
img.pixels.len(),
expected_len,
img.width,
img.height
)));
}
const MAX_CHUNK_HEIGHT: usize = 960;
let total_rows = img.height as usize;
let x_l = (width_bytes & 0xFF) as u8;
let x_h = ((width_bytes >> 8) & 0xFF) as u8;
for chunk_start in (0..total_rows).step_by(MAX_CHUNK_HEIGHT) {
let chunk_height = (total_rows - chunk_start).min(MAX_CHUNK_HEIGHT);
let y_l = (chunk_height & 0xFF) as u8;
let y_h = ((chunk_height >> 8) & 0xFF) as u8;
let byte_start = chunk_start * width_bytes;
let byte_end = byte_start + (chunk_height * width_bytes);
buf.extend_from_slice(&[GS, b'v', b'0', 0, x_l, x_h, y_l, y_h]);
buf.extend_from_slice(&img.pixels[byte_start..byte_end]);
}
Ok(())
}
}
impl Dialect for EscPos {
fn name(&self) -> &'static str {
"ESC/POS"
}
fn encode(&self, command: &Command, buf: &mut Vec<u8>) -> Result<()> {
match command {
Command::Init => {
self.char_size_mask.store(0, Ordering::Relaxed);
if let Ok(mut cp) = self.active_codepage.write() {
*cp = CodePage::Pc437;
}
buf.extend_from_slice(&[ESC, b'@']);
}
Command::Text(text) => {
if text.is_ascii() {
buf.extend_from_slice(text.as_bytes());
} else {
let cp = self
.active_codepage
.read()
.map(|c| *c)
.unwrap_or(CodePage::Pc437);
let encoded = cp.encode_text(text);
buf.extend_from_slice(&encoded);
}
}
Command::Feed(lines) => match *lines {
0 => {}
1 => buf.push(LF),
n => buf.extend_from_slice(&[ESC, b'd', n]),
},
Command::Cut(mode) => {
let cut_code = match mode {
CutMode::Full => 0x00,
CutMode::Partial => 0x01,
};
buf.extend_from_slice(&[GS, b'V', cut_code]);
}
Command::Align(alignment) => {
let code = match alignment {
Alignment::Left => 0,
Alignment::Center => 1,
Alignment::Right => 2,
};
buf.extend_from_slice(&[ESC, b'a', code]);
}
Command::Bold(enable) => {
buf.extend_from_slice(&[ESC, b'E', u8::from(*enable)]);
}
Command::Underline(mode) => {
let code = match mode {
UnderlineMode::Off => 0,
UnderlineMode::Single => 1,
UnderlineMode::Double => 2,
};
buf.extend_from_slice(&[ESC, b'-', code]);
}
Command::Invert(enable) => {
buf.extend_from_slice(&[GS, b'B', u8::from(*enable)]);
}
Command::DoubleHeight(enable) => {
let current = self.char_size_mask.load(Ordering::Relaxed);
let updated = if *enable {
current | 0x01 } else {
current & !0x01
};
self.char_size_mask.store(updated, Ordering::Relaxed);
buf.extend_from_slice(&[GS, b'!', updated]);
}
Command::DoubleWidth(enable) => {
let current = self.char_size_mask.load(Ordering::Relaxed);
let updated = if *enable {
current | 0x10 } else {
current & !0x10
};
self.char_size_mask.store(updated, Ordering::Relaxed);
buf.extend_from_slice(&[GS, b'!', updated]);
}
Command::Font(family) => {
let code = match family {
FontFamily::A => 0,
FontFamily::B => 1,
};
buf.extend_from_slice(&[ESC, b'M', code]);
}
Command::DrawerKick(pin) => {
let m = match pin {
DrawerPin::Pin2 => 0,
DrawerPin::Pin5 => 1,
};
buf.extend_from_slice(&[ESC, b'p', m, 25, 250]);
}
Command::Beep { count, duration } => {
let n = (*count).clamp(1, 9);
let t = (*duration).clamp(1, 9);
buf.extend_from_slice(&[ESC, b'B', n, t]);
}
Command::LineSpacing(spacing) => match spacing {
None => buf.extend_from_slice(&[ESC, b'2']),
Some(dots) => buf.extend_from_slice(&[ESC, b'3', *dots]),
},
Command::UpsideDown(enable) => {
buf.extend_from_slice(&[ESC, b'{', u8::from(*enable)]);
}
Command::CodePage(page) => {
if let Ok(mut cp) = self.active_codepage.write() {
*cp = *page;
}
let code = match page {
CodePage::Pc437 => 0,
CodePage::Katakana => 1,
CodePage::Pc850 => 2,
CodePage::Pc860 => 3,
CodePage::Pc863 => 4,
CodePage::Pc865 => 5,
CodePage::Wpc1252 => 16,
CodePage::Pc866 => 17,
CodePage::Pc852 => 18,
CodePage::Pc858 => 19,
CodePage::Pc720 => 32,
CodePage::Pc864 => 37,
CodePage::Pc737 => 14,
CodePage::Wpc1250 => 45,
CodePage::Wpc1251 => 46,
CodePage::Wpc1253 => 47,
CodePage::Wpc1254 => 48,
CodePage::Wpc1255 => 49,
CodePage::Wpc1256 => 50,
CodePage::Wpc1257 => 51,
CodePage::Wpc1258 => 52,
CodePage::Pc857 => 13,
CodePage::Iso8859_15 => 40,
CodePage::Pc874 => 20,
CodePage::Custom(n) => *n,
};
buf.extend_from_slice(&[ESC, b't', code]);
}
Command::InternationalCharset(charset) => {
buf.extend_from_slice(&[ESC, b'R', charset.code()]);
}
Command::PrintDensity(density) => {
let m = match density {
PrintDensity::Light => 253, PrintDensity::Normal => 0, PrintDensity::Dark => 3, PrintDensity::HighContrast => 6, PrintDensity::Custom(val) => *val,
};
buf.extend_from_slice(&[GS, b'(', b'K', 0x02, 0x00, 0x30, m]);
}
Command::HeatingParameters(params) => {
buf.extend_from_slice(&[
ESC,
b'7',
params.max_heating_dots,
params.heating_time,
params.heating_interval,
]);
}
Command::Barcode(data) => self.encode_barcode(data, buf)?,
Command::QrCode(data) => self.encode_qr(data, buf)?,
Command::Image(img) => self.encode_image(img, buf)?,
Command::Raw(raw_bytes) => {
buf.extend_from_slice(raw_bytes);
}
}
Ok(())
}
fn status_query_command(&self) -> Vec<u8> {
vec![DLE, EOT, 1, DLE, EOT, 2, DLE, EOT, 3, DLE, EOT, 4]
}
fn expected_status_bytes(&self) -> usize {
4
}
fn parse_status_response(&self, bytes: &[u8]) -> Result<PrinterStatus> {
if bytes.is_empty() {
return Err(PapermintError::Dialect(
"empty status response from ESC/POS printer".into(),
));
}
let mut status = PrinterStatus::default();
if bytes.len() >= 4 {
let b1 = bytes[0];
let b2 = bytes[1];
let b3 = bytes[2];
let b4 = bytes[3];
status.is_online = (b1 & 0x08) == 0;
status.drawer = if (b1 & 0x04) != 0 {
DrawerStatus::Open
} else {
DrawerStatus::Closed
};
status.cover = if (b2 & 0x04) != 0 {
CoverStatus::Open
} else {
CoverStatus::Closed
};
status.cutter_error = (b3 & 0x08) != 0;
status.head_overheated = (b3 & 0x40) != 0;
if (b4 & 0x60) != 0 || (b2 & 0x20) != 0 {
status.paper = PaperStatus::Empty;
} else if (b4 & 0x0C) != 0 {
status.paper = PaperStatus::NearEnd;
} else {
status.paper = PaperStatus::Adequate;
}
} else {
let b = bytes[0];
status.is_online = (b & 0x08) == 0;
status.drawer = if (b & 0x04) != 0 {
DrawerStatus::Open
} else {
DrawerStatus::Closed
};
status.cover = if (b & 0x20) != 0 {
CoverStatus::Open
} else {
CoverStatus::Closed
};
if (b & 0x60) == 0x60 || (b & 0x40) != 0 {
status.paper = PaperStatus::Empty;
} else if (b & 0x0C) == 0x0C {
status.paper = PaperStatus::NearEnd;
} else {
status.paper = PaperStatus::Adequate;
}
}
Ok(status)
}
}