ql-label 0.2.1

Brother QL series label printer driver for Rust
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
use log::{debug, error, info, warn};
use rusb::{Context, Device, DeviceDescriptor, DeviceHandle, Direction, TransferType, UsbContext};
use std::time::Duration;

use crate::{
    error::{Error, PrinterError},
    media::Media,
    model::Model,
    utils::TwoColorMatrix,
    Matrix,
};

// Vendoer id of Brother Industries, Ltd
const VENDOR_ID: u16 = 0x04f9;

#[derive(Debug, Clone, Copy)]
#[allow(dead_code)]
struct Endpoint {
    config: u8,
    iface: u8,
    setting: u8,
    address: u8,
}

pub struct Printer {
    handle: Box<DeviceHandle<Context>>,
    endpoint_out: Endpoint,
    endpoint_in: Endpoint,
    config: Config,
}

impl Printer {
    /// Create a new printer instance with the specified configuration.
    ///
    /// This constructor handles USB device enumeration, connection, and initialization.
    /// It will search for a Brother P-Touch printer matching the model and serial number
    /// specified in the configuration.
    ///
    /// # Arguments
    /// * `config` - Printer configuration containing model, serial, media, and print settings
    ///
    /// # Returns
    /// * `Ok(Printer)` - Successfully connected printer instance
    /// * `Err(Error)` - Connection failed, device not found, or USB error
    ///
    /// # Example
    /// ```rust,no_run
    /// # use ptouch::{Config, Model, Media, ContinuousType, Printer};
    /// let config = Config::new(Model::QL820NWB, "E8N117P02180".to_string(), 
    ///                         Media::Continuous(ContinuousType::Continuous62));
    /// let printer = Printer::new(config)?;
    /// # Ok::<(), ptouch::Error>(())
    /// ```
    pub fn new(config: Config) -> Result<Self, Error> {
        // rusb::set_log_level(rusb::LogLevel::Debug);
        match Context::new() {
            Ok(mut context) => {
                match Self::open_device(&mut context, config.model.pid(), config.serial.clone()) {
                    Ok((mut device, device_desc, handle)) => {
                        handle.reset()?;

                        let endpoint_in = match Self::find_endpoint(
                            &mut device,
                            &device_desc,
                            Direction::In,
                            TransferType::Bulk,
                        ) {
                            Some(endpoint) => endpoint,
                            None => return Err(Error::MissingEndpoint),
                        };

                        let endpoint_out = match Self::find_endpoint(
                            &mut device,
                            &device_desc,
                            Direction::Out,
                            TransferType::Bulk,
                        ) {
                            Some(endpoint) => endpoint,
                            None => return Err(Error::MissingEndpoint),
                        };

                        // QL-800では`has_kernel_driver`が`true`となる
                        // QL-820NWBでは`has_kernel_driver`が`false`となる
                        // `has_kernel_driver`が`true`の場合に、カーネルドライバーをデタッチしないとエラーとなる
                        //
                        handle.set_auto_detach_kernel_driver(true)?;
                        let has_kernel_driver = match handle.kernel_driver_active(0) {
                            Ok(true) => {
                                handle.detach_kernel_driver(0).ok();
                                true
                            }
                            _ => false,
                        };
                        info!(" Kernel driver support is {}", has_kernel_driver);
                        handle.set_active_configuration(1)?;
                        handle.claim_interface(0)?;
                        handle.set_alternate_setting(0, 0)?;

                        Ok(Printer {
                            handle: Box::new(handle),
                            endpoint_out,
                            endpoint_in,
                            config,
                        })
                    }
                    Err(err) => {
                        debug!("Device connection failed: {:?}", err);
                        Err(Error::DeviceOffline)
                    }
                }
            }
            Err(err) => Err(Error::UsbError(err)),
        }
    }

    /// Cancel current print job and reset printer state.
    ///
    /// Sends an initialization command to cancel any ongoing print job
    /// and reset the printer to a ready state.
    ///
    /// # Returns
    /// * `Ok(())` - Cancel command sent successfully
    /// * `Err(Error)` - Communication error
    ///
    /// # Example
    /// ```rust,no_run
    /// # use ptouch::{Config, Model, Media, ContinuousType, Printer};
    /// # let config = Config::new(Model::QL820NWB, "serial".to_string(), 
    /// #                         Media::Continuous(ContinuousType::Continuous62));
    /// let printer = Printer::new(config)?;
    /// printer.cancel()?; // Cancel any ongoing job
    /// # Ok::<(), ptouch::Error>(())
    /// ```
    pub fn cancel(&self) -> Result<(), Error> {
        let buf = self.initialize();
        self.write(buf)?;
        Ok(())
    }

