我正在尝试构建一个简单的蓝牙串行应用程序来连接到我的arduino。我现在正在使用ionic2来制作android app.right,我所要做的就是列出所有可用的蓝牙设备。以下是我的代码:
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() { }
}
每当我做离子服务时,我都会犯很多错误,主要是因为无法识别蓝牙(缺少功能实现)。它也不允许我构建应用程序。
请帮忙。
非常感谢
答案 0 :(得分:3)
查看文档
isEnabled()
平台:Android iOS Windows Phone
报告蓝牙是否已启用
返回:
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";
}
});
});
}
}
}
答案 1 :(得分:1)
以下代码用于扫描蓝牙设备
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();
});
}
注意:这对我有用