Issue with Bluetooth LE Connection in Ionic-Angular with Capacitor-community Bluetooth-LE plugin

157 views Asked by At

I need help connecting an ESC-POS bluetooth printer using this plugin.

Here's my print service code:

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');
    }
  }
}

The above code is what I have tried but does seem to work.

I have already asked the question here, but I am yet to get any response.

0

There are 0 answers