    /// Read current printer status including media type, errors, and phase.
    ///
    /// This method is convenient for inspection when a new media is added
    /// or to check for printer errors before starting a print job.
    ///
    /// # Returns
    /// * `Ok(Status)` - Current printer status information
    /// * `Err(Error)` - Communication error or timeout
    ///
    /// # Example
    /// ```rust,no_run
    /// # use ptouch::{Config, Model, Media, ContinuousType, Printer};
    /// # let config = Config::new(Model::QL820NWB, "serial".to_string(), 
    /// #                         Media::Continuous(ContinuousType::Continuous62));
    /// let printer = Printer::new(config)?;
    /// match printer.check_status() {
    ///     Ok(status) => println!("Printer ready: {:?}", status),
    ///     Err(e) => eprintln!("Printer error: {:?}", e),
    /// }
    /// # Ok::<(), ptouch::Error>(())
    /// ```
    pub fn check_status(&self) -> Result<Status, Error> {
        self.request_status()?;
        self.read_status()
    }

    /// Print single-color labels.
    ///
    /// This method prints labels using black ink only. For two-color printing,
    /// use `print_two_color()` method instead.
    ///
    /// # Arguments
    /// * `images` - Iterator of `Matrix` (`Vec<Vec<u8>>`) containing 1-bit bitmap data
    ///
    /// # Returns
    /// * `Ok(())` - Print job completed successfully
    /// * `Err(Error)` - Printer error, communication error, or media mismatch
    ///
    /// # Image Format
    /// - Width: 720 pixels (90 bytes) for normal printers, 1296 pixels for wide printers
    /// - Height: Variable, depends on label length
    /// - Format: 1-bit bitmap packed into bytes (8 pixels per byte)
    ///
    /// # Example
    /// ```rust,no_run
    /// # use ptouch::{Config, Model, Media, ContinuousType, Printer, Matrix};
    /// let config = Config::new(Model::QL820NWB, "serial".to_string(), 
    ///                         Media::Continuous(ContinuousType::Continuous62));
    /// let printer = Printer::new(config)?;
    /// 
    /// // Create simple black and white pattern
    /// let image_data: Matrix = vec![vec![0xFF; 90]; 300]; // 300 lines of solid black
    /// 
    /// printer.print(vec![image_data].into_iter())?;
    /// # Ok::<(), ptouch::Error>(())
    /// ```
    pub fn print(&self, images: impl Iterator<Item = Matrix>) -> Result<(), Error> {
        info!("Requesting printer status before print job");

        self.request_status()?;

        match self.read_status() {
            Ok(status) => {
                info!("Verifying correct media is installed");
                status.check_media(self.config.media)?;

                info!("Starting print job");
                self.print_label(images)?;
                Ok(())
            }
            Err(err) => {
                error!("Failed to read printer status: {:?}", err);
                Err(err)
            }
        }
    }

    /// Print two-color labels using black and red colors.
    ///
    /// This method is specifically designed for QL-820NWB printers with
    /// red/black tape installed. The configuration must have `two_colors(true)`
    /// enabled for this method to work.
    ///
    /// # Arguments
    /// * `images` - Iterator of `TwoColorMatrix` containing black and red image data
    ///
    /// # Returns
    /// * `Ok(())` - Print job completed successfully
    /// * `Err(Error)` - Printer error, communication error, or invalid configuration
    ///
    /// # Example
    /// ```rust,no_run
    /// # use ptouch::{Config, Model, Media, ContinuousType, Printer, TwoColorMatrix};
    /// let config = Config::new(Model::QL820NWB, "serial".to_string(), 
    ///                         Media::Continuous(ContinuousType::Continuous62Red))
    ///     .two_colors(true);
    /// let printer = Printer::new(config)?;
    /// 
    /// // Create two-color image data
    /// let black_data = vec![vec![0u8; 90]; 300];
    /// let red_data = vec![vec![0u8; 90]; 300];
    /// let two_color = TwoColorMatrix::new(black_data, red_data)?;
    /// 
    /// printer.print_two_color(vec![two_color].into_iter())?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn print_two_color(&self, images: impl Iterator<Item = TwoColorMatrix>) -> Result<(), Error> {
        if !self.config.two_colors {
            return Err(Error::InvalidConfig("Two-color printing not enabled in config".to_string()));
        }

        info!("Requesting printer status before two-color print job");

        self.request_status()?;

