コンテンツにスキップ
QISHU DOCUMENT ARCHIVE

啓枢アーカイブ

製品ドキュメント、インターフェース資料、エンジニアリング記録の入口です。

sdk / typescript

TypeScript SDK

Web、ミニプログラム、Node、ブリッジランタイム向けの NIB プリンター SDK 導入説明。

TypeScript SDK は Web、ミニプログラム、UniApp、Taro、Node ツール、ネイティブブリッジランタイムに適しています。初めて使うときは、まず 1 つだけ覚えてください。テンプレートコードは印刷命令だけを生成し、プラットフォームコードはバイト列をプリンターへ書き込むことだけを担当します。

パッケージ 用途
@boxliy/nib 標準集約パッケージ。core、Boxliy/Aryten/Lin8inch 方言、画像機能を export します。
@nib/core ConnectedDevicewriteTo()WriteOptions、受信ソース、クエリ分配。
@nib/esc-boxliy@nib/tspl-boxliy@nib/cpcl-boxliy Boxliy ESC、TSPL、CPCL 命令ビルダーとレスポンス parser。
@nib/esc@nib/tspl@nib/cpcl Aryten 互換方言。
@nib/esc-lin8inch@nib/tspl-lin8inch Lin8inch 方言。
@nib/bluetooth-ble-core BLE characteristic 選択、UUID マッチング、credit フロー制御。
@nib/wechat-bluetooth-ble@nib/uniapp-bluetooth-ble@nib/taro-bluetooth-ble WeChat、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
}

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 側ですでに分割が処理されている場合にだけ、分割の無効化を検討してください。

異なる言語や異なる方言のサンプルを混用しないでください。現在の TypeScript の EscBoxliy は ESC コマンド、クエリ、画像などの機能に適していますが、Java/Swift のような text('...') サンプル形式ではありません。通常のテキスト内容は TSPL/CPCL の text(...) API を選ぶか、具体的な ESC 方言が対応するメソッドで raw bytes を生成してください。

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

@nib/bluetooth-ble-core は 2 種類の 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 でよく使う受信とクエリの型は、ReceiveSourcePollingReceiveSourceCallbackReceiveSourceNotifyReceiveSourcereceiveSourceOf()QueryDispatcherPendingQuery です。

Boxliy 方言はレスポンス parser を提供します。

方言 parser
ESC EscResponseParser
TSPL TsplResponseParser
CPCL CpclResponseParser

ステータスをクエリするときは、まず方言ビルダーでクエリ命令を生成してデバイスへ書き込み、次にデバイス応答を対応する 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

ObjectMethod / CommandPurposeParameters
ConnectedDeviceorigin(), 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 / WriteOptionswriteTo(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 / QueryDispatcherappend(), 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 adaptersBleCreditOptions, 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

ObjectMethod / CommandPurposeParameters
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()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 / 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()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 / CpclArytenbytes(), 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.
EscLin8inchbatteryLevel(), 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.
TsplLin8inchautomaticStatusFeedback(), 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

ObjectMethod / CommandPurposeParameters
EscResponse / TsplResponse / CpclResponsegetQuery(), 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 のどれに対応しているか確認してから、ビルダーを選びます。
  • プラットフォームの Bluetooth、USB、ブリッジ API はすべて adapter 層に置き、テンプレート層はバイト列だけを生成します。
  • 各テンプレートにバイトスナップショットテストを残し、UI 変更で命令を壊さないようにします。
  • BLE デバイスでは、実機で MTU、分割サイズ、credit 通知、切断後の再接続を検証してください。