brother_ql 3.0.1

Compile and print images using Brother QL label printers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! Printer status information parsing and types
//!
//! This module provides types and parsing for the 32-byte status packets
//! returned by Brother QL printers.

use bitflags::bitflags;

use crate::{
    commands::VariousModeSettings, error::StatusParsingError, media::LabelType,
    printer::PrinterModel,
};

bitflags! {
/// Error flags reported by the printer
///
/// A bitfield containing all active error conditions on the printer.
/// Multiple errors can be set simultaneously. Use [`StatusInformation::has_errors`]
/// to check if any errors are present.
///
/// # Common Errors
/// - **NoMediaError**: No media is loaded in the printer
/// - **CoverOpenError**: The printer cover is open
/// - **CutterJamError**: The automatic cutter is jammed
/// - **ReplaceMediaError**: The media needs to be replaced
///
/// # Example
/// ```no_run
/// # use brother_ql::{
/// #     connection::{PrinterConnection, UsbConnection, UsbConnectionInfo},
/// #     printer::PrinterModel,
/// #     status::ErrorFlags,
/// # };
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let info = UsbConnectionInfo::from_model(PrinterModel::QL820NWB);
/// let mut connection = UsbConnection::open(info)?;
/// let status = connection.get_status()?;
///
/// if status.errors.contains(ErrorFlags::NoMediaError) {
///     println!("Please load media");
/// }
/// if status.errors.contains(ErrorFlags::CoverOpenError) {
///     println!("Please close the printer cover");
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ErrorFlags: u16 {
    /// No media is loaded
    const NoMediaError = 0b1 << 0;
    /// End of media reached (die-cut labels only)
    const EndOfMediaError = 0b1 << 1;
    /// Cutter is jammed
    const CutterJamError=0b1 << 2;
    /// Printer is currently in use
    const PrinterInUseError = 0b1 << 4;
    /// Printer was turned off
    const PrinterTurnedOffError = 0b1 << 5;
    /// High voltage adapter error (not used)
    const HighVoltageAdapterError = 0b1 << 6;
    /// Fan motor error (not used)
    const FanMotorError = 0b1 << 7;
    /// Media needs to be replaced
    const ReplaceMediaError = 0b1 << 8;
    /// Expansion buffer is full
    const ExpansionBufferFullError = 0b1 << 9;
    /// Communication error occurred
    const CommunicationError = 0b1 << 10;
    /// Communication buffer is full (not used)
    const CommunicationBufferFullError = 0b1 << 11;
    /// Printer cover is open
    const CoverOpenError = 0b1 << 12;
    /// Cancel key was pressed (not used)
    const CancelKeyError = 0b1 << 13;
    /// Media cannot be fed or end of media
    const FeedingError = 0b1 << 14;
    /// System error occurred
    const SystemError = 0b1 << 15;
    const _ = !0;
}
}

/// Type of status message from the printer
///
/// Indicates what kind of status update the printer is sending.
/// Different status types are sent at different points during printing:
///
/// - **`StatusRequestReply`**: Initial response to a status request
/// - **`PhaseChange`**: Printer is transitioning between receiving and printing
/// - **`PrintingCompleted`**: A page has finished printing
///
/// Error conditions are indicated through the [`ErrorFlags`] field rather
/// than through the status type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StatusType {
    /// Reply to a status request
    StatusRequestReply,
    /// Printing has completed
    PrintingCompleted,
    /// An error has occurred
    ErrorOccurred,
    /// Printer was turned off
    TurnedOff,
    /// Notification message
    Notification,
    /// Phase change notification
    PhaseChange,
}

