-
-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathindex.ts
More file actions
1117 lines (1003 loc) · 33.8 KB
/
Copy pathindex.ts
File metadata and controls
1117 lines (1003 loc) · 33.8 KB
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
import type { Adapter } from "@node-escpos/adapter";
import EventEmitter from "eventemitter3";
import getPixels from "get-pixels";
import iconv from "iconv-lite";
import { MutableBuffer } from "mutable-buffer";
import qr from "qr-image";
import * as _ from "./commands";
import Image from "./image";
import {
ErrorCauseStatus,
OfflineCauseStatus,
PrinterStatus,
RollPaperSensorStatus,
} from "./statuses";
import type {
DeviceStatus,
StatusClassConstructor,
} from "./statuses";
import * as utils from "./utils";
import type { AnyCase } from "./utils";
export interface PrinterOptions {
encoding?: string | undefined
width?: number | undefined
}
export type PrinterModel = null | "qsprinter" | "xprinter";
/**
* 'dhdw', 'dwh' and 'dhw' are treated as 'dwdh'
*/
export type RasterMode = AnyCase<"normal" | "dw" | "dh" | "dwdh" | "dhdw" | "dwh" | "dhw">;
export interface QrImageOptions extends qr.Options {
mode: RasterMode
}
export type BitmapDensity = AnyCase<"s8" | "d8" | "s24" | "d24">;
export type StyleString = AnyCase<"normal" | `${"b" | ""}${"i" | ""}${"u" | "u2" | ""}`>;
export type FeedControlSequence = AnyCase<"lf" | "glf" | "ff" | "cr" | "ht" | "vt">;
export type Alignment = AnyCase<"lt" | "ct" | "rt">;
export type FontFamily = AnyCase<"a" | "b" | "c">;
export type HardwareCommand = AnyCase<"init" | "select" | "reset">;
export type BarcodeType = AnyCase<"UPC_A" | "UPC-A" | "UPC-E" | "UPC_E" | "EAN13" | "EAN8" | "CODE39" | "ITF" | "NW7" | "CODE93" | "CODE128">;
export type BarcodePosition = AnyCase<"off" | "abv" | "blw" | "bth">;
export type BarcodeFont = AnyCase<"a" | "b">;
export interface BarcodeOptions {
width: number
height: number
position?: BarcodePosition | undefined
font?: BarcodeFont | undefined
includeParity?: boolean | undefined
}
export type LegacyBarcodeArguments = [
width: number,
height: number,
position?: BarcodePosition | undefined,
font?: BarcodeFont | undefined,
];
export type QRLevel = AnyCase<"l" | "m" | "q" | "h">;
export type TableAlignment = AnyCase<"left" | "center" | "right">;
export type CustomTableItem = {
text: string
align?: TableAlignment
style?: StyleString | undefined
} & ({ width: number } | { cols: number });
export interface CustomTableOptions {
size: [number, number]
encoding: string
}
export class Printer<AdapterCloseArgs extends []> extends EventEmitter {
public adapter: Adapter<AdapterCloseArgs>;
public buffer = new MutableBuffer();
protected options: PrinterOptions | undefined;
protected encoding: string;
protected width: number;
protected _model: PrinterModel = null;
/**
* [function ESC/POS Printer]
* @param {[Adapter]} adapter [eg: usb, network, or serialport]
* @param {[PrinterOptions]} options
* @return {[Printer]} printer [the escpos printer instance]
*/
constructor(adapter: Adapter<AdapterCloseArgs>, options: PrinterOptions) {
super();
this.adapter = adapter;
this.options = options;
this.encoding = options.encoding ?? "GB18030";
this.width = options.width ?? 48;
}
/**
* Set printer model to recognize model-specific commands.
* Supported models: [ null, 'qsprinter' ]
*
* For generic printers, set model to null
*
* [function set printer model]
* @param {[String]} model [mandatory]
* @return {[Printer]} printer [the escpos printer instance]
*/
model(model: PrinterModel) {
this._model = model;
return this;
}
/**
* Set character code table
* @param {[Number]} codeTable
* @return {[Printer]} printer [the escpos printer instance]
*/
setCharacterCodeTable(codeTable: number) {
this.buffer.write(_.ESC);
this.buffer.write(_.TAB);
this.buffer.writeUInt8(codeTable);
return this;
}
/**
* Set charset
* @param {[Number]} charset
* @return {[Printer]} printer [the escpos printer instance]
*/
setCharset(charset: number = _.CHARACTER_SET.TM_T20.US) {
this.buffer.write(_.ESC);
this.buffer.write("\x52");
this.buffer.writeUInt8(charset);
return this;
}
/**
* Fix bottom margin
* @param {[String]} size
* @return {[Printer]} printer [the escpos printer instance]
*/
marginBottom(size: number) {
this.buffer.write(_.MARGINS.BOTTOM);
this.buffer.writeUInt8(size);
return this;
}
/**
* Fix left margin
* @param {[String]} size
* @return {[Printer]} printer [the escpos printer instance]
*/
marginLeft(size: number) {
this.buffer.write(_.MARGINS.LEFT);
this.buffer.writeUInt8(size);
return this;
}
/**
* Set left margin using GS command
* @param {[String]} size
* @return {[Printer]} printer [the escpos printer instance]
*/
setMarginLeft(size: number): Printer<AdapterCloseArgs> {
if (size > 65535) {
throw new Error("Max margin range exceeded");
}
// 1D 4C nL nH
this.buffer.write(_.GS);
this.buffer.write("\x4C");
const nL_nH = utils.intLowHighHex(size, 2);
this.buffer.write(Buffer.from(nL_nH, 'hex'));
return this;
}
/**
* Fix right margin
* @param {[String]} size
* @return {[Printer]} printer [the escpos printer instance]
*/
marginRight(size: number) {
this.buffer.write(_.MARGINS.RIGHT);
this.buffer.writeUInt8(size);
return this;
}
/**
* [function print]
* @param {[String]} content [mandatory]
* @return {[Printer]} printer [the escpos printer instance]
*/
print(content: string | Buffer) {
this.buffer.write(content);
return this;
}
/**
* [function print pure content with End Of Line]
* @param {[String]} content [mandatory]
* @return {[Printer]} printer [the escpos printer instance]
*/
println(content: string) {
return this.print(content + _.EOL);
}
/**
* [function print End Of Line]
* @param {[Number]} Amount of new lines
* @return {[Printer]} printer [the escpos printer instance]
*/
newLine(count = 1) {
if (count <= 0)
throw Error('Count cannot be less or equal than 0');
else
return this.print(_.EOL.repeat(count));
}
/**
* [function Print encoded alpha-numeric text with End Of Line]
* @param {[String]} content [mandatory]
* @param {[String]} encoding [optional]
* @return {[Printer]} printer [the escpos printer instance]
*/
text(content: string, encoding = this.encoding) {
return this.print(iconv.encode(`${content}${_.EOL}`, encoding));
}
/**
* [function Print draw line End Of Line]
* @param {[Buffer|string]} character [optional]
* @return {[Printer]} printer [the escpos printer instance]
*/
drawLine(character: Buffer | string = "-") {
let buffer: Buffer;
// Allow to print hex codes from codepage
if (Buffer.isBuffer(character)) {
buffer = character;
} else {
buffer = Buffer.from(character);
}
for (let i = 0; i < this.width; i++)
this.buffer.write(buffer);
this.newLine();
return this;
}
/**
* [function Print table with End Of Line]
* @param {[data]} data [mandatory]
* @param {[String]} encoding [optional]
* @return {[Printer]} printer [the escpos printer instance]
*/
table(data: (string | number)[], encoding = this.encoding) {
const cellWidth = this.width / data.length;
let lineTxt = "";
for (let i = 0; i < data.length; i++) {
lineTxt += data[i].toString();
const spaces = cellWidth - data[i].toString().length;
for (let j = 0; j < spaces; j++) lineTxt += " ";
}
this.buffer.write(iconv.encode(lineTxt + _.EOL, encoding));
return this;
}
/**
* [function Print custom table with End Of Line]
* @param {[data]} data [mandatory]
* @param {[String]} options [optional]
* @return {[Printer]} printer [the escpos printer instance]
*/
tableCustom(data: CustomTableItem[], options: CustomTableOptions = { size: [1, 1], encoding: this.encoding }): this {
const [width, height] = options.size;
const baseWidth = Math.floor(this.width / width);
let cellWidth = Math.floor(baseWidth / data.length);
let leftoverSpace = baseWidth - cellWidth * data.length; // by only data[].width
let lineStr = "";
let secondLineEnabled = false;
const secondLine = [];
for (let i = 0; i < data.length; i++) {
const obj = data[i];
const align = utils.upperCase(obj.align || "left");
const textLength = utils.textLength(obj.text);
if ("width" in obj) {
cellWidth = baseWidth * obj.width;
}
else if (obj.cols) {
cellWidth = obj.cols / width;
leftoverSpace = 0;
}
let originalText: string | null = null;
if (cellWidth < textLength) {
originalText = obj.text;
obj.text = utils.textSubstring(obj.text, 0, cellWidth);
}
if (align === "CENTER") {
const spaces = (cellWidth - textLength) / 2;
for (let s = 0; s < spaces; s++) lineStr += " ";
if (obj.text !== "") {
if (obj.style) lineStr += `${this._getStyle(obj.style)}${obj.text}${this._getStyle("NORMAL")}`;
else lineStr += obj.text;
}
for (let s = 0; s < spaces - 1; s++) lineStr += " ";
}
else if (align === "RIGHT") {
let spaces = cellWidth - textLength;
if (leftoverSpace > 0) {
spaces += leftoverSpace;
leftoverSpace = 0;
}
for (let s = 0; s < spaces; s++) lineStr += " ";
if (obj.text !== "") {
if (obj.style) lineStr += `${this._getStyle(obj.style)}${obj.text}${this._getStyle("NORMAL")}`;
else lineStr += obj.text;
}
}
else {
if (obj.text !== "") {
if (obj.style) lineStr += `${this._getStyle(obj.style)}${obj.text}${this._getStyle("NORMAL")}`;
else lineStr += obj.text;
}
let spaces = Math.floor(cellWidth - textLength);
if (leftoverSpace > 0) {
spaces += leftoverSpace;
leftoverSpace = 0;
}
for (let s = 0; s < spaces; s++) lineStr += " ";
}
if (originalText !== null) {
secondLineEnabled = true;
obj.text = utils.textSubstring(originalText, cellWidth);
secondLine.push(obj);
}
else {
obj.text = "";
secondLine.push(obj);
}
}
// Set size to line
if (width > 1 || height > 1) {
lineStr = (
_.TEXT_FORMAT.TXT_CUSTOM_SIZE(width, height)
+ lineStr
+ _.TEXT_FORMAT.TXT_NORMAL
);
}
// Write the line
this.buffer.write(
iconv.encode(lineStr + _.EOL, options.encoding || this.encoding),
);
if (secondLineEnabled) {
// Writes second line if has
return this.tableCustom(secondLine, options);
}
else {
return this;
}
}
/**
* [function Print encoded alpha-numeric text without End Of Line]
* @param {[String]} content [mandatory]
* @param {[String]} encoding [optional]
* @return {[Printer]} printer [the escpos printer instance]
*/
pureText(content: string, encoding = this.encoding) {
return this.print(iconv.encode(content, encoding));
}
/**
* [function encode text]
* @param {[String]} encoding [mandatory]
* @return {[Printer]} printer [the escpos printer instance]
*/
encode(encoding: string) {
this.encoding = encoding;
return this;
}
/**
* [line feed]
* @param {[type]} n Number of lines
* @return {[Printer]} printer [the escpos printer instance]
*/
feed(n = 1) {
this.buffer.write(new Array(n).fill(_.EOL).join(""));
return this;
}
/**
* [feed control sequences]
* @param {[type]} ctrl [description]
* @return {[Printer]} printer [the escpos printer instance]
*/
control(ctrl: FeedControlSequence) {
this.buffer.write(_.FEED_CONTROL_SEQUENCES[
`CTL_${utils.upperCase(ctrl)}` as const
]);
return this;
}
/**
* [text align]
* @param {[type]} align [description]
* @return {[Printer]} printer [the escpos printer instance]
*/
align(align: Alignment) {
this.buffer.write(_.TEXT_FORMAT[
`TXT_ALIGN_${utils.upperCase(align)}` as const
]);
return this;
}
/**
* [font family]
* @param {[type]} family [description]
* @return {[Printer]} printer [the escpos printer instance]
*/
font(family: FontFamily) {
this.buffer.write(_.TEXT_FORMAT[
`TXT_FONT_${utils.upperCase(family)}` as const
]);
if (family.toUpperCase() === "A")
this.width = this.options?.width || 42;
else
this.width = this.options?.width || 56;
return this;
}
/**
* [font style]
* @return {[Printer]} printer [the escpos printer instance]
*/
_getStyle(string: StyleString): string;
_getStyle(bold: boolean, italic: boolean, underline: boolean | 0 | 1 | 2): string;
_getStyle(boldOrString: boolean | StyleString, italic?: boolean, underline?: boolean | 0 | 1 | 2) {
if (typeof boldOrString === "string") {
switch (utils.upperCase(boldOrString)) {
case "B":
return this._getStyle(true, false, 0);
case "I":
return this._getStyle(false, true, 0);
case "U":
return this._getStyle(false, false, 1);
case "U2":
return this._getStyle(false, false, 2);
case "BI":
return this._getStyle(true, true, 0);
case "BIU":
return this._getStyle(true, true, 1);
case "BIU2":
return this._getStyle(true, true, 2);
case "BU":
return this._getStyle(true, false, 1);
case "BU2":
return this._getStyle(true, false, 2);
case "IU":
return this._getStyle(false, true, 1);
case "IU2":
return this._getStyle(false, true, 2);
case "NORMAL":
default:
return this._getStyle(false, false, 0);
}
}
else {
let styled = `${
boldOrString ? _.TEXT_FORMAT.TXT_BOLD_ON : _.TEXT_FORMAT.TXT_BOLD_OFF
}${
italic ? _.TEXT_FORMAT.TXT_ITALIC_ON : _.TEXT_FORMAT.TXT_ITALIC_OFF
}`;
if (underline === 0 || underline === false) styled += _.TEXT_FORMAT.TXT_UNDERL_OFF;
else if (underline === 1 || underline === true) styled += _.TEXT_FORMAT.TXT_UNDERL_ON;
else if (underline === 2) styled += _.TEXT_FORMAT.TXT_UNDERL2_ON;
return styled;
}
}
/**
* [font style]
* @return {[Printer]} printer [the escpos printer instance]
*/
style(string: StyleString): this;
style(bold: boolean, italic: boolean, underline: boolean | 0 | 1 | 2): this;
style(boldOrString: boolean | StyleString, italic?: boolean, underline?: boolean | 0 | 1 | 2) {
const style = (typeof boldOrString === "string")
? this._getStyle(boldOrString)
: this._getStyle(boldOrString, italic as boolean, underline as boolean);
this.buffer.write(style);
return this;
}
/**
* [font size]
* @param {[String]} width [description]
* @param {[String]} height [description]
* @return {[Printer]} printer [the escpos printer instance]
*/
size(width: number, height: number) {
this.buffer.write(_.TEXT_FORMAT.TXT_CUSTOM_SIZE(width, height));
return this;
}
/**
* [set character spacing]
* @param {[type]} n [description]
* @return {[Printer]} printer [the escpos printer instance]
*/
spacing(n?: number | null) {
if (n === undefined || n === null) {
this.buffer.write(_.CHARACTER_SPACING.CS_DEFAULT);
}
else {
this.buffer.write(_.CHARACTER_SPACING.CS_SET);
this.buffer.writeUInt8(n);
}
return this;
}
/**
* [set line spacing]
* @param {[type]} n [description]
* @return {[Printer]} printer [the escpos printer instance]
*/
lineSpace(n?: number | null) {
if (n === undefined || n === null) {
this.buffer.write(_.LINE_SPACING.LS_DEFAULT);
}
else {
this.buffer.write(_.LINE_SPACING.LS_SET);
this.buffer.writeUInt8(n);
}
return this;
}
/**
* [hardware]
* @param {[type]} hw [description]
* @return {[Printer]} printer [the escpos printer instance]
*/
hardware(hw: HardwareCommand) {
this.buffer.write(_.HARDWARE[`HW_${utils.upperCase(hw)}` as const]);
return this;
}
/**
* [barcode]
* @param {[type]} code [description]
* @param {[type]} type [description]
* @param {[type]} options [description]
* @return {[Printer]} printer [the escpos printer instance]
*/
barcode(code: number | string, type: BarcodeType, options : BarcodeOptions) {
options.font = options.font ?? "a";
options.position = options.position ?? "blw";
options.includeParity = options.includeParity ?? true;
const convertCode = (typeof code === 'number') ? code.toString(10) : code;
let parityBit = "";
let codeLength = "";
if (typeof type === "undefined" || type === null)
throw new TypeError("barcode type is required");
if (type === "EAN13" && convertCode.length !== 12)
throw new Error("EAN13 Barcode type requires code length 12");
if (type === "EAN8" && convertCode.length !== 7)
throw new Error("EAN8 Barcode type requires code length 7");
if (["UPC_A", "UPC-A", "UPC-E", "UPC_E", "EAN13", "EAN8", "ITF", "NW7"].includes(type) && !/^\d+$/.test(convertCode))
throw new Error(type + " Barcode type only support numbers")
if (this._model === "qsprinter")
this.buffer.write(_.MODEL.QSPRINTER.BARCODE_MODE.ON);
if (this._model === "qsprinter") {
// qsprinter has no BARCODE_WIDTH command (as of v7.5)
}
else if (utils.isKey(options.width, _.BARCODE_FORMAT.BARCODE_WIDTH)) {
this.buffer.write(_.BARCODE_FORMAT.BARCODE_WIDTH[options.width]);
}
else {
this.buffer.write(_.BARCODE_FORMAT.BARCODE_WIDTH_DEFAULT);
}
if (options.height >= 1 && options.height <= 255) {
this.buffer.write(_.BARCODE_FORMAT.BARCODE_HEIGHT(options.height));
}
else {
if (this._model === "qsprinter")
this.buffer.write(_.MODEL.QSPRINTER.BARCODE_HEIGHT_DEFAULT);
else
this.buffer.write(_.BARCODE_FORMAT.BARCODE_HEIGHT_DEFAULT);
}
if (this._model === "qsprinter") {
// Qsprinter has no barcode font
}
else {
this.buffer.write(_.BARCODE_FORMAT[
`BARCODE_FONT_${utils.upperCase(options.font)}` as const
]);
}
this.buffer.write(_.BARCODE_FORMAT[
`BARCODE_TXT_${utils.upperCase(options.position)}` as const
]);
let normalizedType = utils.upperCase(type);
if (normalizedType === "UPC-A") normalizedType = "UPC_A";
else if (normalizedType === "UPC-E") normalizedType = "UPC_E";
this.buffer.write(_.BARCODE_FORMAT[
`BARCODE_${normalizedType}` as const
]);
if (options.includeParity) {
if (type === "EAN13" || type === "EAN8")
parityBit = utils.getParityBit(convertCode);
}
if (type === "CODE128" || type === "CODE93")
codeLength = utils.codeLength(convertCode);
if ((this._model === "xprinter") && type === "CODE128") {
const code128Data = utils.genCode128forXprinter(convertCode);
this.buffer.write(code128Data);
} else {
this.buffer.write(`${codeLength + convertCode + (options.includeParity ? parityBit : "")}\x00`); // Allow to skip the parity byte
}
if (this._model === "qsprinter")
this.buffer.write(_.MODEL.QSPRINTER.BARCODE_MODE.OFF);
return this;
}
/**
* [print qrcode]
* @param {[type]} content [description]
* @param {[type]} version [description]
* @param {[type]} level [description]
* @param {[type]} size [description]
* @return {[Printer]} printer [the escpos printer instance]
*/
qrcode(content: string, version?: number | undefined, level?: QRLevel | undefined, size?: number | undefined) {
if (this._model !== "qsprinter") {
this.buffer.write(_.CODE2D_FORMAT.TYPE_QR);
this.buffer.write(_.CODE2D_FORMAT.CODE2D);
this.buffer.writeUInt8(version ?? 3);
this.buffer.write(_.CODE2D_FORMAT[
`QR_LEVEL_${utils.upperCase(level ?? "L")}` as const
]);
this.buffer.writeUInt8(size ?? 6);
this.buffer.writeUInt16LE(content.length);
this.buffer.write(content);
}
else {
const dataRaw = iconv.encode(content, "utf8");
if (dataRaw.length < 1 && dataRaw.length > 2710)
throw new Error("Invalid code length in byte. Must be between 1 and 2710");
// Set pixel size
if (!size || (size && typeof size !== "number"))
size = _.MODEL.QSPRINTER.CODE2D_FORMAT.PIXEL_SIZE.DEFAULT;
else if (size && size < _.MODEL.QSPRINTER.CODE2D_FORMAT.PIXEL_SIZE.MIN)
size = _.MODEL.QSPRINTER.CODE2D_FORMAT.PIXEL_SIZE.MIN;
else if (size && size > _.MODEL.QSPRINTER.CODE2D_FORMAT.PIXEL_SIZE.MAX)
size = _.MODEL.QSPRINTER.CODE2D_FORMAT.PIXEL_SIZE.MAX;
this.buffer.write(_.MODEL.QSPRINTER.CODE2D_FORMAT.PIXEL_SIZE.CMD);
this.buffer.writeUInt8(size);
// Set version
if (!version || (version && typeof version !== "number"))
version = _.MODEL.QSPRINTER.CODE2D_FORMAT.VERSION.DEFAULT;
else if (version && version < _.MODEL.QSPRINTER.CODE2D_FORMAT.VERSION.MIN)
version = _.MODEL.QSPRINTER.CODE2D_FORMAT.VERSION.MIN;
else if (version && version > _.MODEL.QSPRINTER.CODE2D_FORMAT.VERSION.MAX)
version = _.MODEL.QSPRINTER.CODE2D_FORMAT.VERSION.MAX;
this.buffer.write(_.MODEL.QSPRINTER.CODE2D_FORMAT.VERSION.CMD);
this.buffer.writeUInt8(version);
// Set level
this.buffer.write(_.MODEL.QSPRINTER.CODE2D_FORMAT.LEVEL.CMD);
this.buffer.write(_.MODEL.QSPRINTER.CODE2D_FORMAT.LEVEL.OPTIONS[
utils.upperCase(level ?? "L")
]);
// Transfer data(code) to buffer
this.buffer.write(_.MODEL.QSPRINTER.CODE2D_FORMAT.SAVEBUF.CMD_P1);
this.buffer.writeUInt16LE(dataRaw.length + _.MODEL.QSPRINTER.CODE2D_FORMAT.LEN_OFFSET);
this.buffer.write(_.MODEL.QSPRINTER.CODE2D_FORMAT.SAVEBUF.CMD_P2);
this.buffer.write(dataRaw);
// Print from buffer
this.buffer.write(_.MODEL.QSPRINTER.CODE2D_FORMAT.PRINTBUF.CMD_P1);
this.buffer.writeUInt16LE(dataRaw.length + _.MODEL.QSPRINTER.CODE2D_FORMAT.LEN_OFFSET);
this.buffer.write(_.MODEL.QSPRINTER.CODE2D_FORMAT.PRINTBUF.CMD_P2);
}
return this;
}
/**
* [print qrcode image]
* @param {[type]} text [description]
* @param {[type]} options [description]
* @return {[Promise]}
*/
qrimage(text: string, options: QrImageOptions = { type: "png", mode: "dhdw" }): Promise<this> {
return new Promise((resolve, reject) => {
const buffer = qr.imageSync(text, options);
const type = ["image", options.type].join("/");
getPixels(buffer, type, (err, pixels) => {
if (err) reject(err);
this.raster(new Image(pixels), options.mode);
resolve(this);
});
});
}
/**
* [image description]
* @param {[type]} image [description]
* @param {[type]} density [description]
* @return {[Printer]} printer [the escpos printer instance]
*/
async image(image: Image, density: BitmapDensity = "d24") {
if (!(image instanceof Image)) throw new TypeError("Only escpos.Image supported");
const n = ~["D8", "S8"].indexOf(utils.upperCase(density)) ? 1 : 3;
const header = _.BITMAP_FORMAT[`BITMAP_${utils.upperCase(density)}` as const];
const bitmap = image.toBitmap(n * 8);
this.lineSpace(0); // set line spacing to 0
bitmap.data.forEach((line) => {
this.buffer.write(header);
this.buffer.writeUInt16LE(line.length / n);
this.buffer.write(line);
this.buffer.write(_.EOL);
});
// added a delay so the printer can process the graphical data
// when connected via slower connection ( e.g.: Serial)
await new Promise<void>((resolve) => {
setTimeout(() => { resolve(); }, 200);
});
return this.lineSpace();
}
/**
* [raster description]
* @param {[type]} image [description]
* @param {[type]} mode Raster mode (
* @return {[Printer]} printer [the escpos printer instance]
*/
raster(image: Image, mode: RasterMode = "NORMAL") {
if (!(image instanceof Image))
throw new TypeError("Only escpos.Image supported");
mode = utils.upperCase(mode);
if (mode === "DHDW"
|| mode === "DWH"
|| mode === "DHW") mode = "DWDH";
const raster = image.toRaster();
const header = _.GSV0_FORMAT[`GSV0_${mode}` as const];
this.buffer.write(header);
this.buffer.writeUInt16LE(raster.width);
this.buffer.writeUInt16LE(raster.height);
this.buffer.write(raster.data);
return this;
}
/**
* [function Send pulse to kick the cash drawer]
* @param {[type]} pin [description]
* @return {[Printer]} printer [the escpos printer instance]
*/
cashdraw(pin: 2 | 5 = 2) {
this.buffer.write(_.CASH_DRAWER[
pin === 5 ? "CD_KICK_5" : "CD_KICK_2"
]);
return this;
}
/**
* Printer Buzzer (Beep sound)
* @param {[Number]} n Refers to the number of buzzer times
* @param {[Number]} t Refers to the buzzer sound length in (t * 100) milliseconds.
*/
beep(n: number, t: number) {
this.buffer.write(_.BEEP);
this.buffer.writeUInt8(n);
this.buffer.writeUInt8(t);
return this;
}
/**
* Send data to hardware and flush buffer
* @return {[Promise]}
*/
flush(): Promise<this> {
return new Promise((resolve, reject) => {
const buf = this.buffer.flush();
this.adapter.write(buf, (error) => {
if (error) reject(error);
else resolve(this);
});
});
}
/**
* Cut paper
* @param {[boolean]} partial set a full or partial cut. Default: full Partial cut is not implemented in all printers
* @param {[number]} feed Number of lines to feed before cutting
* @return {[Printer]} printer [the escpos printer instance]
*/
cut(partial = false, feed = 3) {
this.feed(feed);
this.buffer.write(_.PAPER[
partial ? "PAPER_PART_CUT" : "PAPER_FULL_CUT"
]);
return this;
}
/**
* [close description]
* @param closeArgs Arguments passed to adapter's close function
*/
async close(...closeArgs: AdapterCloseArgs): Promise<this> {
await this.flush();
return new Promise((resolve, reject) => {
this.adapter.close((error) => {
if (error) reject(error);
resolve(this);
}, ...closeArgs);
});
}
/**
* [color select between two print color modes, if your printer supports it]
* @param {Number} color - 0 for primary color (black) 1 for secondary color (red)
* @return {[Printer]} printer [the escpos printer instance]
*/
color(color: 0 | 1) {
if (color !== 0 && color !== 1) {
console.warn(`Unknown color ${color}`);
this.buffer.write(_.COLOR[0]);
}
else { this.buffer.write(_.COLOR[color]); }
return this;
}
/**
* [reverse colors, if your printer supports it]
* @param {Boolean} reverse - True for reverse, false otherwise
* @return {[Printer]} printer [the escpos printer instance]
*/
setReverseColors(reverse: boolean) {
this.buffer.write(reverse ? _.COLOR.REVERSE : _.COLOR.UNREVERSE);
return this;
}
/**
* [writes a low level command to the printer buffer]
*
* @usage
* 1) raw('1d:77:06:1d:6b:02:32:32:30:30:30:30:32:30:30:30:35:30:35:00:0a')
* 2) raw('1d 77 06 1d 6b 02 32 32 30 30 30 30 32 30 30 30 35 30 35 00 0a')
* 3) raw(Buffer.from('1d77061d6b0232323030303032303030353035000a','hex'))
*
* @param data {Buffer|string}
* @returns {Printer}
*/
raw(data: Buffer | string) {
if (Buffer.isBuffer(data)) {
this.buffer.write(data);
}
else if (typeof data === "string") {
data = data.toLowerCase();
this.buffer.write(Buffer.from(data.replace(/(\s|:)/g, ""), "hex"));
}
return this;
}
/**
* get one specific status from the printer using it's class
* @param {string} StatusClass
* @return {Promise} promise returning given status
*/
getStatus<T extends DeviceStatus>(StatusClass: StatusClassConstructor<T>): Promise<T> {
return new Promise<T>((resolve, reject) => {
this.adapter.read((data: Buffer) => {
try {
if(data.length === 0) {
return reject(new Error("Get status timeout"));
}
const byte = data.readInt8(0);
resolve(new StatusClass(byte));
} catch (err) {
if (typeof err === "string") {
console.error(err);
reject(new Error(err));
} else {
console.error(err);
reject(err);
}
}
});
this.adapter.write(StatusClass.commands().join(''));
});
}
/**
* get statuses from the printer
* @return {Promise}
*/
getStatuses(): Promise<DeviceStatus[]> {
return new Promise<DeviceStatus[]> (async (resolve, reject) => {
const results:DeviceStatus[] = [];
try {
results.push(await this.getStatus(PrinterStatus));
results.push(await this.getStatus(RollPaperSensorStatus));
results.push(await this.getStatus(OfflineCauseStatus));
results.push(await this.getStatus(ErrorCauseStatus));
resolve(results);
} catch (err) {
if (typeof err === "string") {
console.error(err);
reject(new Error(err));
} else {
console.error(err);
reject(err);
}
}
});
}
/****************************
/* Receipt Enhancements
/****************************/
/**
* Sets the alignment of the top and bottom logo
* @param {[Alignment]} align - Align left, center or right
*/
private setLogoAlignment(align: Alignment = 'lt'): Printer<AdapterCloseArgs> {
switch(align) {
case 'lt':
case 'LT':
this.buffer.write("\x30");
break;
case 'ct':
case 'CT':
this.buffer.write("\x31");
break;
case 'rt':
case 'RT':
this.buffer.write("\x32");
break;
default:
this.buffer.write("\x30");
break;
}
return this;
}
/**
* [Function 62 & 63] Set top and bottom logo printing
* @param {[String]} pL_pH - Hex string to set the function range
* @param {[String]} fn - Hex string to set the receipt enhancement function
* @param {[Number]} kc1 - NV memory keycode 1 of the logo
* @param {[Number]} kc2 - NV memory keycode 2 of the logo
* @param {[Alignment]} align - Align left, center or right
* @return {[Printer]} printer [the escpos printer instance]
*/
private setLogoPrinting(pL_pH: string, fn: string, kc1: number, kc2: number, align: Alignment = 'lt'): Printer<AdapterCloseArgs> {
if (kc1 < 32 || kc1 > 126) {
throw new Error("Keycode 1 is out of range");
} else if (kc2 < 32 || kc2 > 126) {