跳转到内容

EMAPI SDK 完整索引

本索引按语言收录固定版本中该模块的全部命令参数源文件和枚举。EMAPI 收录命令工厂、载荷、会话和编解码入口;C 收录兼容接口。展开查看参数声明摘录,通过固定版本源码链接核对完整默认值、条件分支和序列化。标题中的命令头预览来自源码字面量,不是完整的指令格式。

声明保留实现中已有的差异。收录表示存在对应实现,不表示所有打印机都支持。发送前请查阅兼容性与验证。

查看协议说明 →

源文件数: 70.

psdk_fruit_emapi.dart

完整参数、默认值与命令编码

chunker.dart

完整参数、默认值与命令编码

const int fileTransferChunkHeaderLength = 4;
const int fileTransferPayloadAlignment = 32;
final capacity =
final capacity = mtu -
final alignedCapacity =
final payloadCapacity = printTransferPayloadCapacity(maxPacketLength);
final chunks = <List<int>>[];
final end = offset + payloadCapacity > data.length
command.dart

完整参数、默认值与命令编码

class EmapiCommand {
EmapiCommand({
required int type,
required int parent,
required int child,
List<int> payload = const [],
}) : type = _checkByte(type, 'type'),
parent = _checkByte(parent, 'parent'),
child = _checkByte(child, 'child'),
payload = List<int>.unmodifiable(payload);
final int type;
final int parent;
final int child;
final List<int> payload;
bool isAckFor({required int parent, required int child}) {
bool isResponseFor({
required int type,
required int parent,
required int child,
}) {
String toString() {
connection.dart

完整参数、默认值与命令编码

Future<void> write(List<int> data);
Future<List<int>> read({required Duration timeout});
constants.dart

完整参数、默认值与命令编码

class EmapiConstants {
static const int frameHead = 0x02;
static const int frameTail = 0x03;
static const int reserved = 0x00;
static const int typeRequest = 0x01;
static const int typeResponse = 0x02;
static const int typeError = 0x03;
static const int typePassthroughRequest = 0x41;
static const int typePassthroughResponse = 0x42;
static const int typePassthroughError = 0x43;
static const int parentSystem = 0x01;
static const int parentPrinter = 0x02;
static const int parentRfid = 0x05;
static const int parentWifi = 0x06;
static const int parentDeviceConfig = 0x07;
static const int parentReport = 0x09;
static const int parentFile = 0x0A;
static const int childDeviceInfo = 0x01;
static const int childSleepShutdown = 0x04;
static const int childSetShutdownTime = 0x05;
static const int childRfidUid = 0x01;
static const int childRfidCardInfo = 0x02;
static const int childRfidPaperLength = 0x03;
static const int childRfidAuthFailureHandling = 0x04;
static const int childWifiConfig = 0x01;
static const int childWifiConnectionState = 0x02;
static const int childWifiHotspotInfo = 0x03;
static const int childWifiConfigStatus = 0x04;
static const int childWifiFileStart = 0x05;
static const int childWifiFileTransfer = 0x06;
static const int childWifiFileEnd = 0x07;
static const int childPrinterParams = 0x01;
static const int childPrintStatus = 0x04;
static const int childTransferData = 0x06;
static const int childPrintSelfTestPage = 0x0C;
static const int childReportPrintResult = 0x01;
static const int childReportPrinterStatus = 0x02;
static const int childReportFlowControl = 0x03;
static const int childReportUpgradeStatus = 0x04;
static const int childReportBluetoothConnection = 0x05;
static const int childReportRfidStatus = 0x0A;
static const int childFileStart = 0x01;
static const int childFileTransfer = 0x02;
static const int childFileEnd = 0x03;
static const int childFileUpgrade = 0x04;
static const int tagMtu = 0x08;
static const int commandHeaderLength = 5;
static const int frameOverheadLength = 9;
static const int printTransferFrameOverheadLength =
static const int crcSeed = 0x35769521;
crc32.dart

完整参数、默认值与命令编码

class EmapiCrc32 {
static const List<int> _table = [
device_connection.dart

完整参数、默认值与命令编码

class ConnectedDeviceEmapiConnection implements EmapiConnection {
ConnectedDeviceEmapiConnection(this.connectedDevice) {
final ConnectedDevice connectedDevice;
final Queue<List<int>> _pendingData = Queue<List<int>>();
final Queue<_PendingRead> _pendingReads = Queue<_PendingRead>();
void _subscribe() {
void _onData(Uint8List data) {
final copiedData = List<int>.from(data);
final pendingRead = _pendingReads.removeFirst();
void _onError(Object error, StackTrace stackTrace) {
final pendingRead = _pendingReads.removeFirst();
void _onDone() {
Future<List<int>> read({required Duration timeout}) async {
if (_pendingData.isNotEmpty) {
final completer = Completer<List<int>>();
late final _PendingRead pendingRead;
late final Timer timer;
Future<void> write(List<int> data) {
class _PendingRead {
final Completer<List<int>> completer;
final Timer timer;
endian.dart

完整参数、默认值与命令编码

class EmapiEndian {
final value = readUint16(data, offset);
final bytes = uint16(value);
final bytes = uint32(value);
frame_codec.dart

完整参数、默认值与命令编码

class FrameCodec {
final dataLength =
final data = <int>[
final frame = <int>[
final dataLength = EmapiEndian.readUint16(frame, 2);
final expectedFrameLength = dataLength + EmapiConstants.frameOverheadLength;
final dataStart = 4;
final dataEnd = dataStart + dataLength;
final data = frame.sublist(dataStart, dataEnd);
final expectedCrc = EmapiEndian.readUint32(frame, dataEnd);
final actualCrc = EmapiCrc32.compute(data);
final payloadLength = EmapiEndian.readUint16(data, 3);
final expectedDataLength = EmapiConstants.commandHeaderLength + payloadLength;
frame_parser.dart

完整参数、默认值与命令编码

class FrameParser {
final List<int> _buffer = <int>[];
final commands = <EmapiCommand>[];
final headIndex = _buffer.indexOf(EmapiConstants.frameHead);
final dataLength = EmapiEndian.readUint16(_buffer, 2);
final frameLength = dataLength + EmapiConstants.frameOverheadLength;
final frame = _buffer.sublist(0, frameLength);
models.dart

完整参数、默认值与命令编码

enum EmapiRfidAuthFailurePolicy {
enum EmapiWifiConnectionState {
class EmapiRfidCardInfo {
const EmapiRfidCardInfo({
this.paperModel,
this.paperLength,
this.paperWidth,
this.paperColor,
this.paperMaterialNumber,
});
final String? paperModel;
final String? paperLength;
final String? paperWidth;
final String? paperColor;
final String? paperMaterialNumber;
class EmapiWifiHotspotInfo {
const EmapiWifiHotspotInfo({
this.ssid,
this.rssi,
this.ip,
this.port,
});
final String? ssid;
final int? rssi;
final String? ip;
final String? port;
class EmapiPrinterParams {
const EmapiPrinterParams({
this.printSize,
this.resolution,
this.dotsPerByte,
});
final int? printSize;
final int? resolution;
final int? dotsPerByte;
class EmapiPrintStatus {
const EmapiPrintStatus({
this.paperStatus,
this.coverStatus,
this.lowBattery,
this.overheat,
this.batteryPercent,
this.batteryVoltage,
this.tphTemperature,
});
final int? paperStatus;
final int? coverStatus;
final int? lowBattery;
final int? overheat;
final int? batteryPercent;
final int? batteryVoltage;
final int? tphTemperature;
const EmapiReport(this.command);
final EmapiCommand command;
class EmapiPrintResultReport extends EmapiReport {
const EmapiPrintResultReport(EmapiCommand command, {required this.result})
: super(command);
final int result;
class EmapiPrinterStatusReport extends EmapiReport {
const EmapiPrinterStatusReport(
EmapiCommand command, {
this.paperStatus,
this.coverStatus,
this.batteryState,
this.overheat,
this.nfcPaperRecognition,
this.batteryLevelStage,
}) : super(command);
final int? paperStatus;
final int? coverStatus;
final int? batteryState;
final int? overheat;
final int? nfcPaperRecognition;
final int? batteryLevelStage;
class EmapiFlowControlReport extends EmapiReport {
const EmapiFlowControlReport(EmapiCommand command, {required this.state})
: super(command);
final int state;
class EmapiUpgradeStatusReport extends EmapiReport {
const EmapiUpgradeStatusReport(EmapiCommand command, {required this.status})
: super(command);
final int status;
class EmapiBluetoothConnectionReport extends EmapiReport {
const EmapiBluetoothConnectionReport(
EmapiCommand command, {
required this.state,
}) : super(command);
final int state;
class EmapiRfidStatusReport extends EmapiReport {
const EmapiRfidStatusReport(
EmapiCommand command, {
this.paperModel,
this.paperLength,
this.paperWidth,
this.paperColor,
this.paperMaterialNumber,
this.remainingPaperLength,
}) : super(command);
final String? paperModel;
final String? paperLength;
final String? paperWidth;
final String? paperColor;
final String? paperMaterialNumber;
final int? remainingPaperLength;
class EmapiWifiConfigStatusReport extends EmapiReport {
const EmapiWifiConfigStatusReport(
EmapiCommand command, {
this.ssid,
this.state,
}) : super(command);
final String? ssid;
final int? state;
class EmapiUnknownReport extends EmapiReport {
const EmapiUnknownReport(EmapiCommand command) : super(command);
payload.dart

完整参数、默认值与命令编码

class EmapiPayload {
printer.dart

完整参数、默认值与命令编码

class EmapiPrinter {
EmapiPrinter({
required EmapiConnection connection,
Duration timeout = const Duration(seconds: 2),
int maxRetries = 3,
int? mtu,
this.fallbackMtu = 512,
}) : _session = EmapiSession(
connection: connection,
timeout: timeout,
maxRetries: maxRetries,
),
_mtu = mtu {
if (fallbackMtu <= 0) {
final EmapiSession _session;
final int fallbackMtu;
Future<EmapiPrinterInfo> queryDeviceInfo() async {
final response = await _session.sendAndWait(
EmapiCommand(
type: EmapiConstants.typeRequest,
parent: EmapiConstants.parentSystem,
child: EmapiConstants.childDeviceInfo,
),
expected: (command) =>
final tlv = Tlv.decode(response.payload);
final info = EmapiPrinterInfo(
deviceType: tlv.string(0x01),
deviceModel: tlv.string(0x02),
brand: tlv.string(0x03),
serialNumber: tlv.string(0x04),
hardwareVersion: tlv.string(0x05),
softwareVersion: tlv.string(0x06),
bootVersion: tlv.string(0x07),
mtu: tlv.uint16(EmapiConstants.tagMtu),
);
Future<void> sleepShutdown() async {
await sendAcked(
type: EmapiConstants.typeRequest,
parent: EmapiConstants.parentSystem,
child: EmapiConstants.childSleepShutdown,
);
Future<void> setShutdownTime({required int minutes}) async {
await sendAcked(
type: EmapiConstants.typeRequest,
parent: EmapiConstants.parentSystem,
child: EmapiConstants.childSetShutdownTime,
payload: EmapiPayload.uint16(minutes),
);
Future<String> queryRfidUid() async {
final response = await sendCommand(
type: EmapiConstants.typeRequest,
responseType: EmapiConstants.typeResponse,
parent: EmapiConstants.parentRfid,
child: EmapiConstants.childRfidUid,
);
Future<EmapiRfidCardInfo> queryRfidCardInfo() async {
final response = await sendCommand(
type: EmapiConstants.typeRequest,
responseType: EmapiConstants.typeResponse,
parent: EmapiConstants.parentRfid,
child: EmapiConstants.childRfidCardInfo,
);
final tlv = Tlv.decode(response.payload);
Future<int> queryRfidPaperLength() async {
final response = await sendCommand(
type: EmapiConstants.typeRequest,
responseType: EmapiConstants.typeResponse,
parent: EmapiConstants.parentRfid,
child: EmapiConstants.childRfidPaperLength,
);
Future<void> setRfidAuthFailureHandling(
EmapiRfidAuthFailurePolicy policy,
) async {
await sendAcked(
type: EmapiConstants.typeRequest,
parent: EmapiConstants.parentRfid,
child: EmapiConstants.childRfidAuthFailureHandling,
payload: EmapiPayload.uint8(
policy == EmapiRfidAuthFailurePolicy.forbidPrint ? 0x01 : 0x00,
),
);
Future<void> setWifiConfig({
required String ssid,
required String password,
int? encryptionMethod,
}) async {
await sendAcked(
type: EmapiConstants.typePassthroughRequest,
responseType: EmapiConstants.typePassthroughResponse,
parent: EmapiConstants.parentWifi,
child: EmapiConstants.childWifiConfig,
payload: Tlv.encode([
TlvEntry.string(0x01, ssid),
TlvEntry.string(0x02, password),
if (encryptionMethod != null) TlvEntry.uint8(0x03, encryptionMethod),
]),
);
Future<EmapiWifiConnectionState> queryWifiConnectionState() async {
final response = await sendCommand(
type: EmapiConstants.typePassthroughRequest,
responseType: EmapiConstants.typePassthroughResponse,
parent: EmapiConstants.parentWifi,
child: EmapiConstants.childWifiConnectionState,
);
Future<EmapiWifiHotspotInfo> queryWifiHotspotInfo() async {
final response = await sendCommand(
type: EmapiConstants.typePassthroughRequest,
responseType: EmapiConstants.typePassthroughResponse,
parent: EmapiConstants.parentWifi,
child: EmapiConstants.childWifiHotspotInfo,
);
final tlv = Tlv.decode(response.payload);
Future<void> startWifiFileDownload({
required int fileType,
required int totalSize,
}) async {
await sendAcked(
type: EmapiConstants.typePassthroughRequest,
responseType: EmapiConstants.typePassthroughResponse,
parent: EmapiConstants.parentWifi,
child: EmapiConstants.childWifiFileStart,
payload: _fileStartPayload(fileType: fileType, totalSize: totalSize),
);
Future<void> transferWifiFileDownloadChunk({
required int index,
required List<int> data,
}) async {
await _validateFileTransferChunk(data);
Future<void> finishWifiFileDownload() async {
await sendAcked(
type: EmapiConstants.typePassthroughRequest,
responseType: EmapiConstants.typePassthroughResponse,
parent: EmapiConstants.parentWifi,
child: EmapiConstants.childWifiFileEnd,
);
Future<EmapiPrinterParams> queryPrinterParams() async {
final response = await sendCommand(
type: EmapiConstants.typeRequest,
responseType: EmapiConstants.typeResponse,
parent: EmapiConstants.parentPrinter,
child: EmapiConstants.childPrinterParams,
);
final tlv = Tlv.decode(response.payload);
Future<EmapiPrintStatus> queryPrintStatus() async {
final response = await sendCommand(
type: EmapiConstants.typeRequest,
responseType: EmapiConstants.typeResponse,
parent: EmapiConstants.parentPrinter,
child: EmapiConstants.childPrintStatus,
);
final tlv = Tlv.decode(response.payload);
Future<void> printSelfTestPage() async {
await sendAcked(
type: EmapiConstants.typeRequest,
parent: EmapiConstants.parentPrinter,
child: EmapiConstants.childPrintSelfTestPage,
);
Future<void> startMainControllerOta({
int fileType = 0x0001,
required int totalSize,
}) async {
await sendAcked(
type: EmapiConstants.typeRequest,
parent: EmapiConstants.parentFile,
child: EmapiConstants.childFileStart,
payload: _fileStartPayload(fileType: fileType, totalSize: totalSize),
);
Future<void> transferMainControllerOtaChunk({
required int index,
required List<int> data,
}) async {
await _validateFileTransferChunk(data);
Future<void> finishMainControllerOta() async {
await sendAcked(
type: EmapiConstants.typeRequest,
parent: EmapiConstants.parentFile,
child: EmapiConstants.childFileEnd,
);
Future<void> upgradeMainController() async {
await sendAcked(
type: EmapiConstants.typeRequest,
parent: EmapiConstants.parentFile,
child: EmapiConstants.childFileUpgrade,
);
Future<void> printEsc(List<int> data) async {
final mtu = await _ensureMtu();
Future<int> _ensureMtu() async {
if (_mtu != null) {
final info = await queryDeviceInfo();
final mtu = info.mtu ?? fallbackMtu;
Future<void> _validateFileTransferChunk(List<int> data) async {
final mtu = await _ensureMtu();
final int capacity;
Future<void> sendAcked({
required int type,
int responseType = EmapiConstants.typeResponse,
required int parent,
required int child,
List<int> payload = const [],
}) async {
await sendCommand(
type: type,
responseType: responseType,
parent: parent,
child: child,
payload: payload,
requireEmptyPayload: true,
);
Future<EmapiCommand> sendCommand({
required int type,
required int responseType,
required int parent,
required int child,
List<int> payload = const [],
bool requireEmptyPayload = false,
}) {
final entry = tlv[tag];
printer_info.dart

完整参数、默认值与命令编码

class EmapiPrinterInfo {
EmapiPrinterInfo({
this.deviceType,
this.deviceModel,
this.brand,
this.serialNumber,
this.hardwareVersion,
this.softwareVersion,
this.bootVersion,
this.mtu,
});
final String? deviceType;
final String? deviceModel;
final String? brand;
final String? serialNumber;
final String? hardwareVersion;
final String? softwareVersion;
final String? bootVersion;
final int? mtu;
protocol_exception.dart

完整参数、默认值与命令编码

class EmapiProtocolException implements Exception {
EmapiProtocolException(this.message);
final String message;
String toString() {
session.dart

完整参数、默认值与命令编码

class EmapiSession {
EmapiSession({
required this.connection,
this.timeout = const Duration(seconds: 2),
this.maxRetries = 3,
}) {
final EmapiConnection connection;
final Duration timeout;
final int maxRetries;
final FrameParser _parser = FrameParser();
final List<EmapiCommand> _pendingCommands = <EmapiCommand>[];
final List<_CommandWaiter> _commandWaiters = <_CommandWaiter>[];
late final StreamController<EmapiReport> _reportsController;
Future<EmapiCommand> sendAndWait(
EmapiCommand command, {
required EmapiResponseMatcher expected,
int? maxRetries,
}) async {
final effectiveMaxRetries = maxRetries ?? this.maxRetries;
final previous = _sendQueue;
final run = previous.then(
(_) => _sendAndWaitLocked(
Future<EmapiCommand> _sendAndWaitLocked(
EmapiCommand command, {
required EmapiResponseMatcher expected,
required int maxRetries,
}) async {
Object? lastError;
for (var attempt = 0; attempt <= maxRetries; attempt++) {
Future<EmapiCommand> _readUntilExpected(EmapiResponseMatcher expected) async {
final stopwatch = Stopwatch()..start();
Future<EmapiCommand> _readNextCommand({
required Stopwatch stopwatch,
}) async {
if (_pendingCommands.isNotEmpty) {
final waiter = _CommandWaiter(_remainingTimeout(stopwatch));
Future<EmapiCommand> _readNextCommandDirect({
required Stopwatch stopwatch,
}) async {
while (true) {
final data = await connection.read(timeout: _remainingTimeout(stopwatch));
final commands = _parser.add(data);
void _ensureReadLoop() {
Future<void> _runReadLoop() async {
while (_shouldRead) {
final readTimeout = _nextReadTimeout();
final data = await connection.read(timeout: readTimeout);
final commands = _parser.add(data);
final remaining = _commandWaiters.first.remaining;
Future<void> _dispatchCommand(EmapiCommand command) async {
if (await _handleReport(command)) {
void _completeExpiredCommandWaiter(TimeoutException error) {
void _completeNextCommandWaiterWithError(
Object error,
StackTrace stackTrace,
) {
final remaining = timeout - stopwatch.elapsed;
Future<bool> _handleReport(EmapiCommand command) async {
if (_isNormalReport(command)) {
Future<void> _waitUntilFlowIdle() async {
if (!_flowBusy) {
final stopwatch = Stopwatch()..start();
final command = await _readNextCommand(stopwatch: stopwatch);
bool _isNormalReport(EmapiCommand command) {
bool _isPassthroughReport(EmapiCommand command) {
void _emitReport(EmapiReport report) {
final tlv = Tlv.decode(command.payload);
final tlv = Tlv.decode(command.payload);
final tlv = Tlv.decode(command.payload);
int _payloadByte(List<int> payload) {
class _CommandWaiter {
final DateTime _deadline;
final Completer<EmapiCommand> completer;
tlv.dart

完整参数、默认值与命令编码

class TlvEntry {
TlvEntry({
required this.tag,
required List<int> value,
}) : value = List<int>.unmodifiable(value);
final int tag;
final List<int> value;
class TlvData {
TlvData(Map<int, TlvEntry> entries) : _entries = Map.unmodifiable(entries);
final Map<int, TlvEntry> _entries;
bool containsTag(int tag) {
final value = _value(tag);
final value = _value(tag);
final value = _value(tag);
final value = _value(tag);
final end = value.isNotEmpty && value.last == 0x00
class Tlv {
final result = <int>[];
final entries = <int, TlvEntry>{};
final tag = data[offset];
final length = EmapiEndian.readUint16(data, offset + 1);
final valueStart = offset + 3;
final valueEnd = valueStart + length;
ConnectedDeviceEmapiConnection.java

完整参数、默认值与命令编码

public final class ConnectedDeviceEmapiConnection implements EmapiConnection {
private final ConnectedDevice device;
public ConnectedDeviceEmapiConnection(ConnectedDevice device) {
public void write(byte[] data) throws IOException {
device.write(data);
public byte[] read(int timeoutMs) throws IOException {
return device.read(ReadOptions.builder().timeout(timeoutMs).build());
public void close() throws IOException {
device.disconnect();
EmapiBluetoothConnectionReport.java

完整参数、默认值与命令编码

public final class EmapiBluetoothConnectionReport extends EmapiReport {
private final int state;
public EmapiBluetoothConnectionReport(EmapiCommand command, int state) {
public int getState() {
EmapiCommand.java

完整参数、默认值与命令编码

public final class EmapiCommand {
private final int type;
private final int parent;
private final int child;
private final byte[] payload;
public EmapiCommand(int type, int parent, int child, byte[] payload) {
public int getType() {
public int getParent() {
public int getChild() {
public byte[] getPayload() {
public int getPayloadLength() {
public boolean isAckFor(int parent, int child) {
public boolean isResponseFor(int type, int parent, int child) {
public boolean isError() {
public String toString() {
public boolean equals(Object other) {
public int hashCode() {
EmapiConnection.java

完整参数、默认值与命令编码

public interface EmapiConnection {
EmapiConnectionException.java

完整参数、默认值与命令编码

public class EmapiConnectionException extends Exception {
public EmapiConnectionException(String message, Throwable cause) {
EmapiFlowControlReport.java

完整参数、默认值与命令编码

public final class EmapiFlowControlReport extends EmapiReport {
private final int state;
public EmapiFlowControlReport(EmapiCommand command, int state) {
public int getState() {
public boolean isBusy() {
EmapiPayload.java

完整参数、默认值与命令编码

public final class EmapiPayload {
public static byte[] uint8(int value) {
public static byte[] uint16(int value) {
public static byte[] uint32(long value) {
public static long readUInt32(byte[] data) {
public static byte[] fileChunk(int index, byte[] data) {
EmapiPrintResultReport.java

完整参数、默认值与命令编码

public final class EmapiPrintResultReport extends EmapiReport {
private final int result;
public EmapiPrintResultReport(EmapiCommand command, int result) {
public int getResult() {
EmapiPrintStatus.java

完整参数、默认值与命令编码

public final class EmapiPrintStatus {
private final Integer paperStatus;
private final Integer coverStatus;
private final Integer lowBattery;
private final Integer overheat;
private final Integer batteryPercent;
private final Integer batteryVoltage;
private final Integer tphTemperature;
public EmapiPrintStatus(Integer paperStatus, Integer coverStatus, Integer lowBattery, Integer overheat,
Integer batteryPercent, Integer batteryVoltage, Integer tphTemperature) {
public Integer getPaperStatus() {
public Integer getCoverStatus() {
public Integer getLowBattery() {
public Integer getOverheat() {
public Integer getBatteryPercent() {
public Integer getBatteryVoltage() {
public Integer getTphTemperature() {
EmapiPrinter.java

完整参数、默认值与命令编码

public final class EmapiPrinter {
private final EmapiConnection connection;
private final EmapiSession session;
private final int fallbackMtu;
private int cachedMtu;
private boolean hasCachedMtu;
public static EmapiPrinterBuilder builder() {
public static EmapiPrinterBuilder connectedDevice(ConnectedDevice device) {
public void open() {
public List<EmapiReport> getReports() {
public EmapiReport readNextReport() throws EmapiConnectionException, EmapiProtocolException {
return session.readNextReport();
public EmapiPrinterInfo queryDeviceInfo() throws EmapiConnectionException, EmapiProtocolException {
EmapiCommand response = sendCommand(
EmapiConstants.TYPE_REQUEST,
EmapiConstants.TYPE_RESPONSE,
EmapiConstants.PARENT_SYSTEM,
EmapiConstants.CHILD_SYSTEM_DEVICE_INFO,
new byte[0],
false
);
public void sleepShutdown() throws EmapiConnectionException, EmapiProtocolException {
sendAcked(EmapiConstants.TYPE_REQUEST, EmapiConstants.TYPE_RESPONSE, EmapiConstants.PARENT_SYSTEM, EmapiConstants.CHILD_SYSTEM_SLEEP_SHUTDOWN, new byte[0]);
public void setShutdownTime(int minutes) throws EmapiConnectionException, EmapiProtocolException {
sendAcked(EmapiConstants.TYPE_REQUEST, EmapiConstants.TYPE_RESPONSE, EmapiConstants.PARENT_SYSTEM, EmapiConstants.CHILD_SYSTEM_SET_SHUTDOWN_TIME, EmapiPayload.uint16(minutes));
public String queryRfidUid() throws EmapiConnectionException, EmapiProtocolException {
EmapiCommand response = sendCommand(EmapiConstants.TYPE_REQUEST, EmapiConstants.TYPE_RESPONSE, EmapiConstants.PARENT_RFID, EmapiConstants.CHILD_RFID_UID, new byte[0], false);
public EmapiRfidCardInfo queryRfidCardInfo() throws EmapiConnectionException, EmapiProtocolException {
try {
List<TlvEntry> tlv = Tlv.decode(sendCommand(EmapiConstants.TYPE_REQUEST, EmapiConstants.TYPE_RESPONSE, EmapiConstants.PARENT_RFID, EmapiConstants.CHILD_RFID_CARD_INFO, new byte[0], false).getPayload());
public long queryRfidPaperLength() throws EmapiConnectionException, EmapiProtocolException {
try {
return EmapiPayload.readUInt32(sendCommand(EmapiConstants.TYPE_REQUEST, EmapiConstants.TYPE_RESPONSE, EmapiConstants.PARENT_RFID, EmapiConstants.CHILD_RFID_PAPER_LENGTH, new byte[0], false).getPayload());
public void setRfidAuthFailureHandling(EmapiRfidAuthFailurePolicy policy) throws EmapiConnectionException, EmapiProtocolException {
int value = policy == EmapiRfidAuthFailurePolicy.FORBID_PRINT ? 1 : 0;
sendAcked(EmapiConstants.TYPE_REQUEST, EmapiConstants.TYPE_RESPONSE, EmapiConstants.PARENT_RFID, EmapiConstants.CHILD_RFID_AUTH_FAILURE_HANDLING, EmapiPayload.uint8(value));
public void setWifiConfig(String ssid, String password) throws EmapiConnectionException, EmapiProtocolException {
setWifiConfig(ssid, password, null);
public void setWifiConfig(String ssid, String password, Integer encryptionMethod) throws EmapiConnectionException, EmapiProtocolException {
TlvEntry[] entries;
if (encryptionMethod == null) {
public EmapiWifiConnectionState queryWifiConnectionState() throws EmapiConnectionException, EmapiProtocolException {
byte[] payload = sendCommand(EmapiConstants.TYPE_PASSTHROUGH_REQUEST, EmapiConstants.TYPE_PASSTHROUGH_RESPONSE, EmapiConstants.PARENT_WIFI, EmapiConstants.CHILD_WIFI_CONNECTION_STATE, new byte[0], false).getPayload();
public EmapiWifiHotspotInfo queryWifiHotspotInfo() throws EmapiConnectionException, EmapiProtocolException {
try {
List<TlvEntry> tlv = Tlv.decode(sendCommand(EmapiConstants.TYPE_PASSTHROUGH_REQUEST, EmapiConstants.TYPE_PASSTHROUGH_RESPONSE, EmapiConstants.PARENT_WIFI, EmapiConstants.CHILD_WIFI_HOTSPOT_INFO, new byte[0], false).getPayload());
public EmapiPrinterParams queryPrinterParams() throws EmapiConnectionException, EmapiProtocolException {
try {
List<TlvEntry> tlv = Tlv.decode(sendCommand(EmapiConstants.TYPE_REQUEST, EmapiConstants.TYPE_RESPONSE, EmapiConstants.PARENT_PRINTER, EmapiConstants.CHILD_PRINTER_PARAMS, new byte[0], false).getPayload());
public EmapiPrintStatus queryPrintStatus() throws EmapiConnectionException, EmapiProtocolException {
try {
List<TlvEntry> tlv = Tlv.decode(sendCommand(EmapiConstants.TYPE_REQUEST, EmapiConstants.TYPE_RESPONSE, EmapiConstants.PARENT_PRINTER, EmapiConstants.CHILD_PRINTER_STATUS, new byte[0], false).getPayload());
public void printSelfTestPage() throws EmapiConnectionException, EmapiProtocolException {
sendAcked(EmapiConstants.TYPE_REQUEST, EmapiConstants.TYPE_RESPONSE, EmapiConstants.PARENT_PRINTER, EmapiConstants.CHILD_PRINTER_SELF_TEST_PAGE, new byte[0]);
public void startMainControllerOta(int fileType, long totalSize) throws EmapiConnectionException, EmapiProtocolException {
sendAcked(EmapiConstants.TYPE_REQUEST, EmapiConstants.TYPE_RESPONSE, EmapiConstants.PARENT_FILE, EmapiConstants.CHILD_FILE_START, fileStartPayload(fileType, totalSize));
public void startMainControllerOta(long totalSize) throws EmapiConnectionException, EmapiProtocolException {
startMainControllerOta(0x0001, totalSize);
public void transferMainControllerOtaChunk(int index, byte[] data) throws EmapiConnectionException, EmapiProtocolException {
validateFileTransferChunk(data);
public void finishMainControllerOta() throws EmapiConnectionException, EmapiProtocolException {
sendAcked(EmapiConstants.TYPE_REQUEST, EmapiConstants.TYPE_RESPONSE, EmapiConstants.PARENT_FILE, EmapiConstants.CHILD_FILE_END, new byte[0]);
public void upgradeMainController() throws EmapiConnectionException, EmapiProtocolException {
sendAcked(EmapiConstants.TYPE_REQUEST, EmapiConstants.TYPE_RESPONSE, EmapiConstants.PARENT_FILE, EmapiConstants.CHILD_FILE_UPGRADE, new byte[0]);
public void startWifiFileDownload(int fileType, long totalSize) throws EmapiConnectionException, EmapiProtocolException {
sendAcked(EmapiConstants.TYPE_PASSTHROUGH_REQUEST, EmapiConstants.TYPE_PASSTHROUGH_RESPONSE, EmapiConstants.PARENT_WIFI, EmapiConstants.CHILD_WIFI_FILE_START, fileStartPayload(fileType, totalSize));
public void transferWifiFileDownloadChunk(int index, byte[] data) throws EmapiConnectionException, EmapiProtocolException {
validateFileTransferChunk(data);
public void finishWifiFileDownload() throws EmapiConnectionException, EmapiProtocolException {
sendAcked(EmapiConstants.TYPE_PASSTHROUGH_REQUEST, EmapiConstants.TYPE_PASSTHROUGH_RESPONSE, EmapiConstants.PARENT_WIFI, EmapiConstants.CHILD_WIFI_FILE_END, new byte[0]);
public void printEsc(byte[] escBytes) throws EmapiConnectionException, EmapiProtocolException {
int mtu = ensureMtu();
public void close() throws EmapiConnectionException {
try {
connection.close();
EmapiPrinterBuilder.java

完整参数、默认值与命令编码

public final class EmapiPrinterBuilder {
private EmapiConnection connection;
private int timeoutMs = 2000;
private int maxRetries = 3;
private int fallbackMtu = 512;
private Integer mtu;
public EmapiPrinterBuilder connection(EmapiConnection connection) {
public EmapiPrinterBuilder connectedDevice(ConnectedDevice device) {
public EmapiPrinterBuilder timeoutMs(int timeoutMs) {
public EmapiPrinterBuilder maxRetries(int maxRetries) {
public EmapiPrinterBuilder fallbackMtu(int fallbackMtu) {
public EmapiPrinterBuilder mtu(int mtu) {
public EmapiPrinter build() {
EmapiPrinterInfo.java

完整参数、默认值与命令编码

public final class EmapiPrinterInfo {
private final String deviceType;
private final String deviceModel;
private final String brand;
private final String serialNumber;
private final String hardwareVersion;
private final String softwareVersion;
private final String bootVersion;
private final Integer mtu;
public EmapiPrinterInfo(int mtu) {
public EmapiPrinterInfo(String deviceType, String deviceModel, String brand, String serialNumber,
String hardwareVersion, String softwareVersion, String bootVersion, Integer mtu) {
public String getDeviceType() {
public String getDeviceModel() {
public String getBrand() {
public String getSerialNumber() {
public String getHardwareVersion() {
public String getSoftwareVersion() {
public String getBootVersion() {
public Integer getMtu() {
EmapiPrinterParams.java

完整参数、默认值与命令编码

public final class EmapiPrinterParams {
private final Long printSize;
private final Long resolution;
private final Long dotsPerByte;
public EmapiPrinterParams(Long printSize, Long resolution, Long dotsPerByte) {
public Long getPrintSize() {
public Long getResolution() {
public Long getDotsPerByte() {
EmapiPrinterStatusReport.java

完整参数、默认值与命令编码

public final class EmapiPrinterStatusReport extends EmapiReport {
private final Integer paperStatus;
private final Integer coverStatus;
private final Integer batteryState;
private final Integer overheat;
private final Integer nfcPaperRecognition;
private final Integer batteryLevelStage;
public EmapiPrinterStatusReport(EmapiCommand command, Integer paperStatus, Integer coverStatus,
Integer batteryState, Integer overheat, Integer nfcPaperRecognition) {
public EmapiPrinterStatusReport(EmapiCommand command, Integer paperStatus, Integer coverStatus,
Integer batteryState, Integer overheat, Integer nfcPaperRecognition,
Integer batteryLevelStage) {
public Integer getPaperStatus() {
public Integer getCoverStatus() {
public Integer getBatteryState() {
public Integer getOverheat() {
public Integer getNfcPaperRecognition() {
public Integer getBatteryLevelStage() {
EmapiProtocolException.java

完整参数、默认值与命令编码

public class EmapiProtocolException extends Exception {
public EmapiProtocolException(String message) {
public EmapiProtocolException(String message, Throwable cause) {
EmapiReport.java

完整参数、默认值与命令编码

public abstract class EmapiReport {
private final EmapiCommand command;
public EmapiCommand getCommand() {
EmapiResponseMatcher.java

完整参数、默认值与命令编码

public abstract class EmapiResponseMatcher {
public abstract boolean matches(EmapiCommand command);
public static EmapiResponseMatcher exactAck(int parent, int child) {
public static EmapiResponseMatcher exactResponse(int parent, int child) {
public static EmapiResponseMatcher exact(int type, int parent, int child, boolean requireEmptyPayload) {
private final int parent;
private final int child;
public boolean matches(EmapiCommand command) {
private final int parent;
private final int child;
public boolean matches(EmapiCommand command) {
private final int type;
private final int parent;
private final int child;
private final boolean requireEmptyPayload;
public boolean matches(EmapiCommand command) {
EmapiRfidAuthFailurePolicy.java

完整参数、默认值与命令编码

public enum EmapiRfidAuthFailurePolicy {
EmapiRfidCardInfo.java

完整参数、默认值与命令编码

public final class EmapiRfidCardInfo {
private final String paperModel;
private final String paperLength;
private final String paperWidth;
private final String paperColor;
private final String paperMaterialNumber;
public EmapiRfidCardInfo(String paperModel, String paperLength, String paperWidth, String paperColor, String paperMaterialNumber) {
public String getPaperModel() {
public String getPaperLength() {
public String getPaperWidth() {
public String getPaperColor() {
public String getPaperMaterialNumber() {
EmapiSession.java

完整参数、默认值与命令编码

public final class EmapiSession {
private final EmapiConnection connection;
private final int timeoutMs;
private final int maxRetries;
private boolean flowBusy;
public EmapiSession(EmapiConnection connection, int timeoutMs, int maxRetries) {
public List<EmapiReport> getReports() {
public EmapiReport readNextReport() throws EmapiConnectionException, EmapiProtocolException {
long deadlineNanos = System.nanoTime() + ((long) timeoutMs * 1000000L);
public EmapiCommand sendAndWait(EmapiCommand command, EmapiResponseMatcher matcher)
throws EmapiConnectionException, EmapiProtocolException {
return sendAndWait(command, matcher, maxRetries);
public EmapiCommand sendAndWait(EmapiCommand command, EmapiResponseMatcher matcher, int maxRetries)
throws EmapiConnectionException, EmapiProtocolException {
if (maxRetries < 0) {
EmapiUnknownReport.java

完整参数、默认值与命令编码

public final class EmapiUnknownReport extends EmapiReport {
public EmapiUnknownReport(EmapiCommand command) {
EmapiUpgradeStatusReport.java

完整参数、默认值与命令编码

public final class EmapiUpgradeStatusReport extends EmapiReport {
private final int status;
public EmapiUpgradeStatusReport(EmapiCommand command, int status) {
public int getStatus() {
EmapiWifiConfigStatusReport.java

完整参数、默认值与命令编码

public final class EmapiWifiConfigStatusReport extends EmapiReport {
private final String ssid;
private final Integer state;
public EmapiWifiConfigStatusReport(EmapiCommand command, String ssid, Integer state) {
public String getSsid() {
public Integer getState() {
EmapiWifiConnectionState.java

完整参数、默认值与命令编码

public enum EmapiWifiConnectionState {
EmapiWifiHotspotInfo.java

完整参数、默认值与命令编码

public final class EmapiWifiHotspotInfo {
private final String ssid;
private final Integer rssi;
private final String ip;
private final String port;
public EmapiWifiHotspotInfo(String ssid, Integer rssi, String ip, String port) {
public String getSsid() {
public Integer getRssi() {
public String getIp() {
public String getPort() {
EmapiConstants.java

完整参数、默认值与命令编码

public final class EmapiConstants {
public static final int FRAME_HEAD = 0x02;
public static final int FRAME_TAIL = 0x03;
public static final int RESERVED = 0x00;
public static final int TYPE_REQUEST = 0x01;
public static final int TYPE_RESPONSE = 0x02;
public static final int TYPE_ERROR = 0x03;
public static final int TYPE_PASSTHROUGH_REQUEST = 0x41;
public static final int TYPE_PASSTHROUGH_RESPONSE = 0x42;
public static final int TYPE_PASSTHROUGH_ERROR = 0x43;
public static final int PARENT_SYSTEM = 0x01;
public static final int PARENT_PRINTER = 0x02;
public static final int PARENT_RFID = 0x05;
public static final int PARENT_WIFI = 0x06;
public static final int PARENT_REPORT = 0x09;
public static final int PARENT_FILE = 0x0a;
public static final int CHILD_SYSTEM_DEVICE_INFO = 0x01;
public static final int CHILD_SYSTEM_SLEEP_SHUTDOWN = 0x04;
public static final int CHILD_SYSTEM_SET_SHUTDOWN_TIME = 0x05;
public static final int CHILD_RFID_UID = 0x01;
public static final int CHILD_RFID_CARD_INFO = 0x02;
public static final int CHILD_RFID_PAPER_LENGTH = 0x03;
public static final int CHILD_RFID_AUTH_FAILURE_HANDLING = 0x04;
public static final int CHILD_WIFI_CONFIG = 0x01;
public static final int CHILD_WIFI_CONNECTION_STATE = 0x02;
public static final int CHILD_WIFI_HOTSPOT_INFO = 0x03;
public static final int CHILD_WIFI_CONFIG_STATUS = 0x04;
public static final int CHILD_WIFI_FILE_START = 0x05;
public static final int CHILD_WIFI_FILE_TRANSFER = 0x06;
public static final int CHILD_WIFI_FILE_END = 0x07;
public static final int CHILD_PRINTER_PARAMS = 0x01;
public static final int CHILD_PRINTER_STATUS = 0x04;
public static final int CHILD_PRINTER_TRANSFER_DATA = 0x06;
public static final int CHILD_PRINTER_SELF_TEST_PAGE = 0x0c;
public static final int CHILD_REPORT_PRINT_RESULT = 0x01;
public static final int CHILD_REPORT_PRINTER_STATUS = 0x02;
public static final int CHILD_REPORT_FLOW_CONTROL = 0x03;
public static final int CHILD_REPORT_UPGRADE_STATUS = 0x04;
public static final int CHILD_REPORT_BLUETOOTH_CONNECTION = 0x05;
public static final int CHILD_FILE_START = 0x01;
public static final int CHILD_FILE_TRANSFER = 0x02;
public static final int CHILD_FILE_END = 0x03;
public static final int CHILD_FILE_UPGRADE = 0x04;
public static final int TAG_MTU = 0x08;
public static final int COMMAND_HEADER_LENGTH = 5;
public static final int FRAME_OVERHEAD_LENGTH = 9;
public static final int PRINT_TRANSFER_FRAME_OVERHEAD_LENGTH = FRAME_OVERHEAD_LENGTH + COMMAND_HEADER_LENGTH;
EmapiCrc32.java

完整参数、默认值与命令编码

public final class EmapiCrc32 {
public static final long SEED = 0x35769521L;
public static long calculate(byte[] buffer, int offset, int length) {
Endian.java

完整参数、默认值与命令编码

public final class Endian {
public static int readUInt16(byte[] buffer, int offset) {
public static long readUInt32(byte[] buffer, int offset) {
public static int readInt16(byte[] buffer, int offset) {
public static void writeUInt16(byte[] buffer, int offset, int value) {
public static void writeUInt32(byte[] buffer, int offset, long value) {
FrameCodec.java

完整参数、默认值与命令编码

public final class FrameCodec {
public static byte[] encode(EmapiCommand command) {
FrameParseResult.java

完整参数、默认值与命令编码

public final class FrameParseResult {
private final EmapiCommand command;
private final String error;
public static FrameParseResult command(EmapiCommand command) {
public static FrameParseResult error(String error) {
public boolean isCommand() {
public boolean isError() {
public EmapiCommand getCommand() {
public String getError() {
FrameParser.java

完整参数、默认值与命令编码

public final class FrameParser {
public List<FrameParseResult> push(byte[] bytes) {
Tlv.java

完整参数、默认值与命令编码

public final class Tlv {
public static final int TAG_MTU = 0x08;
public static byte[] encode(TlvEntry[] entries) {
public static List<TlvEntry> decode(byte[] payload) {
public static TlvEntry find(List<TlvEntry> entries, int tag) {
public static TlvEntry uint8(int tag, int value) {
public static TlvEntry uint16(int tag, int value) {
public static TlvEntry uint32(int tag, long value) {
public static TlvEntry string(int tag, String value) {
public static int readUInt8(TlvEntry entry) {
public static int readUInt16(TlvEntry entry) {
public static long readUInt32(TlvEntry entry) {
public static String readString(TlvEntry entry) {
public static Integer optionalUInt8(List<TlvEntry> entries, int tag) {
public static Integer optionalUInt16(List<TlvEntry> entries, int tag) {
public static Long optionalUInt32(List<TlvEntry> entries, int tag) {
public static String optionalString(List<TlvEntry> entries, int tag) {
public static Integer optionalInt16(List<TlvEntry> entries, int tag) {
TlvEntry.java

完整参数、默认值与命令编码

public final class TlvEntry {
private final int tag;
private final byte[] value;
public TlvEntry(int tag, byte[] value) {
public int getTag() {
public int getLength() {
public byte[] getValue() {
Chunker.java

完整参数、默认值与命令编码

public final class Chunker {
public static final int FILE_TRANSFER_CHUNK_HEADER_LENGTH = 4;
public static final int FILE_TRANSFER_PAYLOAD_ALIGNMENT = 32;
public static List<byte[]> split(byte[] data, int mtu) {
public static int printTransferPayloadCapacity(int mtu) {
public static int fileTransferPayloadCapacity(int mtu) {
emapi.h

完整参数、默认值与命令编码

- (BOOL)writeData:(NSData *)data error:(NSError **)error;
- (nullable NSData *)readDataWithTimeout:(NSTimeInterval)timeout error:(NSError **)error;
@end
@interface EMAPICommand : NSObject
@property(nonatomic, readonly) uint8_t type;
@property(nonatomic, readonly) uint8_t parent;
@property(nonatomic, readonly) uint8_t child;
@property(nonatomic, copy, readonly) NSData *payload;
- (nullable instancetype)initWithType:(NSInteger)type parent:(NSInteger)parent child:(NSInteger)child payload:(NSData *)payload error:(NSError **)error;
- (BOOL)isAckForParent:(uint8_t)parent child:(uint8_t)child;
- (BOOL)isResponseForType:(uint8_t)type parent:(uint8_t)parent child:(uint8_t)child;
- (BOOL)isError;
- (BOOL)isProtocolError;
- (BOOL)isPassthroughError;
@end
@interface EMAPICrc32 : NSObject
+ (uint32_t)compute:(NSData *)data;
+ (uint32_t)compute:(NSData *)data seed:(uint32_t)seed;
@end
@interface EMAPIEndian : NSObject
+ (uint16_t)readUint16:(NSData *)data offset:(NSUInteger)offset error:(NSError **)error;
+ (int16_t)readInt16:(NSData *)data offset:(NSUInteger)offset error:(NSError **)error;
+ (uint32_t)readUint32:(NSData *)data offset:(NSUInteger)offset error:(NSError **)error;
+ (nullable NSData *)uint8:(NSInteger)value error:(NSError **)error;
+ (nullable NSData *)uint16:(NSInteger)value error:(NSError **)error;
+ (nullable NSData *)uint32:(int64_t)value error:(NSError **)error;
@end
@interface EMAPIFrameCodec : NSObject
+ (nullable NSData *)encodeCommand:(EMAPICommand *)command error:(NSError **)error;
+ (nullable EMAPICommand *)decodeFrame:(NSData *)frame error:(NSError **)error;
@end
@interface EMAPIFrameParser : NSObject
- (nullable NSArray<EMAPICommand *> *)addData:(NSData *)data error:(NSError **)error;
@end
@interface EMAPITlvEntry : NSObject
@property(nonatomic, readonly) uint8_t tag;
@property(nonatomic, copy, readonly) NSData *value;
- (nullable instancetype)initWithTag:(NSInteger)tag value:(NSData *)value error:(NSError **)error;
+ (instancetype)uint8WithTag:(uint8_t)tag value:(uint8_t)value;
+ (instancetype)uint16WithTag:(uint8_t)tag value:(uint16_t)value;
+ (instancetype)uint32WithTag:(uint8_t)tag value:(uint32_t)value;
+ (instancetype)stringWithTag:(uint8_t)tag value:(NSString *)value;
@end
@interface EMAPITlvData : NSObject
- (nullable EMAPITlvEntry *)entryForTag:(uint8_t)tag;
- (nullable NSNumber *)uint8ForTag:(uint8_t)tag error:(NSError **)error;
- (nullable NSNumber *)uint16ForTag:(uint8_t)tag error:(NSError **)error;
- (nullable NSNumber *)uint32ForTag:(uint8_t)tag error:(NSError **)error;
- (nullable NSNumber *)int16ForTag:(uint8_t)tag error:(NSError **)error;
- (nullable NSString *)stringForTag:(uint8_t)tag error:(NSError **)error;
@end
@interface EMAPITlv : NSObject
+ (nullable NSData *)encodeEntries:(NSArray<EMAPITlvEntry *> *)entries error:(NSError **)error;
+ (nullable EMAPITlvData *)decodeData:(NSData *)data error:(NSError **)error;
@end
@interface EMAPIPayload : NSObject
+ (nullable NSData *)uint8:(NSInteger)value error:(NSError **)error;
+ (nullable NSData *)uint16:(NSInteger)value error:(NSError **)error;
+ (nullable NSData *)uint32:(int64_t)value error:(NSError **)error;
+ (uint32_t)readUint32:(NSData *)data error:(NSError **)error;
+ (nullable NSData *)fileChunkWithIndex:(NSInteger)index data:(NSData *)data error:(NSError **)error;
@end
@interface EMAPIChunker : NSObject
+ (NSInteger)printTransferPayloadCapacityForMaxPacketLength:(NSInteger)maxPacketLength error:(NSError **)error;
+ (NSInteger)fileTransferPayloadCapacityForMtu:(NSInteger)mtu error:(NSError **)error;
+ (nullable NSArray<NSData *> *)chunkPrintData:(NSData *)data maxPacketLength:(NSInteger)maxPacketLength error:(NSError **)error;
@end
@interface EMAPIPrinterInfo : NSObject
@property(nonatomic, copy, nullable) NSString *deviceType;
@property(nonatomic, copy, nullable) NSString *deviceModel;
@property(nonatomic, copy, nullable) NSString *brand;
@property(nonatomic, copy, nullable) NSString *serialNumber;
@property(nonatomic, copy, nullable) NSString *hardwareVersion;
@property(nonatomic, copy, nullable) NSString *softwareVersion;
@property(nonatomic, copy, nullable) NSString *bootVersion;
@property(nonatomic, strong, nullable) NSNumber *mtu;
@end
@interface EMAPIRfidCardInfo : NSObject
@property(nonatomic, copy, nullable) NSString *paperModel;
@property(nonatomic, copy, nullable) NSString *paperLength;
@property(nonatomic, copy, nullable) NSString *paperWidth;
@property(nonatomic, copy, nullable) NSString *paperColor;
@property(nonatomic, copy, nullable) NSString *paperMaterialNumber;
@end
@interface EMAPIWifiHotspotInfo : NSObject
@property(nonatomic, copy, nullable) NSString *ssid;
@property(nonatomic, strong, nullable) NSNumber *rssi;
@property(nonatomic, copy, nullable) NSString *ip;
@property(nonatomic, copy, nullable) NSString *port;
@end
@interface EMAPIPrinterParams : NSObject
@property(nonatomic, strong, nullable) NSNumber *printSize;
@property(nonatomic, strong, nullable) NSNumber *resolution;
@property(nonatomic, strong, nullable) NSNumber *dotsPerByte;
@end
@interface EMAPIPrintStatus : NSObject
@property(nonatomic, strong, nullable) NSNumber *paperStatus;
@property(nonatomic, strong, nullable) NSNumber *coverStatus;
@property(nonatomic, strong, nullable) NSNumber *lowBattery;
@property(nonatomic, strong, nullable) NSNumber *overheat;
@property(nonatomic, strong, nullable) NSNumber *batteryPercent;
@property(nonatomic, strong, nullable) NSNumber *batteryVoltage;
@property(nonatomic, strong, nullable) NSNumber *tphTemperature;
@end
@interface EMAPIReport : NSObject
@property(nonatomic, strong, readonly) EMAPICommand *command;
- (instancetype)initWithCommand:(EMAPICommand *)command;
@end
@interface EMAPIPrintResultReport : EMAPIReport
@property(nonatomic, assign) uint8_t result;
@end
@interface EMAPIPrinterStatusReport : EMAPIReport
@property(nonatomic, strong, nullable) NSNumber *paperStatus;
@property(nonatomic, strong, nullable) NSNumber *coverStatus;
@property(nonatomic, strong, nullable) NSNumber *batteryState;
@property(nonatomic, strong, nullable) NSNumber *overheat;
@property(nonatomic, strong, nullable) NSNumber *nfcPaperRecognition;
@end
@interface EMAPIFlowControlReport : EMAPIReport
@property(nonatomic, assign) uint8_t state;
- (BOOL)isBusy;
@end
@interface EMAPIUpgradeStatusReport : EMAPIReport
@property(nonatomic, assign) uint8_t status;
@end
@interface EMAPIBluetoothConnectionReport : EMAPIReport
@property(nonatomic, assign) uint8_t state;
@end
@interface EMAPIWifiConfigStatusReport : EMAPIReport
@property(nonatomic, copy, nullable) NSString *ssid;
@property(nonatomic, strong, nullable) NSNumber *state;
@end
@interface EMAPIUnknownReport : EMAPIReport
@end
@interface EMAPISession : NSObject
- (instancetype)initWithConnection:(id<EMAPIConnection>)connection timeout:(NSTimeInterval)timeout maxRetries:(NSInteger)maxRetries;
@property(nonatomic, copy, nullable) EMAPIReportHandler reportHandler;
- (nullable EMAPICommand *)sendCommand:(EMAPICommand *)command expected:(EMAPIResponseMatcher)expected error:(NSError **)error;
- (nullable EMAPIReport *)readNextReportWithError:(NSError **)error;
@end
@interface EMAPIPrinter : NSObject
- (instancetype)initWithConnection:(id<EMAPIConnection>)connection timeout:(NSTimeInterval)timeout maxRetries:(NSInteger)maxRetries mtu:(nullable NSNumber *)mtu fallbackMtu:(NSInteger)fallbackMtu;
+ (instancetype)printerWithConnectedDevice:(id)connectedDevice timeout:(NSTimeInterval)timeout maxRetries:(NSInteger)maxRetries mtu:(nullable NSNumber *)mtu fallbackMtu:(NSInteger)fallbackMtu;
@property(nonatomic, copy, nullable) EMAPIReportHandler reportHandler;
- (nullable EMAPIPrinterInfo *)queryDeviceInfoWithError:(NSError **)error;
- (BOOL)sleepShutdownWithError:(NSError **)error;
- (BOOL)setShutdownTimeMinutes:(NSInteger)minutes error:(NSError **)error;
- (nullable NSString *)queryRfidUidWithError:(NSError **)error;
- (nullable EMAPIRfidCardInfo *)queryRfidCardInfoWithError:(NSError **)error;
- (nullable NSNumber *)queryRfidPaperLengthWithError:(NSError **)error;
- (BOOL)setRfidAuthFailureHandling:(EMAPIRfidAuthFailurePolicy)policy error:(NSError **)error;
- (BOOL)setWifiConfigWithSsid:(NSString *)ssid password:(NSString *)password encryptionMethod:(nullable NSNumber *)encryptionMethod error:(NSError **)error;
- (EMAPIWifiConnectionState)queryWifiConnectionStateWithError:(NSError **)error;
- (nullable EMAPIWifiHotspotInfo *)queryWifiHotspotInfoWithError:(NSError **)error;
- (BOOL)startWifiFileDownloadWithFileType:(NSInteger)fileType totalSize:(uint32_t)totalSize error:(NSError **)error;
- (BOOL)transferWifiFileDownloadChunkWithIndex:(NSInteger)index data:(NSData *)data error:(NSError **)error;
- (BOOL)finishWifiFileDownloadWithError:(NSError **)error;
- (nullable EMAPIPrinterParams *)queryPrinterParamsWithError:(NSError **)error;
- (nullable EMAPIPrintStatus *)queryPrintStatusWithError:(NSError **)error;
- (BOOL)printSelfTestPageWithError:(NSError **)error;
- (BOOL)printEscData:(NSData *)data error:(NSError **)error;
- (BOOL)startMainControllerOtaWithFileType:(NSInteger)fileType totalSize:(uint32_t)totalSize error:(NSError **)error;
- (BOOL)transferMainControllerOtaChunkWithIndex:(NSInteger)index data:(NSData *)data error:(NSError **)error;
- (BOOL)finishMainControllerOtaWithError:(NSError **)error;
- (BOOL)upgradeMainControllerWithError:(NSError **)error;
@end
@interface EMAPIConnectedDeviceConnection : NSObject <EMAPIConnection>
- (instancetype)initWithConnectedDevice:(id)connectedDevice;
@end
emapi.m

完整参数、默认值与命令编码

@end
@end
@end
@end
@interface EMAPIFrameParser ()
@property(nonatomic, strong) NSMutableData *buffer;
@end
@end
@end
@interface EMAPITlvData ()
@property(nonatomic, copy) NSDictionary<NSNumber *, EMAPITlvEntry *> *entries;
- (instancetype)initWithEntries:(NSDictionary<NSNumber *, EMAPITlvEntry *> *)entries;
@end
@end
@end
@end
@end
@end
@end
@interface EMAPISession ()
@property(nonatomic, strong) id<EMAPIConnection> connection;
@property(nonatomic, assign) NSTimeInterval timeout;
@property(nonatomic, assign) NSInteger maxRetries;
@property(nonatomic, strong) EMAPIFrameParser *parser;
@property(nonatomic, strong) NSMutableArray<EMAPICommand *> *pendingCommands;
@property(nonatomic, strong) NSCondition *readCondition;
@property(nonatomic, assign) BOOL flowBusy;
@end
@end
@interface EMAPIPrinter ()
@property(nonatomic, strong) EMAPISession *session;
@property(nonatomic, strong, nullable) NSNumber *mtu;
@property(nonatomic, assign) NSInteger fallbackMtu;
@end
@end
@interface EMAPIConnectedDeviceConnection ()
@property(nonatomic, strong) id connectedDevice;
@end
@end
chunker.rs

完整参数、默认值与命令编码

pub const FILE_TRANSFER_CHUNK_HEADER_LENGTH: usize = 4;
pub const FILE_TRANSFER_PAYLOAD_ALIGNMENT: usize = 32;
pub fn print_transfer_payload_capacity(max_packet_length: usize) -> Result<usize> {
let Some(capacity) = max_packet_length.checked_sub(PRINT_TRANSFER_FRAME_OVERHEAD_LENGTH) else {
return Err(EmapiError::InvalidCapacity {
name: "print transfer payload",
});
pub fn file_transfer_payload_capacity(mtu: usize) -> Result<usize> {
let overhead = FRAME_OVERHEAD_LENGTH + COMMAND_HEADER_LENGTH + FILE_TRANSFER_CHUNK_HEADER_LENGTH;
let Some(capacity) = mtu.checked_sub(overhead) else {
return Err(EmapiError::InvalidCapacity {
name: "file transfer payload",
});
pub fn chunk_print_data(data: &[u8], max_packet_length: usize) -> Result<Vec<Vec<u8>>> {
let payload_capacity = print_transfer_payload_capacity(max_packet_length)?;
let mut chunks = Vec::new();
command.rs

完整参数、默认值与命令编码

pub struct EmapiCommand {
pub command_type: u8,
pub parent: u8,
pub child: u8,
pub payload: Vec<u8>,
pub fn new(command_type: u8, parent: u8, child: u8, payload: impl Into<Vec<u8>>) -> Self {
Self {
command_type,
parent,
child,
payload: payload.into(),
}
}
pub fn try_new(
command_type: u16,
parent: u16,
child: u16,
payload: impl Into<Vec<u8>>,
) -> Result<Self> {
pub fn is_ack_for(&self, parent: u8, child: u8) -> bool {
self.is_response_for(TYPE_RESPONSE, parent, child) && self.payload.is_empty()
}
pub fn is_response_for(&self, command_type: u8, parent: u8, child: u8) -> bool {
self.command_type == command_type && self.parent == parent && self.child == child
}
pub fn is_error(&self) -> bool {
self.command_type == TYPE_ERROR || self.command_type == TYPE_PASSTHROUGH_ERROR
}
pub fn is_protocol_error(&self) -> bool {
self.command_type == TYPE_ERROR
}
pub fn is_passthrough_error(&self) -> bool {
self.command_type == TYPE_PASSTHROUGH_ERROR
}
}
fn check_byte(value: u16, name: &'static str) -> Result<u8> {
connection.rs

完整参数、默认值与命令编码

pub struct ScriptedEmapiConnection {
pub fn new(responses: Vec<Option<Vec<u8>>>) -> Self {
Self {
state: Arc::new(Mutex::new(ScriptedEmapiConnectionState {
responses: responses.into(),
writes: Vec::new(),
reads: 0,
})),
}
}
pub fn writes(&self) -> Vec<Vec<u8>> {
self.state.lock().unwrap().writes.clone()
}
pub fn reads(&self) -> usize {
self.state.lock().unwrap().reads
}
}
impl EmapiConnection for ScriptedEmapiConnection {
fn write(&mut self, data: &[u8]) -> Result<()> {
constants.rs

完整参数、默认值与命令编码

pub const FRAME_HEAD: u8 = 0x02;
pub const FRAME_TAIL: u8 = 0x03;
pub const RESERVED: u8 = 0x00;
pub const TYPE_REQUEST: u8 = 0x01;
pub const TYPE_RESPONSE: u8 = 0x02;
pub const TYPE_ERROR: u8 = 0x03;
pub const TYPE_PASSTHROUGH_REQUEST: u8 = 0x41;
pub const TYPE_PASSTHROUGH_RESPONSE: u8 = 0x42;
pub const TYPE_PASSTHROUGH_ERROR: u8 = 0x43;
pub const PARENT_SYSTEM: u8 = 0x01;
pub const PARENT_PRINTER: u8 = 0x02;
pub const PARENT_RFID: u8 = 0x05;
pub const PARENT_WIFI: u8 = 0x06;
pub const PARENT_REPORT: u8 = 0x09;
pub const PARENT_FILE: u8 = 0x0A;
pub const CHILD_DEVICE_INFO: u8 = 0x01;
pub const CHILD_SLEEP_SHUTDOWN: u8 = 0x04;
pub const CHILD_SET_SHUTDOWN_TIME: u8 = 0x05;
pub const CHILD_RFID_UID: u8 = 0x01;
pub const CHILD_RFID_CARD_INFO: u8 = 0x02;
pub const CHILD_RFID_PAPER_LENGTH: u8 = 0x03;
pub const CHILD_RFID_AUTH_FAILURE_HANDLING: u8 = 0x04;
pub const CHILD_WIFI_CONFIG: u8 = 0x01;
pub const CHILD_WIFI_CONNECTION_STATE: u8 = 0x02;
pub const CHILD_WIFI_HOTSPOT_INFO: u8 = 0x03;
pub const CHILD_WIFI_CONFIG_STATUS: u8 = 0x04;
pub const CHILD_WIFI_FILE_START: u8 = 0x05;
pub const CHILD_WIFI_FILE_TRANSFER: u8 = 0x06;
pub const CHILD_WIFI_FILE_END: u8 = 0x07;
pub const CHILD_PRINTER_PARAMS: u8 = 0x01;
pub const CHILD_PRINT_STATUS: u8 = 0x04;
pub const CHILD_TRANSFER_DATA: u8 = 0x06;
pub const CHILD_PRINT_SELF_TEST_PAGE: u8 = 0x0C;
pub const CHILD_REPORT_PRINT_RESULT: u8 = 0x01;
pub const CHILD_REPORT_PRINTER_STATUS: u8 = 0x02;
pub const CHILD_REPORT_FLOW_CONTROL: u8 = 0x03;
pub const CHILD_REPORT_UPGRADE_STATUS: u8 = 0x04;
pub const CHILD_REPORT_BLUETOOTH_CONNECTION: u8 = 0x05;
pub const CHILD_FILE_START: u8 = 0x01;
pub const CHILD_FILE_TRANSFER: u8 = 0x02;
pub const CHILD_FILE_END: u8 = 0x03;
pub const CHILD_FILE_UPGRADE: u8 = 0x04;
pub const TAG_MTU: u8 = 0x08;
pub const COMMAND_HEADER_LENGTH: usize = 5;
pub const FRAME_OVERHEAD_LENGTH: usize = 9;
pub const PRINT_TRANSFER_FRAME_OVERHEAD_LENGTH: usize =
pub const CRC_SEED: u32 = 0x35769521;
crc32.rs

完整参数、默认值与命令编码

const TABLE: [u32; 256] = [
pub fn compute(data: &[u8]) -> u32 {
compute_with_seed(data, CRC_SEED)
}
pub fn compute_with_seed(data: &[u8], seed: u32) -> u32 {
let mut crc = seed ^ 0xFFFF_FFFF;
for byte in data {
crc = TABLE[((crc ^ u32::from(*byte)) & 0xFF) as usize] ^ (crc >> 8);
device_connection.rs

完整参数、默认值与命令编码

pub struct ConnectedDeviceEmapiConnection<D> {
pub fn new(device: D) -> Self {
Self { device }
}
pub fn write(&mut self, data: &[u8]) -> Result<()> {
EmapiConnection::write(self, data)
}
pub fn read(&mut self, timeout: Duration) -> Result<Vec<u8>> {
EmapiConnection::read(self, timeout)
}
pub fn into_inner(self) -> D {
self.device
}
}
impl<D> EmapiConnection for ConnectedDeviceEmapiConnection<D>
where
D: ConnectedDevice,
{
fn write(&mut self, data: &[u8]) -> Result<()> {
endian.rs

完整参数、默认值与命令编码

pub fn read_uint16(data: &[u8], offset: usize) -> Result<u16> {
check_range(data, offset, 2)?;
Ok(u16::from_le_bytes([data[offset], data[offset + 1]]))
}
pub fn read_int16(data: &[u8], offset: usize) -> Result<i16> {
Ok(read_uint16(data, offset)? as i16)
}
pub fn read_uint32(data: &[u8], offset: usize) -> Result<u32> {
check_range(data, offset, 4)?;
Ok(u32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]))
}
pub fn uint16(value: u16) -> [u8; 2] {
value.to_le_bytes()
}
pub fn uint32(value: u32) -> [u8; 4] {
value.to_le_bytes()
}
pub fn write_uint16(data: &mut [u8], offset: usize, value: u16) -> Result<()> {
check_range(data, offset, 2)?;
data[offset..offset + 2].copy_from_slice(&uint16(value));
pub fn write_uint32(data: &mut [u8], offset: usize, value: u32) -> Result<()> {
check_range(data, offset, 4)?;
data[offset..offset + 4].copy_from_slice(&uint32(value));
error.rs

完整参数、默认值与命令编码

pub type Result<T> = std::result::Result<T, EmapiError>;
pub enum EmapiError {
frame_codec.rs

完整参数、默认值与命令编码

pub struct FrameCodec;
pub fn encode(command: &EmapiCommand) -> Result<Vec<u8>> {
let data_length = COMMAND_HEADER_LENGTH + command.payload.len();
pub fn decode(frame: &[u8]) -> Result<EmapiCommand> {
if frame.len() < FRAME_OVERHEAD_LENGTH {
return Err(EmapiError::FrameTooShort);
frame_parser.rs

完整参数、默认值与命令编码

pub struct FrameParser {
pub fn new() -> Self {
Self::default()
}
pub fn add(&mut self, data: &[u8]) -> Result<Vec<EmapiCommand>> {
self.buffer.extend_from_slice(data);
lib.rs

完整参数、默认值与命令编码

models.rs

完整参数、默认值与命令编码

pub enum EmapiRfidAuthFailurePolicy {
pub enum EmapiWifiConnectionState {
pub struct EmapiRfidCardInfo {
pub paper_model: Option<String>,
pub paper_length: Option<String>,
pub paper_width: Option<String>,
pub paper_color: Option<String>,
pub paper_material_number: Option<String>,
pub struct EmapiWifiHotspotInfo {
pub ssid: Option<String>,
pub rssi: Option<i16>,
pub ip: Option<String>,
pub port: Option<String>,
pub struct EmapiPrinterParams {
pub print_size: Option<u32>,
pub resolution: Option<u32>,
pub dots_per_byte: Option<u32>,
pub struct EmapiPrintStatus {
pub paper_status: Option<u8>,
pub cover_status: Option<u8>,
pub low_battery: Option<u8>,
pub overheat: Option<u8>,
pub battery_percent: Option<u8>,
pub battery_voltage: Option<u16>,
pub tph_temperature: Option<i8>,
pub enum EmapiReport {
pub fn command(&self) -> &EmapiCommand {
match self {
Self::PrintResult { command, .. }
| Self::PrinterStatus { command, .. }
| Self::FlowControl { command, .. }
| Self::UpgradeStatus { command, .. }
| Self::BluetoothConnection { command, .. }
| Self::WifiConfigStatus { command, .. }
| Self::Unknown { command } => command,
}
}
pub fn is_flow_busy(&self) -> bool {
matches!(self, Self::FlowControl { state: 1, .. })
}
}
payload.rs

完整参数、默认值与命令编码

pub struct EmapiPayload;
pub fn uint8(value: u8) -> Vec<u8> {
vec![value]
}
pub fn uint16(value: u16) -> Vec<u8> {
uint16(value).to_vec()
}
pub fn uint32(value: u32) -> Vec<u8> {
uint32(value).to_vec()
}
pub fn read_uint32(data: &[u8]) -> Result<u32> {
if data.len() != 4 {
return Err(EmapiError::Range {
name: "data.length",
min: 4,
max: 4,
value: data.len() as u64,
});
pub fn file_chunk(index: u32, data: &[u8]) -> Result<Vec<u8>> {
if index < 1 || index > u32::from(u16::MAX) {
printer.rs

完整参数、默认值与命令编码

pub struct EmapiPrinter<C> {
pub fn new(connection: C) -> Self {
Self {
session: EmapiSession::new(connection),
fallback_mtu: 512,
mtu: None,
}
}
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.session.set_timeout(timeout);
pub fn with_max_retries(mut self, max_retries: usize) -> Result<Self> {
self.session.set_max_retries(max_retries);
pub fn with_mtu(mut self, mtu: usize) -> Result<Self> {
if mtu == 0 {
return Err(EmapiError::Protocol {
message: "mtu must be greater than zero".to_string(),
});
pub fn with_fallback_mtu(mut self, fallback_mtu: usize) -> Result<Self> {
if fallback_mtu == 0 {
return Err(EmapiError::Protocol {
message: "fallbackMtu must be greater than zero".to_string(),
});
pub fn reports(&self) -> &[EmapiReport] {
self.session.reports()
}
pub fn read_report(&mut self) -> Result<EmapiReport> {
self.session.read_report()
}
pub fn into_inner(self) -> C {
self.session.into_inner()
}
pub fn query_device_info(&mut self) -> Result<EmapiPrinterInfo> {
let response = self.send_command(
TYPE_REQUEST,
TYPE_RESPONSE,
PARENT_SYSTEM,
CHILD_DEVICE_INFO,
Vec::new(),
false,
)?;
let tlv = Tlv::decode(&response.payload)?;
let info = EmapiPrinterInfo {
device_type: tlv.string(0x01)?,
device_model: tlv.string(0x02)?,
brand: tlv.string(0x03)?,
serial_number: tlv.string(0x04)?,
hardware_version: tlv.string(0x05)?,
software_version: tlv.string(0x06)?,
boot_version: tlv.string(0x07)?,
mtu: tlv.uint16(TAG_MTU)?,
};
if let Some(mtu) = info.mtu {
self.mtu = Some(usize::from(mtu));
pub fn sleep_shutdown(&mut self) -> Result<()> {
self.send_acked(
TYPE_REQUEST,
TYPE_RESPONSE,
PARENT_SYSTEM,
CHILD_SLEEP_SHUTDOWN,
[],
)
}
pub fn set_shutdown_time(&mut self, minutes: u16) -> Result<()> {
self.send_acked(
TYPE_REQUEST,
TYPE_RESPONSE,
PARENT_SYSTEM,
CHILD_SET_SHUTDOWN_TIME,
EmapiPayload::uint16(minutes),
)
}
pub fn query_rfid_uid(&mut self) -> Result<String> {
let response = self.send_command(
TYPE_REQUEST,
TYPE_RESPONSE,
PARENT_RFID,
CHILD_RFID_UID,
Vec::new(),
false,
)?;
String::from_utf8(response.payload).map_err(|_| EmapiError::InvalidUtf8)
}
pub fn query_rfid_card_info(&mut self) -> Result<EmapiRfidCardInfo> {
let response = self.send_command(
TYPE_REQUEST,
TYPE_RESPONSE,
PARENT_RFID,
CHILD_RFID_CARD_INFO,
Vec::new(),
false,
)?;
let tlv = Tlv::decode(&response.payload)?;
Ok(EmapiRfidCardInfo {
paper_model: tlv.string(0x01)?,
paper_length: tlv.string(0x02)?,
paper_width: tlv.string(0x03)?,
paper_color: tlv.string(0x04)?,
paper_material_number: tlv.string(0x05)?,
})
}
pub fn query_rfid_paper_length(&mut self) -> Result<u32> {
let response = self.send_command(
TYPE_REQUEST,
TYPE_RESPONSE,
PARENT_RFID,
CHILD_RFID_PAPER_LENGTH,
Vec::new(),
false,
)?;
EmapiPayload::read_uint32(&response.payload)
}
pub fn set_rfid_auth_failure_handling(
&mut self,
policy: EmapiRfidAuthFailurePolicy,
) -> Result<()> {
pub fn set_wifi_config(
&mut self,
ssid: &str,
password: &str,
encryption_method: Option<u8>,
) -> Result<()> {
pub fn query_wifi_connection_state(&mut self) -> Result<EmapiWifiConnectionState> {
let response = self.send_command(
TYPE_PASSTHROUGH_REQUEST,
TYPE_PASSTHROUGH_RESPONSE,
PARENT_WIFI,
CHILD_WIFI_CONNECTION_STATE,
Vec::new(),
false,
)?;
match response.payload.first().copied() {
pub fn query_wifi_hotspot_info(&mut self) -> Result<EmapiWifiHotspotInfo> {
let response = self.send_command(
TYPE_PASSTHROUGH_REQUEST,
TYPE_PASSTHROUGH_RESPONSE,
PARENT_WIFI,
CHILD_WIFI_HOTSPOT_INFO,
Vec::new(),
false,
)?;
let tlv = Tlv::decode(&response.payload)?;
Ok(EmapiWifiHotspotInfo {
ssid: tlv.string(0x01)?,
rssi: tlv_int16(&tlv, 0x02)?,
ip: tlv.string(0x03)?,
port: tlv.string(0x04)?,
})
}
pub fn start_wifi_file_download(&mut self, file_type: u16, total_size: u32) -> Result<()> {
self.send_acked(
TYPE_PASSTHROUGH_REQUEST,
TYPE_PASSTHROUGH_RESPONSE,
PARENT_WIFI,
CHILD_WIFI_FILE_START,
file_start_payload(file_type, total_size)?,
)
}
pub fn transfer_wifi_file_download_chunk(&mut self, index: u32, data: &[u8]) -> Result<()> {
self.validate_file_transfer_chunk(data)?;
self.send_acked(
TYPE_PASSTHROUGH_REQUEST,
TYPE_PASSTHROUGH_RESPONSE,
PARENT_WIFI,
CHILD_WIFI_FILE_TRANSFER,
EmapiPayload::file_chunk(index, data)?,
)
}
pub fn finish_wifi_file_download(&mut self) -> Result<()> {
self.send_acked(
TYPE_PASSTHROUGH_REQUEST,
TYPE_PASSTHROUGH_RESPONSE,
PARENT_WIFI,
CHILD_WIFI_FILE_END,
[],
)
}
pub fn query_printer_params(&mut self) -> Result<EmapiPrinterParams> {
let response = self.send_command(
TYPE_REQUEST,
TYPE_RESPONSE,
PARENT_PRINTER,
CHILD_PRINTER_PARAMS,
Vec::new(),
false,
)?;
let tlv = Tlv::decode(&response.payload)?;
Ok(EmapiPrinterParams {
print_size: tlv.uint32(0x01)?,
resolution: tlv.uint32(0x02)?,
dots_per_byte: tlv.uint32(0x03)?,
})
}
pub fn query_print_status(&mut self) -> Result<EmapiPrintStatus> {
let response = self.send_command(
TYPE_REQUEST,
TYPE_RESPONSE,
PARENT_PRINTER,
CHILD_PRINT_STATUS,
Vec::new(),
false,
)?;
let tlv = Tlv::decode(&response.payload)?;
Ok(EmapiPrintStatus {
paper_status: tlv.uint8(0x01)?,
cover_status: tlv.uint8(0x02)?,
low_battery: tlv.uint8(0x03)?,
overheat: tlv.uint8(0x04)?,
battery_percent: tlv.uint8(0x05)?,
battery_voltage: tlv.uint16(0x06)?,
tph_temperature: tlv.uint8(0x07)?.map(|value| value as i8),
})
}
pub fn print_self_test_page(&mut self) -> Result<()> {
self.send_acked(
TYPE_REQUEST,
TYPE_RESPONSE,
PARENT_PRINTER,
CHILD_PRINT_SELF_TEST_PAGE,
[],
)
}
pub fn start_main_controller_ota(&mut self, file_type: u16, total_size: u32) -> Result<()> {
self.send_acked(
TYPE_REQUEST,
TYPE_RESPONSE,
PARENT_FILE,
CHILD_FILE_START,
file_start_payload(file_type, total_size)?,
)
}
pub fn start_main_controller_ota_default(&mut self, total_size: u32) -> Result<()> {
self.start_main_controller_ota(0x0001, total_size)
}
pub fn transfer_main_controller_ota_chunk(&mut self, index: u32, data: &[u8]) -> Result<()> {
self.validate_file_transfer_chunk(data)?;
self.send_acked(
TYPE_REQUEST,
TYPE_RESPONSE,
PARENT_FILE,
CHILD_FILE_TRANSFER,
EmapiPayload::file_chunk(index, data)?,
)
}
pub fn finish_main_controller_ota(&mut self) -> Result<()> {
self.send_acked(TYPE_REQUEST, TYPE_RESPONSE, PARENT_FILE, CHILD_FILE_END, [])
}
pub fn upgrade_main_controller(&mut self) -> Result<()> {
self.send_acked(
TYPE_REQUEST,
TYPE_RESPONSE,
PARENT_FILE,
CHILD_FILE_UPGRADE,
[],
)
}
pub fn print_esc(&mut self, data: &[u8]) -> Result<()> {
let mtu = self.ensure_mtu()?;
print_transfer_payload_capacity(mtu).map_err(|_| EmapiError::Protocol {
message: format!("invalid max packet length for print transfer: {mtu}"),
})?;
for chunk in chunk_print_data(data, mtu)? {
self.session.send_and_wait_with_max_retries(
EmapiCommand::new(TYPE_REQUEST, PARENT_PRINTER, CHILD_TRANSFER_DATA, chunk),
|command| command.is_ack_for(PARENT_PRINTER, CHILD_TRANSFER_DATA),
0,
)?;
}
Ok(())
}
fn ensure_mtu(&mut self) -> Result<usize> {
pub fn connected_device(device: D) -> Self {
EmapiPrinter::new(ConnectedDeviceEmapiConnection::new(device))
}
}
fn file_start_payload(file_type: u16, total_size: u32) -> Result<Vec<u8>> {
printer_info.rs

完整参数、默认值与命令编码

pub struct EmapiPrinterInfo {
pub device_type: Option<String>,
pub device_model: Option<String>,
pub brand: Option<String>,
pub serial_number: Option<String>,
pub hardware_version: Option<String>,
pub software_version: Option<String>,
pub boot_version: Option<String>,
pub mtu: Option<u16>,
session.rs

完整参数、默认值与命令编码

pub struct EmapiSession<C> {
pub fn new(connection: C) -> Self {
Self {
connection,
timeout: Duration::from_secs(2),
max_retries: 3,
parser: FrameParser::new(),
pending_commands: VecDeque::new(),
reports: Vec::new(),
flow_busy: false,
}
}
pub fn with_timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn set_timeout(&mut self, timeout: Duration) {
pub fn with_max_retries(mut self, max_retries: usize) -> Result<Self> {
self.max_retries = max_retries;
Ok(self)
}
pub fn set_max_retries(&mut self, max_retries: usize) {
pub fn reports(&self) -> &[EmapiReport] {
&self.reports
}
pub fn read_report(&mut self) -> Result<EmapiReport> {
let start = Instant::now();
pub fn into_inner(self) -> C {
self.connection
}
pub fn send_and_wait<F>(&mut self, command: EmapiCommand, expected: F) -> Result<EmapiCommand>
where
F: Fn(&EmapiCommand) -> bool,
pub fn send_and_wait_with_max_retries<F>(
&mut self,
command: EmapiCommand,
expected: F,
max_retries: usize,
) -> Result<EmapiCommand>
tlv.rs

完整参数、默认值与命令编码

pub struct TlvEntry {
pub tag: u8,
pub value: Vec<u8>,
pub fn new(tag: u8, value: impl Into<Vec<u8>>) -> Self {
Self {
tag,
value: value.into(),
}
}
pub fn try_new(tag: u16, value: impl Into<Vec<u8>>) -> Result<Self> {
if tag > 0xFF {
return Err(EmapiError::Range {
name: "tag",
min: 0,
max: 0xFF,
value: u64::from(tag),
});
pub fn uint8(tag: u8, value: u8) -> Result<Self> {
Ok(Self::new(tag, [value]))
}
pub fn uint16(tag: u8, value: u16) -> Result<Self> {
Ok(Self::new(tag, uint16(value)))
}
pub fn uint32(tag: u8, value: u32) -> Result<Self> {
Ok(Self::new(tag, uint32(value)))
}
pub fn string(tag: u8, value: &str) -> Result<Self> {
let mut bytes = value.as_bytes().to_vec();
pub struct TlvData {
pub fn get(&self, tag: u8) -> Option<&TlvEntry> {
self.entries.get(&tag)
}
pub fn contains_tag(&self, tag: u8) -> bool {
self.entries.contains_key(&tag)
}
pub fn uint8(&self, tag: u8) -> Result<Option<u8>> {
let Some(value) = self.value(tag) else {
return Ok(None);
pub fn uint16(&self, tag: u8) -> Result<Option<u16>> {
let Some(value) = self.value(tag) else {
return Ok(None);
pub fn uint32(&self, tag: u8) -> Result<Option<u32>> {
let Some(value) = self.value(tag) else {
return Ok(None);
pub fn string(&self, tag: u8) -> Result<Option<String>> {
let Some(value) = self.value(tag) else {
return Ok(None);
pub struct Tlv;
pub fn encode(entries: &[TlvEntry]) -> Result<Vec<u8>> {
let mut result = Vec::new();
pub fn decode(data: &[u8]) -> Result<TlvData> {
let mut entries = BTreeMap::new();