Qishu Archives
제품 문서, 인터페이스 자료, 엔지니어링 기록을 위한 공통 입구입니다.
TypeScript SDK
Web, 미니프로그램, Node, 브리지 런타임을 위한 NIB 프린터 SDK 연동 설명입니다.
TypeScript SDK는 Web, 미니프로그램, UniApp, Taro, Node 도구, 네이티브 브리지 런타임에 적합합니다. 처음에는 한 가지만 기억하면 됩니다. 템플릿 코드는 인쇄 명령어만 생성하고, 플랫폼 코드는 바이트를 프린터에 쓰는 일만 담당합니다.
패키지 선택
섹션 제목: “패키지 선택”| 패키지 | 용도 |
|---|---|
@boxliy/nib |
표준 통합 패키지입니다. core, Boxliy/Aryten/Lin8inch dialect와 이미지 기능을 내보냅니다. |
@nib/core |
ConnectedDevice, writeTo(), WriteOptions, 수신 소스, 질의 분배를 제공합니다. |
@nib/esc-boxliy, @nib/tspl-boxliy, @nib/cpcl-boxliy |
Boxliy ESC, TSPL, CPCL 명령어 빌더와 응답 parser입니다. |
@nib/esc, @nib/tspl, @nib/cpcl |
Aryten 호환 dialect입니다. |
@nib/esc-lin8inch, @nib/tspl-lin8inch |
Lin8inch dialect입니다. |
@nib/bluetooth-ble-core |
BLE characteristic 선택, UUID 매칭, credit 흐름 제어입니다. |
@nib/wechat-bluetooth-ble, @nib/uniapp-bluetooth-ble, @nib/taro-bluetooth-ble |
WeChat, UniApp, Taro용 BLE adapter입니다. |
@nib/webusb |
브라우저 WebUSB 연결입니다. |
어디서 시작할지 확실하지 않다면 비즈니스 프로젝트는 보통 @boxliy/nib부터 사용합니다. 패키지를 분리하거나 기능을 줄여야 할 때만 하위 모듈을 직접 의존하세요.
ConnectedDevice 계약
섹션 제목: “ConnectedDevice 계약”모든 플랫폼 adapter는 최종적으로 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}WeChat, 미니프로그램 프레임워크, 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가 이미 분할을 처리하고 있을 때만 분할 끄기를 검토하세요.
ESC 텍스트 주의점
섹션 제목: “ESC 텍스트 주의점”다른 언어나 다른 dialect 예제를 섞어 쓰지 마세요. 현재 TypeScript의 EscBoxliy는 ESC 명령, 질의, 이미지 등의 기능에 적합하지만 Java/Swift의 text('...') 예제 형태와는 다릅니다. 일반 텍스트 콘텐츠는 TSPL/CPCL의 text(...) API를 선택하거나, 구체적인 ESC dialect가 지원하는 메서드로 원시 바이트를 생성하세요.
import { EscBoxliy } from '@boxliy/nib'
const script = EscBoxliy.create() .reset() .feed(2) .bytes()
await writeTo(device, script)BLE credit 흐름 제어
섹션 제목: “BLE credit 흐름 제어”@nib/bluetooth-ble-core는 두 가지 credit 전략을 제공합니다.
| API | 용도 |
|---|---|
BleLaneCreditFlowControlStrategy |
기본 lane-credit 전략입니다. credit과 MTU에 따라 분할해 씁니다. |
BleSignalCreditFlowControlStrategy |
signal-credit 전략입니다. credit 알림 의미가 다른 디바이스에 적합합니다. |
BleCreditOptions |
서비스 UUID, 쓰기/읽기/credit characteristic, 초기 credit, MTU, fallback을 구성합니다. |
selectBleCreditCharacteristicPair() |
UUID로 서비스 목록에서 write, read, credit characteristic을 찾습니다. |
기본 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에서 자주 쓰는 수신 및 질의 타입은 ReceiveSource, PollingReceiveSource, CallbackReceiveSource, NotifyReceiveSource, receiveSourceOf(), QueryDispatcher, PendingQuery입니다.
Boxliy dialect는 응답 parser를 제공합니다.
| dialect | parser |
|---|---|
| ESC | EscResponseParser |
| TSPL | TsplResponseParser |
| CPCL | CpclResponseParser |
상태를 질의할 때는 먼저 dialect builder로 질의 명령어를 생성해 디바이스에 쓰고, 디바이스 응답을 해당 parser에 전달합니다. 파싱 로직은 UI 컴포넌트에 흩어 두지 말고 인쇄 세션 계층에 두는 것을 권장합니다.
Methods and Commands
The tables below list the public entry points integration teams usually need. Builder methods generate printer commands; actual availability still depends on the ESC, TSPL, CPCL, or Lin8inch command family supported by the target firmware.
Core, Connection, and Writing
| Object | Method / Command | Purpose | Parameters |
|---|---|---|---|
ConnectedDevice | origin(), deviceName(), connectionState(), disconnect(), canRead(), write(data), read(options), notify(callback), flush() | Abstracts the real printer connection for templates, write pipelines, and query handling. | `write/read/notify` are implemented by platform adapters; `flush` clears adapter queues or buffers. |
writeTo / WriteOptions | writeTo(device, data, options), new WriteOptions(enableChunkWrite, chunkSize) | Writes built bytes to a device with chunking, timeout, cancellation, and flow-control rules. | `enableChunkWrite` toggles chunking; `chunkSize` defaults to 512; `data` can come from builder.bytes(). |
Pen / ReceiveSource / QueryDispatcher | append(), appendByte(), appendBytes(), appendText(), bytes(), reset(), start(), stop(), accept(), receive(), query(), cancel(), shutdown() | Routes device responses into listeners or query dispatchers for status, battery, model, and similar queries. | `append*` appends bytes or text; query matchers map responses to business results. |
BLE adapters | BleCreditOptions, BleLaneCreditFlowControlStrategy, BleSignalCreditFlowControlStrategy, selectBleCreditCharacteristicPair(), isBleUuidMatch() | Handles BLE characteristic selection, MTU chunking, credit notifications, and fallback writes. | Configure UUIDs, initialCredit, initialMtu, payloadMtu, and fallbackMode; platform packages handle WeChat, Taro, UniApp, and WebUSB connections. |
Command Builders
| Object | Method / Command | Purpose | Parameters |
|---|---|---|---|
EscBoxliy / EscAryten | bytes(), 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() | Builds ESC/Boxliy commands for receipt, portable, and ESC-compatible printers. | Most methods take no arguments or numbers; `setCurrentTime` takes date/time fields; `image` takes x/y/bitmap/byteWidth/height/compress. |
TsplBoxliy / TsplAryten | bytes(), 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() | Builds TSPL label commands for templates with paper size, coordinates, barcodes, and QR codes. | TSPL methods mostly use options objects; coordinates and sizes are dots or millimeters according to the TSPL command; text/barcode/QR use content/value, font, rotation, and level. |
CpclBoxliy / CpclAryten | bytes(), reset(), page(), feed(), form(), print(), gapSense(), pageWidth(), text(), setMag(), bold(), underline(), watermark(), line(), box(), inverse(), barcode(), qrcode(), image(), status(), sn() | Builds CPCL label commands for page setup, text, lines, barcodes, and images. | CPCL methods mostly use options objects; `page` takes height/copies/pageWidth; primitives use coordinates, sizes, and line width; images use bitmap or prepared bitmap. |
EscLin8inch | batteryLevel(), extendedModel(), bootVersion(), advancedDensity(), advancedDensityStatus(), mediaProfile(), mediaProfileStatus(), grayMode(), grayscaleImage(), wirelessProvisioning(), wirelessProvisioningStatus(), compressedRasterTransport(), mediaTag(), mediaTagUid(), consumedMediaLength(), remainingMediaLength(), restoreLabelStartPosition(), alternateMotionProfile() | Adds Lin8inch telemetry, media, provisioning, and raster transport commands on top of ESC. | `grayscaleImage` takes image options; `wirelessProvisioning` takes ssid/password/mode; most others are query or switch commands. |
TsplLin8inch | automaticStatusFeedback(), printCompletion(), printerStatus(), firmwareVersion(), serialNumber(), macAddress(), deviceSpeed(), deviceSelfTest(), thermalStatus(), productId(), versionInfo(), selfTestPage(), redDensity(), blackColor(), ribbonEnd(), ribbonEndStatus(), modelSetting(), serialSetting(), versionSetting(), gbkCodepage(), utf8Codepage(), gapDetection() | Adds Lin8inch status feedback, media, ribbon, and presentation commands on top of TSPL. | `printCompletion` takes a token; `redDensity/deviceSpeed` take numbers; `printerStatus` takes a status flag. |
Response Parsing
| Object | Method / Command | Purpose | Parameters |
|---|---|---|---|
EscResponse / TsplResponse / CpclResponse | getQuery(), getType(), getRaw(), getRawHex(), getStatusByte(), getStatusFlags(), hasStatusFlag(), isReady(), getBatteryLevel(), getText(), getMacAddress(), getEventValue(), getDescription() | Parses printer responses into status, battery, text, MAC, event, or unknown response objects. | ESC includes event values; TSPL/CPCL mainly expose status, battery, text, MAC, and descriptions. |
실전 권장 사항
섹션 제목: “실전 권장 사항”- 먼저 프린터가 ESC, TSPL, CPCL 중 무엇을 지원하는지 확인한 뒤 빌더를 선택하세요.
- 플랫폼 블루투스, USB, 브리지 API는 adapter 계층에 두고, 템플릿 계층은 바이트만 생성하세요.
- 각 템플릿에 바이트 스냅샷 테스트를 남겨 UI 변경 중 명령어가 망가지지 않게 하세요.
- BLE 디바이스는 실제 장비에서 MTU, 분할 크기, credit 알림, 연결 끊김 후 재연결을 검증해야 합니다.