首页 > 解决方案 > 如何使用 ionic 4 BluetoothLE 插件连接蓝牙?

问题描述

我是 ionic 4 项目中使用蓝牙插件,使用此插件,我可以获取设备列表但无法连接。你好,我是ionic 4项目中使用蓝牙插件,使用这个插件,我可以获取设备列表但无法连接。

插件:蓝牙LE

完整演示代码:BluetoothLE 演示

这是我的代码:

....
import { BluetoothLE } from '@ionic-native/bluetooth-le/ngx';
import { Platform, ToastController } from '@ionic/angular';
....
public statusMessage: string;
devices: any[] = [];
....
 constructor(public bluetoothle: BluetoothLE,
    public platform: Platform) {
    this.platform.ready().then((readySource) => {
      console.log('Platform ready from', readySource);
      this.bluetoothle.enable();
      this.bluetoothle.initialize().subscribe(ble => {
        console.log('ble', ble.status) // logs 'enabled'
        this.setStatus(ble.status);
      });
    });
  }
....
startScan() {
    this.setStatus('Scanning for Bluetooth LE Devices');
    this.devices = [];  // clear list
    this.bluetoothle.startScan({ services: [] }).subscribe((success) => {
      debugger;
      console.log("startScan: " + JSON.stringify(success));
      this.setStatus(JSON.stringify(success.status));
      this.ngZone.run(() => {
        this.devices.push(success);
      });
    }, (error) => {
      console.log("error: " + JSON.stringify(error));
      this.scanError(JSON.stringify(error));
    })
    setTimeout(() => {
      this.setStatus.bind(this);
    }, 5000, 'Scan complete');
  }

  async connectToDevice(device: any) {
    debugger;
    const alert = await this.alertController.create({
      header: 'Connect',
      message: 'Do you want to connect with?',
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel',
          handler: () => {
            console.log('Cancel clicked');
          }
        },
        {
          text: 'Connect',
          handler: () => {
            this.bluetoothle.connect(device.address).subscribe((success) => {
              debugger;
              console.log(success)
              this.setStatus(JSON.stringify(success));
            }, (error) => {
              debugger;
              console.log(error)
              this.scanError(JSON.stringify(error));
            });
          }
        }
      ]
    });
    alert.present();
  }

  stopScan() {
    this.bluetoothle.stopScan().then((resp) => {
      console.log("stopScan: " + resp);
      this.setStatus(resp.status);
    })
  }

// If location permission is denied, you'll end up here
  async scanError(error: string) {
    this.setStatus('Error ' + error);
    const toast = await this.toastController.create({
      message: 'Error scanning for Bluetooth low energy devices',
      position: 'middle',
      duration: 5000
    });
    toast.present();
  }

  setStatus(message: string) {
    // console.log("message: " + message);
    this.ngZone.run(() => {
      this.statusMessage = message;
    });
  }

网页

<ion-content>
  <ion-list>
    <button ion-item *ngFor="let device of devices" (click)="connectToDevice(device)">
      <h2>{{ device.name || 'Unnamed' }}</h2>
      <p>{{ device.id }}</p>
      <p>RSSI: {{ device.rssi }}</p>
    </button>
  </ion-list>
</ion-content>
<ion-footer>
  <ion-toolbar>
    <p>{{ statusMessage }}</p>
    <ion-buttons slot="end">
      <ion-button fill="clear" (click)="stopScan()">Stop</ion-button>
    </ion-buttons>
  </ion-toolbar>
</ion-footer>

我这样做了,即使我无法连接,我也得到了设备列表和设备地址。请帮忙

标签: angularionic-frameworkionic4

解决方案


推荐阅读