### Install Go SDK Source: https://iprtapp.com/en/psdk/programming/go Use the go get command to add the SDK to your project dependencies. ```bash go get github.com/prtmax/psdk-go ``` -------------------------------- ### Install SDK dependencies Source: https://iprtapp.com/en/psdk/programming/openharmony Execute the installation command after updating the dependency list. ```bash ohpm install ``` -------------------------------- ### Quick Start with FakeConnectedDevice Source: https://iprtapp.com/en/psdk/programming/rust Demonstrates the basic command construction and writing process using the built-in FakeConnectedDevice. ```rust use std::sync::{Arc, Mutex}; use psdk_father::{device::FakeConnectedDevice, psdk::Psdk}; use psdk_fruit_cpcl::{args::CPrint, BaseCpcl}; fn main() -> Result<(), Box> { let device = Arc::new(Mutex::new(FakeConnectedDevice::new())); let mut cpcl = BaseCpcl::with_connected_device(device); let reporter = cpcl .page((400, 576))? .text((50, 50, "商品标签"))? .bar((50, 150, "1234567890", 2, 50))? .print(CPrint::default())? .write()?; println!("write ok: {}, bytes: {}", reporter.ok, reporter.binary.len()); Ok(()) } ``` -------------------------------- ### Construct CPCL Commands Source: https://iprtapp.com/en/psdk/programming/rust Example of building a label layout using CPCL protocol methods. ```rust use psdk_father::psdk::Psdk; use psdk_fruit_cpcl::{ args::{CPrint, CQRCode}, BaseCpcl, }; cpcl .page((400, 576))? .text((30, 40, "商品标签"))? .bar((30, 120, "6901234567890", 2, 60))? .qr_code((380, 80, "https://example.com", 5))? .print(CPrint::default())? .write()?; ``` -------------------------------- ### Construct TSPL Commands Source: https://iprtapp.com/en/psdk/programming/rust Example of building a label layout using TSPL protocol methods. ```rust use psdk_father::psdk::Psdk; use psdk_fruit_tspl::BaseTspl; tspl .page((60, 40))? .gap(true)? .direction(0)? .cls()? .text((50, 50, 1, 1, false, "标签内容"))? .bar((30, 90, 300, 2))? .qr_code((320, 90, 4, "https://example.com", "M"))? .print(1)? .write()?; ``` -------------------------------- ### Construct ESC Commands Source: https://iprtapp.com/en/psdk/programming/rust Example of sending control commands using the ESC protocol. ```rust use psdk_father::psdk::Psdk; use psdk_fruit_esc::BaseEsc; esc .wakeup()? .enable()? .line_dot(16)? .stop_job()? .write()?; ``` -------------------------------- ### Implement Printer Page in OpenHarmony Source: https://iprtapp.com/en/psdk/programming/openharmony A complete component example demonstrating Bluetooth device discovery, connection management, and printing using the PSDK in an OpenHarmony environment. ```typescript import { OhosBluetoothLe } from '@psdk/ohos-bluetooth-le'; import { ConnectedDevice } from '@psdk/frame-father'; import { JluetoothDevice } from '@psdk/device-bluetooth-traits'; import { PrinterUtil } from '../common/PrinterUtil'; import ble from '@ohos.bluetooth.ble'; import promptAction from '@ohos.promptAction'; @Entry @Component struct PrinterPage { @State discoveredDevices: Array> = []; @State connectionState: string = 'Not connected'; @State connectedDevice?: ConnectedDevice = undefined; private ohosBluetoothLe = new OhosBluetoothLe({ allowNoName: false, allowedWriteCharacteristic: '49535343-8841-43F4-A8D4-ECBE34729BB3', allowedReadCharacteristic: '49535343-1e4d-4bd9-ba61-23c647249616' }); aboutToAppear() { this.ohosBluetoothLe.discovered((devices) => { devices.forEach(device => { const isDuplicate = this.discoveredDevices.find( item => item.deviceId === device.deviceId ); if (!isDuplicate) { this.discoveredDevices.push(device); } }); return Promise.resolve(); }); } async discovery() { this.discoveredDevices = []; await this.ohosBluetoothLe.startDiscovery(); } async onConnect(device: JluetoothDevice) { try { promptAction.showToast({ message: 'Connecting...', duration: 2000 }); this.connectedDevice = await this.ohosBluetoothLe.connect(device); PrinterUtil.getInstance().init(this.connectedDevice); this.connectionState = `${this.connectedDevice.deviceName()} connected`; promptAction.showToast({ message: 'Connected successfully', duration: 2000 }); } catch (err) { promptAction.showToast({ message: 'Connection failed', duration: 2000 }); } } async onPrint() { if (!this.connectedDevice) { promptAction.showToast({ message: 'Please connect device', duration: 2000 }); return; } try { const cpcl = PrinterUtil.getInstance().cpcl(); const psdk = cpcl .page({ width: 576, height: 400 }) .center() .text({ x: 0, y: 50, font: 24, content: 'Test Print' }) .print(); await psdk.write({ enableChunkWrite: true, chunkSize: 20 }); promptAction.showToast({ message: 'Print success', duration: 2000 }); } catch (e) { promptAction.showToast({ message: 'Print failed', duration: 2000 }); } } onDisconnect() { if (this.connectedDevice) { this.connectedDevice.disconnect(); this.connectionState = 'Not connected'; this.connectedDevice = undefined; promptAction.showToast({ message: 'Disconnected', duration: 2000 }); } } build() { Column() { Text(this.connectionState) .fontSize(20) .margin(20) Button('Start Discovery') .onClick(() => this.discovery()) .margin(10) List() { ForEach(this.discoveredDevices, (device: JluetoothDevice) => { ListItem() { Text(device.name) .onClick(() => this.onConnect(device)) } }) } .height('40%') Button('Print Test') .onClick(() => this.onPrint()) .margin(10) Button('Disconnect') .onClick(() => this.onDisconnect()) .margin(10) } .width('100%') .height('100%') } } ``` -------------------------------- ### Install SDK Dependencies Source: https://iprtapp.com/en/psdk/programming/rust Add the necessary crates to your Cargo.toml file. You can include all available crates or only the specific protocol crates required for your project. ```toml [dependencies] psdk-father = "0.0.1" psdk-fruit-cpcl = "0.0.1" psdk-fruit-tspl = "0.0.1" psdk-fruit-esc = "0.0.1" ``` ```toml [dependencies] psdk-father = "0.0.1" psdk-fruit-cpcl = "0.0.1" ``` -------------------------------- ### TSPL Command Usage Source: https://iprtapp.com/en/psdk/programming/go Example of constructing a TSPL print job for label printers. ```go printer := tspl.Generic(device) _, err := printer. Size(tsplArgs.NewTSize().SetSize(60, 40)). Gap(tsplArgs.NewTGap().SetGap(3, 0)). Direction(tsplArgs.NewTDirection().SetDirection(0)). CLS(). Text(tsplArgs.NewTText(). SetPosition(50, 50). SetFont(tsplTypes.TSS24). SetContent("标签内容")). Bar(tsplArgs.NewTBar().SetBar(30, 90, 300, 2)). QRCode(tsplArgs.NewTQRCode(). SetPosition(320, 90). SetCellWidth(4). SetECCLevel("M"). SetContent("https://example.com")). Print(tsplArgs.NewTPrint().SetCopies(1)). Write() ``` -------------------------------- ### ESC Command Usage Source: https://iprtapp.com/en/psdk/programming/go Example of basic ESC command sequence for thermal printers. ```go printer := esc.Generic(device) _, err := printer. Wakeup(). Enable(). LineDot(16). StopJob(). Write() ``` -------------------------------- ### CPCL Command Usage Source: https://iprtapp.com/en/psdk/programming/go Example of constructing a CPCL print job including text, barcodes, and QR codes. ```go printer := cpcl.Generic(device) _, err := printer. Page(cpclArgs.NewCPage().SetSize(576, 400)). Bold(true). Text(cpclArgs.NewCText(). SetPosition(30, 40). SetFont(cpclTypes.TSS24). SetContent("商品标签")). Bold(false). Bar(cpclArgs.NewCBar(). SetPosition(30, 120). SetCodeType(cpclTypes.CODE128). SetLineWidth(2). SetHeight(60). SetContent("6901234567890")). QRCode(cpclArgs.NewCQRCode(). SetPosition(380, 80). SetWidth(5). SetCorrectLevel(cpclTypes.CorrectLevelM). SetContent("https://example.com")). Print(). Write() ``` -------------------------------- ### Complete Receipt Printing Sequence Source: https://iprtapp.com/en/psdk/command/escpos A comprehensive example demonstrating initialization, text formatting, barcode/QR code printing, and paper cutting. ```hex 1B 40 // 初始化打印机 // 打印标题 1B 61 01 // 居中 1D 21 11 // 倍宽倍高 [GBK: XX便利店] 0A // 打印副标题 1D 21 00 // 恢复正常大小 [GBK: 订单号: 20240115001] 0A [GBK: ================================] 0A // 打印商品列表 1B 61 00 // 左对齐 [GBK: 可乐 500ml x2 ¥6.00] 0A [GBK: 薯片 大包 x1 ¥8.50] 0A [GBK: 矿泉水 x3 ¥4.50] 0A [GBK: --------------------------------] 0A // 打印合计 1D 21 10 // 倍高 1B 45 01 // 加粗 [GBK: 合计: ¥19.00] 1B 45 00 // 取消加粗 1D 21 00 // 恢复正常 0A 0A // 打印二维码 1B 61 01 // 居中 1D 28 6B 03 00 31 43 05 // 二维码单元大小 1D 28 6B 03 00 31 45 31 // 纠错级别 M 1D 28 6B ... 31 50 30 [URL数据] // 存储数据 1D 28 6B 03 00 31 51 30 // 打印二维码 [GBK: 扫码关注店铺] 0A // 打印条码 1D 68 50 // 条码高度 1D 77 02 // 条码宽度 1D 48 02 // HRI 位置 1D 6B 49 ... [条码数据] // 打印条码 // 走纸并切纸 1B 64 03 // 走纸 3 行 1D 56 42 00 // 切纸 ``` -------------------------------- ### Implement Mock Device and CPCL Printing Source: https://iprtapp.com/en/psdk/programming/go Demonstrates a minimal mock device implementation and the usage of CPCL commands to print text and barcodes. ```go package main import ( "log" adapterTypes "github.com/prtmax/psdk-go/frame/device/adapter/types" "github.com/prtmax/psdk-go/fruits/cpcl" cpclArgs "github.com/prtmax/psdk-go/fruits/cpcl/args" cpclTypes "github.com/prtmax/psdk-go/fruits/cpcl/types" ) type Device struct{} func (d *Device) Write(data []byte) (adapterTypes.WriteReporter, error) { return adapterTypes.WriteReporter{ BytesWritten: len(data), Success: true, }, nil } func (d *Device) Read() ([]byte, error) { return nil, nil } func (d *Device) DeviceName() string { return "Printer" } func (d *Device) ConnectionState() string { return "CONNECTED" } func main() { printer := cpcl.Generic(&Device{}) reporter, err := printer. Page(cpclArgs.NewCPage().SetSize(576, 400)). Text(cpclArgs.NewCText(). SetPosition(50, 50). SetFont(cpclTypes.TSS24). SetContent("商品标签")). Bar(cpclArgs.NewCBar(). SetPosition(50, 150). SetCodeType(cpclTypes.CODE128). SetLineWidth(2). SetHeight(50). SetContent("1234567890")). Print(). Write() if err != nil { log.Fatal(err) } log.Printf("write ok: %v, bytes: %d", reporter.Success, reporter.BytesWritten) } ``` -------------------------------- ### Execute Full Printing Workflow Source: https://iprtapp.com/en/psdk/programming/objectivec Demonstrates the recommended sequence for printing tasks using ESC commands. ```Objective-C // 初始化 ESC 指令对象 AYEscCommand *esc = [AYEscCommand new]; // 唤醒指令 [esc wake]; // 使能打印机 [esc enable]; // 打印图片 [esc image:[UIImage imageNamed:@"label.png"] compress:NO mode:Normal]; // 标签打印定位(连续纸不需要定位!) [esc position]; // 结束打印任务 [esc stopPrintJob]; // 通过蓝牙发送指令 [self.bleHelper writeCommands:esc.commands]; ``` -------------------------------- ### Configure Bluetooth permissions in module.json5 Source: https://iprtapp.com/en/psdk/programming/openharmony Add the necessary Bluetooth and location permissions to enable device discovery and management. ```json { "module": { "requestPermissions": [ { "name": "ohos.permission.ACCESS_BLUETOOTH" }, { "name": "ohos.permission.DISCOVER_BLUETOOTH" }, { "name": "ohos.permission.MANAGE_BLUETOOTH" }, { "name": "ohos.permission.APPROXIMATELY_LOCATION" } ] } } ``` -------------------------------- ### Initialization and Basic Printing Source: https://iprtapp.com/en/psdk/command/escpos Commands for initializing the printer and performing basic print operations. ```APIDOC ## ESC @ (Initialize Printer) ### Description Initializes the printer, clears the print buffer, and restores default settings. ### Hexadecimal 1B 40 ## LF (Print and Line Feed) ### Description Prints the content in the buffer and feeds one line. ### Hexadecimal 0A ## CR (Print and Carriage Return) ### Description Prints the content in the buffer and performs a carriage return. ### Hexadecimal 0D ``` -------------------------------- ### Configure network permissions in module.json5 Source: https://iprtapp.com/en/psdk/programming/openharmony Add the internet permission to enable network-based printer connectivity. ```json { "module": { "requestPermissions": [ { "name": "ohos.permission.INTERNET" } ] } } ``` -------------------------------- ### 二维码打印指令格式 Source: https://iprtapp.com/en/psdk/command/cpcl 定义 QR Code 的打印结构,需配合 SETQRVER 和 ENDQR 使用。 ```text SETQRVER 纠错级别数值 旋转角度 QR X Y M 2 U 宽度 纠错级别A,内容 ENDQR ``` -------------------------------- ### 图形绘制指令 Source: https://iprtapp.com/en/psdk/programming/java 提供在标签上绘制矩形、线条、圆、椭圆及反色区域的方法。 ```java // 填充矩形 tspl.bar(TBar.builder() .x(50).y(100) .width(200).height(2) .build()); // 空心矩形 tspl.box(TBox.builder() .x(50).y(50) .xEnd(300).yEnd(200) .lineWidth(2) .build()); // 斜线 tspl.line(TLine.builder() .x(50).y(50) .xEnd(300).yEnd(200) .lineWidth(2) .build()); // 画圆 tspl.circle(TCircle.builder() .x(200).y(200) .diameter(100) .lineWidth(2) .build()); // 椭圆 tspl.ellipse(TEllipse.builder() .x(200).y(200) .width(150).height(80) .lineWidth(2) .build()); // 反色区域 tspl.reverse(TReverse.builder() .x(50).y(50) .width(200).height(100) .build()); ``` -------------------------------- ### 设置指令 Source: https://iprtapp.com/en/psdk/programming/java 用于配置打印机的高级功能,如自动关机、打印模式、切纸设置及自检。 ```java // 设置关机时间(分钟) tspl.setOffTime(30); // 获取关机时间 tspl.getOffTime(); // 设置热转印模式 tspl.ribbon(true); // 设置热敏模式 tspl.ribbon(false); // 使能切刀 tspl.cut(true); // 使能撕纸 tspl.tear(true); // 使能剥离 tspl.peel(true); // 学习纸张 tspl.detect(); // 打印自检页 tspl.selfTest(); ``` -------------------------------- ### Initialize Printer Lifecycle Source: https://iprtapp.com/en/psdk/programming/objectivec Initializes the printer lifecycle management within a view controller. ```Objective-C @interface PrinterVC () @property (nonatomic, strong) CBPeripheral *currentConnectedPeripheral; @property (nonatomic, strong) Lifecycle *lifeCycle; @end @implementation PrinterVC - (void)viewDidLoad { [super viewDidLoad]; // 初始化生命周期 _lifeCycle = [[Lifecycle alloc] init]; _lifeCycle.connectedDevice(self.device); } ``` -------------------------------- ### Initialize ESC Command Object Source: https://iprtapp.com/en/psdk/programming/objectivec Sets up the ESC command object for printer communication. ```Objective-C #import @property (nonatomic, strong) AYEscCommand *esc; - (void)setupESC { _esc = [AYEscCommand new]; } ``` -------------------------------- ### Add SDK dependencies to oh-package.json5 Source: https://iprtapp.com/en/psdk/programming/openharmony Include the required printer SDK packages in your project's dependency configuration. ```json { "dependencies": { "@psdk/frame-father": "^0.7.6", "@psdk/cpcl": "^0.7.6", "@psdk/tspl": "^0.7.6", "@psdk/esc": "^0.7.6", "@psdk/ohos-bluetooth-le": "^0.7.6", "@psdk/ohos-bluetooth-classic": "^0.7.6", "@psdk/ohos-network": "^0.7.6", "@psdk/ohos-usb": "^0.7.6" } } ``` -------------------------------- ### 查询指令 Source: https://iprtapp.com/en/psdk/programming/java 用于获取打印机当前状态、序列号、电量及固件版本信息。 ```java // 查询打印机状态 tspl.state().write(); // 查询 SN 号 tspl.sn().write(); // 查询电量 tspl.batteryVolume().write(); // 查询固件版本 tspl.version().write(); ``` -------------------------------- ### Run Tests for Command Layer Source: https://iprtapp.com/en/psdk/programming/go Command to run tests for the command layer while avoiding platform-specific build constraints. ```bash go test ./frame/father/... ./frame/toolkit/... ./fruits/... ``` -------------------------------- ### AYEscCommand Configuration Source: https://iprtapp.com/en/psdk/programming/objectivec Methods for configuring printer settings such as shutdown time, print density, and paper types. ```APIDOC ## [Method] shutTime: ### Description Sets the printer automatic shutdown time. ### Parameters - **time** (NSInteger) - Shutdown time in minutes (0 for no auto-shutdown) ## [Method] thickness: ### Description Sets the printing density. ### Parameters - **thickness** (EThickness) - Density level (EThicknessLow, EThicknessMedium, EThicknessHigh) ## [Method] paperType: ### Description Sets the paper type for A4 printers. ### Parameters - **paperType** (EPaperType) - Paper mode (BlackMark, Continuous, Gap, Hole, Tattoo, TattooWrinkles) ## [Method] paperTypeQX: ### Description Sets the paper type for Q1/Q2/Q3/D11/D30/B21/B22 series printers. ### Parameters - **paperTypeQX** (EPaperTypeQX) - Paper mode (Gap, BlackMark, Continuous) ``` -------------------------------- ### QR Code Printing Source: https://iprtapp.com/en/psdk/command/cpcl Prints a QR code using a sequence of commands. ```APIDOC ## QR Code Printing ### Description Prints a QR code using a multi-line command sequence. ### Syntax SETQRVER 纠错级别数值 旋转角度 QR X Y M 2 U 宽度 纠错级别A,内容 ENDQR ### Parameters - **纠错级别数值** (int) - Error correction level (L=1, M=2, Q=3, H=4) - **旋转角度** (int) - Rotation angle (0, 90, 180, 270) - **X** (int) - Starting X coordinate - **Y** (int) - Starting Y coordinate - **宽度** (int) - Cell width (2-20) - **纠错级别A** (string) - Error correction level (L, M, Q, H) - **内容** (string) - QR code data ### Example SETQRVER 2 0 QR 50 100 M 2 U 6 MA,https://example.com ENDQR ``` -------------------------------- ### 基本打印示例 Source: https://iprtapp.com/en/psdk/programming/java 展示了初始化打印机并打印包含简单文本的标签的基本流程。 ```java GenericTSPL tspl = TSPL.generic(connectedDevice); tspl.page(new TPage().width(60).height(40)) .gap(true) .direction(TDirection.builder() .direction(Direction.UP) .mirror(Mirror.NO_MIRROR) .build()) .cls() .text(TText.builder() .x(50).y(50) .font(Font.TSS24) .content("标签内容") .build()) .print(1) .write(); ``` -------------------------------- ### Enable Printer Source: https://iprtapp.com/en/psdk/programming/objectivec Enables the printer for operation. ```Objective-C [esc enable]; ``` -------------------------------- ### Configure BLE Chunked Writing Source: https://iprtapp.com/en/psdk/programming/openharmony Enable chunked writing to handle MTU limitations during BLE data transmission. ```typescript await psdk.write({ enableChunkWrite: true, chunkSize: 20 }); ``` -------------------------------- ### 打印二维码 (QRCODE) Source: https://iprtapp.com/en/psdk/command/tspl 用于打印 QR 码,支持设置纠错级别、单元宽度及旋转角度。 ```TSPL QRCODE X,Y,纠错级别,单元宽度,模式,旋转,M2,S7,"内容" ``` ```TSPL QRCODE 300,50,H,4,A,0,M2,S7,"https://example.com" QRCODE 50,50,M,6,A,0,"产品编号:12345" ``` -------------------------------- ### 文字加粗指令示例 Source: https://iprtapp.com/en/psdk/command/cpcl 开启和关闭文字加粗效果。 ```text SETBOLD 1 TEXT 24 0 50 50 "加粗文字" SETBOLD 0 ``` -------------------------------- ### 设置 QR Code 纠错级别 Source: https://iprtapp.com/en/psdk/command/escpos 设置 QR Code 的纠错级别。 ```hex GS ( k pL pH cn fn n 十六进制: 1D 28 6B 03 00 31 45 n ``` -------------------------------- ### 二维码打印示例 Source: https://iprtapp.com/en/psdk/command/cpcl 展示一个纠错级别为 M 的 QR 二维码打印指令。 ```text SETQRVER 2 0 QR 50 100 M 2 U 6 MA,https://example.com ENDQR ``` -------------------------------- ### 完整标签打印示例 Source: https://iprtapp.com/en/psdk/programming/java 展示了包含标题、分隔线、商品信息、一维条码、二维码及边框的复杂标签布局。 ```java GenericTSPL tspl = TSPL.generic(connectedDevice); tspl.page(new TPage().width(60).height(40)) .gap(true) .direction(TDirection.builder() .direction(Direction.UP) .mirror(Mirror.NO_MIRROR) .build()) .density(8) .speed(4) .cls() // 标题 .text(TText.builder() .x(180).y(30) .font(Font.TSS24) .xmulti(2).ymulti(2) .content("商品标签") .build()) // 分隔线 .bar(TBar.builder() .x(30).y(80) .width(420).height(2) .build()) // 商品信息 .text(TText.builder() .x(30).y(100) .font(Font.TSS24) .content("品名: 有机苹果") .build()) .text(TText.builder() .x(30).y(140) .font(Font.TSS24) .content("规格: 500g/袋") .build()) .text(TText.builder() .x(30).y(180) .font(Font.TSS24) .isBold(true) .content("价格: ¥25.90") .build()) // 一维条码 .barcode(TBarCode.builder() .x(80).y(220) .codeType(CodeType.CODE_128) .height(60) .showType(ShowType.BELOW) .content("6901234567890") .build()) // 二维码 .qrcode(TQRCode.builder() .x(380).y(90) .cellWidth(4) .correctLevel(CorrectLevel.M) .content("https://example.com") .build()) // 边框 .box(TBox.builder() .x(20).y(20) .xEnd(460).yEnd(310) .lineWidth(2) .build()) .print(1) .write(); ``` -------------------------------- ### 文本框打印指令 Source: https://iprtapp.com/en/psdk/command/tspl 用于打印指定区域内的文本段落,支持自动换行。 ```TSPL BLOCK X,Y,宽度,高度,"字体",旋转,X放大,Y放大,"内容" ``` -------------------------------- ### Basic CPCL Label Printing Source: https://iprtapp.com/en/psdk/programming/javascript Demonstrates initializing a CPCL printer and printing a simple page with text and a barcode. ```javascript import { CPCL } from '@psdk/cpcl'; import { Lifecycle } from '@psdk/frame-father'; const lifecycle = new Lifecycle(connectedDevice); const cpcl = CPCL.generic(lifecycle); const reporter = await cpcl .page({ width: 576, height: 400 }) .text({ x: 50, y: 50, content: '商品标签' }) .barcode({ x: 50, y: 150, content: '1234567890' }) .print() .write({ chunkSize: 512 }); console.log('打印结果:', reporter); ``` -------------------------------- ### 打印 DataMatrix 二维码 (DMATRIX) Source: https://iprtapp.com/en/psdk/command/tspl 用于打印 DataMatrix 格式的二维码。 ```TSPL DMATRIX X,Y,宽度,高度,模式,"内容" ``` ```TSPL DMATRIX 50,50,400,400,x8,"DataMatrix Content" ``` -------------------------------- ### 存储 QR Code 数据 Source: https://iprtapp.com/en/psdk/command/escpos 将 QR Code 内容存储到打印机缓冲区。 ```hex GS ( k pL pH cn fn m [数据] 十六进制: 1D 28 6B pL pH 31 50 30 [数据] ``` -------------------------------- ### Implement Custom Device Interface Source: https://iprtapp.com/en/psdk/programming/rust Implement the ConnectedDevice trait to connect the SDK to specific hardware transports like Bluetooth, USB, or Serial. ```rust use psdk_father::{ device::{ConnectedDevice, ConnectionState, DeviceWriteOptions, ReadOptions}, errors::PsdkFatherResult, }; struct MyDevice; impl ConnectedDevice for MyDevice { fn device_name(&self) -> String { "Printer".to_string() } fn connection_state(&self) -> ConnectionState { ConnectionState::Connected } fn disconnect(&self) -> PsdkFatherResult<()> { Ok(()) } fn can_read(&self) -> bool { true } fn write(&self, binary: &[u8]) -> PsdkFatherResult<()> { // Send bytes to printer transport. Ok(()) } fn write_with_options( &self, binary: &[u8], options: DeviceWriteOptions, ) -> PsdkFatherResult<()> { self.write(binary) } fn read(&self, _options: Option) -> PsdkFatherResult> { Ok(Vec::new()) } fn flush(&self) -> PsdkFatherResult<()> { Ok(()) } } ``` -------------------------------- ### Handle SDK Write Errors Source: https://iprtapp.com/en/psdk/programming/openharmony Implement try-catch blocks to manage write operations and display user feedback via toast notifications. ```typescript try { await psdk.write(); console.log('Print success'); } catch (error) { console.error('Print error:', error.message); promptAction.showToast({ message: `Print failed: ${error.message}`, duration: 2000 }); } ``` -------------------------------- ### 文字下划线指令示例 Source: https://iprtapp.com/en/psdk/command/cpcl 开启和关闭文字下划线效果。 ```text UNDERLINE ON TEXT 24 0 50 50 "带下划线的文字" UNDERLINE OFF ``` -------------------------------- ### 旋转条码打印指令 Source: https://iprtapp.com/en/psdk/command/cpcl 通过不同指令实现条码的 0°、90°、180° 和 270° 旋转打印。 ```text VBARCODE 类型 窄条宽度 宽窄比 高度 X Y "内容" BARCODE90 类型 窄条宽度 宽窄比 高度 X Y "内容" BARCODE180 类型 窄条宽度 宽窄比 高度 X Y "内容" BARCODE270 类型 窄条宽度 宽窄比 高度 X Y "内容" ``` -------------------------------- ### AYEscCommand Query Operations Source: https://iprtapp.com/en/psdk/programming/objectivec Methods to query printer status and device information. Results are returned via the escQueryChange callback. ```APIDOC ## [Method] printerInfo / state / batteryVol / btName / printerVersion / mac / sn / printerModel ### Description Queries various printer attributes including status, battery level, Bluetooth name, firmware version, MAC address, serial number, and model. ``` -------------------------------- ### 打印 QR Code Source: https://iprtapp.com/en/psdk/command/escpos 执行打印存储在缓冲区中的 QR Code。 ```hex GS ( k pL pH cn fn m 十六进制: 1D 28 6B 03 00 31 51 30 ``` ```hex 1D 28 6B 03 00 31 43 06 // 设置单元大小为 6 1D 28 6B 03 00 31 45 31 // 设置纠错级别为 M 1D 28 6B 13 00 31 50 30 68 74 74 70 73 3A 2F 2F 65 78 61 6D 70 6C 65 2E 63 6F 6D // 存储数据 "https://example.com" 1D 28 6B 03 00 31 51 30 // 打印二维码 ``` -------------------------------- ### 页面设置指令 Source: https://iprtapp.com/en/psdk/programming/java 用于配置打印机参数,如纸张类型、打印方向、浓度、速度及缓冲区清理。 ```java // 设置页面尺寸(单位:mm) tspl.page(new TPage().width(60).height(40)); // 设置缝隙纸 tspl.gap(true); // 设置黑标纸 tspl.bline(); // 设置连续纸 tspl.continuous(); // 设置打印方向 tspl.direction(TDirection.builder() .direction(Direction.UP) // UP/DOWN .mirror(Mirror.NO_MIRROR) // NO_MIRROR/MIRROR .build()); // 设置浓度(0-15) tspl.density(8); // 设置速度(1-6) tspl.speed(4); // 清除缓冲区 tspl.cls(); ``` -------------------------------- ### Create a Product Label with TSPL Source: https://iprtapp.com/en/psdk/command/tspl Defines a 60x40mm label layout containing product details, a barcode, and a QR code. ```TSPL SIZE 60 mm,40 mm GAP 3 mm,0 DIRECTION 1,0 DENSITY 8 SPEED 4 CLS TEXT 180,30,"TSS24.BF2",0,2,2,"商品标签" BAR 30,80,420,2 TEXT 30,100,"TSS24.BF2",0,1,1,"品名: 有机苹果" TEXT 30,140,"TSS24.BF2",0,1,1,"规格: 500g/袋" TEXT 30,180,"TSS24.BF2",0,1,1,"产地: 山东烟台" TEXT 30,220,"TSS24.BF2",0,1,1,B1,"价格: ¥25.90" BARCODE 80,270,"128",60,1,0,2,4,"6901234567890" QRCODE 380,100,M,4,A,0,"https://example.com/product" PRINT 1 ``` -------------------------------- ### Print Image Source: https://iprtapp.com/en/psdk/programming/objectivec Prints an image with specified compression and mode settings. ```Objective-C typedef NS_ENUM(NSInteger, EImageMode) { Normal = 0, // 正常打印 DoubleWidth, // 倍宽打印 DoubleHeight, // 倍高打印 DoubleAll // 倍宽倍高打印 }; /** * 打印图片 * @param image 图片 * @param compress 是否压缩 * @param mode 打印模式 */ [esc image:image compress:NO mode:Normal]; ``` -------------------------------- ### Text Formatting Source: https://iprtapp.com/en/psdk/command/escpos Commands for adjusting text appearance and alignment. ```APIDOC ## GS ! n (Set Character Size) ### Description Sets the width and height magnification for characters. ### Parameters - **n** (byte) - Required - Bit 0-2: Width (1-8x), Bit 4-6: Height (1-8x). ### Hexadecimal 1D 21 n ## ESC a n (Set Alignment) ### Description Sets the text alignment. ### Parameters - **n** (0-2) - Required - 0: Left, 1: Center, 2: Right. ### Hexadecimal 1B 61 n ## ESC E n (Set Bold) ### Description Enables or disables bold mode. ### Parameters - **n** (0-1) - Required - 0: Disable, 1: Enable. ### Hexadecimal 1B 45 n ## ESC - n (Set Underline) ### Description Sets underline mode. ### Parameters - **n** (0-2) - Required - 0: Off, 1: 1-dot, 2: 2-dot. ### Hexadecimal 1B 2D n ## GS B n (Set Inverse Printing) ### Description Sets black/white reverse printing mode. ### Parameters - **n** (0-1) - Required - 0: Off, 1: On. ### Hexadecimal 1D 42 n ``` -------------------------------- ### 打印并换行 (LF) Source: https://iprtapp.com/en/psdk/command/escpos 打印当前缓冲区内容并执行换行操作。 ```text LF 十六进制: 0A ``` -------------------------------- ### 文本框打印示例 Source: https://iprtapp.com/en/psdk/command/tspl 在 400x200 的区域内打印一段会自动换行的文本。 ```TSPL BLOCK 50,50,400,200,"TSS24.BF2",0,1,1,"这是一段很长的文本,会自动换行显示在文本框内。" ``` -------------------------------- ### QR Code Printing Sequence Source: https://iprtapp.com/en/psdk/command/escpos The sequence of commands required to print a QR code, including unit size, error correction, data storage, and print execution. ```APIDOC ## QR Code Printing Sequence ### Description QR Code printing requires sending multiple commands in a specific order. ### Steps 1. **Set Unit Size (GS ( k)**: 1D 28 6B 03 00 31 43 n (n: 1-16) 2. **Set Error Correction (GS ( k)**: 1D 28 6B 03 00 31 45 n (n: 48-51) 3. **Store Data (GS ( k)**: 1D 28 6B pL pH 31 50 30 [Data] 4. **Print (GS ( k)**: 1D 28 6B 03 00 31 51 30 ``` -------------------------------- ### Receipt Structure Visualization Source: https://iprtapp.com/en/psdk/command/escpos Visual representation of the expected output layout for the receipt printing sequence. ```text ┌─────────────────────────────┐ │ XX便利店 │ ← 居中、倍宽倍高 │ 订单号: 20240115001 │ ← 居中、正常大小 │ ════════════════════════════│ │ 可乐 500ml x2 ¥6.00 │ ← 左对齐 │ 薯片 大包 x1 ¥8.50 │ │ 矿泉水 x3 ¥4.50 │ │ ────────────────────────────│ │ 合计: ¥19.00 │ ← 倍高、加粗 │ │ │ [二维码] │ ← 居中 │ 扫码关注店铺 │ │ │ │ ||||||||||||||| │ ← 条码 │ 6901234567890 │ └─────────────────────────────┘ ``` -------------------------------- ### TEXT (文本打印) Source: https://iprtapp.com/en/psdk/command/tspl 用于在指定坐标打印文本内容,支持字体选择、旋转、缩放及对齐方式。 ```APIDOC ## TEXT ### Description 打印文本内容到指定位置。 ### Syntax TEXT X,Y,"字体",旋转,X放大,Y放大,"内容" TEXT X,Y,"字体",旋转,X放大,Y放大,对齐,"内容" ### Parameters - **X** (int) - 文本起始 X 坐标(dot) - **Y** (int) - 文本起始 Y 坐标(dot) - **字体** (string) - 字体名称 - **旋转** (int) - 旋转角度(0/90/180/270) - **X放大** (int) - 水平放大倍数(1-8) - **Y放大** (int) - 垂直放大倍数(1-8) - **对齐** (int) - 可选,对齐方式(0=默认/左对齐, 1=左对齐, 2=居中, 3=右对齐) - **内容** (string) - 要打印的文本 ### Example TEXT 50,50,"TSS24.BF2",0,1,1,"产品名称" ``` -------------------------------- ### 加粗文本指令 Source: https://iprtapp.com/en/psdk/command/tspl 在字体参数后添加 B1 标记以实现文本加粗效果。 ```TSPL TEXT X,Y,"字体",旋转,X放大,Y放大,B1,"内容" ``` -------------------------------- ### Font and Spacing Source: https://iprtapp.com/en/psdk/command/escpos Commands for selecting fonts and adjusting line spacing. ```APIDOC ## ESC M n (Set Font) ### Description Selects the font type. ### Parameters - **n** (0-1) - Required - 0: Font A (12x24), 1: Font B (9x17). ### Hexadecimal 1B 4D n ## ESC 3 n (Set Line Spacing) ### Description Sets the line spacing. ### Parameters - **n** (byte) - Required - Line spacing in dots. ### Hexadecimal 1B 33 n ## ESC 2 (Restore Default Line Spacing) ### Description Restores the default line spacing. ### Hexadecimal 1B 32 ``` -------------------------------- ### BLOCK (文本框打印) Source: https://iprtapp.com/en/psdk/command/tspl 打印文本段落,支持在指定区域内自动换行。 ```APIDOC ## BLOCK ### Description 打印文本段落,支持自动换行。 ### Syntax BLOCK X,Y,宽度,高度,"字体",旋转,X放大,Y放大,"内容" ### Parameters - **X** (int) - 起始 X 坐标 - **Y** (int) - 起始 Y 坐标 - **宽度** (int) - 文本框宽度 - **高度** (int) - 文本框高度 - **字体** (string) - 字体名称 - **旋转** (int) - 旋转角度 - **X放大** (int) - 水平放大倍数 - **Y放大** (int) - 垂直放大倍数 - **内容** (string) - 要打印的文本 ### Example BLOCK 50,50,400,200,"TSS24.BF2",0,1,1,"这是一段很长的文本,会自动换行显示在文本框内。" ``` -------------------------------- ### 文本打印指令示例 Source: https://iprtapp.com/en/psdk/command/cpcl 使用不同字体编号打印文本内容。 ```text TEXT 24 0 50 50 "产品名称" TEXT 7 0 50 100 "规格型号" T 4 0 50 150 "大号文字" ``` -------------------------------- ### Print Raster Bitmap (GS v 0) Source: https://iprtapp.com/en/psdk/command/escpos Prints a raster bitmap image. ```APIDOC ## GS v 0 m xL xH yL yH [Data] ### Description Prints a raster bitmap image. ### Parameters - **m** (int) - Required - Print mode (0=normal, 1=double-width, 2=double-height, 3=double-width/height). - **xL xH** (int) - Required - Horizontal bytes (width/8). - **yL yH** (int) - Required - Vertical dots (height). - **Data** (bytes) - Required - Bitmap data. ``` -------------------------------- ### Full Paper Cut Command Source: https://iprtapp.com/en/psdk/command/escpos Executes a full paper cut operation. ```hex GS V m 十六进制: 1D 56 m ``` -------------------------------- ### 设置行间距 (ESC 3) Source: https://iprtapp.com/en/psdk/command/escpos 设置行间距点数。 ```text ESC 3 n 十六进制: 1B 33 n ```