        match self.read_status() {
            Ok(status) => {
                info!("Verifying correct media is installed");
                status.check_media(self.config.media)?;

                info!("Starting two-color print job");
                let alternating_images = images.map(|two_color| two_color.to_alternating_matrix());
                self.print_label(alternating_images)?;
                Ok(())
            }
            Err(err) => {
                error!("Failed to read printer status: {:?}", err);
                Err(err)
            }
        }
    }

    // Private helper methods

    fn open_device(
        context: &mut Context,
        pid: u16,
        serial: String,
    ) -> Result<(Device<Context>, DeviceDescriptor, DeviceHandle<Context>), Error> {
        let devices = context.devices()?;

        if devices.is_empty() {
            warn!("Unable to enumerate USB devices");
            return Err(Error::DeviceListNotReadable);
        }
        for device in devices.iter() {
            let device_desc = match device.device_descriptor() {
                Ok(d) => d,
                Err(err) => {
                    debug!("{:#?}", err);
                    continue;
                }
            };
            debug!(
                "vender_id: {:x},  product_id: {:x}",
                device_desc.vendor_id(),
                device_desc.product_id()
            );
            if device_desc.vendor_id() == VENDOR_ID && device_desc.product_id() == pid {
                match device.open() {
                    Ok(handle) => {
                        let timeout = Duration::from_secs(1);
                        let languages = handle.read_languages(timeout)?;

                        if languages.len() > 0 {
                            let language = languages[0];
                            match handle.read_serial_number_string(language, &device_desc, timeout)
                            {
                                Ok(s) => {
                                    if s == serial {
                                        info!("Connected to printer (serial: {})", serial);
                                        return Ok((device, device_desc, handle));
                                    } else {
                                        continue;
                                    }
                                }
                                Err(err) => {
                                    debug!("Cannot read device serial number: {:?}", err);
                                    continue;
                                }
                            }
                        } else {
                            continue;
                        }
                    }
                    Err(err) => {
                        debug!("Unable to open USB device: {:?}", err);
                        continue;
                    }
                }
            }
        }
        error!("No printer found with serial number: {}", serial);
        Err(Error::DeviceOffline)
    }

    fn find_endpoint(
        device: &mut Device<Context>,
        device_desc: &DeviceDescriptor,
        direction: Direction,
        transfer_type: TransferType,
    ) -> Option<Endpoint> {
        for n in 0..device_desc.num_configurations() {
            let config_desc = match device.config_descriptor(n) {
                Ok(c) => c,
                Err(_) => continue,
            };
            for interface in config_desc.interfaces() {
                for interface_desc in interface.descriptors() {
                    for endpoint_desc in interface_desc.endpoint_descriptors() {
                        if endpoint_desc.direction() == direction
                            && endpoint_desc.transfer_type() == transfer_type
                        {
                            return Some(Endpoint {
                                config: config_desc.number(),
                                iface: interface_desc.interface_number(),
                                setting: interface_desc.setting_number(),
                                address: endpoint_desc.address(),
                            });
                        }
                    }
                }
            }
        }
        None
    }

    fn write(&self, buf: Vec<u8>) -> Result<(), Error> {
        // 動的タイムアウト計算
        // - ベースタイムアウト: 5秒
        // - データサイズ依存: 1MB/sの転送速度を仮定
        // - 安全マージン: 2倍
        let base_timeout_secs = 5;
        let transfer_rate_bytes_per_sec = 1_000_000; // 1MB/s
        let safety_margin = 2.0;

        let data_dependent_timeout =
            (buf.len() as f64 / transfer_rate_bytes_per_sec as f64) * safety_margin;
        let total_timeout_secs = base_timeout_secs as f64 + data_dependent_timeout;

        // 最小10秒、最大60秒の範囲でクランプ
        let timeout_secs = total_timeout_secs.max(10.0).min(60.0);
        let timeout = Duration::from_secs(timeout_secs as u64);

        debug!(
            "USB transfer timeout set to {:.1}s for {} bytes",
            timeout_secs,
            buf.len()
        );
        let result = self
            .handle
            .write_bulk(self.endpoint_out.address, &buf, timeout);
        match result {
            Ok(n) => {
                if n == buf.len() {
                    debug!(
                        "Successfully wrote {} bytes to endpoint {:#x}",
                        n, self.endpoint_out.address
                    );
                    Ok(())
                } else {
                    warn!(
                        "USB write incomplete: {} of {} bytes transferred (possible timeout)",
                        n,
                        buf.len()
                    );
                    Err(Error::InvalidResponse(n))
                }
            }
            Err(e) => Err(Error::UsbError(e)),
        }
    }

    fn read_status(&self) -> Result<Status, Error> {
        self.read_status_with_timeout(Duration::from_millis(1000))
    }

    fn read_status_with_timeout(&self, timeout: Duration) -> Result<Status, Error> {
        let mut buf: [u8; 32] = [0x00; 32];
        let mut counter = 0;

        debug!("reading from endpoint_in {:#?}", self.endpoint_in);
        while counter < 100000 {
            match self
                .handle
                .read_bulk(self.endpoint_in.address, &mut buf, timeout)
            {
                // TODO: Check the first 4bytes match to [0x80, 0x20, 0x42, 0x34]
                // TODO: Check the error status
                //
                // buf is pouplated with 32 bytes of data
                Ok(32) => {
                    let status = Status::from_buf(buf);
                    debug!("Raw status code: {:X?}", buf);
                    debug!("Parsed Status struct: {:?}", status);
                    return Ok(status);
                }
                Ok(x) => {
                    debug!("Waiting {counter} {x}");
                    std::thread::sleep(std::time::Duration::from_millis(50));
                }
                Err(e) => return Err(Error::UsbError(e)),
            };
            counter = counter + 1;
        }
        Err(Error::ReadStatusTimeout)
    }

    fn wait_for_print_completion(&self) -> Result<(), Error> {
        let mut attempts = 0;
        const MAX_ATTEMPTS: u32 = 100; // 約5秒のタイムアウト

        debug!("Waiting for print completion...");

        loop {
            let status = self.read_status_with_timeout(Duration::from_millis(1000))?;
            debug!(
                "Print completion check: status_type={:?}, phase={:?}, error={:?}",
                status.status_type, status.phase, status.error
            );

            // エラー状態の即座検出
            if !status.error.is_no_error() {
                error!("Print operation failed: {:?}", status.error);
                return Err(Error::PrinterError(status.error));
            }

            match (status.status_type, status.phase) {
                // エラー状態の即座検出
                (StatusType::Error, _) => {
                    error!("Printer reported error status");
                    return Err(Error::PrinterError(status.error));
                }

                // 印刷完了 -> 受信待機への遷移を待つ
                (StatusType::Completed, Phase::Printing) => {
                    info!("Print finished, verifying printer state");
                    // 完了後、受信状態への遷移を確認
                    std::thread::sleep(Duration::from_millis(100));
                    let final_status = self.read_status_with_timeout(Duration::from_millis(500))?;
                    if matches!(final_status.phase, Phase::Receiving) {
                        info!("Print completed, printer ready for next job");
                        return Ok(());
                    }
                    debug!(
                        "Still waiting for transition to receiving state, current phase: {:?}",
                        final_status.phase
                    );
                }

                // 既に受信状態に戻っている(即座完了)
                (StatusType::PhaseChange, Phase::Receiving) => {
                    info!("Printer ready (already in receiving state)");
                    return Ok(());
                }

                // まだ印刷中
                (StatusType::PhaseChange, Phase::Printing) => {
                    debug!("Print in progress, continuing to monitor");
                    // 短い待機で継続監視
                    std::thread::sleep(Duration::from_millis(50));
                }

                // 予期しない状態
                _ => {
                    debug!("Unexpected status during print completion: {:#?}", status);
                    std::thread::sleep(Duration::from_millis(100));
                }
            }

            attempts += 1;
            if attempts >= MAX_ATTEMPTS {
                error!(
                    "Print completion timed out after {} attempts ({}s)",
                    attempts,
                    attempts * 50 / 1000
                );
                return Err(Error::PrintTimeout);
            }
        }
    }

    fn initialize(&self) -> Vec<u8> {
        let mut buf: Vec<u8> = Vec::new();
        buf.append(&mut [0x00; 400].to_vec());
        buf.append(&mut [0x1B, 0x40].to_vec());
        buf
    }

    fn set_media(&self, buf: &mut std::vec::Vec<u8>, raster_count: u32) {
        buf.extend_from_slice(&[0x1B, 0x69, 0x7A]); // ESC i z

        // n1: 有効フラグ (用紙種類+幅+長さ+ラスター数)
        let valid_flags = 0x02 | 0x04 | 0x08 | 0x40;
        buf.push(valid_flags);

        // n2: 用紙種類 (長尺:0x0A, ダイカット:0x0C)
        let media_type = match self.config.media {
            Media::Continuous(_) => 0x0A,
            Media::DieCut(_) => 0x0B,
        };
        buf.push(media_type);

        // n3, n4: 用紙幅・長さ (mm)
        let spec = self.config.media.spec();
        buf.push(spec.width_mm());
        buf.push(spec.length_mm());

        // n5-n8: ラスター数 (リトルエンディアン)
        let raster_bytes = raster_count.to_le_bytes();
        buf.extend_from_slice(&raster_bytes);

        // n9: 先頭ページフラグ (0=先頭ページ)
        buf.push(0x00);

        // n10: 固定値
        buf.push(0x00);
    }

    fn print_label(&self, images: impl Iterator<Item = Matrix>) -> Result<(), Error> {
        let mut preamble: Vec<u8> = self.initialize();
        preamble.append(&mut [0x1B, 0x69, 0x61, 0x01].to_vec()); // Set raster command mode
        preamble.append(&mut [0x1B, 0x69, 0x21, 0x00].to_vec()); // Set auto status notificatoin mode
                                                                 //
                                                                 // Apply config values
        match self.config.clone().build() {
            Ok(mut buf) => preamble.append(&mut buf),
            Err(err) => return Err(err),
        }

        // QL-800では圧縮モードがサポートされていないため、常に非圧縮とする
        let use_compression = if matches!(self.config.model, Model::QL800) && self.config.compress {
            warn!("QL-800 does not support compression mode, using uncompressed mode instead");
            false
        } else {
            self.config.compress
        };
        
        if use_compression {
            preamble.append(&mut [0x4D, 0x02].to_vec()); // Set to pack bits compression mode
        } else {
            preamble.append(&mut [0x4D, 0x00].to_vec()); // Set to no compression mode
        }

        debug!("{:?}", self.config);

        let mut start_flag: bool = true;
        let mut color = false;

        let mut iter = images.into_iter().peekable();

        loop {
            let mut buf: Vec<u8> = Vec::new();

            match iter.next() {
                Some(image) => {
                    if start_flag {
                        buf.append(&mut preamble);
                    }

                    // ESC i z 印刷情報司令
                    let raster_count = if self.config.two_colors {
                        (image.len() / 2) as u32
                    } else {
                        image.len() as u32
                    };
                    self.set_media(&mut buf, raster_count);
                    if start_flag {
                        buf.append(&mut [0x00, 0x00].to_vec());
                        start_flag = false;
                    } else {
                        buf.append(&mut [0x01, 0x00].to_vec());
                    }

                    // Add raster line image data
                    if self.config.two_colors {
                        for mut row in image {
                            if color {
                                // Black raster line (color code 0x01)
                                buf.append(&mut [0x77, 0x01, 90].to_vec());
                                buf.append(&mut row);
                                color = !color;
                            } else {
                                // Red raster line (color code 0x02)
                                buf.append(&mut [0x77, 0x02, 90].to_vec());
                                buf.append(&mut row);
                                color = !color;
                            }
                        }
                    } else {
                        if use_compression {
                            for row in image {
                                let mut packed = Self::pack_bits(&row);
                                let len = packed.len() as u8;
                                buf.append(&mut [0x67, 0x00, len].to_vec());
                                buf.append(&mut packed);
                            }
                        } else {
                            for mut row in image {
                                buf.append(&mut [0x67, 0x00, 90].to_vec());
                                buf.append(&mut row);
                            }
                        }
                    }

                    if iter.peek().is_some() {
                        buf.push(0x0C); // FF : Print
                        self.write(buf)?;
                        info!("Print command sent, waiting for completion...");

                        // 改善されたステータス待機(中間ページ)
                        self.wait_for_print_completion()?;
                        info!("Page printed successfully");
                    } else {
                        buf.push(0x1A); // Control-Z : Print then Eject
                        self.write(buf)?;
                        info!("Final print command sent, ejecting media...");

                        // 改善されたステータス待機
                        self.wait_for_print_completion()?;
                        info!("Print job completed successfully");

                        self.invalidate()?;
                    }
                }
                None => {
                    break;
                }
            }
        }
        Ok(())
    }

    /// TIFF PackBits圧縮アルゴリズム(Brother QL仕様準拠)
    ///
    /// 仕様:
    /// - 同一データ連続:個数-1を負数で指定 + データ1バイト
    /// - 異なるデータ連続:個数-1を正数で指定 + 全データ
    /// - 90バイト超過時は非圧縮として91バイト送信
    fn pack_bits(data: &[u8]) -> Vec<u8> {
        // 入力データが90バイト固定でない場合はそのまま返す
        if data.len() != 90 {
            return data.to_vec();
        }

        let mut packed = Vec::new();
        let mut i = 0;

        while i < data.len() {
            // Run-length encoding (RLE)のチェック
            let mut run_length = 1;
            let run_value = data[i];

            // 同じ値の連続をカウント(最大128個まで)
            while i + run_length < data.len()
                && run_length < 128
                && data[i + run_length] == run_value
            {
                run_length += 1;
            }

            // RLEが効果的な場合(2個以上の連続)
            if run_length >= 2 {
                // 負数で圧縮指示: -(count-1)
                packed.push((-(run_length as i8 - 1)) as u8);
                packed.push(run_value);
                i += run_length;
            } else {
                // リテラル実行のチェック
                let start_pos = i;
                let mut literal_length = 1;

                // リテラル実行の最適な長さを決定
                while i + literal_length < data.len() && literal_length < 128 {
                    // 次の位置で2個以上同じ値が続く場合は、ここでリテラル実行を終了
                    if i + literal_length + 1 < data.len()
                        && data[i + literal_length] == data[i + literal_length + 1]
                    {
                        break;
                    }
                    literal_length += 1;
                }

                // リテラル実行: 正数で非圧縮指示
                packed.push((literal_length - 1) as u8);
                packed.extend_from_slice(&data[start_pos..start_pos + literal_length]);
                i += literal_length;
            }
        }

        // 重要な最適化: 90バイト超過時は非圧縮として91バイト返す
        if packed.len() > 90 {
            warn!(
                "Data compression ineffective, sending uncompressed ({} bytes)",
                data.len()
            );
            let mut result = Vec::with_capacity(91);
            result.push(89); // 90-1 = 89(90バイトの非圧縮指示)
            result.extend_from_slice(data);
            result
        } else {
            debug!(
                "Compression reduced data from {} to {} bytes ({:.1}% reduction)",
                data.len(),
                packed.len(),
                (1.0 - packed.len() as f64 / data.len() as f64) * 100.0
            );
            packed
        }
    }

    fn request_status(&self) -> Result<(), Error> {
        let mut buf: Vec<u8> = self.initialize();
        buf.append(&mut [0x1b, 0x69, 0x53].to_vec());
        self.write(buf)
    }

    fn invalidate(&self) -> Result<(), Error> {
        let buf: Vec<u8> = self.initialize();
        self.write(buf)
    }
}

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

    #[test]
    fn test_pack_bits_compression() {
        // テスト1: 効果的な圧縮(同一データ連続)
        let all_zeros = vec![0u8; 90];
        let compressed = Printer::pack_bits(&all_zeros);
        println!(
            "All zeros: {} -> {} bytes",
            all_zeros.len(),
            compressed.len()
        );
        assert!(compressed.len() < all_zeros.len(), "圧縮が効果的でない");

        // テスト2: 非効果的な圧縮(ランダムデータ)
        let random_data: Vec<u8> = (0..90).map(|i| (i * 37 + 17) as u8).collect();
        let compressed_random = Printer::pack_bits(&random_data);
        println!(
            "Random data: {} -> {} bytes",
            random_data.len(),
            compressed_random.len()
        );

        // テスト3: 91バイト制限の確認
        if compressed_random.len() > 90 {
            println!("91バイト制限により非圧縮データが返される");
            assert_eq!(compressed_random.len(), 91); // 89 + 90バイトの元データ
            assert_eq!(compressed_random[0], 89); // 非圧縮指示
        }

        // テスト4: 混合パターン(部分的な圧縮効果)
        let mut mixed_data = vec![0u8; 30];
        mixed_data.extend(vec![255u8; 30]);
        mixed_data.extend((0..30).map(|i| i as u8));
        let compressed_mixed = Printer::pack_bits(&mixed_data);
        println!(
            "Mixed data: {} -> {} bytes",
            mixed_data.len(),
            compressed_mixed.len()
        );
    }

    #[test]
    fn test_pack_bits_edge_cases() {
        // エッジケース1: 空のデータ
        let empty_data = vec![];
        let compressed_empty = Printer::pack_bits(&empty_data);
        assert_eq!(compressed_empty, empty_data);

        // エッジケース2: 90バイト以外のサイズ
        let wrong_size = vec![42u8; 50];
        let compressed_wrong = Printer::pack_bits(&wrong_size);
        assert_eq!(compressed_wrong, wrong_size);

        // エッジケース3: 単一バイトの繰り返し(最大圧縮)
        let single_byte = vec![42u8; 90];
        let compressed_single = Printer::pack_bits(&single_byte);
        assert_eq!(compressed_single.len(), 2); // 長さ指示 + データ
        assert_eq!(compressed_single[0], (-(90i8 - 1)) as u8); // -89
        assert_eq!(compressed_single[1], 42);
    }
}

