콘텐츠로 이동
QISHU DOCUMENT ARCHIVE

Qishu Archives

제품 문서, 인터페이스 자료, 엔지니어링 기록을 위한 공통 입구입니다.

sdk / swift

Swift SDK

iOS와 macOS Swift 프로젝트를 위한 NIB 프린터 SDK 연동 설명입니다.

Swift SDK는 새로운 iOS와 macOS 네이티브 프로젝트에 적합합니다. 소스에서 확인 가능한 Package.swift를 찾지 못했으므로, 여기서는 구체적인 SwiftPM product 이름을 쓰지 않습니다. 전달 패키지의 import 방식에 따라 해당 모듈을 연동하세요.

모듈 자주 쓰는 타입
Core NibScript, NibDevice, NibPen, NibWritePipeline, 수신 소스와 질의 분배.
BLE NibBleCentral, NibBleDevice, NibBleConnectionOptions, credit 흐름 제어.
Boxliy dialects NibEscBoxliy, NibTsplBoxliy, NibCpclBoxliy와 응답 parser.
Aryten dialects NibEscAryten, NibTsplAryten, NibCpclAryten.
Image helpers 전달 버전에서 사용할 수 있는 이미지 준비와 인쇄 보조 기능.

NibDevice는 최소 디바이스 계약입니다.

public protocol NibDevice: AnyObject {
var name: String { get }
var connected: Bool { get }
func write(_ data: Data) throws
func read(maxLength: Int) throws -> Data
func close() throws
}

NibScript는 생성된 Data를 보관하며 length, string, hexString을 제공합니다. NibWritePipeline은 분할 쓰기를 담당하고, 기본 chunkSize512 바이트입니다.

let connectedDevice: NibDevice = /* BLE 或平台设备 */
let script = NibTsplAryten()
.size(width: 40, height: 30)
.cls()
.text(x: 20, y: 20, content: "NIB SDK")
.print()
.script
let pipeline = NibWritePipeline()
try pipeline.write(script, to: connectedDevice)

빌더는 스크립트 생성을 담당하고, NibWritePipeline은 스크립트를 분할해 디바이스에 쓰는 일을 담당합니다. 분할 크기를 바꿔야 할 때는 다음과 같이 합니다.

let pipeline = NibWritePipeline(chunkSize: 185)
try pipeline.write(script, to: connectedDevice)

BLE 진입점은 NibBleCentral입니다.

let central = NibBleCentral()
try central.startDiscovery(timeout: 10)
// 用户选择 discoveredDevices 里的目标设备后:
let device = try central.connect(
selectedDevice,
options: NibBleConnectionOptions()
)

NibBleConnectionOptionsserviceUUIDs, writeCharacteristicUUID, readCharacteristicUUID, 연결과 discovery 타임아웃, writeMode, credit, 사용자 정의 flowControl을 구성할 수 있습니다. 쓰기 모드는 NibBleWriteMode.withResponse 또는 .withoutResponse이며, 기본값은 .withoutResponse입니다.

credit API는 다음을 포함합니다.

API 용도
NibBleCreditOptions credit 활성화 여부, UUID, 초기 credit, MTU, 전략, fallback을 구성합니다.
NibBleLaneCreditWriter lane-credit 전략입니다.
NibBleSignalCreditWriter signal-credit 전략입니다.
NibBleFlowControlStrategy 사용자 정의 흐름 제어 전략 프로토콜입니다.

기본 UUID는 FF00 service, FF02 write, FF01 read, FF03 credit입니다. lane-credit 기본 초기 credit은 1, payload overhead는 3입니다. signal-credit 기본 초기 credit은 0, payload overhead는 0입니다. NibBleCreditOptions.signalCredit을 선택하거나 enabled: true를 명시적으로 설정하지 않는 한 기본적으로 활성화되지 않습니다.

Core 수신 타입에는 NibReceiveSource, NibCallbackReceiveSource, NibPollingReceiveSource, NibReceiveListener가 있습니다. 질의 타입에는 NibQueryDispatcher<Response>, NibPendingQuery<Response>, NibResponseMatcher<Response>가 있습니다.

