Skip to content
启枢科技文档

启枢档案馆

这里是后续撰写产品文档的入口页。左侧负责文档分类与章节层级,右侧保留正式文档正文、提示块、代码、表格与上一页 / 下一页的位置。

sdk / typescript

TypeScript SDK

面向 Web、小程序、Node 和桥接运行时的 NIB 打印机 SDK 接入说明。

TypeScript SDK 适合 Web、小程序、UniApp、Taro、Node 工具和原生桥接运行时。初学时可以先记住一件事:模板代码只生成打印指令,平台代码只负责把字节写进打印机。

用途
@boxliy/nib 标准聚合包,导出 core、Boxliy/Aryten/Lin8inch 方言和图片能力。
@nib/core ConnectedDevicewriteTo()WriteOptions、接收源和查询分发。
@nib/esc-boxliy@nib/tspl-boxliy@nib/cpcl-boxliy Boxliy ESC、TSPL、CPCL 指令构建器和响应解析器。
@nib/esc@nib/tspl@nib/cpcl Aryten 兼容方言。
@nib/esc-lin8inch@nib/tspl-lin8inch Lin8inch 方言。
@nib/bluetooth-ble-core BLE 特征值选择、UUID 匹配和 credit 流控。
@nib/wechat-bluetooth-ble@nib/uniapp-bluetooth-ble@nib/taro-bluetooth-ble 微信、UniApp、Taro 的 BLE 适配。
@nib/webusb 浏览器 WebUSB 连接。

如果不确定从哪里开始,业务项目通常先用 @boxliy/nib;只有在需要拆包或裁剪能力时,再直接依赖底层模块。

所有平台适配器最后都要提供 core 的 ConnectedDevice

interface ConnectedDevice {
origin(): any
deviceName(): string
connectionState(): ConnectionState
disconnect(): Promise<void>
canRead(): boolean
write(data: Uint8Array): Promise<void>
read(options?: ReadOptions): Promise<Uint8Array>
notify(callback: (value: Uint8Array) => Promise<void>): void
flush(): void
}

微信、小程序框架、WebUSB 或原生 App 的 API 可以完全不同,但只要包装成这个接口,同一套打印模板就可以复用。

推荐从 TSPL 标签示例开始,因为它清楚表达纸张尺寸、清空画布、放置文字和打印份数:

import { TsplAryten } from '@boxliy/nib'
await TsplAryten.create()
.size(40, 30)
.cls()
.text({ x: 20, y: 20, content: 'NIB SDK' })
.print()
.writeTo(device)

writeTo(device) 会把构建器里的字节写入设备,然后清空当前构建器。也可以先拿到字节,再手动写入:

import { WriteOptions, writeTo } from '@boxliy/nib'
const data = TsplAryten.create()
.size(40, 30)
.cls()
.text({ x: 20, y: 20, content: 'NIB SDK' })
.print()
.bytes()
await writeTo(device, data, new WriteOptions(true, 512))

writeTo() 默认启用分片写入,默认分片大小是 512 字节。只有设备或平台 API 已经处理好分片时,才考虑关闭分片。

不要把不同语言或不同方言的示例混用。当前 TypeScript 的 EscBoxliy 适合 ESC 命令、查询、图片等能力,但不是 Java/Swift 那种 text('...') 示例形态。普通文本内容可以选择 TSPL/CPCL 的 text(...) API,或按具体 ESC 方言支持的方法生成原始字节。

import { EscBoxliy } from '@boxliy/nib'
const script = EscBoxliy.create()
.reset()
.feed(2)
.bytes()
await writeTo(device, script)

@nib/bluetooth-ble-core 提供两类 credit 策略:

API 用途
BleLaneCreditFlowControlStrategy 默认的 lane-credit 策略,按 credit 和 MTU 分片写入。
BleSignalCreditFlowControlStrategy signal-credit 策略,适合 credit 通知语义不同的设备。
BleCreditOptions 配置服务 UUID、写入/读取/credit 特征值、初始 credit、MTU 和 fallback。
selectBleCreditCharacteristicPair() 按 UUID 从服务列表中找到 write、read、credit 特征值。

默认 UUID 是:

默认值
service FF00
write characteristic FF02
read characteristic FF01
credit characteristic FF03

默认 lane-credit 初始 credit 是 1,初始 MTU 是 20,payload overhead 是 3。signal-credit 默认初始 credit 是 0,payload overhead 是 0。如果启用 fallbackMode: 'bypass-write',credit 超时时可以退回普通写入;默认行为是失败。

core 里常用的接收和查询类型是 ReceiveSourcePollingReceiveSourceCallbackReceiveSourceNotifyReceiveSourcereceiveSourceOf()QueryDispatcherPendingQuery

Boxliy 方言提供响应解析器:

方言 解析器
ESC EscResponseParser
TSPL TsplResponseParser
CPCL CpclResponseParser

查询状态时,先用方言构建器生成查询指令并写入设备,再把设备回包交给对应 parser。解析逻辑建议放在打印会话层,不要散落在 UI 组件里。

方法与命令清单

下面列出这个语言 SDK 中常用且对接方需要理解的公开入口。构建器方法会生成对应打印机指令;是否能在某台机器上使用,仍以机器固件支持的 ESC、TSPL、CPCL 或 Lin8inch 指令组为准。

Core、连接与写入