///
/// Status received from the printer encoded to Rust friendly type.
///
#[derive(Debug)]
#[allow(dead_code)]
pub struct Status {
    model: Model,
    error: PrinterError,
    media: Option<Media>,
    mode: u8,
    status_type: StatusType,
    phase: Phase,
    notification: Notification,
    id: u8,
}

impl Status {
    fn from_buf(buf: [u8; 32]) -> Self {
        Status {
            model: Model::from_code(buf[4]),
            error: PrinterError::from_buf(buf),
            media: Media::from_buf(buf),
            mode: buf[15],
            status_type: StatusType::from_code(buf[18]),
            phase: Phase::from_buf(buf),
            notification: Notification::from_code(buf[22]),
            id: buf[14],
        }
    }

    pub fn check_media(self, expected_media: Media) -> Result<(), Error> {
        match self.media {
            Some(actual_media) => {
                if actual_media == expected_media {
                    Ok(())
                } else {
                    Err(Error::MediaMismatch {
                        expected: expected_media,
                        actual: actual_media,
                    })
                }
            }
            None => Err(Error::NoMediaInstalled),
        }
    }
}

// StatusType

#[derive(Debug, PartialEq, Clone, Copy)]
enum StatusType {
    ReplyToRequest,
    Completed,
    Error,
    Offline,
    Notification,
    PhaseChange,
    Unknown,
}

