正在复制的BLE设备列表

时间:2018-02-24 09:44:21

标签: javascript angular ionic-framework ionic2 ionic-native

您好,目前我正在开发一个名为BLE Scanner的Ionic项目。我一直在努力寻找解决方案,最终设法连接到这些设备。以下是我在互联网上找到的代码:

home.ts(只需忽略DetailPage)

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { BLE } from '@ionic-native/ble';
import { DevicePage } from '../device/device';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  devices: any[];
  isScanning:boolean;

  constructor(public navCtrl: NavController,
              private ble: BLE) {
    this.devices=[];
    this.isScanning =false;
  }

  startScanning(){
    console.log("Scanning ..");
    this.devices=[];
    this.isScanning=true;
    this.ble.startScan([]).subscribe(
      device => {
        this.devices.push(device);
      }
    );

    setTimeout(() => {
      this.ble.stopScan().then(() => {
      console.log("Scanning has stopped");
      console.log(JSON.stringify(this.devices))
      this.isScanning = false;
      });
      }, 5000);
  }

  connectToDevice(device){
    console.log("Connect To Device");
    console.log(JSON.stringify(this.devices));
    this.navCtrl.push(DevicePage, {
      device: device
    });
  }
}

和home.html

<ion-content>
  <ion-list inset>
    <ion-item-sliding *ngFor="let device of devices">
      <button ion-item (click)="connectToDevice(device)">
        <h2>Device: {{ device.name }}</h2>
        <p>ID: {{ device.id }}</p>
        <p>RRSI: {{ device.rssi }}</p>
      </button>
    </ion-item-sliding>
  </ion-list>
  <ion-spinner *ngIf="isScanning==true" name="circles"></ion-spinner>
</ion-content>

因此出现了一个问题:BLE设备列表正在重复,因为RSSI一直在波动,我不知道如何在RSSI不断更新时只显示每个设备一次。

这是我当前的应用程序,因为您可以看到只有一个名为RADUSB的设备,但多次显示

my current app

请帮我弄清楚解决这个问题的方法。我很感激每一个建议。谢谢!

1 个答案:

答案 0 :(得分:1)

您正在startScan中插入列表。添加一项检查以查看它是否已包含该设备。

this.ble.startScan([]).subscribe(
      device => {
        if(this.devices.findIndex((dev:any)=>dev.id===device.id)==-1)
            this.devices.push(device);
      });