看了网上的几个例子,发现写的都比较乱,正好有业务需要,所以就封装了一个蓝牙库,采用Promise实现,将过程变得极其简单,主要代码如下:
connectDevice: function () {
return bleComm.open().then(res => {
return bleComm.getStatus();
}).then(res => {
return bleComm.startScan();
}).then(res => {
return bleComm.getDevices();
}).then(res => {
return bleComm.foundDevice();
}).then(res => {
return bleComm.stopScan();
}).then(res => {
return bleComm.connect();
}).then(res => {
return bleComm.getServices();
}).then(res => {
return bleComm.getCharacteristics();
}).then(res => {
return bleComm.registerNotify();
})
}