impl StatusType {
    fn from_code(code: u8) -> StatusType {
        match code {
            0x00 => Self::ReplyToRequest,
            0x01 => Self::Completed,
            0x02 => Self::Error,
            0x04 => Self::Offline,
            0x05 => Self::Notification,
            0x06 => Self::PhaseChange,
            _ => Self::Unknown,
        }
    }
}
// Phase

#[derive(Debug, PartialEq, Clone, Copy)]
pub enum Phase {
    Receiving,
    Printing,
    Waiting(u16),
    // Printing(u16),
}

impl Phase {
    fn from_buf(buf: [u8; 32]) -> Self {
        match buf[19] {
            0x00 => Self::Receiving,
            0x01 => Self::Printing,
            _ => Self::Waiting(0),
        }
    }
}

// Notification

#[derive(Debug)]
enum Notification {
    NotAvailable,
    CoolingStarted,
    CoolingFinished,
}

impl Notification {
    fn from_code(code: u8) -> Self {
        match code {
            0x03 => Self::CoolingStarted,
            0x04 => Self::CoolingFinished,
            _ => Self::NotAvailable,
        }
    }
}

/// Config
///
#[derive(Debug, Clone, Copy)]
enum AutoCut {
    Enabled(u8),
    Disabled,
}

#[derive(Debug, Clone)]
pub struct Config {
    model: Model,
    serial: String,
    media: Media,
    auto_cut: AutoCut,
    two_colors: bool,
    cut_at_end: bool,
    high_resolution: bool,
    feed: u16,
    compress: bool,
}