对象方法 / 命令作用参数说明
ConnectedDeviceorigin(), deviceName(), connectionState(), disconnect(), canRead(), write(data), read(options), notify(callback), flush()抽象真实打印机连接,供模板、写入管线和查询层统一使用。`write/read/notify` 由平台适配器实现;`flush` 清理平台写入队列或缓存。
writeTo / WriteOptionswriteTo(device, data, options), new WriteOptions(enableChunkWrite, chunkSize)把已经构建好的字节按分片、超时、取消和流控规则写入设备。`enableChunkWrite` 控制是否分片;`chunkSize` 默认 512;`data` 可来自 builder.bytes()。
Pen / ReceiveSource / QueryDispatcherappend(), appendByte(), appendBytes(), appendText(), bytes(), reset(), start(), stop(), accept(), receive(), query(), cancel(), shutdown()把设备回包接入监听器或查询分发器,用于状态、电量、型号等查询。`append*` 追加字节或文本;查询的 matcher 负责把回包映射成业务结果。
BLE adaptersBleCreditOptions, BleLaneCreditFlowControlStrategy, BleSignalCreditFlowControlStrategy, selectBleCreditCharacteristicPair(), isBleUuidMatch()处理 BLE 特征值选择、MTU 分片、credit 通知和 fallback 写入。配置 UUID、initialCredit、initialMtu、payloadMtu、fallbackMode;平台包负责微信、Taro、UniApp、WebUSB 连接。

指令构建器

对象方法 / 命令作用参数说明
EscBoxliy / EscArytenbytes(), reset(), lineDot(), backLineDot(), batteryVolume(), enable(), getShutdownTime(), learnLabelGap(), line(), location(), mac(), info(), model(), name(), paperType(), position(), printerVersion(), setShutdownTime(), sn(), state(), stopJob(), thickness(), version(), wakeup(), setBTType(), cut(), lineDotCut(), nn(), setCurrentTime(), image()生成 ESC/Boxliy 基础指令,适合小票、便携打印机和支持 ESC 的机型。多数方法无参或使用 number;`setCurrentTime` 传年月日时分秒;`image` 传 x/y/bitmap/byteWidth/height/compress。
TsplBoxliy / TsplArytenbytes(), reset(), size(), gap(), bline(), continuous(), label(), cls(), direction(), speed(), density(), reference(), offset(), shift(), ribbon(), tear(), peel(), cut(), print(), bar(), line(), box(), circle(), ellipse(), text(), textBox(), barcode(), qrcode(), dmatrix(), image(), downloadBmp(), putImage()生成 TSPL 标签指令,适合需要纸张尺寸、坐标、条码和二维码的标签模板。TSPL 方法多使用 options 对象;坐标和尺寸是点或毫米,取决于对应 TSPL 命令;文字/条码/二维码传 content/value、font、rotation、level。
CpclBoxliy / CpclArytenbytes(), reset(), page(), feed(), form(), print(), gapSense(), pageWidth(), text(), setMag(), bold(), underline(), watermark(), line(), box(), inverse(), barcode(), qrcode(), image(), status(), sn()生成 CPCL 标签指令,适合 CPCL 机型的页面、文字、线条、条码和图片。CPCL 方法多使用 options 对象;`page` 传 height/copies/pageWidth;图元传坐标、宽高和线宽;图片传 bitmap 或 prepared bitmap。
EscLin8inchbatteryLevel(), extendedModel(), bootVersion(), advancedDensity(), advancedDensityStatus(), mediaProfile(), mediaProfileStatus(), grayMode(), grayscaleImage(), wirelessProvisioning(), wirelessProvisioningStatus(), compressedRasterTransport(), mediaTag(), mediaTagUid(), consumedMediaLength(), remainingMediaLength(), restoreLabelStartPosition(), alternateMotionProfile()在 ESC 基础上增加 Lin8inch 遥测、介质、配网和光栅传输相关命令。`grayscaleImage` 传图片参数;`wirelessProvisioning` 传 ssid/password/mode;其余多为查询或开关命令。
TsplLin8inchautomaticStatusFeedback(), printCompletion(), printerStatus(), firmwareVersion(), serialNumber(), macAddress(), deviceSpeed(), deviceSelfTest(), thermalStatus(), productId(), versionInfo(), selfTestPage(), redDensity(), blackColor(), ribbonEnd(), ribbonEndStatus(), modelSetting(), serialSetting(), versionSetting(), gbkCodepage(), utf8Codepage(), gapDetection()在 TSPL 基础上增加 Lin8inch 状态反馈、介质、色带和出纸配置命令。`printCompletion` 传 token;`redDensity/deviceSpeed` 传数字;`printerStatus` 传状态 flag。

回包解析

对象方法 / 命令作用参数说明
EscResponse / TsplResponse / CpclResponsegetQuery(), getType(), getRaw(), getRawHex(), getStatusByte(), getStatusFlags(), hasStatusFlag(), isReady(), getBatteryLevel(), getText(), getMacAddress(), getEventValue(), getDescription()把打印机回包解析成状态、电量、文本、MAC、事件或未知响应。ESC 有事件值;TSPL/CPCL 主要返回状态、电量、文本、MAC 和描述。
  • 先确认打印机支持 ESC、TSPL 还是 CPCL,再选构建器。
  • 平台蓝牙、USB、桥接 API 都放在 adapter 层,模板层只生成字节。
  • 每个模板都保留字节快照测试,避免改 UI 时改坏指令。
  • BLE 设备要在真机上验证 MTU、分片大小、credit 通知和断线重连。