impl TryFrom<u8> for StatusType {
    type Error = StatusParsingError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0x00 => Ok(Self::StatusRequestReply),
            0x01 => Ok(Self::PrintingCompleted),
            0x02 => Ok(Self::ErrorOccurred),
            0x04 => Ok(Self::TurnedOff),
            0x05 => Ok(Self::Notification),
            0x06 => Ok(Self::PhaseChange),
            unused @ 0x08..=0x20 => Err(StatusParsingError {
                reason: format!("{unused:#x} is an unused status type"),
            }),
            reserved @ 0x21..=0xff => Err(StatusParsingError {
                reason: format!("{reserved:#x} is a reserved status type"),
            }),
            invalid => Err(StatusParsingError {
                reason: format!("invalid status type {invalid:#x}"),
            }),
        }
    }
}

/// Current phase of the printer
///
/// The printer alternates between these two phases during operation:
///
/// - **Receiving**: Ready to receive print data
/// - **Printing**: Currently printing a page
///
/// Phase transitions are reported via [`StatusType::PhaseChange`] status updates.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Phase {
    /// Receiving data from the host
    Receiving,
    /// Printing a page
    Printing,
}

impl TryFrom<[u8; 3]> for Phase {
    type Error = StatusParsingError;

    fn try_from(value: [u8; 3]) -> Result<Self, Self::Error> {
        match value {
            [0x00, 0x00, 0x00] => Ok(Self::Receiving),
            [0x01, 0x00, 0x00] => Ok(Self::Printing),
            [a, b, c] => Err(StatusParsingError {
                reason: format!("invalid phase state {a:#x}{b:x}{c:x}"),
            }),
        }
    }
}

/// Notification from the printer
///
/// Some printers may send notifications about cooling cycles.
/// Most of the time, no notification is available.
#[derive(Debug, Clone, Copy)]
pub enum Notification {
    /// No notification available
    Unavailable,
    /// Printer has started a cooling cycle
    CoolingStarted,
    /// Printer has finished a cooling cycle
    CoolingFinished,
}

impl TryFrom<u8> for Notification {
    type Error = StatusParsingError;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0x00 => Ok(Self::Unavailable),
            0x03 => Ok(Self::CoolingStarted),
            0x04 => Ok(Self::CoolingFinished),
            invalid => Err(StatusParsingError {
                reason: format!("invalid notification number {invalid:#x}"),
            }),
        }
    }
}

/// Status information received from the printer
///
/// Contains complete status information parsed from the 32-byte status packet
/// returned by Brother QL printers. Status information includes the printer model,
/// error conditions, media information, and the current operational phase.
///
/// # Fields Overview
/// - **model**: The specific printer model
/// - **errors**: Active error conditions (if any)
/// - **`media_width`**: Width of loaded media in millimeters
/// - **`media_type`**: Type of media (continuous or die-cut)
/// - **`media_length`**: Length in millimeters (for die-cut labels)
/// - **`status_type`**: Type of this status message
/// - **phase**: Current operational phase (receiving or printing)
///
/// # Example
/// ```no_run
/// # use brother_ql::{
/// #     connection::{PrinterConnection, UsbConnection, UsbConnectionInfo},
/// #     printer::PrinterModel,
/// # };
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let info = UsbConnectionInfo::from_model(PrinterModel::QL820NWB);
/// let mut connection = UsbConnection::open(info)?;
///
/// let status = connection.get_status()?;
/// println!("Printer: {:?}", status.model);
/// println!("Media: {}mm wide", status.media_width);
/// println!("Phase: {:?}", status.phase);
///
/// if status.has_errors() {
///     eprintln!("Errors detected: {:?}", status.errors);
/// } else {
///     println!("Printer is ready!");
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct StatusInformation {
    /// The printer model
    pub model: PrinterModel,
    /// Error flags indicating any active error conditions
    pub errors: ErrorFlags,
    /// Media width in millimeters
    pub media_width: u8,
    /// Media type (continuous or die-cut), if detected
    pub media_type: Option<LabelType>,
    /// Various mode settings active on the printer
    pub mode: VariousModeSettings,
    /// Media length in millimeters (only relevant for die-cut labels)
    pub media_length: u8,
    /// Type of this status message
    pub status_type: StatusType,
    /// Current operational phase
    pub phase: Phase,
    /// Optional notification from the printer
    pub notification: Notification,
}