impl Config {
    /// Initialize configuration data with default values.
    ///
    /// This method receives model and media.  They are not modifiable after the initialization.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use ptouch::{Config, ContinuousType, Media, Model};
    /// 
    /// let media = Media::Continuous(ContinuousType::Continuous29);
    /// let model = Model::QL800;
    /// let config = Config::new(model, "serial".to_string(), media);
    /// ```
    ///
    pub fn new(model: Model, serial: String, media: Media) -> Config {
        Config {
            model,
            serial,
            media,
            auto_cut: AutoCut::Enabled(1),
            two_colors: false,
            cut_at_end: true,
            high_resolution: false,
            feed: media.get_default_feed_dots(),
            compress: false,
        }
    }

    /// Enable auto cut after printing specified number of labels.
    ///
    /// # Arguments
    /// * `size` - Number of labels to print before auto-cutting (1-255)
    ///
    /// # Example
    /// ```rust,no_run
    /// # use ptouch::{Config, Model, Media, ContinuousType};
    /// let config = Config::new(Model::QL820NWB, "serial".to_string(), 
    ///                         Media::Continuous(ContinuousType::Continuous62))
    ///     .enable_auto_cut(3); // Cut after every 3 labels
    /// ```
    pub fn enable_auto_cut(self, size: u8) -> Self {
        Config {
            auto_cut: AutoCut::Enabled(size),
            ..self
        }
    }