NibReceiveSource는 응답을 AsyncStream<Data>로 변환할 수 있는 dataStream() 확장을 제공합니다.

for await data in device.receiveSource.dataStream() {
let response = NibTsplResponseParser.parse(query: .status, raw: data)
if response.isReady {
break
}
}

Boxliy dialect parser 이름은 다음과 같습니다.

dialect parser
ESC NibEscResponseParser
TSPL NibTsplResponseParser
CPCL NibCpclResponseParser

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
NibDevice / NibScriptwrite(_ data), read(maxLength), close(), length, string, hexStringAbstracts the real printer connection for templates, write pipelines, and query handling.`maxLength` limits read size; `NibScript` wraps built Data.
NibPen / NibWritePipelineappend(bytes), append(data), append(text), crlf(), clear(), reset(), write(script, to), write(data, to)Writes built bytes to a device with chunking, timeout, cancellation, and flow-control rules.`chunkSize` is configured when constructing the pipeline; returns written byte count.
NibBleCentral / NibBleDevicestartDiscovery(), stopDiscovery(), connect(), disconnect(), discover(options), write(), read(), close()Handles BLE characteristic selection, MTU chunking, credit notifications, and fallback writes.`NibBleConnectionOptions` configures service/write/read UUIDs, timeouts, writeMode, and credit.
NibReceiveSource / NibQueryDispatcherstart(listener), stop(), accept(), receive(), query(timeout, matcher), wait(), cancel(), shutdown(), dataStream()Routes device responses into listeners or query dispatchers for status, battery, model, and similar queries.`matcher` returns a typed response; `wait(timeout:)` waits for query completion.

Command Builders

ObjectMethod / CommandPurposeParameters
NibEscBoxliy / NibEscArytenreset(), text(), newLine(), bold(), underline(), fontSize(), lineRow(), feed(), lineDot(), backLineDot(), location(), cut(), lineDotCut(), batteryVolume(), info(), model(), version(), printerVersion(), name(), mac(), sn(), state(), status(), enable(), stopJob(), wakeup(), barcode(), qrcode(), image(), raw(), clear()Builds ESC/Boxliy commands for receipt, portable, and ESC-compatible printers.Swift ESC directly supports `text`; barcode, QR, and image parameters follow the method signatures.
NibTsplBoxliy / NibTsplArytensize(), cls(), print(), gap(), text(), barcode(), qrcode(), bitmap(), status(), state(), batteryVolume(), version(), versions(), model(), models(), sn(), sns(), raw(), clear()Builds TSPL label commands for templates with paper size, coordinates, barcodes, and QR codes.`text` takes x/y/font/rotation/xMulti/yMulti/content; `bitmap` takes Data or a prepared bitmap.
NibCpclBoxliy / NibCpclArytenbegin(), pageWidth(), text(), barcode(), qrcode(), line(), box(), image(), form(), print(), status(), sn(), model(), version(), batteryVolume(), raw(), clear()Builds CPCL label commands for page setup, text, lines, barcodes, and images.`begin` takes height/copies; `line/box` take coordinates and thickness; `image` takes data/byteWidth/height/compress.

Response Parsing

ObjectMethod / CommandPurposeParameters
NibEscResponseParser / NibTsplResponseParser / NibCpclResponseParserparse(raw), parse(query, raw)Parses printer responses into status, battery, text, MAC, event, or unknown response objects.Returned structs include query, type, raw, rawHex, statusByte, statusFlags, isReady, battery, text, and description fields.
  • 먼저 모델이 ESC, TSPL, CPCL 중 무엇을 지원하는지 확인한 뒤 빌더를 선택하세요.
  • BLE 권한, 스캔, 재연결, App 수명주기 로직은 연결 계층에 두세요.
  • 템플릿 계층은 용지 크기, 좌표, 이미지, 텍스트 콘텐츠만 처리하게 하세요.
  • 실제 장비에서 write mode, MTU, credit 알림, 큰 이미지, 연속 인쇄를 검증하세요.