impl StatusInformation {
    /// Check if any errors are present
    ///
    /// Returns `true` if the [`errors`](Self::errors) field contains any error flags.
    ///
    /// # Example
    /// ```no_run
    /// # use brother_ql::{
    /// #     connection::{PrinterConnection, UsbConnection, UsbConnectionInfo},
    /// #     printer::PrinterModel,
    /// # };
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let info = UsbConnectionInfo::from_model(PrinterModel::QL820NWB);
    /// # let mut connection = UsbConnection::open(info)?;
    /// let status = connection.get_status()?;
    ///
    /// if status.has_errors() {
    ///     println!("Error flags: {:?}", status.errors);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }
}

impl std::fmt::Display for StatusInformation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "Printer: {}", self.model)?;
        match self.media_type {
            Some(LabelType::Continuous) => {
                writeln!(f, "Media: {}mm continuous", self.media_width)?;
            }
            Some(LabelType::DieCut) => {
                writeln!(
                    f,
                    "Media: {}mm x {}mm die-cut",
                    self.media_width, self.media_length
                )?;
            }
            None => {
                writeln!(f, "Media: unknown")?;
            }
        }
        writeln!(f, "Phase: {:?}", self.phase)?;
        write!(f, "Status: {:?}", self.status_type)?;
        if self.has_errors() {
            write!(f, "\nErrors: {:?}", self.errors)?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Build a minimal valid 32-byte status packet
    fn valid_status_packet() -> [u8; 32] {
        let mut buf = [0u8; 32];
        buf[0] = 0x80; // Print head mark
        buf[1] = 0x20; // Size
        buf[2] = 0x42; // Reserved
        buf[3] = 0x34; // Series code
        buf[4] = 0x41; // Model: QL820NWB
        buf[5] = 0x30; // Reserved
        buf[6] = 0x04; // Reserved (printer replies with 0x04)
        buf[7] = 0x00; // Reserved
        buf[8] = 0x00; // Error info 1
        buf[9] = 0x00; // Error info 2
        buf[10] = 62; // Media width
        buf[11] = 0x0a; // Media type: Continuous
        buf[12] = 0x00; // Reserved
        buf[13] = 0x00; // Reserved
        buf[14] = 0x15; // Reserved (printer replies with 0x15)
        buf[15] = 0x00; // Mode: auto_cut off
        buf[16] = 0x00; // Reserved
        buf[17] = 0x00; // Media length
        buf[18] = 0x00; // Status type: StatusRequestReply
        buf[19] = 0x00; // Phase: Receiving
        buf[20] = 0x00;
        buf[21] = 0x00;
        buf[22] = 0x00; // Notification: Unavailable
        buf[23] = 0x00; // Reserved
        buf[24] = 0x00; // Reserved
        buf
    }

    #[test]
    fn parse_valid_status_packet() {
        let packet = valid_status_packet();
        let status = StatusInformation::try_from(&packet[..]).unwrap();
        assert_eq!(status.model, PrinterModel::QL820NWB);
        assert_eq!(status.media_width, 62);
        assert_eq!(status.media_type, Some(LabelType::Continuous));
        assert_eq!(status.status_type, StatusType::StatusRequestReply);
        assert_eq!(status.phase, Phase::Receiving);
        assert!(!status.has_errors());
    }

    #[test]
    fn parse_status_with_errors() {
        let mut packet = valid_status_packet();
        packet[8] = 0x01; // NoMediaError
        let status = StatusInformation::try_from(&packet[..]).unwrap();
        assert!(status.has_errors());
        assert!(status.errors.contains(ErrorFlags::NoMediaError));
    }

    #[test]
    fn parse_status_wrong_size() {
        let short = [0u8; 16];
        assert!(StatusInformation::try_from(&short[..]).is_err());
    }

    #[test]
    fn status_type_roundtrip() {
        assert_eq!(
            StatusType::try_from(0x00).unwrap(),
            StatusType::StatusRequestReply
        );
        assert_eq!(
            StatusType::try_from(0x01).unwrap(),
            StatusType::PrintingCompleted
        );
        assert_eq!(
            StatusType::try_from(0x02).unwrap(),
            StatusType::ErrorOccurred
        );
        assert_eq!(StatusType::try_from(0x06).unwrap(), StatusType::PhaseChange);
        assert!(StatusType::try_from(0x08).is_err());
    }

    #[test]
    fn phase_roundtrip() {
        assert_eq!(
            Phase::try_from([0x00, 0x00, 0x00]).unwrap(),
            Phase::Receiving
        );
        assert_eq!(
            Phase::try_from([0x01, 0x00, 0x00]).unwrap(),
            Phase::Printing
        );
        assert!(Phase::try_from([0x02, 0x00, 0x00]).is_err());
    }

    #[test]
    fn display_impl() {
        let packet = valid_status_packet();
        let status = StatusInformation::try_from(&packet[..]).unwrap();
        let display = format!("{status}");
        assert!(display.contains("QL-820NWB"));
        assert!(display.contains("62mm"));
        assert!(display.contains("continuous"));
    }
}

