小程序藍牙連接的開發1.0流程圖


大致流程:
* 1、 開啟藍牙適配
   * 2、 獲取藍牙適配器狀態,判斷設備藍牙是否可用。
   * 3、 判斷藍牙適配器可用時開啟掃描藍牙設備和開啟獲取已連接的藍牙設備
   * 4、 如果開啟掃描藍牙設備失敗5s后自動再次開啟掃描
   * 5、 開啟掃描藍牙設備成功后開啟監聽已掃描的設備
   * 6、 如果已掃描到的新設備含FeiZhi名(個人產品需要)的設備則開始連接該設備
   * 7、 開啟獲取已連接藍牙設備開啟獲取設備成功后判斷以獲取的設備名包含FeiZhi(個人產品需要)字符串的設備則開始連接該設備
   * 8、 開始獲取已連接藍牙設備沒有成功獲取到已連接的藍牙設備5s后自動重新開啟獲取。
   * 9、 開始連接某設備時停止掃描設備,停止循環獲取已連接設備。
   * 10、連接成功后停止掃描設備,停止循環獲取已連接設備

 

暗示

1、app.js的onLaunch() 方法里中調用開啟連接 this.startConnect();彈出提示框,開啟適配,如果失敗提示設備藍牙不可用,同時開啟藍牙適配器狀態監聽。

 

startConnect: function () {

var that = this;

wx.showLoading({

title: '開啟藍牙適配'

});

wx.openBluetoothAdapter({

success: function (res) {

console.log("初始化藍牙適配器");

console.log(res);

that.getBluetoothAdapterState();

},

fail: function (err) {

console.log(err);

wx.showToast({

title: '藍牙初始化失敗',

icon: 'success',

duration: 2000

})

setTimeout(function () {

wx.hideToast()

}, 2000)

}

});

wx.onBluetoothAdapterStateChange(function (res) {

var available = res.available;

if (available) {

that.getBluetoothAdapterState();

}

})

}
2、初始化藍牙適配器成功,調用this.getBluetoothAdapterState() 獲取本機藍牙適配器狀態,判斷是否可用,available為false則因為用戶沒有開啟系統藍牙。同時判斷程序還沒有開始搜索藍牙設備,調用this.startBluetoothDevicesDiscovery();開始掃描附近的藍牙設備,同時調用this.getConnectedBluetoothDevices() 開啟獲取本機已配對的藍牙設備。

getBluetoothAdapterState: function () {

var that = this;

wx.getBluetoothAdapterState({

success: function (res) {

var available = res.available,

discovering = res.discovering;

if (!available) {

wx.showToast({

title: '設備無法開啟藍牙連接',

icon: 'success',

duration: 2000

})

setTimeout(function () {

wx.hideToast()

}, 2000)

} else {

if (!discovering) {

that.startBluetoothDevicesDiscovery();

that.getConnectedBluetoothDevices();

}

}

}

})

}
3、開始搜索藍牙設備startBluetoothDevicesDiscovery() , 提示藍牙搜索。

startBluetoothDevicesDiscovery: function () {

var that = this;

wx.showLoading({

title: '藍牙搜索'

});

wx.startBluetoothDevicesDiscovery({

services: [],

allowDuplicatesKey: false,

success: function (res) {

if (!res.isDiscovering) {

that.getBluetoothAdapterState();

} else {

that.onBluetoothDeviceFound();

}

},

fail: function (err) {

console.log(err);

}

});

}
4、獲取已配對的藍牙設備。此方法特別說明參數services(Array)是必填的,但是官方示例中以及各種坑爹demo里從沒見過有誰填寫,但是不填寫這個屬性此方法無法獲取到任何已配對設備。如果要調用此方法則是需要連接特定設備,並且知道該設備的一個主服務serviceId。如果未知可以先手動連接一次想要連接的設備,然后獲取service列表,記錄屬性primary為true的值至少一個。

getConnectedBluetoothDevices: function () {

var that = this;

wx.getConnectedBluetoothDevices({

services: [that.serviceId],

success: function (res) {

console.log("獲取處於連接狀態的設備", res);

var devices = res['devices'], flag = false, index = 0, conDevList = [];

devices.forEach(function (value, index, array) {

if (value['name'].indexOf('FeiZhi') != -1) {

// 如果存在包含FeiZhi字段的設備

flag = true;

index += 1;

conDevList.push(value['deviceId']);

that.deviceId = value['deviceId'];

return;

}

});

if (flag) {

this.connectDeviceIndex = 0;

that.loopConnect(conDevList);

} else {

if (!this.getConnectedTimer) {

that.getConnectedTimer = setTimeout(function () {

that.getConnectedBluetoothDevices();

}, 5000);

}

}

},

fail: function (err) {

if (!this.getConnectedTimer) {

that.getConnectedTimer = setTimeout(function () {

that.getConnectedBluetoothDevices();

}, 5000);

}

}

});

}
5、開啟藍牙搜索功能失敗,則回到第2步重新檢查藍牙是適配器是否可用,開啟藍牙搜索功能成功后開啟發現附近藍牙設備事件監聽。this.onBluetoothDeviceFound()