    /// Disable automatic cutting of labels.
    ///
    /// When disabled, labels will need to be manually torn or cut.
    ///
    /// # Example
    /// ```rust,no_run
    /// # use ptouch::{Config, Model, Media, ContinuousType};
    /// let config = Config::new(Model::QL820NWB, "serial".to_string(), 
    ///                         Media::Continuous(ContinuousType::Continuous62))
    ///     .disable_auto_cut();
    /// ```
    pub fn disable_auto_cut(self) -> Self {
        Config {
            auto_cut: AutoCut::Disabled,
            ..self
        }
    }

    /// Control whether to cut the tape at the end of a print job.
    ///
    /// # Arguments
    /// * `flag` - `true` to cut at end, `false` to leave uncut
    ///
    /// # Example
    /// ```rust,no_run
    /// # use ptouch::{Config, Model, Media, ContinuousType};
    /// let config = Config::new(Model::QL820NWB, "serial".to_string(), 
    ///                         Media::Continuous(ContinuousType::Continuous62))
    ///     .cut_at_end(true); // Cut at the end of job
    /// ```
    pub fn cut_at_end(self, flag: bool) -> Self {
        Config {
            cut_at_end: flag,
            ..self
        }
    }

    /// Enable or disable high resolution printing.
    ///
    /// High resolution doubles the vertical resolution from 300 DPI to 600 DPI.
    /// When enabled, image height should be doubled accordingly.
    ///
    /// # Arguments
    /// * `high` - `true` for 600 DPI, `false` for 300 DPI
    ///
    /// # Example
    /// ```rust,no_run
    /// # use ptouch::{Config, Model, Media, ContinuousType};
    /// let config = Config::new(Model::QL820NWB, "serial".to_string(), 
    ///                         Media::Continuous(ContinuousType::Continuous62))
    ///     .high_resolution(true); // Enable 600 DPI
    /// ```
    pub fn high_resolution(self, high: bool) -> Self {
        Config {
            high_resolution: high,
            ..self
        }
    }

