You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic-Angular中Capacitor社区Bluetooth-LE插件蓝牙LE连接问题

Capacitor Bluetooth-LE 实现ESC-POS蓝牙打印机连接打印故障排查

我尝试借助Capacitor社区的Bluetooth-LE插件实现ESC-POS蓝牙打印机的连接与打印功能,编写了如下打印服务代码,但无法正常工作,希望得到帮助解决问题。

import { Injectable } from '@angular/core';
import { CommonService } from './common.service';
import ThermalPrinterEncoder from 'thermal-printer-encoder';
import { BleClient, numbersToDataView, numberToUUID } from '@capacitor-community/bluetooth-le';

@Injectable({
  providedIn: 'root'
})
export class PrinterService {

  private PRINTER_SERVICE_UUID!:string;
  private PRINTER_CHARACTERISTIC_UUID!:string;
  private PRINTER_MAC:string = 'DC:0D:30:B7:90:F0'; //Printer BT Address

  private encoder = new ThermalPrinterEncoder({
    language: 'esc-pos',
    width: 58,
    wordWrap: true
  });


  constructor(
    private common: CommonService,
  ) {}

  async printTest() {
    try {
      let img = new Image();
      img.src = 'assets/img/logo.png';

      const result = this.encoder.initialize();

      result
        .text('This is a print test')
        .newline()
        .text('Do not mind what you are seeing')
        .newline()
        .cut('full');

      const resultByte = result.encode();

      await BleClient.initialize();

      // Get the device using the MAC address
      const devices = await BleClient.getDevices();
      const device = devices.find((dev) => dev.address === this.PRINTER_MAC);

      if (!device) {
        this.common.showToast('Printer not found.','danger');
        return;
      }

      // Connect to the printer
      await BleClient.connect(device.deviceId, (deviceId) => onDisconnect(deviceId));
      this.common.showToast('Connected to printer: '+ device,'success');

      // Send print commands to the printer
      await BleClient.write(device.deviceId, this.PRINTER_SERVICE_UUID, this.PRINTER_CHARACTERISTIC_UUID, resultByte);
      this.common.showToast('Print successful!','success');

      // Disconnect from the printer
      await BleClient.disconnect(device.deviceId);
      this.common.showToast('Disconnected from printer: '+ device,'danger');
    } catch (error:any) {
      this.common.showToast('Error printing to the printer: ' + error,'danger');
    }
  }
}

核心问题排查与修复建议

  • 未初始化服务/特征UUID:代码中PRINTER_SERVICE_UUID和PRINTER_CHARACTERISTIC_UUID仅声明未赋值,多数ESC-POS蓝牙打印机使用标准UUID,可先尝试赋值:

    private PRINTER_SERVICE_UUID = '0000ffe0-0000-1000-8000-00805f9b34fb';
    private PRINTER_CHARACTERISTIC_UUID = '0000ffe1-0000-1000-8000-00805f9b34fb';
    

    若打印机使用自定义UUID,需通过discoverServices接口获取设备实际的服务和特征值。

  • 设备获取逻辑错误:BleClient.getDevices()仅返回已配对或连接过的设备,若打印机未配对,需替换为主动扫描设备的逻辑:

    const device = await BleClient.requestDevice({
      services: [this.PRINTER_SERVICE_UUID],
      optionalServices: []
    });
    
  • 断开回调函数未定义:connect方法中传入的onDisconnect函数未实现,需补充定义:

    const onDisconnect = (deviceId: string) => {
      this.common.showToast('打印机已断开连接', 'danger');
    };
    
  • 数据格式不兼容:BleClient.write要求传入DataView类型数据,需将编码后的字节数组转换为对应格式:

    const dataView = numbersToDataView(resultByte);
    await BleClient.write(device.deviceId, this.PRINTER_SERVICE_UUID, this.PRINTER_CHARACTERISTIC_UUID, dataView);
    
  • 连接后需发现服务:连接设备后需先调用discoverServices确认目标服务和特征存在,避免使用无效UUID:

    await BleClient.connect(device.deviceId, onDisconnect);
    const services = await BleClient.discoverServices(device.deviceId);
    console.log('设备服务列表:', services); // 打印确认目标服务是否存在
    
  • 图片加载未处理异步:若后续需要打印图片,需等待图片加载完成再执行编码逻辑:

    await new Promise((resolve, reject) => {
      img.onload = resolve;
      img.onerror = reject;
    });
    result.image(img); // 新增图片打印逻辑
    

内容的提问来源于stack exchange,提问作者Kelly O'blair

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 11:17:50