npm package: @captureid/capacitor5-cidrfid
Description: CaptureID RFID Reader Plugin
Author: Uwe Hoppe
Latest version: 0.0.43

[![appcenterbanner](https://captureid.de/wp-content/uploads/2020/03/capID.png)](https://www.captureid.de/)

# Ionic Capacitor Plugin for Mobile Print

This plugin provides the ability to use the CaptureID Printer Library to easily integrate Bluetooth printing into your app(s).

<!-- Capacitor Catalog -->

* [Requirements](#requirements)
* [How does it work?](#how-does-it-work)
* [Getting Started](#getting-started)
* [Plugin Usage](#plugin-usage)
* [API Reference](#api-reference)
* [Sample Code](#sample-code)

<!-- Capacitor Catalog -->

## Requirements

The CaptureID Printer plugin expires after a 3 month evaluation period.
After this period you must request a valid license key. This license must be purchased separatly and is not included in this package. For additional Information of the CaptureID Licensing and how to get access to a valid license Key visit our Website under ([https://www.captureid.de](https://www.captureid.de)). 

## How does it work?

The CaptureID Printer Plugin can be used in Ionic Capacitor app's to support label printing on SATO mobile Printers (MB200i, PW208nx).
It enables you to easily scan for SATO Bluetooth Printers, connect to an selected printer or the last connected printer.

## Getting Started

Install the plugin into your existing project by running the command

```shell
npm install capacitor-cidprint@latest
```
run the build command to integrate the plugin code and it's libraries into your android project and to open the project in Android Studio

```javascript
ionic capacitor run android
``` 

insert the line "add(CIDPrint.class);" into the app's main activity file.

```java
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Initializes the Bridge
    this.init(savedInstanceState, new ArrayList<Class<? extends Plugin>>() {{
      // Additional plugins you've installed go here
      // Ex: add(TotallyAwesomePlugin.class);
      add(CIDPrint.class);
    }});
  }

```

## Plugin Usage

With the CaptureID Printer plugin installed and configured, the only thing left is to add the necessary code to your app.

1. Call the provided functions and add the callbacks.

2. Some methods return a promise.

3. The method "discoverDevices" calls the Discover Listener, You can register the listener by adding the Listener Callback method with the Plugins.CIDPrint.addListener(ListenerTypes.DISCOVER, (result: any) => {
    let data: PrinterEvent = result.result[0];}); command.
4. the result contains Result Type of PrinterEvent. The PrinterEvent structure
    consist of the following fields:
    
    - __type__: PrinterEventType;
    - __status__: PrinterStatusType;
    - __message__: string;
    - __error__: number;
    - __device__: Device;
    - __devices__: Device[];
    - __action__: PrinterActionType;

## API Reference

- __initCIDPrinterLib()__: Promise<{}>;
- __closeCIDPrinterLib()__: Promise<{}>;
- __activateLicense(options: { productKey: string; })__: Promise<{value: string;}>;
- __enableBluetoothPrinting(options: { enable: boolean; })__: Promise<{value: string;}>;
- __getPairedDevices()__: Promise<{}>;
- __discoverDevices()__: void;
- __connectToPreferredPrinter(options: { mac: string; })__: Promise<{value: string;}>;
- __printData(options: { data: string; })__: Promise<{data: string;}>;
- __printLabelWithData(options: { label: string; data: string[]; })__: Promise<{value: string;}>;
- __printLabel(options: { label: string; })__: Promise<{value: string;}>;

### initCIDPrinterLib

```javascript
await initCIDPrinterLib();
```
Version 0.1.0
Parameters:

- __none__

### closeCIDPrinterLib

```javascript
await closeCIDPrinterLib();
```
Version 0.1.0
Parameters:

- __none__

### activateLicense

```javascript
await activateLicense(key: string, customer: string);
```
Version 0.1.0
Parameters:

- __key__ *(string)* - valid Licensekey.

- __customer__ *(string)* - valid CustomerId.

### enableBluetoothPrinting

```javascript
await enableBluetoothPrinting(enable: boolean);
```
Version 1.0.0
Parameters:

- __enable__ *(boolean)* - Enables/disables the Printing via  Bluetooth.

### getPairedDevices

```javascript
getPairedDevices();
```
Version 0.1.0

Parameters:

- __none__
- 
### discoverDevices

```javascript
discoverDevices();
```
Version 0.1.0

Parameters:

- __none__

### printData

```javascript
printData(data: string);
```
Version 0.1.0

Parameters:

- __data__ *(string)* - data to be printed.

### printLabelWithData

```javascript
printLabelWithData(label: string, data: string[]);
```
Version 0.1.0

Parameters:

- __label__: path and filename of the label template file relative to the android project assets folder.

- __data[]__: array of strings representing a value for each placeholder (count and length of the array and the contained strings must match the variables in the label template)

### printLabel

```javascript
printLabel(label: String);
```
Version 0.1.0

Parameters:

- __label__: path and filename of the label template file relative to the android project assets folder.

### connectToPreferredPrinter

```javascript
connectToPreferredPrinter(mac: string);
```
Version 0.1.0

Parameters:

- __mac__: Bluetooth Mac Address of the printer to connect or an empty string. If an empty string is provided a connection to the last connected printer is established.

## Sample Code

### Discover printers

```hint
For the sample code to work it is required to call initCIDPrinter and enableBlutoothPrinting.
```

Register the callback method for the discover procedure

```javascript
  discoverListener = Plugins.CIDPrint.addListener(ListenerTypes.DISCOVER, (result: any) => {
    let data: PrinterEvent = result.result[0];
    if(data.action === PrinterActionType.LIST_PRINTER) {
      this.setState({ devmac: data.device.devicemac, devname: data.device.devicename });
    } else if(data.action === PrinterActionType.LIST_PRINTERS) {
      this.setState({ devices: data.devices });
    }
  });
  
  discover() {
    CIDPrint.discoverDevices();
  }

```

call discover to start the Blutooth Discover procedure.

if a mobile SATO Bluetooth printer is detected the listener is invoked with a PrinterActionType of LIST_PRINTER and the Printers Mac Address and Device Name in the device field of the PrinterEvent Structure.

On finish Discover process the callback method is invoked with a LIST_PRINTERS PrinterActionType and a list of all dicovered SATO Printers is available in the devices field of the PrinterEvent Structure.


complete source code

```javascript
import { IonButton, IonContent, IonHeader, IonItem, IonList, IonPage, IonText, IonTitle, IonToolbar } from '@ionic/react';
import { Plugins } from '@capacitor/core';
import React, { Component } from 'react';
import ExploreContainer from '../components/ExploreContainer';
import './Home.css';
import 'capacitor-cidprint';
import { Device, ListenerTypes, PrinterActionType, PrinterEvent } from 'capacitor-cidprint';
import { useLocation } from 'react-router';
import { convertCompilerOptionsFromJson } from 'typescript';

const { CIDPrint } = Plugins;

export class Home extends Component {
  state = {
    enabled: false,
    connected: false,
    devname: '',
    devmac: '',
    devices: Array<Device>()
  }
  constructor(props: any) {
    super(props);
    this.state = { enabled: false, connected: false, devname: '', devmac: '', devices: [] };
  }

  discoverListener = Plugins.CIDPrint.addListener(ListenerTypes.DISCOVER, (result: any) => {
    let data: PrinterEvent = result.result[0];
    if(data.action === PrinterActionType.LIST_PRINTER) {
      this.setState({ devmac: data.device.devicemac, devname: data.device.devicename });
    } else if(data.action === PrinterActionType.LIST_PRINTERS) {
      this.setState({ devices: data.devices });
    }
  });

  printListener = Plugins.CIDPrint.addListener(ListenerTypes.PRINT, (result: any) => {
    let data: PrinterEvent = result.result[0];
    if(data.action === PrinterActionType.LIST_PRINTER) {
      this.setState({ devmac: data.device.devicemac, devname: data.device.devicename });
    } else if(data.action === PrinterActionType.LIST_PRINTERS) {
      if(data.devices.length > 0) {
        this.setState({ devmac: data.devices[0].devicemac, devname: data.devices[0].devicename });
      }
    }
  });

  async init() {
    await CIDPrint.initCIDPrinterLib();
  }

  async enableBluetooth() {
    this.setState({ enabled: await CIDPrint.enableBluetoothPrinting({enable: true})})
  }

  discover() {
    CIDPrint.discoverDevices();
  }

  async connect(printer: Device) {
    this.setState({connected: await CIDPrint.connectToPreferredPrinter({mac: printer.devicemac })})
  }

  async print(label: String, data: String[]) {
    console.log('vorher');
    await CIDPrint.printLabel({label: 'label41.dat'})
    console.log('nachher');
  }

  render() {
    return (
      <IonPage>
        <IonHeader>
          <IonToolbar>
            <IonTitle>Bluetooth Print</IonTitle>
          </IonToolbar>
        </IonHeader>
        <IonContent fullscreen>
          <IonButton onClick={() => this.init()}>Initialize Plugin</IonButton>
          <IonButton onClick={() => this.enableBluetooth()}>Enable Bluetooth</IonButton>
          <IonButton disabled={!this.state.enabled} onClick={() => this.discover()}>Discover Bluetooth Printer</IonButton>
          <IonButton disabled={!this.state.connected} onClick={() => this.print('', ['', ''])}>Print Label</IonButton>
          <IonList>
             {this.state.devices.map((item) => (
              <IonItem onClick={() => this.connect(item)}><IonText>{ item.devicename } -- { item.devicemac }</IonText></IonItem>
            ))}
           </IonList>
         </IonContent>
      </IonPage>
    );
  }
}

export default Home;

```