    /// Set the feeding length in dots.
    ///
    /// Controls how much tape is fed before printing starts.
    /// Different media types have different valid ranges.
    ///
    /// # Arguments
    /// * `feed` - Feed length in dots
    ///
    /// # Example
    /// ```rust,no_run
    /// # use ptouch::{Config, Model, Media, ContinuousType};
    /// let config = Config::new(Model::QL820NWB, "serial".to_string(), 
    ///                         Media::Continuous(ContinuousType::Continuous62))
    ///     .set_feed_in_dots(150); // Set feed to 150 dots
    /// ```
    pub fn set_feed_in_dots(self, feed: u16) -> Self {
        Config { feed, ..self }
    }

    /// Enable or disable two-color printing (black and red).
    ///
    /// Only supported on QL-820NWB with compatible red/black tape.
    /// When enabled, use `print_two_color()` method instead of `print()`.
    ///
    /// # Arguments
    /// * `two_colors` - `true` to enable two-color printing
    ///
    /// # Example
    /// ```rust,no_run
    /// # use ptouch::{Config, Model, Media, ContinuousType};
    /// let config = Config::new(Model::QL820NWB, "serial".to_string(), 
    ///                         Media::Continuous(ContinuousType::Continuous62Red))
    ///     .two_colors(true); // Enable red and black printing
    /// ```
    pub fn two_colors(self, two_colors: bool) -> Self {
        Config { two_colors, ..self }
    }

    /// Enable or disable data compression.
    ///
    /// Uses PackBits compression to reduce USB transfer size.
    /// Automatically disabled for QL-800 model due to hardware limitations.
    ///
    /// # Arguments
    /// * `flag` - `true` to enable compression
    ///
    /// # Example
    /// ```rust,no_run
    /// # use ptouch::{Config, Model, Media, ContinuousType};
    /// let config = Config::new(Model::QL820NWB, "serial".to_string(), 
    ///                         Media::Continuous(ContinuousType::Continuous62))
    ///     .compress(true); // Enable compression
    /// ```
    pub fn compress(self, flag: bool) -> Self {
        Config {
            compress: flag,
            ..self
        }
    }

    fn build(self) -> Result<Vec<u8>, Error> {
        let mut buf: Vec<u8> = Vec::new();

        // Set feeding values in dots
        {
            match self.media.check_feed_value(self.feed) {
                Ok(feed) => {
                    buf.append(&mut [0x1B, 0x69, 0x64].to_vec());
                    buf.append(&mut feed.to_vec());
                }
                Err(msg) => return Err(Error::InvalidConfig(msg)),
            }
        }
        // Set auto cut settings
        {
            let mut various_mode: u8 = 0b0000_0000;
            let mut auto_cut_num: u8 = 1;

            if let AutoCut::Enabled(n) = self.auto_cut {
                various_mode = various_mode | 0b0100_0000;
                auto_cut_num = n;
            }

            debug!("Auto-cut mode configured: {:#04x}", various_mode);
            debug!("Auto-cut frequency: {} pages", auto_cut_num);

            buf.append(&mut [0x1B, 0x69, 0x4D, various_mode].to_vec()); // ESC i M : Set various mode
            buf.append(&mut [0x1B, 0x69, 0x41, auto_cut_num].to_vec()); // ESC i A : Set auto cut number
        }
        // Set expanded mode
        {
            let mut expanded_mode: u8 = 0b00000000;

            if self.two_colors {
                expanded_mode = expanded_mode | 0b0000_0001;
            }

            if self.cut_at_end {
                expanded_mode = expanded_mode | 0b0000_1000;
            };

            if self.high_resolution {
                expanded_mode = expanded_mode | 0b0100_0000;
            }

            debug!("Print mode settings: {:#04x}", expanded_mode);

            buf.append(&mut [0x1B, 0x69, 0x4B, expanded_mode].to_vec()); // ESC i K : Set expanded mode
        }
        Ok(buf)
    }
}