impl TryFrom<&[u8]> for StatusInformation {
    type Error = StatusParsingError;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        let status: &[u8; 32] = value.try_into().map_err(|_| StatusParsingError {
            reason: format!("invalid size of {}B", value.len()),
        })?;
        let check_fixed_field = |offset: usize,
                                 name: &str,
                                 expected_value: u8|
         -> Result<(), StatusParsingError> {
            if status[offset] != expected_value {
                return Err(StatusParsingError {
                    reason: format!(
                        "expected value {expected_value:#x} for field {name} at offset {offset} but was {:#x}",
                        status[offset]
                    ),
                });
            }
            Ok(())
        };
        check_fixed_field(0, "Print head mark", 0x80)?;
        check_fixed_field(1, "Size", 0x20)?;
        check_fixed_field(2, "Reserved", 0x42)?;
        check_fixed_field(3, "Series code", 0x34)?;
        let model = PrinterModel::try_from(status[4])?;
        check_fixed_field(5, "Reserved", 0x30)?;
        // NOTE: The printer replies with 0x04
        // check_fixed_field(6, "Reserved", 0x30)?;
        check_fixed_field(7, "Reserved", 0x00)?;
        let errors = ErrorFlags::from_bits_retain(u16::from_le_bytes([status[8], status[9]]));
        let media_width = status[10];
        let media_type = match status[11] {
            0x00 => None,
            other => Some(LabelType::try_from(other)?),
        };
        check_fixed_field(12, "Reserved", 0x00)?;
        check_fixed_field(13, "Reserved", 0x00)?;
        // NOTE: The printer replies with 0x15
        // check_fixed_field(14, "Reserved", 0x3f)?;
        let mode = VariousModeSettings::try_from(status[15])?;
        check_fixed_field(16, "Reserved", 0x00)?;
        let media_length = status[17];
        let status_type = StatusType::try_from(status[18])?;
        let phase_bytes: [u8; 3] = status[19..=21]
            .try_into()
            .expect("This conversion is infallible due to the earlier size assertion");
        let phase = Phase::try_from(phase_bytes)?;
        let notification = Notification::try_from(status[22])?;
        check_fixed_field(23, "Reserved", 0x00)?;
        check_fixed_field(24, "Reserved", 0x00)?;
        // Remaining 7 bytes are not specified at all
        Ok(StatusInformation {
            model,
            errors,
            media_width,
            media_type,
            mode,
            media_length,
            status_type,
            phase,
            notification,
        })
    }
}