小程序蓝牙通讯

一:连接流程

1.openBluetoothAdapter 获取手机蓝牙的状态(是否已打开蓝牙,手机是否支持蓝牙功能)

2.startBluetoothDevicesDiscovery 开始搜索蓝牙设备

3.getBluetoothDevices  已获取的蓝牙设备列表

4.connectBLEDevice  开始匹配连接设备

5.getBLEDeviceServices  获取设备services服务列表

6.getBLEDeviceCharacteristics  获取蓝牙设备characteristics特征值列表

7.notifyBLECharacteristicValueChange  开启设备notify功能

8.onBLECharacteristicValueChange  监听回调变化获取设备返回数据

9.writeBLECharacteristicValue  想蓝牙设备写入数据

二:完整代码

import apiUrl from '../../utils/utils';
Page({
    data: {
        list: [],
    },
    onReady() {
        var that = this;
        //获取本机蓝牙开关状态
        my.openBluetoothAdapter({
            success: (res) => {
                if (!res.isSupportBLE) {
                    my.alert({ content: '抱歉,您的手机蓝牙暂不可用' });
                    return;
                }else{
                    //开始搜寻附近的蓝牙外围设备
                    my.startBluetoothDevicesDiscovery({
                        allowDuplicatesKey: false,
                        success: (res) => {
                            //获取搜索设备
                            setTimeout(function () {
                                my.getBluetoothDevices({
                                    success: (res) => {
                                        let devices = res.devices;
                                        let len = devices.length;
                                        that.setData({
                                            list: devices,
                                        })
                                        if (len == 0) {
                                            //未收到设备处理
                                            my.hideLoading(); 
                                            my.alert({
                                                title: '获取搜索设备为空',
                                                content: "周边无设备",
                                                buttonText: "确定",
                                                success: () => {

                                                },
                                            });    
                                        } else {
                                            that.open(res.devices);
                                        }
                                        my.stopBluetoothDevicesDiscovery({
                                            success: (res) => {
                                                console.log(res)
                                            },
                                            fail:(res) => {

                                            },
                                        });
                                    },
                                    fail:(res) => {
                                        //获取设备
                                        my.alert({
                                            title: '获取搜索设备列表',
                                            content: JSON.stringify(res),
                                            buttonText: '我知道了',
                                        });
                                        my.stopBluetoothDevicesDiscovery({
                                            success: (res) => {
                                                console.log(res)
                                            },
                                            fail:(res) => {

                                            },
                                        });
                                    }
                                });
                            }, 1000);
                        },
                        fail:(res) => {
                            //开始搜索附近蓝牙
                            my.alert({
                                title: '开始搜索附近蓝牙',
                                content: JSON.stringify(res),
                                buttonText: '我知道了',
                            });
                        },
                    });
                }
            },
            fail:(res) => {
                //本机蓝牙开关状态
                my.alert({
                    title: '本机蓝牙开关状态',
                    content: JSON.stringify(res),
                    buttonText: '我知道了',
                });
            },
        });
    },
    open(arr){
        var that = this;
        var target = false;
        for (let x = 0; x < arr.length; x++) {
            if(arr[x].name == 'XXXXXXXXXXXXX'){
                target = true;
                useAsyncAwait();
                async function useAsyncAwait(){
                    await that.deviceIdOpen(arr[x].deviceId)
                }               
            }
        }
        if(target == false){
            my.alert({
                title: '未获取到对应设备',
                content: '请重试',
                buttonText: '我知道了',
            });
        }
    },
    deviceIdOpen(connectedDeviceId){
        var that = this;
        console.log('zyy open' + connectedDeviceId)
        //开始匹配连接设备
        my.connectBLEDevice({
            deviceId: connectedDeviceId,
            success: (res) => {
                console.log('zyy connectBLEDevice'+connectedDeviceId)
                // 获取设备uuid(服务列表)
                my.getBLEDeviceServices({
                    deviceId: connectedDeviceId,
                    success: (res) => {
                        console.log('zyy getBLEDeviceServices'+connectedDeviceId)
                        var services = res.services;
                        for (var y = 0; y < services.length; y++) {
                            var serviceId = services[y].serviceId;
                            if(serviceId == 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX'){
                                //获取蓝牙设备特征值
                                my.getBLEDeviceCharacteristics({
                                    deviceId: connectedDeviceId,
                                    serviceId: serviceId,
                                    success: (res) => {
                                        var characteristic = res.characteristics;
                                        for (var z = 0; z < characteristic.length; z++) {
                                            var characteristicId = characteristic[z].characteristicId;
                                            if(characteristicId == 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX'){
                                                // 启用低功耗蓝牙设备特征值变化时的 notify 功能
                                                my.notifyBLECharacteristicValueChange({
                                                    state: true, // 启用 notify 功能
                                                    deviceId: connectedDeviceId,
                                                    serviceId: serviceId,
                                                    characteristicId: characteristicId,
                                                    success: (res) => {
                                                        //向低功耗蓝牙设备特征值中写入数据
                                                        setTimeout(function () {
                                                        my.writeBLECharacteristicValue({
                                                            deviceId: connectedDeviceId,
                                                            serviceId: serviceId,
                                                            characteristicId: characteristicId,
                                                            value: 'XXXXXXXXXXXXXXXXXXXX',
                                                            success: (resa) => {
                                                                //读取蓝牙返回数据
                                                                my.alert({
                                                                    title: '写入数据成功',
                                                                    content: JSON.stringify(res),
                                                                    buttonText: '我知道了',
                                                                });
                                      // my.onBLECharacteristicValueChange(that.getdata) }, fail:(res)
=> { //向低功耗蓝牙设备特征值中写入数据 my.alert({ title: '写入数据失败', content: JSON.stringify(res), buttonText: '我知道了', }); }, complete: (res)=>{ my.alert({ title: 'connectedDeviceId', content: connectedDeviceId, buttonText: '我知道了', }); } }); }, 500); my.onBLECharacteristicValueChange(that.getdata); }, fail:(res) => { // 启用低功耗蓝牙设备特征值变化时的 notify 功能 my.alert({ title: 'notify 功能开启', content: res, buttonText: '我知道了', }); }, }); } } }, fail:(res) => { //获取设备特征值 my.alert({ title: '获取特征值失败', content: JSON.stringify(res), buttonText: '我知道了', }); }, complete: (res)=>{ } }); } } }, fail:(res) => { // 获取设备uuid(服务列表) my.alert({ title: 'services服务列表获取失败', content: JSON.stringify(res), buttonText: '我知道了', }); }, }); }, fail:(res) => { //开始连接设备 my.alert({ title: '开始连接设备', content: JSON.stringify(res), buttonText: '我知道了', }); }, }); }, getdata(res){ //将change事件移除避免出现多个返回值监听 my.offBLECharacteristicValueChange(); setTimeout(function () { //断开蓝牙 my.disconnectBLEDevice({ deviceId:res.deviceId, success: (res) => { } }); }, 300); my.alert({ title: '获取蓝牙返回值', content: JSON.stringify(res), buttonText: '我知道了', }); }, });

三:常见问题

1.不能正确获取蓝牙设备列表

加上一个延迟setTimeout操作,从开始获取到获取全部需要时间,是异步操作。

2.性能损耗

在蓝牙设备获取结束时应当关闭中止获取stopBluetoothDevicesDiscovery。

3.在设备遍历内进行异步操作,将每次都获取到最后一个设备进行连接

将异步转同步,在每一个异步时间处理结束时,再进行下一个循环++事件,async+await。

4.写入数据成功,但是并没有触发获取设备返回值

要先监听change事件的变化,再写入数据,不然第一次很难监听到返回值。

同时在change事件内将方法关闭以及蓝牙关闭,避免一次连接返回多次返回值,以及对下一次连接的影响。

猜你喜欢

转载自www.cnblogs.com/yuanyuan0809/p/9467031.html
今日推荐