onBluetoothDeviceFound: function () {

var that = this;

console.log('onBluetoothDeviceFound');

wx.onBluetoothDeviceFound(function (res) {

console.log('new device list has founded')

console.log(res);

if (res.devices[0]) {

var name = res.devices[0]['name'];

if (name != '') {

if (name.indexOf('FeiZhi') != -1) {

var deviceId = res.devices[0]['deviceId'];

that.deviceId = deviceId;

console.log(that.deviceId);

that.startConnectDevices();

}

}

}

})

}
此方法可自定義過濾一些無效的藍牙設備比如name為空的,個人產品開發中需要過濾devices name 不含有FeiZhi字符串的設備。

6、在第5步中發現了某個想配對的設備,則獲取到該設備的deviceId,然后開始配對該設備 this.startConnectDevices()。

startConnectDevices: function (ltype, array) {

var that = this;

clearTimeout(that.getConnectedTimer);

that.getConnectedTimer = null;

clearTimeout(that.discoveryDevicesTimer);

that.stopBluetoothDevicesDiscovery();

this.isConnectting = true;

wx.createBLEConnection({

deviceId: that.deviceId,

success: function (res) {

if (res.errCode == 0) {

setTimeout(function () {

that.getService(that.deviceId);

}, 5000)

}

},

fail: function (err) {

console.log('連接失敗:', err);

if (ltype == 'loop') {

that.connectDeviceIndex += 1;

that.loopConnect(array);

} else {

that.startBluetoothDevicesDiscovery();

that.getConnectedBluetoothDevices();

}

},

complete: function () {

console.log('complete connect devices');

this.isConnectting = false;

}

});

}

開啟連接后為了避免出現沖突,一旦開啟連接則終止掃描附近藍牙設備,終止讀取本機已配對設備。

#####7、連接成功后根據deiviceId獲取設備的所有服務。this.getService(deviceId);

getService: function (deviceId) {

var that = this;

// 監聽藍牙連接

wx.onBLEConnectionStateChange(function (res) {

console.log(res);

});

// 獲取藍牙設備service值

wx.getBLEDeviceServices({

deviceId: deviceId,

success: function (res) {

that.getCharacter(deviceId, res.services);

}

})

}
8、讀取服務的特征值。

getCharacter: function (deviceId, services) {

var that = this;

services.forEach(function (value, index, array) {

if (value == that.serviceId) {

that.serviceId = array[index];

}

});

wx.getBLEDeviceCharacteristics({

deviceId: deviceId,

serviceId: that.serviceId,

success: function (res) {

that.writeBLECharacteristicValue(deviceId, that.serviceId, that.characterId_write);

that.openNotifyService(deviceId, that.serviceId, that.characterId_read);

},

fail: function (err) {

console.log(err);

},

complete: function () {

console.log('complete');

}

})

}
9、如果掃描到的設備中沒有想要連接的設備,可以嘗試使用系統藍牙手動配對,然后再小程序中調用getConnectedBluetoothDevices() 獲取本機已配對的藍牙設備,然后過濾設備(可能獲取多個已配對的藍牙設備)。將以獲取的藍牙設備deviceId放入到一個數組中調用自定義方法this.loopConnect(); 思路:通過遞歸調用獲取已配對藍牙設備的deviceId,如果獲取到了就去連接,devicesId[x] 為空說明上傳調用getConnectedBluetoothDevices()時獲取到的已配對設備全部連接失敗了。則開啟重新獲取已配對藍牙設備,並開啟掃描附近藍牙設備。

loopConnect: function (devicesId) {

var that = this;

var listLen = devicesId.length;

if (devicesId[this.connectDeviceIndex]) {

this.deviceId = devicesId[this.connectDeviceIndex];

this.startConnectDevices('loop', devicesId);

} else {

console.log('已配對的設備小程序藍牙連接失敗');

that.startBluetoothDevicesDiscovery();

that.getConnectedBluetoothDevices();

}

}
10、**startConnectDevices('loop', array)方法,是當獲取已配對藍牙設備進行連接時這樣調用。其中的處理邏輯上文已經貼出,意思就是在連接失敗后fail方法里累加一個全局變量,然后回調loopConnect(array)方法。

**11、手動連接,上文介紹的方法是為了直接自動連接,如果不需要自動連接,可在使用方法getBluetoothDevices() 將會獲取到已掃描到的藍牙設備的列表,可以做個頁面顯示出設備名,點擊該設備開始連接。

注意:

1、that.serviceId 是在初始化時設置的,由於對需要連接設備的主服務serivceId和各種特征值都是已知的因此可以這樣做。如果不可知可以做一個掃描方法自己檢查特征值的用途。

2、 連接成功后的writeBLECharacteristicValue和openNotifyService操作需要注意,如果同時開啟這兩項操作要先調用wirte再開啟notify(原因未知,個人心得)。

3、經人提醒還可以再完善一下在onBlueToothAdapterStateChange()**可以監聽藍牙適配器狀態,以此判斷連接過程中或連接后用戶開關了設備藍牙,如果判斷到關了藍牙提示請開啟,如果監聽到開啟了,就重新回到第1步。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM