2016-12-01 15 views
0

Я пытаюсь создать простое приложение для подключения к Bluetooth, чтобы подключиться к моему ардуино. Я использую ionic2 для создания андроида app.right сейчас, все, что я пытаюсь сделать, это перечислить все доступные Bluetooth-устройства. Ниже мой код:Bluetooth Serial Ionic 2

import { Component } from '@angular/core'; 
import { BluetoothSerial } from 'ionic-native'; 
import { NavController } from 'ionic-angular'; 

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

public working:string; 
public var2: string ; 

bluetoothSerial.isEnabled(
    function() { 
     this.working= "Bluetooth is enabled"; 
    }, 
    function() { 
     this.working="Bluetooth is *not* enabled"; 
    } 
); 

public lists = []; 

bluetoothSerial.discoverUnpaired(function(devices) { 
    this.lists.push(devices); 
}, function(){ this.var2 = 'could not find any bluetooth device';}); 

    constructor() { } 

} 

Всякий раз, когда я ионную служить мне делать много ошибок, в основном потому, что Bluetooth не распознается (реализация функции отсутствует). Это также не позволяет мне создавать приложение.

Пожалуйста, помогите нам в этом.

Спасибо большое

ответ

2

Глядя на документы

isEnabled()

Платформы: Android IOS Windows Phone

Reports, если Bluetooth включен

Возврат: Promise возвращает обещание

Пара вещей. Вы не можете назвать свой метод таким. Вы должны капитализировать ваш BluetoothSerial Вы должны поместить его в функцию

import { Component } from '@angular/core'; 
import { BluetoothSerial } from 'ionic-native'; 
import { NavController } from 'ionic-angular'; 

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

public working:string; 
public var2: string ; 
public lists = []; 

constructor(){ 
    this.getAlBluetoothDevices(); 
} 

// put BluetoothSerial inside a function, can't be called different 
getAllBluetoothDevices(){ 
    // async so keep everything in this method 
    BluetoothSerial.isEnabled().then((data)=> { 
     // not sure of returning value, probably a boolean 
     console.log("dont know what it returns"+data); 

     // returns all the available devices, not just the unpaired ones 
     BluetoothSerial.list().then((allDevices) => { 
      // set the list to returned value 
      this.lists = allDevices; 
      if(!this.lists.length > 0){ 
       this.var2 = "could not find any bluetooth devices"; 
      } 
     }); 
    }); 
    } 
} 

}

+0

Спасибо большое! Я высоко ценю ваше время и помощь. Я попробую ваш данный код и вернусь к вам с обновлением. Спасибо –

+0

Конечно, я сам не использовал tis-библиотеку. Изучите документы ionic2 для них, если у вас есть свободное время :) https://ionicframework.com/docs/v2/native/bluetooth-serial/ – Ivaro18

+0

Привет, помощник, ваш код работал эффективно, удалив 'this.getAlBluetoothDevices(); 'from constrcutor(), я не знаю, почему это проблема. Кроме того, BS.list отображает только парные устройства, которые не являются непарными (это также упоминается в документах BS). Но у меня его работающий помощник ... Следующее, что я собираюсь попробовать подключиться к устройству arduino и посмотреть, работает ли он. –

0

Код ниже для проверки устройства Bluetooth

startScanning(){ 
     this.isScanning =true; 
      this.bluetoothSerial.isEnabled().then(()=>{ 
      this.bluetoothSerial.discoverUnpaired().then((allDevices)=>{ 
       this.devices=allDevices; 
       this.isScanning =false; 
      }); 
     }); 

И этот код для подключения к устройство

onDeviceReady(){ 
    let device = this.navParams.get('device'); 


     this.bluetoothSerial.connect(device.id).subscribe((data)=>{ 
      let alert = this.alertCtrl.create({ 
       title: 'Bluetooth', 
       subTitle: data, 
       buttons: ['ok'] 
       }); 
       alert.present(); 
     },error=>{ 
      let alert = this.alertCtrl.create({ 
       title: 'Bluetooth', 
       subTitle: error, 
       buttons: ['ok'] 
       }); 
       alert.present(); 
     }); 

    } 

Примечание: он работает для меня